vdbe.c 161 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303
  1. /*
  2. ** 2001 September 15
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** The code in this file implements execution method of the
  13. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  14. ** handles housekeeping details such as creating and deleting
  15. ** VDBE instances. This file is solely interested in executing
  16. ** the VDBE program.
  17. **
  18. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  19. ** to a VDBE.
  20. **
  21. ** The SQL parser generates a program which is then executed by
  22. ** the VDBE to do the work of the SQL statement. VDBE programs are
  23. ** similar in form to assembly language. The program consists of
  24. ** a linear sequence of operations. Each operation has an opcode
  25. ** and 3 operands. Operands P1 and P2 are integers. Operand P3
  26. ** is a null-terminated string. The P2 operand must be non-negative.
  27. ** Opcodes will typically ignore one or more operands. Many opcodes
  28. ** ignore all three operands.
  29. **
  30. ** Computation results are stored on a stack. Each entry on the
  31. ** stack is either an integer, a null-terminated string, a floating point
  32. ** number, or the SQL "NULL" value. An inplicit conversion from one
  33. ** type to the other occurs as necessary.
  34. **
  35. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  36. ** function which does the work of interpreting a VDBE program.
  37. ** But other routines are also provided to help in building up
  38. ** a program instruction by instruction.
  39. **
  40. ** Various scripts scan this source file in order to generate HTML
  41. ** documentation, headers files, or other derived files. The formatting
  42. ** of the code in this file is, therefore, important. See other comments
  43. ** in this file for details. If in doubt, do not deviate from existing
  44. ** commenting and indentation practices when changing or adding code.
  45. **
  46. ** $Id: vdbe.c,v 1.660 2007/12/13 21:54:11 drh Exp $
  47. */
  48. #include "sqliteInt.h"
  49. #include <ctype.h>
  50. #include "vdbeInt.h"
  51. /*
  52. ** The following global variable is incremented every time a cursor
  53. ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes. The test
  54. ** procedures use this information to make sure that indices are
  55. ** working correctly. This variable has no function other than to
  56. ** help verify the correct operation of the library.
  57. */
  58. #ifdef SQLITE_TEST
  59. int sqlite3_search_count = 0;
  60. #endif
  61. /*
  62. ** When this global variable is positive, it gets decremented once before
  63. ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
  64. ** field of the sqlite3 structure is set in order to simulate and interrupt.
  65. **
  66. ** This facility is used for testing purposes only. It does not function
  67. ** in an ordinary build.
  68. */
  69. #ifdef SQLITE_TEST
  70. int sqlite3_interrupt_count = 0;
  71. #endif
  72. /*
  73. ** The next global variable is incremented each type the OP_Sort opcode
  74. ** is executed. The test procedures use this information to make sure that
  75. ** sorting is occurring or not occuring at appropriate times. This variable
  76. ** has no function other than to help verify the correct operation of the
  77. ** library.
  78. */
  79. #ifdef SQLITE_TEST
  80. int sqlite3_sort_count = 0;
  81. #endif
  82. /*
  83. ** The next global variable records the size of the largest MEM_Blob
  84. ** or MEM_Str that has appeared on the VDBE stack. The test procedures
  85. ** use this information to make sure that the zero-blob functionality
  86. ** is working correctly. This variable has no function other than to
  87. ** help verify the correct operation of the library.
  88. */
  89. #ifdef SQLITE_TEST
  90. int sqlite3_max_blobsize = 0;
  91. #endif
  92. /*
  93. ** Release the memory associated with the given stack level. This
  94. ** leaves the Mem.flags field in an inconsistent state.
  95. */
  96. #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
  97. /*
  98. ** Convert the given stack entity into a string if it isn't one
  99. ** already. Return non-zero if a malloc() fails.
  100. */
  101. #define Stringify(P, enc) \
  102. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  103. { goto no_mem; }
  104. /*
  105. ** The header of a record consists of a sequence variable-length integers.
  106. ** These integers are almost always small and are encoded as a single byte.
  107. ** The following macro takes advantage this fact to provide a fast decode
  108. ** of the integers in a record header. It is faster for the common case
  109. ** where the integer is a single byte. It is a little slower when the
  110. ** integer is two or more bytes. But overall it is faster.
  111. **
  112. ** The following expressions are equivalent:
  113. **
  114. ** x = sqlite3GetVarint32( A, &B );
  115. **
  116. ** x = GetVarint( A, B );
  117. **
  118. */
  119. #define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
  120. /*
  121. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  122. ** a pointer to a dynamically allocated string where some other entity
  123. ** is responsible for deallocating that string. Because the stack entry
  124. ** does not control the string, it might be deleted without the stack
  125. ** entry knowing it.
  126. **
  127. ** This routine converts an ephemeral string into a dynamically allocated
  128. ** string that the stack entry itself controls. In other words, it
  129. ** converts an MEM_Ephem string into an MEM_Dyn string.
  130. */
  131. #define Deephemeralize(P) \
  132. if( ((P)->flags&MEM_Ephem)!=0 \
  133. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  134. /*
  135. ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
  136. ** P if required.
  137. */
  138. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  139. /*
  140. ** Argument pMem points at a memory cell that will be passed to a
  141. ** user-defined function or returned to the user as the result of a query.
  142. ** The second argument, 'db_enc' is the text encoding used by the vdbe for
  143. ** stack variables. This routine sets the pMem->enc and pMem->type
  144. ** variables used by the sqlite3_value_*() routines.
  145. */
  146. #define storeTypeInfo(A,B) _storeTypeInfo(A)
  147. static void _storeTypeInfo(Mem *pMem){
  148. int flags = pMem->flags;
  149. if( flags & MEM_Null ){
  150. pMem->type = SQLITE_NULL;
  151. }
  152. else if( flags & MEM_Int ){
  153. pMem->type = SQLITE_INTEGER;
  154. }
  155. else if( flags & MEM_Real ){
  156. pMem->type = SQLITE_FLOAT;
  157. }
  158. else if( flags & MEM_Str ){
  159. pMem->type = SQLITE_TEXT;
  160. }else{
  161. pMem->type = SQLITE_BLOB;
  162. }
  163. }
  164. /*
  165. ** Pop the stack N times.
  166. */
  167. static void popStack(Mem **ppTos, int N){
  168. Mem *pTos = *ppTos;
  169. while( N>0 ){
  170. N--;
  171. Release(pTos);
  172. pTos--;
  173. }
  174. *ppTos = pTos;
  175. }
  176. /*
  177. ** Allocate cursor number iCur. Return a pointer to it. Return NULL
  178. ** if we run out of memory.
  179. */
  180. static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
  181. Cursor *pCx;
  182. assert( iCur<p->nCursor );
  183. if( p->apCsr[iCur] ){
  184. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  185. }
  186. p->apCsr[iCur] = pCx = sqlite3MallocZero( sizeof(Cursor) );
  187. if( pCx ){
  188. pCx->iDb = iDb;
  189. }
  190. return pCx;
  191. }
  192. /*
  193. ** Try to convert a value into a numeric representation if we can
  194. ** do so without loss of information. In other words, if the string
  195. ** looks like a number, convert it into a number. If it does not
  196. ** look like a number, leave it alone.
  197. */
  198. static void applyNumericAffinity(Mem *pRec){
  199. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  200. int realnum;
  201. sqlite3VdbeMemNulTerminate(pRec);
  202. if( (pRec->flags&MEM_Str)
  203. && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
  204. i64 value;
  205. sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
  206. if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
  207. sqlite3VdbeMemRelease(pRec);
  208. pRec->u.i = value;
  209. pRec->flags = MEM_Int;
  210. }else{
  211. sqlite3VdbeMemRealify(pRec);
  212. }
  213. }
  214. }
  215. }
  216. /*
  217. ** Processing is determine by the affinity parameter:
  218. **
  219. ** SQLITE_AFF_INTEGER:
  220. ** SQLITE_AFF_REAL:
  221. ** SQLITE_AFF_NUMERIC:
  222. ** Try to convert pRec to an integer representation or a
  223. ** floating-point representation if an integer representation
  224. ** is not possible. Note that the integer representation is
  225. ** always preferred, even if the affinity is REAL, because
  226. ** an integer representation is more space efficient on disk.
  227. **
  228. ** SQLITE_AFF_TEXT:
  229. ** Convert pRec to a text representation.
  230. **
  231. ** SQLITE_AFF_NONE:
  232. ** No-op. pRec is unchanged.
  233. */
  234. static void applyAffinity(
  235. Mem *pRec, /* The value to apply affinity to */
  236. char affinity, /* The affinity to be applied */
  237. u8 enc /* Use this text encoding */
  238. ){
  239. if( affinity==SQLITE_AFF_TEXT ){
  240. /* Only attempt the conversion to TEXT if there is an integer or real
  241. ** representation (blob and NULL do not get converted) but no string
  242. ** representation.
  243. */
  244. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  245. sqlite3VdbeMemStringify(pRec, enc);
  246. }
  247. pRec->flags &= ~(MEM_Real|MEM_Int);
  248. }else if( affinity!=SQLITE_AFF_NONE ){
  249. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  250. || affinity==SQLITE_AFF_NUMERIC );
  251. applyNumericAffinity(pRec);
  252. if( pRec->flags & MEM_Real ){
  253. sqlite3VdbeIntegerAffinity(pRec);
  254. }
  255. }
  256. }
  257. /*
  258. ** Try to convert the type of a function argument or a result column
  259. ** into a numeric representation. Use either INTEGER or REAL whichever
  260. ** is appropriate. But only do the conversion if it is possible without
  261. ** loss of information and return the revised type of the argument.
  262. **
  263. ** This is an EXPERIMENTAL api and is subject to change or removal.
  264. */
  265. int sqlite3_value_numeric_type(sqlite3_value *pVal){
  266. Mem *pMem = (Mem*)pVal;
  267. applyNumericAffinity(pMem);
  268. storeTypeInfo(pMem, 0);
  269. return pMem->type;
  270. }
  271. /*
  272. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  273. ** not the internal Mem* type.
  274. */
  275. void sqlite3ValueApplyAffinity(
  276. sqlite3_value *pVal,
  277. u8 affinity,
  278. u8 enc
  279. ){
  280. applyAffinity((Mem *)pVal, affinity, enc);
  281. }
  282. #ifdef SQLITE_DEBUG
  283. /*
  284. ** Write a nice string representation of the contents of cell pMem
  285. ** into buffer zBuf, length nBuf.
  286. */
  287. void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  288. char *zCsr = zBuf;
  289. int f = pMem->flags;
  290. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  291. if( f&MEM_Blob ){
  292. int i;
  293. char c;
  294. if( f & MEM_Dyn ){
  295. c = 'z';
  296. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  297. }else if( f & MEM_Static ){
  298. c = 't';
  299. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  300. }else if( f & MEM_Ephem ){
  301. c = 'e';
  302. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  303. }else{
  304. c = 's';
  305. }
  306. sqlite3_snprintf(100, zCsr, "%c", c);
  307. zCsr += strlen(zCsr);
  308. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  309. zCsr += strlen(zCsr);
  310. for(i=0; i<16 && i<pMem->n; i++){
  311. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  312. zCsr += strlen(zCsr);
  313. }
  314. for(i=0; i<16 && i<pMem->n; i++){
  315. char z = pMem->z[i];
  316. if( z<32 || z>126 ) *zCsr++ = '.';
  317. else *zCsr++ = z;
  318. }
  319. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  320. zCsr += strlen(zCsr);
  321. if( f & MEM_Zero ){
  322. sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
  323. zCsr += strlen(zCsr);
  324. }
  325. *zCsr = '\0';
  326. }else if( f & MEM_Str ){
  327. int j, k;
  328. zBuf[0] = ' ';
  329. if( f & MEM_Dyn ){
  330. zBuf[1] = 'z';
  331. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  332. }else if( f & MEM_Static ){
  333. zBuf[1] = 't';
  334. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  335. }else if( f & MEM_Ephem ){
  336. zBuf[1] = 'e';
  337. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  338. }else{
  339. zBuf[1] = 's';
  340. }
  341. k = 2;
  342. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  343. k += strlen(&zBuf[k]);
  344. zBuf[k++] = '[';
  345. for(j=0; j<15 && j<pMem->n; j++){
  346. u8 c = pMem->z[j];
  347. if( c>=0x20 && c<0x7f ){
  348. zBuf[k++] = c;
  349. }else{
  350. zBuf[k++] = '.';
  351. }
  352. }
  353. zBuf[k++] = ']';
  354. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  355. k += strlen(&zBuf[k]);
  356. zBuf[k++] = 0;
  357. }
  358. }
  359. #endif
  360. #ifdef VDBE_PROFILE
  361. /*
  362. ** The following routine only works on pentium-class processors.
  363. ** It uses the RDTSC opcode to read the cycle count value out of the
  364. ** processor and returns that value. This can be used for high-res
  365. ** profiling.
  366. */
  367. __inline__ unsigned long long int hwtime(void){
  368. unsigned long long int x;
  369. __asm__("rdtsc\n\t"
  370. "mov %%edx, %%ecx\n\t"
  371. :"=A" (x));
  372. return x;
  373. }
  374. #endif
  375. /*
  376. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  377. ** sqlite3_interrupt() routine has been called. If it has been, then
  378. ** processing of the VDBE program is interrupted.
  379. **
  380. ** This macro added to every instruction that does a jump in order to
  381. ** implement a loop. This test used to be on every single instruction,
  382. ** but that meant we more testing that we needed. By only testing the
  383. ** flag on jump instructions, we get a (small) speed improvement.
  384. */
  385. #define CHECK_FOR_INTERRUPT \
  386. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  387. /*
  388. ** Execute as much of a VDBE program as we can then return.
  389. **
  390. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  391. ** close the program with a final OP_Halt and to set up the callbacks
  392. ** and the error message pointer.
  393. **
  394. ** Whenever a row or result data is available, this routine will either
  395. ** invoke the result callback (if there is one) or return with
  396. ** SQLITE_ROW.
  397. **
  398. ** If an attempt is made to open a locked database, then this routine
  399. ** will either invoke the busy callback (if there is one) or it will
  400. ** return SQLITE_BUSY.
  401. **
  402. ** If an error occurs, an error message is written to memory obtained
  403. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  404. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  405. **
  406. ** If the callback ever returns non-zero, then the program exits
  407. ** immediately. There will be no error message but the p->rc field is
  408. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  409. **
  410. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  411. ** routine to return SQLITE_ERROR.
  412. **
  413. ** Other fatal errors return SQLITE_ERROR.
  414. **
  415. ** After this routine has finished, sqlite3VdbeFinalize() should be
  416. ** used to clean up the mess that was left behind.
  417. */
  418. int sqlite3VdbeExec(
  419. Vdbe *p /* The VDBE */
  420. ){
  421. int pc; /* The program counter */
  422. Op *pOp; /* Current operation */
  423. int rc = SQLITE_OK; /* Value to return */
  424. sqlite3 *db = p->db; /* The database */
  425. u8 encoding = ENC(db); /* The database encoding */
  426. Mem *pTos; /* Top entry in the operand stack */
  427. #ifdef VDBE_PROFILE
  428. unsigned long long start; /* CPU clock count at start of opcode */
  429. int origPc; /* Program counter at start of opcode */
  430. #endif
  431. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  432. int nProgressOps = 0; /* Opcodes executed since progress callback. */
  433. #endif
  434. #ifndef NDEBUG
  435. Mem *pStackLimit;
  436. #endif
  437. if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
  438. assert( db->magic==SQLITE_MAGIC_BUSY );
  439. pTos = p->pTos;
  440. sqlite3BtreeMutexArrayEnter(&p->aMutex);
  441. if( p->rc==SQLITE_NOMEM ){
  442. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  443. ** sqlite3_column_text16() failed. */
  444. goto no_mem;
  445. }
  446. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  447. p->rc = SQLITE_OK;
  448. assert( p->explain==0 );
  449. if( p->popStack ){
  450. popStack(&pTos, p->popStack);
  451. p->popStack = 0;
  452. }
  453. p->resOnStack = 0;
  454. db->busyHandler.nBusy = 0;
  455. CHECK_FOR_INTERRUPT;
  456. sqlite3VdbeIOTraceSql(p);
  457. #ifdef SQLITE_DEBUG
  458. if( (p->db->flags & SQLITE_VdbeListing)!=0
  459. || sqlite3OsAccess(db->pVfs, "vdbe_explain", SQLITE_ACCESS_EXISTS)
  460. ){
  461. int i;
  462. printf("VDBE Program Listing:\n");
  463. sqlite3VdbePrintSql(p);
  464. for(i=0; i<p->nOp; i++){
  465. sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
  466. }
  467. }
  468. if( sqlite3OsAccess(db->pVfs, "vdbe_trace", SQLITE_ACCESS_EXISTS) ){
  469. p->trace = stdout;
  470. }
  471. #endif
  472. for(pc=p->pc; rc==SQLITE_OK; pc++){
  473. assert( pc>=0 && pc<p->nOp );
  474. assert( pTos<=&p->aStack[pc] );
  475. if( db->mallocFailed ) goto no_mem;
  476. #ifdef VDBE_PROFILE
  477. origPc = pc;
  478. start = hwtime();
  479. #endif
  480. pOp = &p->aOp[pc];
  481. /* Only allow tracing if SQLITE_DEBUG is defined.
  482. */
  483. #ifdef SQLITE_DEBUG
  484. if( p->trace ){
  485. if( pc==0 ){
  486. printf("VDBE Execution Trace:\n");
  487. sqlite3VdbePrintSql(p);
  488. }
  489. sqlite3VdbePrintOp(p->trace, pc, pOp);
  490. }
  491. if( p->trace==0 && pc==0
  492. && sqlite3OsAccess(db->pVfs, "vdbe_sqltrace", SQLITE_ACCESS_EXISTS) ){
  493. sqlite3VdbePrintSql(p);
  494. }
  495. #endif
  496. /* Check to see if we need to simulate an interrupt. This only happens
  497. ** if we have a special test build.
  498. */
  499. #ifdef SQLITE_TEST
  500. if( sqlite3_interrupt_count>0 ){
  501. sqlite3_interrupt_count--;
  502. if( sqlite3_interrupt_count==0 ){
  503. sqlite3_interrupt(db);
  504. }
  505. }
  506. #endif
  507. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  508. /* Call the progress callback if it is configured and the required number
  509. ** of VDBE ops have been executed (either since this invocation of
  510. ** sqlite3VdbeExec() or since last time the progress callback was called).
  511. ** If the progress callback returns non-zero, exit the virtual machine with
  512. ** a return code SQLITE_ABORT.
  513. */
  514. if( db->xProgress ){
  515. if( db->nProgressOps==nProgressOps ){
  516. int prc;
  517. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  518. prc =db->xProgress(db->pProgressArg);
  519. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  520. if( prc!=0 ){
  521. rc = SQLITE_INTERRUPT;
  522. goto vdbe_halt;
  523. }
  524. nProgressOps = 0;
  525. }
  526. nProgressOps++;
  527. }
  528. #endif
  529. #ifndef NDEBUG
  530. /* This is to check that the return value of static function
  531. ** opcodeNoPush() (see vdbeaux.c) returns values that match the
  532. ** implementation of the virtual machine in this file. If
  533. ** opcodeNoPush() returns non-zero, then the stack is guarenteed
  534. ** not to grow when the opcode is executed. If it returns zero, then
  535. ** the stack may grow by at most 1.
  536. **
  537. ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not
  538. ** available if NDEBUG is defined at build time.
  539. */
  540. pStackLimit = pTos;
  541. if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
  542. pStackLimit++;
  543. }
  544. #endif
  545. switch( pOp->opcode ){
  546. /*****************************************************************************
  547. ** What follows is a massive switch statement where each case implements a
  548. ** separate instruction in the virtual machine. If we follow the usual
  549. ** indentation conventions, each case should be indented by 6 spaces. But
  550. ** that is a lot of wasted space on the left margin. So the code within
  551. ** the switch statement will break with convention and be flush-left. Another
  552. ** big comment (similar to this one) will mark the point in the code where
  553. ** we transition back to normal indentation.
  554. **
  555. ** The formatting of each case is important. The makefile for SQLite
  556. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  557. ** file looking for lines that begin with "case OP_". The opcodes.h files
  558. ** will be filled with #defines that give unique integer values to each
  559. ** opcode and the opcodes.c file is filled with an array of strings where
  560. ** each string is the symbolic name for the corresponding opcode. If the
  561. ** case statement is followed by a comment of the form "/# same as ... #/"
  562. ** that comment is used to determine the particular value of the opcode.
  563. **
  564. ** If a comment on the same line as the "case OP_" construction contains
  565. ** the word "no-push", then the opcode is guarenteed not to grow the
  566. ** vdbe stack when it is executed. See function opcode() in
  567. ** vdbeaux.c for details.
  568. **
  569. ** Documentation about VDBE opcodes is generated by scanning this file
  570. ** for lines of that contain "Opcode:". That line and all subsequent
  571. ** comment lines are used in the generation of the opcode.html documentation
  572. ** file.
  573. **
  574. ** SUMMARY:
  575. **
  576. ** Formatting is important to scripts that scan this file.
  577. ** Do not deviate from the formatting style currently in use.
  578. **
  579. *****************************************************************************/
  580. /* Opcode: Goto * P2 *
  581. **
  582. ** An unconditional jump to address P2.
  583. ** The next instruction executed will be
  584. ** the one at index P2 from the beginning of
  585. ** the program.
  586. */
  587. case OP_Goto: { /* no-push */
  588. CHECK_FOR_INTERRUPT;
  589. pc = pOp->p2 - 1;
  590. break;
  591. }
  592. /* Opcode: Gosub * P2 *
  593. **
  594. ** Push the current address plus 1 onto the return address stack
  595. ** and then jump to address P2.
  596. **
  597. ** The return address stack is of limited depth. If too many
  598. ** OP_Gosub operations occur without intervening OP_Returns, then
  599. ** the return address stack will fill up and processing will abort
  600. ** with a fatal error.
  601. */
  602. case OP_Gosub: { /* no-push */
  603. assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
  604. p->returnStack[p->returnDepth++] = pc+1;
  605. pc = pOp->p2 - 1;
  606. break;
  607. }
  608. /* Opcode: Return * * *
  609. **
  610. ** Jump immediately to the next instruction after the last unreturned
  611. ** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
  612. ** processing aborts with a fatal error.
  613. */
  614. case OP_Return: { /* no-push */
  615. assert( p->returnDepth>0 );
  616. p->returnDepth--;
  617. pc = p->returnStack[p->returnDepth] - 1;
  618. break;
  619. }
  620. /* Opcode: Halt P1 P2 P3
  621. **
  622. ** Exit immediately. All open cursors, Fifos, etc are closed
  623. ** automatically.
  624. **
  625. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  626. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  627. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  628. ** whether or not to rollback the current transaction. Do not rollback
  629. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  630. ** then back out all changes that have occurred during this execution of the
  631. ** VDBE, but do not rollback the transaction.
  632. **
  633. ** If P3 is not null then it is an error message string.
  634. **
  635. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  636. ** every program. So a jump past the last instruction of the program
  637. ** is the same as executing Halt.
  638. */
  639. case OP_Halt: { /* no-push */
  640. p->pTos = pTos;
  641. p->rc = pOp->p1;
  642. p->pc = pc;
  643. p->errorAction = pOp->p2;
  644. if( pOp->p3 ){
  645. sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
  646. }
  647. rc = sqlite3VdbeHalt(p);
  648. assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
  649. if( rc==SQLITE_BUSY ){
  650. p->rc = rc = SQLITE_BUSY;
  651. }else{
  652. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  653. }
  654. goto vdbe_return;
  655. }
  656. /* Opcode: StackDepth P1 * *
  657. **
  658. ** If P1 is less than zero, then store the current stack depth
  659. ** in P1. If P1 is zero or greater, verify that the current stack
  660. ** depth is equal to P1 and throw an exception if it is not.
  661. **
  662. ** This opcode is used for internal consistency checking.
  663. */
  664. case OP_StackDepth: { /* no-push */
  665. int n = pTos - p->aStack + 1;
  666. if( pOp->p1<0 ){
  667. pOp->p1 = n;
  668. }else if( pOp->p1!=n ){
  669. p->pTos = pTos;
  670. p->rc = rc = SQLITE_INTERNAL;
  671. p->pc = pc;
  672. p->errorAction = OE_Rollback;
  673. sqlite3SetString(&p->zErrMsg, "internal error: VDBE stack leak", (char*)0);
  674. goto vdbe_return;
  675. }
  676. break;
  677. }
  678. /* Opcode: Integer P1 * *
  679. **
  680. ** The 32-bit integer value P1 is pushed onto the stack.
  681. */
  682. case OP_Integer: {
  683. pTos++;
  684. pTos->flags = MEM_Int;
  685. pTos->u.i = pOp->p1;
  686. break;
  687. }
  688. /* Opcode: Int64 * * P3
  689. **
  690. ** P3 is a pointer to a 64-bit integer value.
  691. ** Push that value onto the stack.
  692. */
  693. case OP_Int64: {
  694. pTos++;
  695. assert( pOp->p3!=0 );
  696. pTos->flags = MEM_Int;
  697. memcpy(&pTos->u.i, pOp->p3, 8);
  698. break;
  699. }
  700. /* Opcode: Real * * P3
  701. **
  702. ** P3 is a pointer to a 64-bit floating point value. Push that value
  703. ** onto the stack.
  704. */
  705. case OP_Real: { /* same as TK_FLOAT, */
  706. pTos++;
  707. pTos->flags = MEM_Real;
  708. memcpy(&pTos->r, pOp->p3, 8);
  709. break;
  710. }
  711. /* Opcode: String8 * * P3
  712. **
  713. ** P3 points to a nul terminated UTF-8 string. This opcode is transformed
  714. ** into an OP_String before it is executed for the first time.
  715. */
  716. case OP_String8: { /* same as TK_STRING */
  717. assert( pOp->p3!=0 );
  718. pOp->opcode = OP_String;
  719. pOp->p1 = strlen(pOp->p3);
  720. assert( SQLITE_MAX_SQL_LENGTH <= SQLITE_MAX_LENGTH );
  721. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  722. #ifndef SQLITE_OMIT_UTF16
  723. if( encoding!=SQLITE_UTF8 ){
  724. pTos++;
  725. sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
  726. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem;
  727. if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
  728. pTos->flags &= ~(MEM_Dyn);
  729. pTos->flags |= MEM_Static;
  730. if( pOp->p3type==P3_DYNAMIC ){
  731. sqlite3_free(pOp->p3);
  732. }
  733. pOp->p3type = P3_DYNAMIC;
  734. pOp->p3 = pTos->z;
  735. pOp->p1 = pTos->n;
  736. assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
  737. break;
  738. }
  739. #endif
  740. /* Otherwise fall through to the next case, OP_String */
  741. }
  742. /* Opcode: String P1 * P3
  743. **
  744. ** The string value P3 of length P1 (bytes) is pushed onto the stack.
  745. */
  746. case OP_String: {
  747. assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
  748. pTos++;
  749. assert( pOp->p3!=0 );
  750. pTos->flags = MEM_Str|MEM_Static|MEM_Term;
  751. pTos->z = pOp->p3;
  752. pTos->n = pOp->p1;
  753. pTos->enc = encoding;
  754. break;
  755. }
  756. /* Opcode: Null * * *
  757. **
  758. ** Push a NULL onto the stack.
  759. */
  760. case OP_Null: {
  761. pTos++;
  762. pTos->flags = MEM_Null;
  763. pTos->n = 0;
  764. break;
  765. }
  766. #ifndef SQLITE_OMIT_BLOB_LITERAL
  767. /* Opcode: HexBlob * * P3
  768. **
  769. ** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
  770. ** vdbe stack.
  771. **
  772. ** The first time this instruction executes, in transforms itself into a
  773. ** 'Blob' opcode with a binary blob as P3.
  774. */
  775. case OP_HexBlob: { /* same as TK_BLOB */
  776. pOp->opcode = OP_Blob;
  777. pOp->p1 = strlen(pOp->p3)/2;
  778. assert( SQLITE_MAX_SQL_LENGTH <= SQLITE_MAX_LENGTH );
  779. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  780. if( pOp->p1 ){
  781. char *zBlob = sqlite3HexToBlob(db, pOp->p3);
  782. if( !zBlob ) goto no_mem;
  783. if( pOp->p3type==P3_DYNAMIC ){
  784. sqlite3_free(pOp->p3);
  785. }
  786. pOp->p3 = zBlob;
  787. pOp->p3type = P3_DYNAMIC;
  788. }else{
  789. if( pOp->p3type==P3_DYNAMIC ){
  790. sqlite3_free(pOp->p3);
  791. }
  792. pOp->p3type = P3_STATIC;
  793. pOp->p3 = "";
  794. }
  795. /* Fall through to the next case, OP_Blob. */
  796. }
  797. /* Opcode: Blob P1 * P3
  798. **
  799. ** P3 points to a blob of data P1 bytes long. Push this
  800. ** value onto the stack. This instruction is not coded directly
  801. ** by the compiler. Instead, the compiler layer specifies
  802. ** an OP_HexBlob opcode, with the hex string representation of
  803. ** the blob as P3. This opcode is transformed to an OP_Blob
  804. ** the first time it is executed.
  805. */
  806. case OP_Blob: {
  807. pTos++;
  808. assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
  809. sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
  810. pTos->enc = encoding;
  811. break;
  812. }
  813. #endif /* SQLITE_OMIT_BLOB_LITERAL */
  814. /* Opcode: Variable P1 * *
  815. **
  816. ** Push the value of variable P1 onto the stack. A variable is
  817. ** an unknown in the original SQL string as handed to sqlite3_compile().
  818. ** Any occurance of the '?' character in the original SQL is considered
  819. ** a variable. Variables in the SQL string are number from left to
  820. ** right beginning with 1. The values of variables are set using the
  821. ** sqlite3_bind() API.
  822. */
  823. case OP_Variable: {
  824. int j = pOp->p1 - 1;
  825. Mem *pVar;
  826. assert( j>=0 && j<p->nVar );
  827. pVar = &p->aVar[j];
  828. if( sqlite3VdbeMemTooBig(pVar) ){
  829. goto too_big;
  830. }
  831. pTos++;
  832. sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
  833. break;
  834. }
  835. /* Opcode: Pop P1 * *
  836. **
  837. ** P1 elements are popped off of the top of stack and discarded.
  838. */
  839. case OP_Pop: { /* no-push */
  840. assert( pOp->p1>=0 );
  841. popStack(&pTos, pOp->p1);
  842. assert( pTos>=&p->aStack[-1] );
  843. break;
  844. }
  845. /* Opcode: Dup P1 P2 *
  846. **
  847. ** A copy of the P1-th element of the stack
  848. ** is made and pushed onto the top of the stack.
  849. ** The top of the stack is element 0. So the
  850. ** instruction "Dup 0 0 0" will make a copy of the
  851. ** top of the stack.
  852. **
  853. ** If the content of the P1-th element is a dynamically
  854. ** allocated string, then a new copy of that string
  855. ** is made if P2==0. If P2!=0, then just a pointer
  856. ** to the string is copied.
  857. **
  858. ** Also see the Pull instruction.
  859. */
  860. case OP_Dup: {
  861. Mem *pFrom = &pTos[-pOp->p1];
  862. assert( pFrom<=pTos && pFrom>=p->aStack );
  863. pTos++;
  864. sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
  865. if( pOp->p2 ){
  866. Deephemeralize(pTos);
  867. }
  868. break;
  869. }
  870. /* Opcode: Pull P1 * *
  871. **
  872. ** The P1-th element is removed from its current location on
  873. ** the stack and pushed back on top of the stack. The
  874. ** top of the stack is element 0, so "Pull 0 0 0" is
  875. ** a no-op. "Pull 1 0 0" swaps the top two elements of
  876. ** the stack.
  877. **
  878. ** See also the Dup instruction.
  879. */
  880. case OP_Pull: { /* no-push */
  881. Mem *pFrom = &pTos[-pOp->p1];
  882. int i;
  883. Mem ts;
  884. ts = *pFrom;
  885. Deephemeralize(pTos);
  886. for(i=0; i<pOp->p1; i++, pFrom++){
  887. Deephemeralize(&pFrom[1]);
  888. assert( (pFrom[1].flags & MEM_Ephem)==0 );
  889. *pFrom = pFrom[1];
  890. if( pFrom->flags & MEM_Short ){
  891. assert( pFrom->flags & (MEM_Str|MEM_Blob) );
  892. assert( pFrom->z==pFrom[1].zShort );
  893. pFrom->z = pFrom->zShort;
  894. }
  895. }
  896. *pTos = ts;
  897. if( pTos->flags & MEM_Short ){
  898. assert( pTos->flags & (MEM_Str|MEM_Blob) );
  899. assert( pTos->z==pTos[-pOp->p1].zShort );
  900. pTos->z = pTos->zShort;
  901. }
  902. break;
  903. }
  904. /* Opcode: Push P1 * *
  905. **
  906. ** Overwrite the value of the P1-th element down on the
  907. ** stack (P1==0 is the top of the stack) with the value
  908. ** of the top of the stack. Then pop the top of the stack.
  909. */
  910. case OP_Push: { /* no-push */
  911. Mem *pTo = &pTos[-pOp->p1];
  912. assert( pTo>=p->aStack );
  913. sqlite3VdbeMemMove(pTo, pTos);
  914. pTos--;
  915. break;
  916. }
  917. /* Opcode: Callback P1 * *
  918. **
  919. ** The top P1 values on the stack represent a single result row from
  920. ** a query. This opcode causes the sqlite3_step() call to terminate
  921. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  922. ** structure to provide access to the top P1 values as the result
  923. ** row. When the sqlite3_step() function is run again, the top P1
  924. ** values will be automatically popped from the stack before the next
  925. ** instruction executes.
  926. */
  927. case OP_Callback: { /* no-push */
  928. Mem *pMem;
  929. Mem *pFirstColumn;
  930. assert( p->nResColumn==pOp->p1 );
  931. /* Data in the pager might be moved or changed out from under us
  932. ** in between the return from this sqlite3_step() call and the
  933. ** next call to sqlite3_step(). So deephermeralize everything on
  934. ** the stack. Note that ephemeral data is never stored in memory
  935. ** cells so we do not have to worry about them.
  936. */
  937. pFirstColumn = &pTos[0-pOp->p1];
  938. for(pMem = p->aStack; pMem<pFirstColumn; pMem++){
  939. Deephemeralize(pMem);
  940. }
  941. /* Invalidate all ephemeral cursor row caches */
  942. p->cacheCtr = (p->cacheCtr + 2)|1;
  943. /* Make sure the results of the current row are \000 terminated
  944. ** and have an assigned type. The results are deephemeralized as
  945. ** as side effect.
  946. */
  947. for(; pMem<=pTos; pMem++ ){
  948. sqlite3VdbeMemNulTerminate(pMem);
  949. storeTypeInfo(pMem, encoding);
  950. }
  951. /* Set up the statement structure so that it will pop the current
  952. ** results from the stack when the statement returns.
  953. */
  954. p->resOnStack = 1;
  955. p->nCallback++;
  956. p->popStack = pOp->p1;
  957. p->pc = pc + 1;
  958. p->pTos = pTos;
  959. rc = SQLITE_ROW;
  960. goto vdbe_return;
  961. }
  962. /* Opcode: Concat P1 P2 *
  963. **
  964. ** Look at the first P1+2 elements of the stack. Append them all
  965. ** together with the lowest element first. The original P1+2 elements
  966. ** are popped from the stack if P2==0 and retained if P2==1. If
  967. ** any element of the stack is NULL, then the result is NULL.
  968. **
  969. ** When P1==1, this routine makes a copy of the top stack element
  970. ** into memory obtained from sqlite3_malloc().
  971. */
  972. case OP_Concat: { /* same as TK_CONCAT */
  973. char *zNew;
  974. i64 nByte;
  975. int nField;
  976. int i, j;
  977. Mem *pTerm;
  978. /* Loop through the stack elements to see how long the result will be. */
  979. nField = pOp->p1 + 2;
  980. pTerm = &pTos[1-nField];
  981. nByte = 0;
  982. for(i=0; i<nField; i++, pTerm++){
  983. assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
  984. if( pTerm->flags&MEM_Null ){
  985. nByte = -1;
  986. break;
  987. }
  988. ExpandBlob(pTerm);
  989. Stringify(pTerm, encoding);
  990. nByte += pTerm->n;
  991. }
  992. if( nByte<0 ){
  993. /* If nByte is less than zero, then there is a NULL value on the stack.
  994. ** In this case just pop the values off the stack (if required) and
  995. ** push on a NULL.
  996. */
  997. if( pOp->p2==0 ){
  998. popStack(&pTos, nField);
  999. }
  1000. pTos++;
  1001. pTos->flags = MEM_Null;
  1002. }else{
  1003. /* Otherwise malloc() space for the result and concatenate all the
  1004. ** stack values.
  1005. */
  1006. if( nByte+2>SQLITE_MAX_LENGTH ){
  1007. goto too_big;
  1008. }
  1009. zNew = sqlite3DbMallocRaw(db, nByte+2 );
  1010. if( zNew==0 ) goto no_mem;
  1011. j = 0;
  1012. pTerm = &pTos[1-nField];
  1013. for(i=j=0; i<nField; i++, pTerm++){
  1014. int n = pTerm->n;
  1015. assert( pTerm->flags & (MEM_Str|MEM_Blob) );
  1016. memcpy(&zNew[j], pTerm->z, n);
  1017. j += n;
  1018. }
  1019. zNew[j] = 0;
  1020. zNew[j+1] = 0;
  1021. assert( j==nByte );
  1022. if( pOp->p2==0 ){
  1023. popStack(&pTos, nField);
  1024. }
  1025. pTos++;
  1026. pTos->n = j;
  1027. pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
  1028. pTos->xDel = 0;
  1029. pTos->enc = encoding;
  1030. pTos->z = zNew;
  1031. }
  1032. break;
  1033. }
  1034. /* Opcode: Add * * *
  1035. **
  1036. ** Pop the top two elements from the stack, add them together,
  1037. ** and push the result back onto the stack. If either element
  1038. ** is a string then it is converted to a double using the atof()
  1039. ** function before the addition.
  1040. ** If either operand is NULL, the result is NULL.
  1041. */
  1042. /* Opcode: Multiply * * *
  1043. **
  1044. ** Pop the top two elements from the stack, multiply them together,
  1045. ** and push the result back onto the stack. If either element
  1046. ** is a string then it is converted to a double using the atof()
  1047. ** function before the multiplication.
  1048. ** If either operand is NULL, the result is NULL.
  1049. */
  1050. /* Opcode: Subtract * * *
  1051. **
  1052. ** Pop the top two elements from the stack, subtract the
  1053. ** first (what was on top of the stack) from the second (the
  1054. ** next on stack)
  1055. ** and push the result back onto the stack. If either element
  1056. ** is a string then it is converted to a double using the atof()
  1057. ** function before the subtraction.
  1058. ** If either operand is NULL, the result is NULL.
  1059. */
  1060. /* Opcode: Divide * * *
  1061. **
  1062. ** Pop the top two elements from the stack, divide the
  1063. ** first (what was on top of the stack) from the second (the
  1064. ** next on stack)
  1065. ** and push the result back onto the stack. If either element
  1066. ** is a string then it is converted to a double using the atof()
  1067. ** function before the division. Division by zero returns NULL.
  1068. ** If either operand is NULL, the result is NULL.
  1069. */
  1070. /* Opcode: Remainder * * *
  1071. **
  1072. ** Pop the top two elements from the stack, divide the
  1073. ** first (what was on top of the stack) from the second (the
  1074. ** next on stack)
  1075. ** and push the remainder after division onto the stack. If either element
  1076. ** is a string then it is converted to a double using the atof()
  1077. ** function before the division. Division by zero returns NULL.
  1078. ** If either operand is NULL, the result is NULL.
  1079. */
  1080. case OP_Add: /* same as TK_PLUS, no-push */
  1081. case OP_Subtract: /* same as TK_MINUS, no-push */
  1082. case OP_Multiply: /* same as TK_STAR, no-push */
  1083. case OP_Divide: /* same as TK_SLASH, no-push */
  1084. case OP_Remainder: { /* same as TK_REM, no-push */
  1085. Mem *pNos = &pTos[-1];
  1086. int flags;
  1087. assert( pNos>=p->aStack );
  1088. flags = pTos->flags | pNos->flags;
  1089. if( (flags & MEM_Null)!=0 ){
  1090. Release(pTos);
  1091. pTos--;
  1092. Release(pTos);
  1093. pTos->flags = MEM_Null;
  1094. }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
  1095. i64 a, b;
  1096. a = pTos->u.i;
  1097. b = pNos->u.i;
  1098. switch( pOp->opcode ){
  1099. case OP_Add: b += a; break;
  1100. case OP_Subtract: b -= a; break;
  1101. case OP_Multiply: b *= a; break;
  1102. case OP_Divide: {
  1103. if( a==0 ) goto divide_by_zero;
  1104. /* Dividing the largest possible negative 64-bit integer (1<<63) by
  1105. ** -1 returns an integer to large to store in a 64-bit data-type. On
  1106. ** some architectures, the value overflows to (1<<63). On others,
  1107. ** a SIGFPE is issued. The following statement normalizes this
  1108. ** behaviour so that all architectures behave as if integer
  1109. ** overflow occured.
  1110. */
  1111. if( a==-1 && b==(((i64)1)<<63) ) a = 1;
  1112. b /= a;
  1113. break;
  1114. }
  1115. default: {
  1116. if( a==0 ) goto divide_by_zero;
  1117. if( a==-1 ) a = 1;
  1118. b %= a;
  1119. break;
  1120. }
  1121. }
  1122. Release(pTos);
  1123. pTos--;
  1124. Release(pTos);
  1125. pTos->u.i = b;
  1126. pTos->flags = MEM_Int;
  1127. }else{
  1128. double a, b;
  1129. a = sqlite3VdbeRealValue(pTos);
  1130. b = sqlite3VdbeRealValue(pNos);
  1131. switch( pOp->opcode ){
  1132. case OP_Add: b += a; break;
  1133. case OP_Subtract: b -= a; break;
  1134. case OP_Multiply: b *= a; break;
  1135. case OP_Divide: {
  1136. if( a==0.0 ) goto divide_by_zero;
  1137. b /= a;
  1138. break;
  1139. }
  1140. default: {
  1141. i64 ia = (i64)a;
  1142. i64 ib = (i64)b;
  1143. if( ia==0 ) goto divide_by_zero;
  1144. if( ia==-1 ) ia = 1;
  1145. b = ib % ia;
  1146. break;
  1147. }
  1148. }
  1149. if( sqlite3_isnan(b) ){
  1150. goto divide_by_zero;
  1151. }
  1152. Release(pTos);
  1153. pTos--;
  1154. Release(pTos);
  1155. pTos->r = b;
  1156. pTos->flags = MEM_Real;
  1157. if( (flags & MEM_Real)==0 ){
  1158. sqlite3VdbeIntegerAffinity(pTos);
  1159. }
  1160. }
  1161. break;
  1162. divide_by_zero:
  1163. Release(pTos);
  1164. pTos--;
  1165. Release(pTos);
  1166. pTos->flags = MEM_Null;
  1167. break;
  1168. }
  1169. /* Opcode: CollSeq * * P3
  1170. **
  1171. ** P3 is a pointer to a CollSeq struct. If the next call to a user function
  1172. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  1173. ** be returned. This is used by the built-in min(), max() and nullif()
  1174. ** functions.
  1175. **
  1176. ** The interface used by the implementation of the aforementioned functions
  1177. ** to retrieve the collation sequence set by this opcode is not available
  1178. ** publicly, only to user functions defined in func.c.
  1179. */
  1180. case OP_CollSeq: { /* no-push */
  1181. assert( pOp->p3type==P3_COLLSEQ );
  1182. break;
  1183. }
  1184. /* Opcode: Function P1 P2 P3
  1185. **
  1186. ** Invoke a user function (P3 is a pointer to a Function structure that
  1187. ** defines the function) with P2 arguments taken from the stack. Pop all
  1188. ** arguments from the stack and push back the result.
  1189. **
  1190. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  1191. ** function was determined to be constant at compile time. If the first
  1192. ** argument was constant then bit 0 of P1 is set. This is used to determine
  1193. ** whether meta data associated with a user function argument using the
  1194. ** sqlite3_set_auxdata() API may be safely retained until the next
  1195. ** invocation of this opcode.
  1196. **
  1197. ** See also: AggStep and AggFinal
  1198. */
  1199. case OP_Function: {
  1200. int i;
  1201. Mem *pArg;
  1202. sqlite3_context ctx;
  1203. sqlite3_value **apVal;
  1204. int n = pOp->p2;
  1205. apVal = p->apArg;
  1206. assert( apVal || n==0 );
  1207. pArg = &pTos[1-n];
  1208. for(i=0; i<n; i++, pArg++){
  1209. apVal[i] = pArg;
  1210. storeTypeInfo(pArg, encoding);
  1211. }
  1212. assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
  1213. if( pOp->p3type==P3_FUNCDEF ){
  1214. ctx.pFunc = (FuncDef*)pOp->p3;
  1215. ctx.pVdbeFunc = 0;
  1216. }else{
  1217. ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
  1218. ctx.pFunc = ctx.pVdbeFunc->pFunc;
  1219. }
  1220. ctx.s.flags = MEM_Null;
  1221. ctx.s.z = 0;
  1222. ctx.s.xDel = 0;
  1223. ctx.s.db = db;
  1224. ctx.isError = 0;
  1225. if( ctx.pFunc->needCollSeq ){
  1226. assert( pOp>p->aOp );
  1227. assert( pOp[-1].p3type==P3_COLLSEQ );
  1228. assert( pOp[-1].opcode==OP_CollSeq );
  1229. ctx.pColl = (CollSeq *)pOp[-1].p3;
  1230. }
  1231. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  1232. (*ctx.pFunc->xFunc)(&ctx, n, apVal);
  1233. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  1234. if( db->mallocFailed ){
  1235. /* Even though a malloc() has failed, the implementation of the
  1236. ** user function may have called an sqlite3_result_XXX() function
  1237. ** to return a value. The following call releases any resources
  1238. ** associated with such a value.
  1239. **
  1240. ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
  1241. ** fails also (the if(...) statement above). But if people are
  1242. ** misusing sqlite, they have bigger problems than a leaked value.
  1243. */
  1244. sqlite3VdbeMemRelease(&ctx.s);
  1245. goto no_mem;
  1246. }
  1247. popStack(&pTos, n);
  1248. /* If any auxilary data functions have been called by this user function,
  1249. ** immediately call the destructor for any non-static values.
  1250. */
  1251. if( ctx.pVdbeFunc ){
  1252. sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
  1253. pOp->p3 = (char *)ctx.pVdbeFunc;
  1254. pOp->p3type = P3_VDBEFUNC;
  1255. }
  1256. /* If the function returned an error, throw an exception */
  1257. if( ctx.isError ){
  1258. sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
  1259. rc = SQLITE_ERROR;
  1260. }
  1261. /* Copy the result of the function to the top of the stack */
  1262. sqlite3VdbeChangeEncoding(&ctx.s, encoding);
  1263. pTos++;
  1264. pTos->flags = 0;
  1265. sqlite3VdbeMemMove(pTos, &ctx.s);
  1266. if( sqlite3VdbeMemTooBig(pTos) ){
  1267. goto too_big;
  1268. }
  1269. break;
  1270. }
  1271. /* Opcode: BitAnd * * *
  1272. **
  1273. ** Pop the top two elements from the stack. Convert both elements
  1274. ** to integers. Push back onto the stack the bit-wise AND of the
  1275. ** two elements.
  1276. ** If either operand is NULL, the result is NULL.
  1277. */
  1278. /* Opcode: BitOr * * *
  1279. **
  1280. ** Pop the top two elements from the stack. Convert both elements
  1281. ** to integers. Push back onto the stack the bit-wise OR of the
  1282. ** two elements.
  1283. ** If either operand is NULL, the result is NULL.
  1284. */
  1285. /* Opcode: ShiftLeft * * *
  1286. **
  1287. ** Pop the top two elements from the stack. Convert both elements
  1288. ** to integers. Push back onto the stack the second element shifted
  1289. ** left by N bits where N is the top element on the stack.
  1290. ** If either operand is NULL, the result is NULL.
  1291. */
  1292. /* Opcode: ShiftRight * * *
  1293. **
  1294. ** Pop the top two elements from the stack. Convert both elements
  1295. ** to integers. Push back onto the stack the second element shifted
  1296. ** right by N bits where N is the top element on the stack.
  1297. ** If either operand is NULL, the result is NULL.
  1298. */
  1299. case OP_BitAnd: /* same as TK_BITAND, no-push */
  1300. case OP_BitOr: /* same as TK_BITOR, no-push */
  1301. case OP_ShiftLeft: /* same as TK_LSHIFT, no-push */
  1302. case OP_ShiftRight: { /* same as TK_RSHIFT, no-push */
  1303. Mem *pNos = &pTos[-1];
  1304. i64 a, b;
  1305. assert( pNos>=p->aStack );
  1306. if( (pTos->flags | pNos->flags) & MEM_Null ){
  1307. popStack(&pTos, 2);
  1308. pTos++;
  1309. pTos->flags = MEM_Null;
  1310. break;
  1311. }
  1312. a = sqlite3VdbeIntValue(pNos);
  1313. b = sqlite3VdbeIntValue(pTos);
  1314. switch( pOp->opcode ){
  1315. case OP_BitAnd: a &= b; break;
  1316. case OP_BitOr: a |= b; break;
  1317. case OP_ShiftLeft: a <<= b; break;
  1318. case OP_ShiftRight: a >>= b; break;
  1319. default: /* CANT HAPPEN */ break;
  1320. }
  1321. Release(pTos);
  1322. pTos--;
  1323. Release(pTos);
  1324. pTos->u.i = a;
  1325. pTos->flags = MEM_Int;
  1326. break;
  1327. }
  1328. /* Opcode: AddImm P1 * *
  1329. **
  1330. ** Add the value P1 to whatever is on top of the stack. The result
  1331. ** is always an integer.
  1332. **
  1333. ** To force the top of the stack to be an integer, just add 0.
  1334. */
  1335. case OP_AddImm: { /* no-push */
  1336. assert( pTos>=p->aStack );
  1337. sqlite3VdbeMemIntegerify(pTos);
  1338. pTos->u.i += pOp->p1;
  1339. break;
  1340. }
  1341. /* Opcode: ForceInt P1 P2 *
  1342. **
  1343. ** Convert the top of the stack into an integer. If the current top of
  1344. ** the stack is not numeric (meaning that is is a NULL or a string that
  1345. ** does not look like an integer or floating point number) then pop the
  1346. ** stack and jump to P2. If the top of the stack is numeric then
  1347. ** convert it into the least integer that is greater than or equal to its
  1348. ** current value if P1==0, or to the least integer that is strictly
  1349. ** greater than its current value if P1==1.
  1350. */
  1351. case OP_ForceInt: { /* no-push */
  1352. i64 v;
  1353. assert( pTos>=p->aStack );
  1354. applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
  1355. if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
  1356. Release(pTos);
  1357. pTos--;
  1358. pc = pOp->p2 - 1;
  1359. break;
  1360. }
  1361. if( pTos->flags & MEM_Int ){
  1362. v = pTos->u.i + (pOp->p1!=0);
  1363. }else{
  1364. /* FIX ME: should this not be assert( pTos->flags & MEM_Real ) ??? */
  1365. sqlite3VdbeMemRealify(pTos);
  1366. v = (int)pTos->r;
  1367. if( pTos->r>(double)v ) v++;
  1368. if( pOp->p1 && pTos->r==(double)v ) v++;
  1369. }
  1370. Release(pTos);
  1371. pTos->u.i = v;
  1372. pTos->flags = MEM_Int;
  1373. break;
  1374. }
  1375. /* Opcode: MustBeInt P1 P2 *
  1376. **
  1377. ** Force the top of the stack to be an integer. If the top of the
  1378. ** stack is not an integer and cannot be converted into an integer
  1379. ** without data loss, then jump immediately to P2, or if P2==0
  1380. ** raise an SQLITE_MISMATCH exception.
  1381. **
  1382. ** If the top of the stack is not an integer and P2 is not zero and
  1383. ** P1 is 1, then the stack is popped. In all other cases, the depth
  1384. ** of the stack is unchanged.
  1385. */
  1386. case OP_MustBeInt: { /* no-push */
  1387. assert( pTos>=p->aStack );
  1388. applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
  1389. if( (pTos->flags & MEM_Int)==0 ){
  1390. if( pOp->p2==0 ){
  1391. rc = SQLITE_MISMATCH;
  1392. goto abort_due_to_error;
  1393. }else{
  1394. if( pOp->p1 ) popStack(&pTos, 1);
  1395. pc = pOp->p2 - 1;
  1396. }
  1397. }else{
  1398. Release(pTos);
  1399. pTos->flags = MEM_Int;
  1400. }
  1401. break;
  1402. }
  1403. /* Opcode: RealAffinity * * *
  1404. **
  1405. ** If the top of the stack is an integer, convert it to a real value.
  1406. **
  1407. ** This opcode is used when extracting information from a column that
  1408. ** has REAL affinity. Such column values may still be stored as
  1409. ** integers, for space efficiency, but after extraction we want them
  1410. ** to have only a real value.
  1411. */
  1412. case OP_RealAffinity: { /* no-push */
  1413. assert( pTos>=p->aStack );
  1414. if( pTos->flags & MEM_Int ){
  1415. sqlite3VdbeMemRealify(pTos);
  1416. }
  1417. break;
  1418. }
  1419. #ifndef SQLITE_OMIT_CAST
  1420. /* Opcode: ToText * * *
  1421. **
  1422. ** Force the value on the top of the stack to be text.
  1423. ** If the value is numeric, convert it to a string using the
  1424. ** equivalent of printf(). Blob values are unchanged and
  1425. ** are afterwards simply interpreted as text.
  1426. **
  1427. ** A NULL value is not changed by this routine. It remains NULL.
  1428. */
  1429. case OP_ToText: { /* same as TK_TO_TEXT, no-push */
  1430. assert( pTos>=p->aStack );
  1431. if( pTos->flags & MEM_Null ) break;
  1432. assert( MEM_Str==(MEM_Blob>>3) );
  1433. pTos->flags |= (pTos->flags&MEM_Blob)>>3;
  1434. applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
  1435. rc = ExpandBlob(pTos);
  1436. assert( pTos->flags & MEM_Str );
  1437. pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
  1438. break;
  1439. }
  1440. /* Opcode: ToBlob * * *
  1441. **
  1442. ** Force the value on the top of the stack to be a BLOB.
  1443. ** If the value is numeric, convert it to a string first.
  1444. ** Strings are simply reinterpreted as blobs with no change
  1445. ** to the underlying data.
  1446. **
  1447. ** A NULL value is not changed by this routine. It remains NULL.
  1448. */
  1449. case OP_ToBlob: { /* same as TK_TO_BLOB, no-push */
  1450. assert( pTos>=p->aStack );
  1451. if( pTos->flags & MEM_Null ) break;
  1452. if( (pTos->flags & MEM_Blob)==0 ){
  1453. applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
  1454. assert( pTos->flags & MEM_Str );
  1455. pTos->flags |= MEM_Blob;
  1456. }
  1457. pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
  1458. break;
  1459. }
  1460. /* Opcode: ToNumeric * * *
  1461. **
  1462. ** Force the value on the top of the stack to be numeric (either an
  1463. ** integer or a floating-point number.)
  1464. ** If the value is text or blob, try to convert it to an using the
  1465. ** equivalent of atoi() or atof() and store 0 if no such conversion
  1466. ** is possible.
  1467. **
  1468. ** A NULL value is not changed by this routine. It remains NULL.
  1469. */
  1470. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, no-push */
  1471. assert( pTos>=p->aStack );
  1472. if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
  1473. sqlite3VdbeMemNumerify(pTos);
  1474. }
  1475. break;
  1476. }
  1477. #endif /* SQLITE_OMIT_CAST */
  1478. /* Opcode: ToInt * * *
  1479. **
  1480. ** Force the value on the top of the stack to be an integer. If
  1481. ** The value is currently a real number, drop its fractional part.
  1482. ** If the value is text or blob, try to convert it to an integer using the
  1483. ** equivalent of atoi() and store 0 if no such conversion is possible.
  1484. **
  1485. ** A NULL value is not changed by this routine. It remains NULL.
  1486. */
  1487. case OP_ToInt: { /* same as TK_TO_INT, no-push */
  1488. assert( pTos>=p->aStack );
  1489. if( (pTos->flags & MEM_Null)==0 ){
  1490. sqlite3VdbeMemIntegerify(pTos);
  1491. }
  1492. break;
  1493. }
  1494. #ifndef SQLITE_OMIT_CAST
  1495. /* Opcode: ToReal * * *
  1496. **
  1497. ** Force the value on the top of the stack to be a floating point number.
  1498. ** If The value is currently an integer, convert it.
  1499. ** If the value is text or blob, try to convert it to an integer using the
  1500. ** equivalent of atoi() and store 0 if no such conversion is possible.
  1501. **
  1502. ** A NULL value is not changed by this routine. It remains NULL.
  1503. */
  1504. case OP_ToReal: { /* same as TK_TO_REAL, no-push */
  1505. assert( pTos>=p->aStack );
  1506. if( (pTos->flags & MEM_Null)==0 ){
  1507. sqlite3VdbeMemRealify(pTos);
  1508. }
  1509. break;
  1510. }
  1511. #endif /* SQLITE_OMIT_CAST */
  1512. /* Opcode: Eq P1 P2 P3
  1513. **
  1514. ** Pop the top two elements from the stack. If they are equal, then
  1515. ** jump to instruction P2. Otherwise, continue to the next instruction.
  1516. **
  1517. ** If the 0x100 bit of P1 is true and either operand is NULL then take the
  1518. ** jump. If the 0x100 bit of P1 is clear then fall thru if either operand
  1519. ** is NULL.
  1520. **
  1521. ** If the 0x200 bit of P1 is set and either operand is NULL then
  1522. ** both operands are converted to integers prior to comparison.
  1523. ** NULL operands are converted to zero and non-NULL operands are
  1524. ** converted to 1. Thus, for example, with 0x200 set, NULL==NULL is true
  1525. ** whereas it would normally be NULL. Similarly, NULL==123 is false when
  1526. ** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
  1527. **
  1528. ** The least significant byte of P1 (mask 0xff) must be an affinity character -
  1529. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  1530. ** to coerce both values
  1531. ** according to the affinity before the comparison is made. If the byte is
  1532. ** 0x00, then numeric affinity is used.
  1533. **
  1534. ** Once any conversions have taken place, and neither value is NULL,
  1535. ** the values are compared. If both values are blobs, or both are text,
  1536. ** then memcmp() is used to determine the results of the comparison. If
  1537. ** both values are numeric, then a numeric comparison is used. If the
  1538. ** two values are of different types, then they are inequal.
  1539. **
  1540. ** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  1541. ** stack if the jump would have been taken, or a 0 if not. Push a
  1542. ** NULL if either operand was NULL.
  1543. **
  1544. ** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
  1545. ** structure) that defines how to compare text.
  1546. */
  1547. /* Opcode: Ne P1 P2 P3
  1548. **
  1549. ** This works just like the Eq opcode except that the jump is taken if
  1550. ** the operands from the stack are not equal. See the Eq opcode for
  1551. ** additional information.
  1552. */
  1553. /* Opcode: Lt P1 P2 P3
  1554. **
  1555. ** This works just like the Eq opcode except that the jump is taken if
  1556. ** the 2nd element down on the stack is less than the top of the stack.
  1557. ** See the Eq opcode for additional information.
  1558. */
  1559. /* Opcode: Le P1 P2 P3
  1560. **
  1561. ** This works just like the Eq opcode except that the jump is taken if
  1562. ** the 2nd element down on the stack is less than or equal to the
  1563. ** top of the stack. See the Eq opcode for additional information.
  1564. */
  1565. /* Opcode: Gt P1 P2 P3
  1566. **
  1567. ** This works just like the Eq opcode except that the jump is taken if
  1568. ** the 2nd element down on the stack is greater than the top of the stack.
  1569. ** See the Eq opcode for additional information.
  1570. */
  1571. /* Opcode: Ge P1 P2 P3
  1572. **
  1573. ** This works just like the Eq opcode except that the jump is taken if
  1574. ** the 2nd element down on the stack is greater than or equal to the
  1575. ** top of the stack. See the Eq opcode for additional information.
  1576. */
  1577. case OP_Eq: /* same as TK_EQ, no-push */
  1578. case OP_Ne: /* same as TK_NE, no-push */
  1579. case OP_Lt: /* same as TK_LT, no-push */
  1580. case OP_Le: /* same as TK_LE, no-push */
  1581. case OP_Gt: /* same as TK_GT, no-push */
  1582. case OP_Ge: { /* same as TK_GE, no-push */
  1583. Mem *pNos;
  1584. int flags;
  1585. int res;
  1586. char affinity;
  1587. pNos = &pTos[-1];
  1588. flags = pTos->flags|pNos->flags;
  1589. /* If either value is a NULL P2 is not zero, take the jump if the least
  1590. ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
  1591. ** the stack.
  1592. */
  1593. if( flags&MEM_Null ){
  1594. if( (pOp->p1 & 0x200)!=0 ){
  1595. /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
  1596. ** magic SQL value it normally is - treat it as if it were another
  1597. ** integer".
  1598. **
  1599. ** With 0x200 set, if either operand is NULL then both operands
  1600. ** are converted to integers prior to being passed down into the
  1601. ** normal comparison logic below. NULL operands are converted to
  1602. ** zero and non-NULL operands are converted to 1. Thus, for example,
  1603. ** with 0x200 set, NULL==NULL is true whereas it would normally
  1604. ** be NULL. Similarly, NULL!=123 is true.
  1605. */
  1606. sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
  1607. sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
  1608. }else{
  1609. /* If the 0x200 bit of P1 is clear and either operand is NULL then
  1610. ** the result is always NULL. The jump is taken if the 0x100 bit
  1611. ** of P1 is set.
  1612. */
  1613. popStack(&pTos, 2);
  1614. if( pOp->p2 ){
  1615. if( pOp->p1 & 0x100 ){
  1616. pc = pOp->p2-1;
  1617. }
  1618. }else{
  1619. pTos++;
  1620. pTos->flags = MEM_Null;
  1621. }
  1622. break;
  1623. }
  1624. }
  1625. affinity = pOp->p1 & 0xFF;
  1626. if( affinity ){
  1627. applyAffinity(pNos, affinity, encoding);
  1628. applyAffinity(pTos, affinity, encoding);
  1629. }
  1630. assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
  1631. ExpandBlob(pNos);
  1632. ExpandBlob(pTos);
  1633. res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
  1634. switch( pOp->opcode ){
  1635. case OP_Eq: res = res==0; break;
  1636. case OP_Ne: res = res!=0; break;
  1637. case OP_Lt: res = res<0; break;
  1638. case OP_Le: res = res<=0; break;
  1639. case OP_Gt: res = res>0; break;
  1640. default: res = res>=0; break;
  1641. }
  1642. popStack(&pTos, 2);
  1643. if( pOp->p2 ){
  1644. if( res ){
  1645. pc = pOp->p2-1;
  1646. }
  1647. }else{
  1648. pTos++;
  1649. pTos->flags = MEM_Int;
  1650. pTos->u.i = res;
  1651. }
  1652. break;
  1653. }
  1654. /* Opcode: And * * *
  1655. **
  1656. ** Pop two values off the stack. Take the logical AND of the
  1657. ** two values and push the resulting boolean value back onto the
  1658. ** stack.
  1659. */
  1660. /* Opcode: Or * * *
  1661. **
  1662. ** Pop two values off the stack. Take the logical OR of the
  1663. ** two values and push the resulting boolean value back onto the
  1664. ** stack.
  1665. */
  1666. case OP_And: /* same as TK_AND, no-push */
  1667. case OP_Or: { /* same as TK_OR, no-push */
  1668. Mem *pNos = &pTos[-1];
  1669. int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
  1670. assert( pNos>=p->aStack );
  1671. if( pTos->flags & MEM_Null ){
  1672. v1 = 2;
  1673. }else{
  1674. sqlite3VdbeMemIntegerify(pTos);
  1675. v1 = pTos->u.i==0;
  1676. }
  1677. if( pNos->flags & MEM_Null ){
  1678. v2 = 2;
  1679. }else{
  1680. sqlite3VdbeMemIntegerify(pNos);
  1681. v2 = pNos->u.i==0;
  1682. }
  1683. if( pOp->opcode==OP_And ){
  1684. static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  1685. v1 = and_logic[v1*3+v2];
  1686. }else{
  1687. static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  1688. v1 = or_logic[v1*3+v2];
  1689. }
  1690. popStack(&pTos, 2);
  1691. pTos++;
  1692. if( v1==2 ){
  1693. pTos->flags = MEM_Null;
  1694. }else{
  1695. pTos->u.i = v1==0;
  1696. pTos->flags = MEM_Int;
  1697. }
  1698. break;
  1699. }
  1700. /* Opcode: Negative * * *
  1701. **
  1702. ** Treat the top of the stack as a numeric quantity. Replace it
  1703. ** with its additive inverse. If the top of the stack is NULL
  1704. ** its value is unchanged.
  1705. */
  1706. /* Opcode: AbsValue * * *
  1707. **
  1708. ** Treat the top of the stack as a numeric quantity. Replace it
  1709. ** with its absolute value. If the top of the stack is NULL
  1710. ** its value is unchanged.
  1711. */
  1712. case OP_Negative: /* same as TK_UMINUS, no-push */
  1713. case OP_AbsValue: {
  1714. assert( pTos>=p->aStack );
  1715. if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){
  1716. sqlite3VdbeMemNumerify(pTos);
  1717. }
  1718. if( pTos->flags & MEM_Real ){
  1719. Release(pTos);
  1720. if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
  1721. pTos->r = -pTos->r;
  1722. }
  1723. pTos->flags = MEM_Real;
  1724. }else if( pTos->flags & MEM_Int ){
  1725. Release(pTos);
  1726. if( pOp->opcode==OP_Negative || pTos->u.i<0 ){
  1727. pTos->u.i = -pTos->u.i;
  1728. }
  1729. pTos->flags = MEM_Int;
  1730. }
  1731. break;
  1732. }
  1733. /* Opcode: Not * * *
  1734. **
  1735. ** Interpret the top of the stack as a boolean value. Replace it
  1736. ** with its complement. If the top of the stack is NULL its value
  1737. ** is unchanged.
  1738. */
  1739. case OP_Not: { /* same as TK_NOT, no-push */
  1740. assert( pTos>=p->aStack );
  1741. if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
  1742. sqlite3VdbeMemIntegerify(pTos);
  1743. assert( (pTos->flags & MEM_Dyn)==0 );
  1744. pTos->u.i = !pTos->u.i;
  1745. pTos->flags = MEM_Int;
  1746. break;
  1747. }
  1748. /* Opcode: BitNot * * *
  1749. **
  1750. ** Interpret the top of the stack as an value. Replace it
  1751. ** with its ones-complement. If the top of the stack is NULL its
  1752. ** value is unchanged.
  1753. */
  1754. case OP_BitNot: { /* same as TK_BITNOT, no-push */
  1755. assert( pTos>=p->aStack );
  1756. if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
  1757. sqlite3VdbeMemIntegerify(pTos);
  1758. assert( (pTos->flags & MEM_Dyn)==0 );
  1759. pTos->u.i = ~pTos->u.i;
  1760. pTos->flags = MEM_Int;
  1761. break;
  1762. }
  1763. /* Opcode: Noop * * *
  1764. **
  1765. ** Do nothing. This instruction is often useful as a jump
  1766. ** destination.
  1767. */
  1768. /*
  1769. ** The magic Explain opcode are only inserted when explain==2 (which
  1770. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  1771. ** This opcode records information from the optimizer. It is the
  1772. ** the same as a no-op. This opcodesnever appears in a real VM program.
  1773. */
  1774. case OP_Explain:
  1775. case OP_Noop: { /* no-push */
  1776. break;
  1777. }
  1778. /* Opcode: If P1 P2 *
  1779. **
  1780. ** Pop a single boolean from the stack. If the boolean popped is
  1781. ** true, then jump to p2. Otherwise continue to the next instruction.
  1782. ** An integer is false if zero and true otherwise. A string is
  1783. ** false if it has zero length and true otherwise.
  1784. **
  1785. ** If the value popped of the stack is NULL, then take the jump if P1
  1786. ** is true and fall through if P1 is false.
  1787. */
  1788. /* Opcode: IfNot P1 P2 *
  1789. **
  1790. ** Pop a single boolean from the stack. If the boolean popped is
  1791. ** false, then jump to p2. Otherwise continue to the next instruction.
  1792. ** An integer is false if zero and true otherwise. A string is
  1793. ** false if it has zero length and true otherwise.
  1794. **
  1795. ** If the value popped of the stack is NULL, then take the jump if P1
  1796. ** is true and fall through if P1 is false.
  1797. */
  1798. case OP_If: /* no-push */
  1799. case OP_IfNot: { /* no-push */
  1800. int c;
  1801. assert( pTos>=p->aStack );
  1802. if( pTos->flags & MEM_Null ){
  1803. c = pOp->p1;
  1804. }else{
  1805. #ifdef SQLITE_OMIT_FLOATING_POINT
  1806. c = sqlite3VdbeIntValue(pTos);
  1807. #else
  1808. c = sqlite3VdbeRealValue(pTos)!=0.0;
  1809. #endif
  1810. if( pOp->opcode==OP_IfNot ) c = !c;
  1811. }
  1812. Release(pTos);
  1813. pTos--;
  1814. if( c ) pc = pOp->p2-1;
  1815. break;
  1816. }
  1817. /* Opcode: IsNull P1 P2 *
  1818. **
  1819. ** Check the top of the stack and jump to P2 if the top of the stack
  1820. ** is NULL. If P1 is positive, then pop P1 elements from the stack
  1821. ** regardless of whether or not the jump is taken. If P1 is negative,
  1822. ** pop -P1 elements from the stack only if the jump is taken and leave
  1823. ** the stack unchanged if the jump is not taken.
  1824. */
  1825. case OP_IsNull: { /* same as TK_ISNULL, no-push */
  1826. if( pTos->flags & MEM_Null ){
  1827. pc = pOp->p2-1;
  1828. if( pOp->p1<0 ){
  1829. popStack(&pTos, -pOp->p1);
  1830. }
  1831. }
  1832. if( pOp->p1>0 ){
  1833. popStack(&pTos, pOp->p1);
  1834. }
  1835. break;
  1836. }
  1837. /* Opcode: NotNull P1 P2 *
  1838. **
  1839. ** Jump to P2 if the top abs(P1) values on the stack are all not NULL.
  1840. ** Regardless of whether or not the jump is taken, pop the stack
  1841. ** P1 times if P1 is greater than zero. But if P1 is negative,
  1842. ** leave the stack unchanged.
  1843. */
  1844. case OP_NotNull: { /* same as TK_NOTNULL, no-push */
  1845. int i, cnt;
  1846. cnt = pOp->p1;
  1847. if( cnt<0 ) cnt = -cnt;
  1848. assert( &pTos[1-cnt] >= p->aStack );
  1849. for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
  1850. if( i>=cnt ) pc = pOp->p2-1;
  1851. if( pOp->p1>0 ) popStack(&pTos, cnt);
  1852. break;
  1853. }
  1854. /* Opcode: SetNumColumns P1 P2 *
  1855. **
  1856. ** Before the OP_Column opcode can be executed on a cursor, this
  1857. ** opcode must be called to set the number of fields in the table.
  1858. **
  1859. ** This opcode sets the number of columns for cursor P1 to P2.
  1860. **
  1861. ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
  1862. ** before this op-code.
  1863. */
  1864. case OP_SetNumColumns: { /* no-push */
  1865. Cursor *pC;
  1866. assert( (pOp->p1)<p->nCursor );
  1867. assert( p->apCsr[pOp->p1]!=0 );
  1868. pC = p->apCsr[pOp->p1];
  1869. pC->nField = pOp->p2;
  1870. break;
  1871. }
  1872. /* Opcode: Column P1 P2 P3
  1873. **
  1874. ** Interpret the data that cursor P1 points to as a structure built using
  1875. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  1876. ** information about the format of the data.) Push onto the stack the value
  1877. ** of the P2-th column contained in the data. If there are less that (P2+1)
  1878. ** values in the record, push a NULL onto the stack.
  1879. **
  1880. ** If the KeyAsData opcode has previously executed on this cursor, then the
  1881. ** field might be extracted from the key rather than the data.
  1882. **
  1883. ** If the column contains fewer than P2 fields, then push a NULL. Or
  1884. ** if P3 is of type P3_MEM, then push the P3 value. The P3 value will
  1885. ** be default value for a column that has been added using the ALTER TABLE
  1886. ** ADD COLUMN command. If P3 is an ordinary string, just push a NULL.
  1887. ** When P3 is a string it is really just a comment describing the value
  1888. ** to be pushed, not a default value.
  1889. */
  1890. case OP_Column: {
  1891. u32 payloadSize; /* Number of bytes in the record */
  1892. int p1 = pOp->p1; /* P1 value of the opcode */
  1893. int p2 = pOp->p2; /* column number to retrieve */
  1894. Cursor *pC = 0; /* The VDBE cursor */
  1895. char *zRec; /* Pointer to complete record-data */
  1896. BtCursor *pCrsr; /* The BTree cursor */
  1897. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  1898. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  1899. u32 nField; /* number of fields in the record */
  1900. int len; /* The length of the serialized data for the column */
  1901. int i; /* Loop counter */
  1902. char *zData; /* Part of the record being decoded */
  1903. Mem sMem; /* For storing the record being decoded */
  1904. sMem.flags = 0;
  1905. assert( p1<p->nCursor );
  1906. pTos++;
  1907. pTos->flags = MEM_Null;
  1908. /* This block sets the variable payloadSize to be the total number of
  1909. ** bytes in the record.
  1910. **
  1911. ** zRec is set to be the complete text of the record if it is available.
  1912. ** The complete record text is always available for pseudo-tables
  1913. ** If the record is stored in a cursor, the complete record text
  1914. ** might be available in the pC->aRow cache. Or it might not be.
  1915. ** If the data is unavailable, zRec is set to NULL.
  1916. **
  1917. ** We also compute the number of columns in the record. For cursors,
  1918. ** the number of columns is stored in the Cursor.nField element. For
  1919. ** records on the stack, the next entry down on the stack is an integer
  1920. ** which is the number of records.
  1921. */
  1922. pC = p->apCsr[p1];
  1923. assert( pC!=0 );
  1924. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1925. assert( pC->pVtabCursor==0 );
  1926. #endif
  1927. if( pC->pCursor!=0 ){
  1928. /* The record is stored in a B-Tree */
  1929. rc = sqlite3VdbeCursorMoveto(pC);
  1930. if( rc ) goto abort_due_to_error;
  1931. zRec = 0;
  1932. pCrsr = pC->pCursor;
  1933. if( pC->nullRow ){
  1934. payloadSize = 0;
  1935. }else if( pC->cacheStatus==p->cacheCtr ){
  1936. payloadSize = pC->payloadSize;
  1937. zRec = (char*)pC->aRow;
  1938. }else if( pC->isIndex ){
  1939. i64 payloadSize64;
  1940. sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  1941. payloadSize = payloadSize64;
  1942. }else{
  1943. sqlite3BtreeDataSize(pCrsr, &payloadSize);
  1944. }
  1945. nField = pC->nField;
  1946. }else if( pC->pseudoTable ){
  1947. /* The record is the sole entry of a pseudo-table */
  1948. payloadSize = pC->nData;
  1949. zRec = pC->pData;
  1950. pC->cacheStatus = CACHE_STALE;
  1951. assert( payloadSize==0 || zRec!=0 );
  1952. nField = pC->nField;
  1953. pCrsr = 0;
  1954. }else{
  1955. zRec = 0;
  1956. payloadSize = 0;
  1957. pCrsr = 0;
  1958. nField = 0;
  1959. }
  1960. /* If payloadSize is 0, then just push a NULL onto the stack. */
  1961. if( payloadSize==0 ){
  1962. assert( pTos->flags==MEM_Null );
  1963. break;
  1964. }
  1965. if( payloadSize>SQLITE_MAX_LENGTH ){
  1966. goto too_big;
  1967. }
  1968. assert( p2<nField );
  1969. /* Read and parse the table header. Store the results of the parse
  1970. ** into the record header cache fields of the cursor.
  1971. */
  1972. if( pC && pC->cacheStatus==p->cacheCtr ){
  1973. aType = pC->aType;
  1974. aOffset = pC->aOffset;
  1975. }else{
  1976. u8 *zIdx; /* Index into header */
  1977. u8 *zEndHdr; /* Pointer to first byte after the header */
  1978. u32 offset; /* Offset into the data */
  1979. int szHdrSz; /* Size of the header size field at start of record */
  1980. int avail; /* Number of bytes of available data */
  1981. aType = pC->aType;
  1982. if( aType==0 ){
  1983. pC->aType = aType = sqlite3DbMallocRaw(db, 2*nField*sizeof(aType) );
  1984. }
  1985. if( aType==0 ){
  1986. goto no_mem;
  1987. }
  1988. pC->aOffset = aOffset = &aType[nField];
  1989. pC->payloadSize = payloadSize;
  1990. pC->cacheStatus = p->cacheCtr;
  1991. /* Figure out how many bytes are in the header */
  1992. if( zRec ){
  1993. zData = zRec;
  1994. }else{
  1995. if( pC->isIndex ){
  1996. zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
  1997. }else{
  1998. zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
  1999. }
  2000. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  2001. ** save the payload in the pC->aRow cache. That will save us from
  2002. ** having to make additional calls to fetch the content portion of
  2003. ** the record.
  2004. */
  2005. if( avail>=payloadSize ){
  2006. zRec = zData;
  2007. pC->aRow = (u8*)zData;
  2008. }else{
  2009. pC->aRow = 0;
  2010. }
  2011. }
  2012. /* The following assert is true in all cases accept when
  2013. ** the database file has been corrupted externally.
  2014. ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
  2015. szHdrSz = GetVarint((u8*)zData, offset);
  2016. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  2017. ** record header in most cases. But they will fail to get the complete
  2018. ** record header if the record header does not fit on a single page
  2019. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  2020. ** acquire the complete header text.
  2021. */
  2022. if( !zRec && avail<offset ){
  2023. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
  2024. if( rc!=SQLITE_OK ){
  2025. goto op_column_out;
  2026. }
  2027. zData = sMem.z;
  2028. }
  2029. zEndHdr = (u8 *)&zData[offset];
  2030. zIdx = (u8 *)&zData[szHdrSz];
  2031. /* Scan the header and use it to fill in the aType[] and aOffset[]
  2032. ** arrays. aType[i] will contain the type integer for the i-th
  2033. ** column and aOffset[i] will contain the offset from the beginning
  2034. ** of the record to the start of the data for the i-th column
  2035. */
  2036. for(i=0; i<nField; i++){
  2037. if( zIdx<zEndHdr ){
  2038. aOffset[i] = offset;
  2039. zIdx += GetVarint(zIdx, aType[i]);
  2040. offset += sqlite3VdbeSerialTypeLen(aType[i]);
  2041. }else{
  2042. /* If i is less that nField, then there are less fields in this
  2043. ** record than SetNumColumns indicated there are columns in the
  2044. ** table. Set the offset for any extra columns not present in
  2045. ** the record to 0. This tells code below to push a NULL onto the
  2046. ** stack instead of deserializing a value from the record.
  2047. */
  2048. aOffset[i] = 0;
  2049. }
  2050. }
  2051. Release(&sMem);
  2052. sMem.flags = MEM_Null;
  2053. /* If we have read more header data than was contained in the header,
  2054. ** or if the end of the last field appears to be past the end of the
  2055. ** record, then we must be dealing with a corrupt database.
  2056. */
  2057. if( zIdx>zEndHdr || offset>payloadSize ){
  2058. rc = SQLITE_CORRUPT_BKPT;
  2059. goto op_column_out;
  2060. }
  2061. }
  2062. /* Get the column information. If aOffset[p2] is non-zero, then
  2063. ** deserialize the value from the record. If aOffset[p2] is zero,
  2064. ** then there are not enough fields in the record to satisfy the
  2065. ** request. In this case, set the value NULL or to P3 if P3 is
  2066. ** a pointer to a Mem object.
  2067. */
  2068. if( aOffset[p2] ){
  2069. assert( rc==SQLITE_OK );
  2070. if( zRec ){
  2071. zData = &zRec[aOffset[p2]];
  2072. }else{
  2073. len = sqlite3VdbeSerialTypeLen(aType[p2]);
  2074. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
  2075. if( rc!=SQLITE_OK ){
  2076. goto op_column_out;
  2077. }
  2078. zData = sMem.z;
  2079. }
  2080. sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
  2081. pTos->enc = encoding;
  2082. }else{
  2083. if( pOp->p3type==P3_MEM ){
  2084. sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
  2085. }else{
  2086. pTos->flags = MEM_Null;
  2087. }
  2088. }
  2089. /* If we dynamically allocated space to hold the data (in the
  2090. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  2091. ** dynamically allocated space over to the pTos structure.
  2092. ** This prevents a memory copy.
  2093. */
  2094. if( (sMem.flags & MEM_Dyn)!=0 ){
  2095. assert( pTos->flags & MEM_Ephem );
  2096. assert( pTos->flags & (MEM_Str|MEM_Blob) );
  2097. assert( pTos->z==sMem.z );
  2098. assert( sMem.flags & MEM_Term );
  2099. pTos->flags &= ~MEM_Ephem;
  2100. pTos->flags |= MEM_Dyn|MEM_Term;
  2101. }
  2102. /* pTos->z might be pointing to sMem.zShort[]. Fix that so that we
  2103. ** can abandon sMem */
  2104. rc = sqlite3VdbeMemMakeWriteable(pTos);
  2105. op_column_out:
  2106. break;
  2107. }
  2108. /* Opcode: MakeRecord P1 P2 P3
  2109. **
  2110. ** Convert the top abs(P1) entries of the stack into a single entry
  2111. ** suitable for use as a data record in a database table or as a key
  2112. ** in an index. The details of the format are irrelavant as long as
  2113. ** the OP_Column opcode can decode the record later and as long as the
  2114. ** sqlite3VdbeRecordCompare function will correctly compare two encoded
  2115. ** records. Refer to source code comments for the details of the record
  2116. ** format.
  2117. **
  2118. ** The original stack entries are popped from the stack if P1>0 but
  2119. ** remain on the stack if P1<0.
  2120. **
  2121. ** If P2 is not zero and one or more of the entries are NULL, then jump
  2122. ** to the address given by P2. This feature can be used to skip a
  2123. ** uniqueness test on indices.
  2124. **
  2125. ** P3 may be a string that is P1 characters long. The nth character of the
  2126. ** string indicates the column affinity that should be used for the nth
  2127. ** field of the index key (i.e. the first character of P3 corresponds to the
  2128. ** lowest element on the stack).
  2129. **
  2130. ** The mapping from character to affinity is given by the SQLITE_AFF_
  2131. ** macros defined in sqliteInt.h.
  2132. **
  2133. ** If P3 is NULL then all index fields have the affinity NONE.
  2134. **
  2135. ** See also OP_MakeIdxRec
  2136. */
  2137. /* Opcode: MakeIdxRec P1 P2 P3
  2138. **
  2139. ** This opcode works just OP_MakeRecord except that it reads an extra
  2140. ** integer from the stack (thus reading a total of abs(P1+1) entries)
  2141. ** and appends that extra integer to the end of the record as a varint.
  2142. ** This results in an index key.
  2143. */
  2144. case OP_MakeIdxRec:
  2145. case OP_MakeRecord: {
  2146. /* Assuming the record contains N fields, the record format looks
  2147. ** like this:
  2148. **
  2149. ** ------------------------------------------------------------------------
  2150. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  2151. ** ------------------------------------------------------------------------
  2152. **
  2153. ** Data(0) is taken from the lowest element of the stack and data(N-1) is
  2154. ** the top of the stack.
  2155. **
  2156. ** Each type field is a varint representing the serial type of the
  2157. ** corresponding data element (see sqlite3VdbeSerialType()). The
  2158. ** hdr-size field is also a varint which is the offset from the beginning
  2159. ** of the record to data0.
  2160. */
  2161. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  2162. Mem *pRec; /* The new record */
  2163. Mem *pRowid = 0; /* Rowid appended to the new record */
  2164. u64 nData = 0; /* Number of bytes of data space */
  2165. int nHdr = 0; /* Number of bytes of header space */
  2166. u64 nByte = 0; /* Data space required for this record */
  2167. int nZero = 0; /* Number of zero bytes at the end of the record */
  2168. int nVarint; /* Number of bytes in a varint */
  2169. u32 serial_type; /* Type field */
  2170. int containsNull = 0; /* True if any of the data fields are NULL */
  2171. Mem *pData0; /* Bottom of the stack */
  2172. int leaveOnStack; /* If true, leave the entries on the stack */
  2173. int nField; /* Number of fields in the record */
  2174. int jumpIfNull; /* Jump here if non-zero and any entries are NULL. */
  2175. int addRowid; /* True to append a rowid column at the end */
  2176. char *zAffinity; /* The affinity string for the record */
  2177. int file_format; /* File format to use for encoding */
  2178. int i; /* Space used in zNewRecord[] */
  2179. char zTemp[NBFS]; /* Space to hold small records */
  2180. leaveOnStack = ((pOp->p1<0)?1:0);
  2181. nField = pOp->p1 * (leaveOnStack?-1:1);
  2182. jumpIfNull = pOp->p2;
  2183. addRowid = pOp->opcode==OP_MakeIdxRec;
  2184. zAffinity = pOp->p3;
  2185. pData0 = &pTos[1-nField];
  2186. assert( pData0>=p->aStack );
  2187. containsNull = 0;
  2188. file_format = p->minWriteFileFormat;
  2189. /* Loop through the elements that will make up the record to figure
  2190. ** out how much space is required for the new record.
  2191. */
  2192. for(pRec=pData0; pRec<=pTos; pRec++){
  2193. int len;
  2194. if( zAffinity ){
  2195. applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
  2196. }
  2197. if( pRec->flags&MEM_Null ){
  2198. containsNull = 1;
  2199. }
  2200. if( pRec->flags&MEM_Zero && pRec->n>0 ){
  2201. ExpandBlob(pRec);
  2202. }
  2203. serial_type = sqlite3VdbeSerialType(pRec, file_format);
  2204. len = sqlite3VdbeSerialTypeLen(serial_type);
  2205. nData += len;
  2206. nHdr += sqlite3VarintLen(serial_type);
  2207. if( pRec->flags & MEM_Zero ){
  2208. /* Only pure zero-filled BLOBs can be input to this Opcode.
  2209. ** We do not allow blobs with a prefix and a zero-filled tail. */
  2210. nZero += pRec->u.i;
  2211. }else if( len ){
  2212. nZero = 0;
  2213. }
  2214. }
  2215. /* If we have to append a varint rowid to this record, set pRowid
  2216. ** to the value of the rowid and increase nByte by the amount of space
  2217. ** required to store it.
  2218. */
  2219. if( addRowid ){
  2220. pRowid = &pTos[0-nField];
  2221. assert( pRowid>=p->aStack );
  2222. sqlite3VdbeMemIntegerify(pRowid);
  2223. serial_type = sqlite3VdbeSerialType(pRowid, 0);
  2224. nData += sqlite3VdbeSerialTypeLen(serial_type);
  2225. nHdr += sqlite3VarintLen(serial_type);
  2226. nZero = 0;
  2227. }
  2228. /* Add the initial header varint and total the size */
  2229. nHdr += nVarint = sqlite3VarintLen(nHdr);
  2230. if( nVarint<sqlite3VarintLen(nHdr) ){
  2231. nHdr++;
  2232. }
  2233. nByte = nHdr+nData-nZero;
  2234. if( nByte>SQLITE_MAX_LENGTH ){
  2235. goto too_big;
  2236. }
  2237. /* Allocate space for the new record. */
  2238. if( nByte>sizeof(zTemp) ){
  2239. zNewRecord = sqlite3DbMallocRaw(db, nByte);
  2240. if( !zNewRecord ){
  2241. goto no_mem;
  2242. }
  2243. }else{
  2244. zNewRecord = (u8*)zTemp;
  2245. }
  2246. /* Write the record */
  2247. i = sqlite3PutVarint(zNewRecord, nHdr);
  2248. for(pRec=pData0; pRec<=pTos; pRec++){
  2249. serial_type = sqlite3VdbeSerialType(pRec, file_format);
  2250. i += sqlite3PutVarint(&zNewRecord[i], serial_type); /* serial type */
  2251. }
  2252. if( addRowid ){
  2253. i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0));
  2254. }
  2255. for(pRec=pData0; pRec<=pTos; pRec++){ /* serial data */
  2256. i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
  2257. }
  2258. if( addRowid ){
  2259. i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0);
  2260. }
  2261. assert( i==nByte );
  2262. /* Pop entries off the stack if required. Push the new record on. */
  2263. if( !leaveOnStack ){
  2264. popStack(&pTos, nField+addRowid);
  2265. }
  2266. pTos++;
  2267. pTos->n = nByte;
  2268. if( nByte<=sizeof(zTemp) ){
  2269. assert( zNewRecord==(unsigned char *)zTemp );
  2270. pTos->z = pTos->zShort;
  2271. memcpy(pTos->zShort, zTemp, nByte);
  2272. pTos->flags = MEM_Blob | MEM_Short;
  2273. }else{
  2274. assert( zNewRecord!=(unsigned char *)zTemp );
  2275. pTos->z = (char*)zNewRecord;
  2276. pTos->flags = MEM_Blob | MEM_Dyn;
  2277. pTos->xDel = 0;
  2278. }
  2279. if( nZero ){
  2280. pTos->u.i = nZero;
  2281. pTos->flags |= MEM_Zero;
  2282. }
  2283. pTos->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  2284. /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
  2285. if( jumpIfNull && containsNull ){
  2286. pc = jumpIfNull - 1;
  2287. }
  2288. break;
  2289. }
  2290. /* Opcode: Statement P1 * *
  2291. **
  2292. ** Begin an individual statement transaction which is part of a larger
  2293. ** BEGIN..COMMIT transaction. This is needed so that the statement
  2294. ** can be rolled back after an error without having to roll back the
  2295. ** entire transaction. The statement transaction will automatically
  2296. ** commit when the VDBE halts.
  2297. **
  2298. ** The statement is begun on the database file with index P1. The main
  2299. ** database file has an index of 0 and the file used for temporary tables
  2300. ** has an index of 1.
  2301. */
  2302. case OP_Statement: { /* no-push */
  2303. int i = pOp->p1;
  2304. Btree *pBt;
  2305. if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0
  2306. && (db->autoCommit==0 || db->activeVdbeCnt>1) ){
  2307. assert( sqlite3BtreeIsInTrans(pBt) );
  2308. assert( (p->btreeMask & (1<<i))!=0 );
  2309. if( !sqlite3BtreeIsInStmt(pBt) ){
  2310. rc = sqlite3BtreeBeginStmt(pBt);
  2311. p->openedStatement = 1;
  2312. }
  2313. }
  2314. break;
  2315. }
  2316. /* Opcode: AutoCommit P1 P2 *
  2317. **
  2318. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  2319. ** back any currently active btree transactions. If there are any active
  2320. ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
  2321. **
  2322. ** This instruction causes the VM to halt.
  2323. */
  2324. case OP_AutoCommit: { /* no-push */
  2325. u8 i = pOp->p1;
  2326. u8 rollback = pOp->p2;
  2327. assert( i==1 || i==0 );
  2328. assert( i==1 || rollback==0 );
  2329. assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
  2330. if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
  2331. /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
  2332. ** still running, and a transaction is active, return an error indicating
  2333. ** that the other VMs must complete first.
  2334. */
  2335. sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
  2336. " transaction - SQL statements in progress", (char*)0);
  2337. rc = SQLITE_ERROR;
  2338. }else if( i!=db->autoCommit ){
  2339. if( pOp->p2 ){
  2340. assert( i==1 );
  2341. sqlite3RollbackAll(db);
  2342. db->autoCommit = 1;
  2343. }else{
  2344. db->autoCommit = i;
  2345. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  2346. p->pTos = pTos;
  2347. p->pc = pc;
  2348. db->autoCommit = 1-i;
  2349. p->rc = rc = SQLITE_BUSY;
  2350. goto vdbe_return;
  2351. }
  2352. }
  2353. if( p->rc==SQLITE_OK ){
  2354. rc = SQLITE_DONE;
  2355. }else{
  2356. rc = SQLITE_ERROR;
  2357. }
  2358. goto vdbe_return;
  2359. }else{
  2360. sqlite3SetString(&p->zErrMsg,
  2361. (!i)?"cannot start a transaction within a transaction":(
  2362. (rollback)?"cannot rollback - no transaction is active":
  2363. "cannot commit - no transaction is active"), (char*)0);
  2364. rc = SQLITE_ERROR;
  2365. }
  2366. break;
  2367. }
  2368. /* Opcode: Transaction P1 P2 *
  2369. **
  2370. ** Begin a transaction. The transaction ends when a Commit or Rollback
  2371. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  2372. ** transaction might also be rolled back if an error is encountered.
  2373. **
  2374. ** P1 is the index of the database file on which the transaction is
  2375. ** started. Index 0 is the main database file and index 1 is the
  2376. ** file used for temporary tables.
  2377. **
  2378. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  2379. ** obtained on the database file when a write-transaction is started. No
  2380. ** other process can start another write transaction while this transaction is
  2381. ** underway. Starting a write transaction also creates a rollback journal. A
  2382. ** write transaction must be started before any changes can be made to the
  2383. ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
  2384. ** on the file.
  2385. **
  2386. ** If P2 is zero, then a read-lock is obtained on the database file.
  2387. */
  2388. case OP_Transaction: { /* no-push */
  2389. int i = pOp->p1;
  2390. Btree *pBt;
  2391. assert( i>=0 && i<db->nDb );
  2392. assert( (p->btreeMask & (1<<i))!=0 );
  2393. pBt = db->aDb[i].pBt;
  2394. if( pBt ){
  2395. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  2396. if( rc==SQLITE_BUSY ){
  2397. p->pc = pc;
  2398. p->rc = rc = SQLITE_BUSY;
  2399. p->pTos = pTos;
  2400. goto vdbe_return;
  2401. }
  2402. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
  2403. goto abort_due_to_error;
  2404. }
  2405. }
  2406. break;
  2407. }
  2408. /* Opcode: ReadCookie P1 P2 *
  2409. **
  2410. ** Read cookie number P2 from database P1 and push it onto the stack.
  2411. ** P2==0 is the schema version. P2==1 is the database format.
  2412. ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
  2413. ** the main database file and P1==1 is the database file used to store
  2414. ** temporary tables.
  2415. **
  2416. ** If P1 is negative, then this is a request to read the size of a
  2417. ** databases free-list. P2 must be set to 1 in this case. The actual
  2418. ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
  2419. ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
  2420. **
  2421. ** There must be a read-lock on the database (either a transaction
  2422. ** must be started or there must be an open cursor) before
  2423. ** executing this instruction.
  2424. */
  2425. case OP_ReadCookie: {
  2426. int iMeta;
  2427. int iDb = pOp->p1;
  2428. int iCookie = pOp->p2;
  2429. assert( pOp->p2<SQLITE_N_BTREE_META );
  2430. if( iDb<0 ){
  2431. iDb = (-1*(iDb+1));
  2432. iCookie *= -1;
  2433. }
  2434. assert( iDb>=0 && iDb<db->nDb );
  2435. assert( db->aDb[iDb].pBt!=0 );
  2436. assert( (p->btreeMask & (1<<iDb))!=0 );
  2437. /* The indexing of meta values at the schema layer is off by one from
  2438. ** the indexing in the btree layer. The btree considers meta[0] to
  2439. ** be the number of free pages in the database (a read-only value)
  2440. ** and meta[1] to be the schema cookie. The schema layer considers
  2441. ** meta[1] to be the schema cookie. So we have to shift the index
  2442. ** by one in the following statement.
  2443. */
  2444. rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
  2445. pTos++;
  2446. pTos->u.i = iMeta;
  2447. pTos->flags = MEM_Int;
  2448. break;
  2449. }
  2450. /* Opcode: SetCookie P1 P2 *
  2451. **
  2452. ** Write the top of the stack into cookie number P2 of database P1.
  2453. ** P2==0 is the schema version. P2==1 is the database format.
  2454. ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
  2455. ** the main database file and P1==1 is the database file used to store
  2456. ** temporary tables.
  2457. **
  2458. ** A transaction must be started before executing this opcode.
  2459. */
  2460. case OP_SetCookie: { /* no-push */
  2461. Db *pDb;
  2462. assert( pOp->p2<SQLITE_N_BTREE_META );
  2463. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  2464. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  2465. pDb = &db->aDb[pOp->p1];
  2466. assert( pDb->pBt!=0 );
  2467. assert( pTos>=p->aStack );
  2468. sqlite3VdbeMemIntegerify(pTos);
  2469. /* See note about index shifting on OP_ReadCookie */
  2470. rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i);
  2471. if( pOp->p2==0 ){
  2472. /* When the schema cookie changes, record the new cookie internally */
  2473. pDb->pSchema->schema_cookie = pTos->u.i;
  2474. db->flags |= SQLITE_InternChanges;
  2475. }else if( pOp->p2==1 ){
  2476. /* Record changes in the file format */
  2477. pDb->pSchema->file_format = pTos->u.i;
  2478. }
  2479. assert( (pTos->flags & MEM_Dyn)==0 );
  2480. pTos--;
  2481. if( pOp->p1==1 ){
  2482. /* Invalidate all prepared statements whenever the TEMP database
  2483. ** schema is changed. Ticket #1644 */
  2484. sqlite3ExpirePreparedStatements(db);
  2485. }
  2486. break;
  2487. }
  2488. /* Opcode: VerifyCookie P1 P2 *
  2489. **
  2490. ** Check the value of global database parameter number 0 (the
  2491. ** schema version) and make sure it is equal to P2.
  2492. ** P1 is the database number which is 0 for the main database file
  2493. ** and 1 for the file holding temporary tables and some higher number
  2494. ** for auxiliary databases.
  2495. **
  2496. ** The cookie changes its value whenever the database schema changes.
  2497. ** This operation is used to detect when that the cookie has changed
  2498. ** and that the current process needs to reread the schema.
  2499. **
  2500. ** Either a transaction needs to have been started or an OP_Open needs
  2501. ** to be executed (to establish a read lock) before this opcode is
  2502. ** invoked.
  2503. */
  2504. case OP_VerifyCookie: { /* no-push */
  2505. int iMeta;
  2506. Btree *pBt;
  2507. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  2508. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  2509. pBt = db->aDb[pOp->p1].pBt;
  2510. if( pBt ){
  2511. rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
  2512. }else{
  2513. rc = SQLITE_OK;
  2514. iMeta = 0;
  2515. }
  2516. if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
  2517. sqlite3_free(p->zErrMsg);
  2518. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  2519. /* If the schema-cookie from the database file matches the cookie
  2520. ** stored with the in-memory representation of the schema, do
  2521. ** not reload the schema from the database file.
  2522. **
  2523. ** If virtual-tables are in use, this is not just an optimisation.
  2524. ** Often, v-tables store their data in other SQLite tables, which
  2525. ** are queried from within xNext() and other v-table methods using
  2526. ** prepared queries. If such a query is out-of-date, we do not want to
  2527. ** discard the database schema, as the user code implementing the
  2528. ** v-table would have to be ready for the sqlite3_vtab structure itself
  2529. ** to be invalidated whenever sqlite3_step() is called from within
  2530. ** a v-table method.
  2531. */
  2532. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  2533. sqlite3ResetInternalSchema(db, pOp->p1);
  2534. }
  2535. sqlite3ExpirePreparedStatements(db);
  2536. rc = SQLITE_SCHEMA;
  2537. }
  2538. break;
  2539. }
  2540. /* Opcode: OpenRead P1 P2 P3
  2541. **
  2542. ** Open a read-only cursor for the database table whose root page is
  2543. ** P2 in a database file. The database file is determined by an
  2544. ** integer from the top of the stack. 0 means the main database and
  2545. ** 1 means the database used for temporary tables. Give the new
  2546. ** cursor an identifier of P1. The P1 values need not be contiguous
  2547. ** but all P1 values should be small integers. It is an error for
  2548. ** P1 to be negative.
  2549. **
  2550. ** If P2==0 then take the root page number from the next of the stack.
  2551. **
  2552. ** There will be a read lock on the database whenever there is an
  2553. ** open cursor. If the database was unlocked prior to this instruction
  2554. ** then a read lock is acquired as part of this instruction. A read
  2555. ** lock allows other processes to read the database but prohibits
  2556. ** any other process from modifying the database. The read lock is
  2557. ** released when all cursors are closed. If this instruction attempts
  2558. ** to get a read lock but fails, the script terminates with an
  2559. ** SQLITE_BUSY error code.
  2560. **
  2561. ** The P3 value is a pointer to a KeyInfo structure that defines the
  2562. ** content and collating sequence of indices. P3 is NULL for cursors
  2563. ** that are not pointing to indices.
  2564. **
  2565. ** See also OpenWrite.
  2566. */
  2567. /* Opcode: OpenWrite P1 P2 P3
  2568. **
  2569. ** Open a read/write cursor named P1 on the table or index whose root
  2570. ** page is P2. If P2==0 then take the root page number from the stack.
  2571. **
  2572. ** The P3 value is a pointer to a KeyInfo structure that defines the
  2573. ** content and collating sequence of indices. P3 is NULL for cursors
  2574. ** that are not pointing to indices.
  2575. **
  2576. ** This instruction works just like OpenRead except that it opens the cursor
  2577. ** in read/write mode. For a given table, there can be one or more read-only
  2578. ** cursors or a single read/write cursor but not both.
  2579. **
  2580. ** See also OpenRead.
  2581. */
  2582. case OP_OpenRead: /* no-push */
  2583. case OP_OpenWrite: { /* no-push */
  2584. int i = pOp->p1;
  2585. int p2 = pOp->p2;
  2586. int wrFlag;
  2587. Btree *pX;
  2588. int iDb;
  2589. Cursor *pCur;
  2590. Db *pDb;
  2591. assert( pTos>=p->aStack );
  2592. sqlite3VdbeMemIntegerify(pTos);
  2593. iDb = pTos->u.i;
  2594. assert( (pTos->flags & MEM_Dyn)==0 );
  2595. pTos--;
  2596. assert( iDb>=0 && iDb<db->nDb );
  2597. assert( (p->btreeMask & (1<<iDb))!=0 );
  2598. pDb = &db->aDb[iDb];
  2599. pX = pDb->pBt;
  2600. assert( pX!=0 );
  2601. if( pOp->opcode==OP_OpenWrite ){
  2602. wrFlag = 1;
  2603. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  2604. p->minWriteFileFormat = pDb->pSchema->file_format;
  2605. }
  2606. }else{
  2607. wrFlag = 0;
  2608. }
  2609. if( p2<=0 ){
  2610. assert( pTos>=p->aStack );
  2611. sqlite3VdbeMemIntegerify(pTos);
  2612. p2 = pTos->u.i;
  2613. assert( (pTos->flags & MEM_Dyn)==0 );
  2614. pTos--;
  2615. assert( p2>=2 );
  2616. }
  2617. assert( i>=0 );
  2618. pCur = allocateCursor(p, i, iDb);
  2619. if( pCur==0 ) goto no_mem;
  2620. pCur->nullRow = 1;
  2621. if( pX==0 ) break;
  2622. /* We always provide a key comparison function. If the table being
  2623. ** opened is of type INTKEY, the comparision function will be ignored. */
  2624. rc = sqlite3BtreeCursor(pX, p2, wrFlag,
  2625. sqlite3VdbeRecordCompare, pOp->p3,
  2626. &pCur->pCursor);
  2627. if( pOp->p3type==P3_KEYINFO ){
  2628. pCur->pKeyInfo = (KeyInfo*)pOp->p3;
  2629. pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
  2630. pCur->pKeyInfo->enc = ENC(p->db);
  2631. }else{
  2632. pCur->pKeyInfo = 0;
  2633. pCur->pIncrKey = &pCur->bogusIncrKey;
  2634. }
  2635. switch( rc ){
  2636. case SQLITE_BUSY: {
  2637. p->pc = pc;
  2638. p->rc = rc = SQLITE_BUSY;
  2639. p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
  2640. goto vdbe_return;
  2641. }
  2642. case SQLITE_OK: {
  2643. int flags = sqlite3BtreeFlags(pCur->pCursor);
  2644. /* Sanity checking. Only the lower four bits of the flags byte should
  2645. ** be used. Bit 3 (mask 0x08) is unpreditable. The lower 3 bits
  2646. ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
  2647. ** 2 (zerodata for indices). If these conditions are not met it can
  2648. ** only mean that we are dealing with a corrupt database file
  2649. */
  2650. if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
  2651. rc = SQLITE_CORRUPT_BKPT;
  2652. goto abort_due_to_error;
  2653. }
  2654. pCur->isTable = (flags & BTREE_INTKEY)!=0;
  2655. pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
  2656. /* If P3==0 it means we are expected to open a table. If P3!=0 then
  2657. ** we expect to be opening an index. If this is not what happened,
  2658. ** then the database is corrupt
  2659. */
  2660. if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
  2661. || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
  2662. rc = SQLITE_CORRUPT_BKPT;
  2663. goto abort_due_to_error;
  2664. }
  2665. break;
  2666. }
  2667. case SQLITE_EMPTY: {
  2668. pCur->isTable = pOp->p3type!=P3_KEYINFO;
  2669. pCur->isIndex = !pCur->isTable;
  2670. rc = SQLITE_OK;
  2671. break;
  2672. }
  2673. default: {
  2674. goto abort_due_to_error;
  2675. }
  2676. }
  2677. break;
  2678. }
  2679. /* Opcode: OpenEphemeral P1 P2 P3
  2680. **
  2681. ** Open a new cursor P1 to a transient table.
  2682. ** The cursor is always opened read/write even if
  2683. ** the main database is read-only. The transient or virtual
  2684. ** table is deleted automatically when the cursor is closed.
  2685. **
  2686. ** P2 is the number of columns in the virtual table.
  2687. ** The cursor points to a BTree table if P3==0 and to a BTree index
  2688. ** if P3 is not 0. If P3 is not NULL, it points to a KeyInfo structure
  2689. ** that defines the format of keys in the index.
  2690. **
  2691. ** This opcode was once called OpenTemp. But that created
  2692. ** confusion because the term "temp table", might refer either
  2693. ** to a TEMP table at the SQL level, or to a table opened by
  2694. ** this opcode. Then this opcode was call OpenVirtual. But
  2695. ** that created confusion with the whole virtual-table idea.
  2696. */
  2697. case OP_OpenEphemeral: { /* no-push */
  2698. int i = pOp->p1;
  2699. Cursor *pCx;
  2700. static const int openFlags =
  2701. SQLITE_OPEN_READWRITE |
  2702. SQLITE_OPEN_CREATE |
  2703. SQLITE_OPEN_EXCLUSIVE |
  2704. SQLITE_OPEN_DELETEONCLOSE |
  2705. SQLITE_OPEN_TRANSIENT_DB;
  2706. assert( i>=0 );
  2707. pCx = allocateCursor(p, i, -1);
  2708. if( pCx==0 ) goto no_mem;
  2709. pCx->nullRow = 1;
  2710. rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
  2711. &pCx->pBt);
  2712. if( rc==SQLITE_OK ){
  2713. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  2714. }
  2715. if( rc==SQLITE_OK ){
  2716. /* If a transient index is required, create it by calling
  2717. ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
  2718. ** opening it. If a transient table is required, just use the
  2719. ** automatically created table with root-page 1 (an INTKEY table).
  2720. */
  2721. if( pOp->p3 ){
  2722. int pgno;
  2723. assert( pOp->p3type==P3_KEYINFO );
  2724. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
  2725. if( rc==SQLITE_OK ){
  2726. assert( pgno==MASTER_ROOT+1 );
  2727. rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
  2728. pOp->p3, &pCx->pCursor);
  2729. pCx->pKeyInfo = (KeyInfo*)pOp->p3;
  2730. pCx->pKeyInfo->enc = ENC(p->db);
  2731. pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
  2732. }
  2733. pCx->isTable = 0;
  2734. }else{
  2735. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
  2736. pCx->isTable = 1;
  2737. pCx->pIncrKey = &pCx->bogusIncrKey;
  2738. }
  2739. }
  2740. pCx->nField = pOp->p2;
  2741. pCx->isIndex = !pCx->isTable;
  2742. break;
  2743. }
  2744. /* Opcode: OpenPseudo P1 * *
  2745. **
  2746. ** Open a new cursor that points to a fake table that contains a single
  2747. ** row of data. Any attempt to write a second row of data causes the
  2748. ** first row to be deleted. All data is deleted when the cursor is
  2749. ** closed.
  2750. **
  2751. ** A pseudo-table created by this opcode is useful for holding the
  2752. ** NEW or OLD tables in a trigger. Also used to hold the a single
  2753. ** row output from the sorter so that the row can be decomposed into
  2754. ** individual columns using the OP_Column opcode.
  2755. */
  2756. case OP_OpenPseudo: { /* no-push */
  2757. int i = pOp->p1;
  2758. Cursor *pCx;
  2759. assert( i>=0 );
  2760. pCx = allocateCursor(p, i, -1);
  2761. if( pCx==0 ) goto no_mem;
  2762. pCx->nullRow = 1;
  2763. pCx->pseudoTable = 1;
  2764. pCx->pIncrKey = &pCx->bogusIncrKey;
  2765. pCx->isTable = 1;
  2766. pCx->isIndex = 0;
  2767. break;
  2768. }
  2769. /* Opcode: Close P1 * *
  2770. **
  2771. ** Close a cursor previously opened as P1. If P1 is not
  2772. ** currently open, this instruction is a no-op.
  2773. */
  2774. case OP_Close: { /* no-push */
  2775. int i = pOp->p1;
  2776. if( i>=0 && i<p->nCursor ){
  2777. sqlite3VdbeFreeCursor(p, p->apCsr[i]);
  2778. p->apCsr[i] = 0;
  2779. }
  2780. break;
  2781. }
  2782. /* Opcode: MoveGe P1 P2 *
  2783. **
  2784. ** Pop the top of the stack and use its value as a key. Reposition
  2785. ** cursor P1 so that it points to the smallest entry that is greater
  2786. ** than or equal to the key that was popped ffrom the stack.
  2787. ** If there are no records greater than or equal to the key and P2
  2788. ** is not zero, then jump to P2.
  2789. **
  2790. ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
  2791. */
  2792. /* Opcode: MoveGt P1 P2 *
  2793. **
  2794. ** Pop the top of the stack and use its value as a key. Reposition
  2795. ** cursor P1 so that it points to the smallest entry that is greater
  2796. ** than the key from the stack.
  2797. ** If there are no records greater than the key and P2 is not zero,
  2798. ** then jump to P2.
  2799. **
  2800. ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
  2801. */
  2802. /* Opcode: MoveLt P1 P2 *
  2803. **
  2804. ** Pop the top of the stack and use its value as a key. Reposition
  2805. ** cursor P1 so that it points to the largest entry that is less
  2806. ** than the key from the stack.
  2807. ** If there are no records less than the key and P2 is not zero,
  2808. ** then jump to P2.
  2809. **
  2810. ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
  2811. */
  2812. /* Opcode: MoveLe P1 P2 *
  2813. **
  2814. ** Pop the top of the stack and use its value as a key. Reposition
  2815. ** cursor P1 so that it points to the largest entry that is less than
  2816. ** or equal to the key that was popped from the stack.
  2817. ** If there are no records less than or eqal to the key and P2 is not zero,
  2818. ** then jump to P2.
  2819. **
  2820. ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
  2821. */
  2822. case OP_MoveLt: /* no-push */
  2823. case OP_MoveLe: /* no-push */
  2824. case OP_MoveGe: /* no-push */
  2825. case OP_MoveGt: { /* no-push */
  2826. int i = pOp->p1;
  2827. Cursor *pC;
  2828. assert( pTos>=p->aStack );
  2829. assert( i>=0 && i<p->nCursor );
  2830. pC = p->apCsr[i];
  2831. assert( pC!=0 );
  2832. if( pC->pCursor!=0 ){
  2833. int res, oc;
  2834. oc = pOp->opcode;
  2835. pC->nullRow = 0;
  2836. *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
  2837. if( pC->isTable ){
  2838. i64 iKey;
  2839. sqlite3VdbeMemIntegerify(pTos);
  2840. iKey = intToKey(pTos->u.i);
  2841. if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
  2842. pC->movetoTarget = iKey;
  2843. pC->deferredMoveto = 1;
  2844. assert( (pTos->flags & MEM_Dyn)==0 );
  2845. pTos--;
  2846. break;
  2847. }
  2848. rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
  2849. if( rc!=SQLITE_OK ){
  2850. goto abort_due_to_error;
  2851. }
  2852. pC->lastRowid = pTos->u.i;
  2853. pC->rowidIsValid = res==0;
  2854. }else{
  2855. assert( pTos->flags & MEM_Blob );
  2856. ExpandBlob(pTos);
  2857. rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
  2858. if( rc!=SQLITE_OK ){
  2859. goto abort_due_to_error;
  2860. }
  2861. pC->rowidIsValid = 0;
  2862. }
  2863. pC->deferredMoveto = 0;
  2864. pC->cacheStatus = CACHE_STALE;
  2865. *pC->pIncrKey = 0;
  2866. #ifdef SQLITE_TEST
  2867. sqlite3_search_count++;
  2868. #endif
  2869. if( oc==OP_MoveGe || oc==OP_MoveGt ){
  2870. if( res<0 ){
  2871. rc = sqlite3BtreeNext(pC->pCursor, &res);
  2872. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  2873. pC->rowidIsValid = 0;
  2874. }else{
  2875. res = 0;
  2876. }
  2877. }else{
  2878. assert( oc==OP_MoveLt || oc==OP_MoveLe );
  2879. if( res>=0 ){
  2880. rc = sqlite3BtreePrevious(pC->pCursor, &res);
  2881. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  2882. pC->rowidIsValid = 0;
  2883. }else{
  2884. /* res might be negative because the table is empty. Check to
  2885. ** see if this is the case.
  2886. */
  2887. res = sqlite3BtreeEof(pC->pCursor);
  2888. }
  2889. }
  2890. if( res ){
  2891. if( pOp->p2>0 ){
  2892. pc = pOp->p2 - 1;
  2893. }else{
  2894. pC->nullRow = 1;
  2895. }
  2896. }
  2897. }
  2898. Release(pTos);
  2899. pTos--;
  2900. break;
  2901. }
  2902. /* Opcode: Distinct P1 P2 *
  2903. **
  2904. ** Use the top of the stack as a record created using MakeRecord. P1 is a
  2905. ** cursor on a table that declared as an index. If that table contains an
  2906. ** entry that matches the top of the stack fall thru. If the top of the stack
  2907. ** matches no entry in P1 then jump to P2.
  2908. **
  2909. ** The cursor is left pointing at the matching entry if it exists. The
  2910. ** record on the top of the stack is not popped.
  2911. **
  2912. ** This instruction is similar to NotFound except that this operation
  2913. ** does not pop the key from the stack.
  2914. **
  2915. ** The instruction is used to implement the DISTINCT operator on SELECT
  2916. ** statements. The P1 table is not a true index but rather a record of
  2917. ** all results that have produced so far.
  2918. **
  2919. ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
  2920. */
  2921. /* Opcode: Found P1 P2 *
  2922. **
  2923. ** Top of the stack holds a blob constructed by MakeRecord. P1 is an index.
  2924. ** If an entry that matches the top of the stack exists in P1 then
  2925. ** jump to P2. If the top of the stack does not match any entry in P1
  2926. ** then fall thru. The P1 cursor is left pointing at the matching entry
  2927. ** if it exists. The blob is popped off the top of the stack.
  2928. **
  2929. ** This instruction is used to implement the IN operator where the
  2930. ** left-hand side is a SELECT statement. P1 may be a true index, or it
  2931. ** may be a temporary index that holds the results of the SELECT
  2932. ** statement.
  2933. **
  2934. ** This instruction checks if index P1 contains a record for which
  2935. ** the first N serialised values exactly match the N serialised values
  2936. ** in the record on the stack, where N is the total number of values in
  2937. ** the stack record (stack record is a prefix of the P1 record).
  2938. **
  2939. ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
  2940. */
  2941. /* Opcode: NotFound P1 P2 *
  2942. **
  2943. ** The top of the stack holds a blob constructed by MakeRecord. P1 is
  2944. ** an index. If no entry exists in P1 that matches the blob then jump
  2945. ** to P2. If an entry does existing, fall through. The cursor is left
  2946. ** pointing to the entry that matches. The blob is popped from the stack.
  2947. **
  2948. ** The difference between this operation and Distinct is that
  2949. ** Distinct does not pop the key from the stack.
  2950. **
  2951. ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
  2952. */
  2953. case OP_Distinct: /* no-push */
  2954. case OP_NotFound: /* no-push */
  2955. case OP_Found: { /* no-push */
  2956. int i = pOp->p1;
  2957. int alreadyExists = 0;
  2958. Cursor *pC;
  2959. assert( pTos>=p->aStack );
  2960. assert( i>=0 && i<p->nCursor );
  2961. assert( p->apCsr[i]!=0 );
  2962. if( (pC = p->apCsr[i])->pCursor!=0 ){
  2963. int res;
  2964. assert( pC->isTable==0 );
  2965. assert( pTos->flags & MEM_Blob );
  2966. Stringify(pTos, encoding);
  2967. if( pOp->opcode==OP_Found ){
  2968. pC->pKeyInfo->prefixIsEqual = 1;
  2969. }
  2970. rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
  2971. pC->pKeyInfo->prefixIsEqual = 0;
  2972. if( rc!=SQLITE_OK ){
  2973. break;
  2974. }
  2975. alreadyExists = (res==0);
  2976. pC->deferredMoveto = 0;
  2977. pC->cacheStatus = CACHE_STALE;
  2978. }
  2979. if( pOp->opcode==OP_Found ){
  2980. if( alreadyExists ) pc = pOp->p2 - 1;
  2981. }else{
  2982. if( !alreadyExists ) pc = pOp->p2 - 1;
  2983. }
  2984. if( pOp->opcode!=OP_Distinct ){
  2985. Release(pTos);
  2986. pTos--;
  2987. }
  2988. break;
  2989. }
  2990. /* Opcode: IsUnique P1 P2 *
  2991. **
  2992. ** The top of the stack is an integer record number. Call this
  2993. ** record number R. The next on the stack is an index key created
  2994. ** using MakeIdxRec. Call it K. This instruction pops R from the
  2995. ** stack but it leaves K unchanged.
  2996. **
  2997. ** P1 is an index. So it has no data and its key consists of a
  2998. ** record generated by OP_MakeRecord where the last field is the
  2999. ** rowid of the entry that the index refers to.
  3000. **
  3001. ** This instruction asks if there is an entry in P1 where the
  3002. ** fields matches K but the rowid is different from R.
  3003. ** If there is no such entry, then there is an immediate
  3004. ** jump to P2. If any entry does exist where the index string
  3005. ** matches K but the record number is not R, then the record
  3006. ** number for that entry is pushed onto the stack and control
  3007. ** falls through to the next instruction.
  3008. **
  3009. ** See also: Distinct, NotFound, NotExists, Found
  3010. */
  3011. case OP_IsUnique: { /* no-push */
  3012. int i = pOp->p1;
  3013. Mem *pNos = &pTos[-1];
  3014. Cursor *pCx;
  3015. BtCursor *pCrsr;
  3016. i64 R;
  3017. /* Pop the value R off the top of the stack
  3018. */
  3019. assert( pNos>=p->aStack );
  3020. sqlite3VdbeMemIntegerify(pTos);
  3021. R = pTos->u.i;
  3022. assert( (pTos->flags & MEM_Dyn)==0 );
  3023. pTos--;
  3024. assert( i>=0 && i<p->nCursor );
  3025. pCx = p->apCsr[i];
  3026. assert( pCx!=0 );
  3027. pCrsr = pCx->pCursor;
  3028. if( pCrsr!=0 ){
  3029. int res;
  3030. i64 v; /* The record number on the P1 entry that matches K */
  3031. char *zKey; /* The value of K */
  3032. int nKey; /* Number of bytes in K */
  3033. int len; /* Number of bytes in K without the rowid at the end */
  3034. int szRowid; /* Size of the rowid column at the end of zKey */
  3035. /* Make sure K is a string and make zKey point to K
  3036. */
  3037. assert( pNos->flags & MEM_Blob );
  3038. Stringify(pNos, encoding);
  3039. zKey = pNos->z;
  3040. nKey = pNos->n;
  3041. szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
  3042. len = nKey-szRowid;
  3043. /* Search for an entry in P1 where all but the last four bytes match K.
  3044. ** If there is no such entry, jump immediately to P2.
  3045. */
  3046. assert( pCx->deferredMoveto==0 );
  3047. pCx->cacheStatus = CACHE_STALE;
  3048. rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
  3049. if( rc!=SQLITE_OK ){
  3050. goto abort_due_to_error;
  3051. }
  3052. if( res<0 ){
  3053. rc = sqlite3BtreeNext(pCrsr, &res);
  3054. if( res ){
  3055. pc = pOp->p2 - 1;
  3056. break;
  3057. }
  3058. }
  3059. rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res);
  3060. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  3061. if( res>0 ){
  3062. pc = pOp->p2 - 1;
  3063. break;
  3064. }
  3065. /* At this point, pCrsr is pointing to an entry in P1 where all but
  3066. ** the final entry (the rowid) matches K. Check to see if the
  3067. ** final rowid column is different from R. If it equals R then jump
  3068. ** immediately to P2.
  3069. */
  3070. rc = sqlite3VdbeIdxRowid(pCrsr, &v);
  3071. if( rc!=SQLITE_OK ){
  3072. goto abort_due_to_error;
  3073. }
  3074. if( v==R ){
  3075. pc = pOp->p2 - 1;
  3076. break;
  3077. }
  3078. /* The final varint of the key is different from R. Push it onto
  3079. ** the stack. (The record number of an entry that violates a UNIQUE
  3080. ** constraint.)
  3081. */
  3082. pTos++;
  3083. pTos->u.i = v;
  3084. pTos->flags = MEM_Int;
  3085. }
  3086. break;
  3087. }
  3088. /* Opcode: NotExists P1 P2 *
  3089. **
  3090. ** Use the top of the stack as a integer key. If a record with that key
  3091. ** does not exist in table of P1, then jump to P2. If the record
  3092. ** does exist, then fall thru. The cursor is left pointing to the
  3093. ** record if it exists. The integer key is popped from the stack.
  3094. **
  3095. ** The difference between this operation and NotFound is that this
  3096. ** operation assumes the key is an integer and that P1 is a table whereas
  3097. ** NotFound assumes key is a blob constructed from MakeRecord and
  3098. ** P1 is an index.
  3099. **
  3100. ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
  3101. */
  3102. case OP_NotExists: { /* no-push */
  3103. int i = pOp->p1;
  3104. Cursor *pC;
  3105. BtCursor *pCrsr;
  3106. assert( pTos>=p->aStack );
  3107. assert( i>=0 && i<p->nCursor );
  3108. assert( p->apCsr[i]!=0 );
  3109. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  3110. int res;
  3111. u64 iKey;
  3112. assert( pTos->flags & MEM_Int );
  3113. assert( p->apCsr[i]->isTable );
  3114. iKey = intToKey(pTos->u.i);
  3115. rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
  3116. pC->lastRowid = pTos->u.i;
  3117. pC->rowidIsValid = res==0;
  3118. pC->nullRow = 0;
  3119. pC->cacheStatus = CACHE_STALE;
  3120. /* res might be uninitialized if rc!=SQLITE_OK. But if rc!=SQLITE_OK
  3121. ** processing is about to abort so we really do not care whether or not
  3122. ** the following jump is taken. (In other words, do not stress over
  3123. ** the error that valgrind sometimes shows on the next statement when
  3124. ** running ioerr.test and similar failure-recovery test scripts.) */
  3125. if( res!=0 ){
  3126. pc = pOp->p2 - 1;
  3127. pC->rowidIsValid = 0;
  3128. }
  3129. }
  3130. Release(pTos);
  3131. pTos--;
  3132. break;
  3133. }
  3134. /* Opcode: Sequence P1 * *
  3135. **
  3136. ** Push an integer onto the stack which is the next available
  3137. ** sequence number for cursor P1. The sequence number on the
  3138. ** cursor is incremented after the push.
  3139. */
  3140. case OP_Sequence: {
  3141. int i = pOp->p1;
  3142. assert( pTos>=p->aStack );
  3143. assert( i>=0 && i<p->nCursor );
  3144. assert( p->apCsr[i]!=0 );
  3145. pTos++;
  3146. pTos->u.i = p->apCsr[i]->seqCount++;
  3147. pTos->flags = MEM_Int;
  3148. break;
  3149. }
  3150. /* Opcode: NewRowid P1 P2 *
  3151. **
  3152. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  3153. ** The record number is not previously used as a key in the database
  3154. ** table that cursor P1 points to. The new record number is pushed
  3155. ** onto the stack.
  3156. **
  3157. ** If P2>0 then P2 is a memory cell that holds the largest previously
  3158. ** generated record number. No new record numbers are allowed to be less
  3159. ** than this value. When this value reaches its maximum, a SQLITE_FULL
  3160. ** error is generated. The P2 memory cell is updated with the generated
  3161. ** record number. This P2 mechanism is used to help implement the
  3162. ** AUTOINCREMENT feature.
  3163. */
  3164. case OP_NewRowid: {
  3165. int i = pOp->p1;
  3166. i64 v = 0;
  3167. Cursor *pC;
  3168. assert( i>=0 && i<p->nCursor );
  3169. assert( p->apCsr[i]!=0 );
  3170. if( (pC = p->apCsr[i])->pCursor==0 ){
  3171. /* The zero initialization above is all that is needed */
  3172. }else{
  3173. /* The next rowid or record number (different terms for the same
  3174. ** thing) is obtained in a two-step algorithm.
  3175. **
  3176. ** First we attempt to find the largest existing rowid and add one
  3177. ** to that. But if the largest existing rowid is already the maximum
  3178. ** positive integer, we have to fall through to the second
  3179. ** probabilistic algorithm
  3180. **
  3181. ** The second algorithm is to select a rowid at random and see if
  3182. ** it already exists in the table. If it does not exist, we have
  3183. ** succeeded. If the random rowid does exist, we select a new one
  3184. ** and try again, up to 1000 times.
  3185. **
  3186. ** For a table with less than 2 billion entries, the probability
  3187. ** of not finding a unused rowid is about 1.0e-300. This is a
  3188. ** non-zero probability, but it is still vanishingly small and should
  3189. ** never cause a problem. You are much, much more likely to have a
  3190. ** hardware failure than for this algorithm to fail.
  3191. **
  3192. ** The analysis in the previous paragraph assumes that you have a good
  3193. ** source of random numbers. Is a library function like lrand48()
  3194. ** good enough? Maybe. Maybe not. It's hard to know whether there
  3195. ** might be subtle bugs is some implementations of lrand48() that
  3196. ** could cause problems. To avoid uncertainty, SQLite uses its own
  3197. ** random number generator based on the RC4 algorithm.
  3198. **
  3199. ** To promote locality of reference for repetitive inserts, the
  3200. ** first few attempts at chosing a random rowid pick values just a little
  3201. ** larger than the previous rowid. This has been shown experimentally
  3202. ** to double the speed of the COPY operation.
  3203. */
  3204. int res, rx=SQLITE_OK, cnt;
  3205. i64 x;
  3206. cnt = 0;
  3207. if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
  3208. BTREE_INTKEY ){
  3209. rc = SQLITE_CORRUPT_BKPT;
  3210. goto abort_due_to_error;
  3211. }
  3212. assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
  3213. assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
  3214. #ifdef SQLITE_32BIT_ROWID
  3215. # define MAX_ROWID 0x7fffffff
  3216. #else
  3217. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  3218. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  3219. ** to provide the constant while making all compilers happy.
  3220. */
  3221. # define MAX_ROWID ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  3222. #endif
  3223. if( !pC->useRandomRowid ){
  3224. if( pC->nextRowidValid ){
  3225. v = pC->nextRowid;
  3226. }else{
  3227. rc = sqlite3BtreeLast(pC->pCursor, &res);
  3228. if( rc!=SQLITE_OK ){
  3229. goto abort_due_to_error;
  3230. }
  3231. if( res ){
  3232. v = 1;
  3233. }else{
  3234. sqlite3BtreeKeySize(pC->pCursor, &v);
  3235. v = keyToInt(v);
  3236. if( v==MAX_ROWID ){
  3237. pC->useRandomRowid = 1;
  3238. }else{
  3239. v++;
  3240. }
  3241. }
  3242. }
  3243. #ifndef SQLITE_OMIT_AUTOINCREMENT
  3244. if( pOp->p2 ){
  3245. Mem *pMem;
  3246. assert( pOp->p2>0 && pOp->p2<p->nMem ); /* P2 is a valid memory cell */
  3247. pMem = &p->aMem[pOp->p2];
  3248. sqlite3VdbeMemIntegerify(pMem);
  3249. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P2) holds an integer */
  3250. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  3251. rc = SQLITE_FULL;
  3252. goto abort_due_to_error;
  3253. }
  3254. if( v<pMem->u.i+1 ){
  3255. v = pMem->u.i + 1;
  3256. }
  3257. pMem->u.i = v;
  3258. }
  3259. #endif
  3260. if( v<MAX_ROWID ){
  3261. pC->nextRowidValid = 1;
  3262. pC->nextRowid = v+1;
  3263. }else{
  3264. pC->nextRowidValid = 0;
  3265. }
  3266. }
  3267. if( pC->useRandomRowid ){
  3268. assert( pOp->p2==0 ); /* SQLITE_FULL must have occurred prior to this */
  3269. v = db->priorNewRowid;
  3270. cnt = 0;
  3271. do{
  3272. if( v==0 || cnt>2 ){
  3273. sqlite3Randomness(sizeof(v), &v);
  3274. if( cnt<5 ) v &= 0xffffff;
  3275. }else{
  3276. unsigned char r;
  3277. sqlite3Randomness(1, &r);
  3278. v += r + 1;
  3279. }
  3280. if( v==0 ) continue;
  3281. x = intToKey(v);
  3282. rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
  3283. cnt++;
  3284. }while( cnt<1000 && rx==SQLITE_OK && res==0 );
  3285. db->priorNewRowid = v;
  3286. if( rx==SQLITE_OK && res==0 ){
  3287. rc = SQLITE_FULL;
  3288. goto abort_due_to_error;
  3289. }
  3290. }
  3291. pC->rowidIsValid = 0;
  3292. pC->deferredMoveto = 0;
  3293. pC->cacheStatus = CACHE_STALE;
  3294. }
  3295. pTos++;
  3296. pTos->u.i = v;
  3297. pTos->flags = MEM_Int;
  3298. break;
  3299. }
  3300. /* Opcode: Insert P1 P2 P3
  3301. **
  3302. ** Write an entry into the table of cursor P1. A new entry is
  3303. ** created if it doesn't already exist or the data for an existing
  3304. ** entry is overwritten. The data is the value on the top of the
  3305. ** stack. The key is the next value down on the stack. The key must
  3306. ** be an integer. The stack is popped twice by this instruction.
  3307. **
  3308. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  3309. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P2 is set,
  3310. ** then rowid is stored for subsequent return by the
  3311. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  3312. **
  3313. ** Parameter P3 may point to a string containing the table-name, or
  3314. ** may be NULL. If it is not NULL, then the update-hook
  3315. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  3316. **
  3317. ** This instruction only works on tables. The equivalent instruction
  3318. ** for indices is OP_IdxInsert.
  3319. */
  3320. case OP_Insert: { /* no-push */
  3321. Mem *pNos = &pTos[-1];
  3322. int i = pOp->p1;
  3323. Cursor *pC;
  3324. assert( pNos>=p->aStack );
  3325. assert( i>=0 && i<p->nCursor );
  3326. assert( p->apCsr[i]!=0 );
  3327. if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
  3328. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  3329. assert( pNos->flags & MEM_Int );
  3330. assert( pC->isTable );
  3331. iKey = intToKey(pNos->u.i);
  3332. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  3333. if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i;
  3334. if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){
  3335. pC->nextRowidValid = 0;
  3336. }
  3337. if( pTos->flags & MEM_Null ){
  3338. pTos->z = 0;
  3339. pTos->n = 0;
  3340. }else{
  3341. assert( pTos->flags & (MEM_Blob|MEM_Str) );
  3342. }
  3343. if( pC->pseudoTable ){
  3344. sqlite3_free(pC->pData);
  3345. pC->iKey = iKey;
  3346. pC->nData = pTos->n;
  3347. if( pTos->flags & MEM_Dyn ){
  3348. pC->pData = pTos->z;
  3349. pTos->flags = MEM_Null;
  3350. }else{
  3351. pC->pData = sqlite3_malloc( pC->nData+2 );
  3352. if( !pC->pData ) goto no_mem;
  3353. memcpy(pC->pData, pTos->z, pC->nData);
  3354. pC->pData[pC->nData] = 0;
  3355. pC->pData[pC->nData+1] = 0;
  3356. }
  3357. pC->nullRow = 0;
  3358. }else{
  3359. int nZero;
  3360. if( pTos->flags & MEM_Zero ){
  3361. nZero = pTos->u.i;
  3362. }else{
  3363. nZero = 0;
  3364. }
  3365. rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  3366. pTos->z, pTos->n, nZero,
  3367. pOp->p2 & OPFLAG_APPEND);
  3368. }
  3369. pC->rowidIsValid = 0;
  3370. pC->deferredMoveto = 0;
  3371. pC->cacheStatus = CACHE_STALE;
  3372. /* Invoke the update-hook if required. */
  3373. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
  3374. const char *zDb = db->aDb[pC->iDb].zName;
  3375. const char *zTbl = pOp->p3;
  3376. int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  3377. assert( pC->isTable );
  3378. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  3379. assert( pC->iDb>=0 );
  3380. }
  3381. }
  3382. popStack(&pTos, 2);
  3383. break;
  3384. }
  3385. /* Opcode: Delete P1 P2 P3
  3386. **
  3387. ** Delete the record at which the P1 cursor is currently pointing.
  3388. **
  3389. ** The cursor will be left pointing at either the next or the previous
  3390. ** record in the table. If it is left pointing at the next record, then
  3391. ** the next Next instruction will be a no-op. Hence it is OK to delete
  3392. ** a record from within an Next loop.
  3393. **
  3394. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  3395. ** incremented (otherwise not).
  3396. **
  3397. ** If P1 is a pseudo-table, then this instruction is a no-op.
  3398. */
  3399. case OP_Delete: { /* no-push */
  3400. int i = pOp->p1;
  3401. Cursor *pC;
  3402. assert( i>=0 && i<p->nCursor );
  3403. pC = p->apCsr[i];
  3404. assert( pC!=0 );
  3405. if( pC->pCursor!=0 ){
  3406. i64 iKey;
  3407. /* If the update-hook will be invoked, set iKey to the rowid of the
  3408. ** row being deleted.
  3409. */
  3410. if( db->xUpdateCallback && pOp->p3 ){
  3411. assert( pC->isTable );
  3412. if( pC->rowidIsValid ){
  3413. iKey = pC->lastRowid;
  3414. }else{
  3415. rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
  3416. if( rc ){
  3417. goto abort_due_to_error;
  3418. }
  3419. iKey = keyToInt(iKey);
  3420. }
  3421. }
  3422. rc = sqlite3VdbeCursorMoveto(pC);
  3423. if( rc ) goto abort_due_to_error;
  3424. rc = sqlite3BtreeDelete(pC->pCursor);
  3425. pC->nextRowidValid = 0;
  3426. pC->cacheStatus = CACHE_STALE;
  3427. /* Invoke the update-hook if required. */
  3428. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
  3429. const char *zDb = db->aDb[pC->iDb].zName;
  3430. const char *zTbl = pOp->p3;
  3431. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
  3432. assert( pC->iDb>=0 );
  3433. }
  3434. }
  3435. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  3436. break;
  3437. }
  3438. /* Opcode: ResetCount P1 * *
  3439. **
  3440. ** This opcode resets the VMs internal change counter to 0. If P1 is true,
  3441. ** then the value of the change counter is copied to the database handle
  3442. ** change counter (returned by subsequent calls to sqlite3_changes())
  3443. ** before it is reset. This is used by trigger programs.
  3444. */
  3445. case OP_ResetCount: { /* no-push */
  3446. if( pOp->p1 ){
  3447. sqlite3VdbeSetChanges(db, p->nChange);
  3448. }
  3449. p->nChange = 0;
  3450. break;
  3451. }
  3452. /* Opcode: RowData P1 * *
  3453. **
  3454. ** Push onto the stack the complete row data for cursor P1.
  3455. ** There is no interpretation of the data. It is just copied
  3456. ** onto the stack exactly as it is found in the database file.
  3457. **
  3458. ** If the cursor is not pointing to a valid row, a NULL is pushed
  3459. ** onto the stack.
  3460. */
  3461. /* Opcode: RowKey P1 * *
  3462. **
  3463. ** Push onto the stack the complete row key for cursor P1.
  3464. ** There is no interpretation of the key. It is just copied
  3465. ** onto the stack exactly as it is found in the database file.
  3466. **
  3467. ** If the cursor is not pointing to a valid row, a NULL is pushed
  3468. ** onto the stack.
  3469. */
  3470. case OP_RowKey:
  3471. case OP_RowData: {
  3472. int i = pOp->p1;
  3473. Cursor *pC;
  3474. u32 n;
  3475. /* Note that RowKey and RowData are really exactly the same instruction */
  3476. pTos++;
  3477. assert( i>=0 && i<p->nCursor );
  3478. pC = p->apCsr[i];
  3479. assert( pC->isTable || pOp->opcode==OP_RowKey );
  3480. assert( pC->isIndex || pOp->opcode==OP_RowData );
  3481. assert( pC!=0 );
  3482. if( pC->nullRow ){
  3483. pTos->flags = MEM_Null;
  3484. }else if( pC->pCursor!=0 ){
  3485. BtCursor *pCrsr = pC->pCursor;
  3486. rc = sqlite3VdbeCursorMoveto(pC);
  3487. if( rc ) goto abort_due_to_error;
  3488. if( pC->nullRow ){
  3489. pTos->flags = MEM_Null;
  3490. break;
  3491. }else if( pC->isIndex ){
  3492. i64 n64;
  3493. assert( !pC->isTable );
  3494. sqlite3BtreeKeySize(pCrsr, &n64);
  3495. if( n64>SQLITE_MAX_LENGTH ){
  3496. goto too_big;
  3497. }
  3498. n = n64;
  3499. }else{
  3500. sqlite3BtreeDataSize(pCrsr, &n);
  3501. }
  3502. if( n>SQLITE_MAX_LENGTH ){
  3503. goto too_big;
  3504. }
  3505. pTos->n = n;
  3506. if( n<=NBFS ){
  3507. pTos->flags = MEM_Blob | MEM_Short;
  3508. pTos->z = pTos->zShort;
  3509. }else{
  3510. char *z = sqlite3_malloc( n );
  3511. if( z==0 ) goto no_mem;
  3512. pTos->flags = MEM_Blob | MEM_Dyn;
  3513. pTos->xDel = 0;
  3514. pTos->z = z;
  3515. }
  3516. if( pC->isIndex ){
  3517. rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
  3518. }else{
  3519. rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z);
  3520. }
  3521. }else if( pC->pseudoTable ){
  3522. pTos->n = pC->nData;
  3523. assert( pC->nData<=SQLITE_MAX_LENGTH );
  3524. pTos->z = pC->pData;
  3525. pTos->flags = MEM_Blob|MEM_Ephem;
  3526. }else{
  3527. pTos->flags = MEM_Null;
  3528. }
  3529. pTos->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  3530. break;
  3531. }
  3532. /* Opcode: Rowid P1 * *
  3533. **
  3534. ** Push onto the stack an integer which is the key of the table entry that
  3535. ** P1 is currently point to.
  3536. */
  3537. case OP_Rowid: {
  3538. int i = pOp->p1;
  3539. Cursor *pC;
  3540. i64 v;
  3541. assert( i>=0 && i<p->nCursor );
  3542. pC = p->apCsr[i];
  3543. assert( pC!=0 );
  3544. rc = sqlite3VdbeCursorMoveto(pC);
  3545. if( rc ) goto abort_due_to_error;
  3546. pTos++;
  3547. if( pC->rowidIsValid ){
  3548. v = pC->lastRowid;
  3549. }else if( pC->pseudoTable ){
  3550. v = keyToInt(pC->iKey);
  3551. }else if( pC->nullRow || pC->pCursor==0 ){
  3552. pTos->flags = MEM_Null;
  3553. break;
  3554. }else{
  3555. assert( pC->pCursor!=0 );
  3556. sqlite3BtreeKeySize(pC->pCursor, &v);
  3557. v = keyToInt(v);
  3558. }
  3559. pTos->u.i = v;
  3560. pTos->flags = MEM_Int;
  3561. break;
  3562. }
  3563. /* Opcode: NullRow P1 * *
  3564. **
  3565. ** Move the cursor P1 to a null row. Any OP_Column operations
  3566. ** that occur while the cursor is on the null row will always push
  3567. ** a NULL onto the stack.
  3568. */
  3569. case OP_NullRow: { /* no-push */
  3570. int i = pOp->p1;
  3571. Cursor *pC;
  3572. assert( i>=0 && i<p->nCursor );
  3573. pC = p->apCsr[i];
  3574. assert( pC!=0 );
  3575. pC->nullRow = 1;
  3576. pC->rowidIsValid = 0;
  3577. break;
  3578. }
  3579. /* Opcode: Last P1 P2 *
  3580. **
  3581. ** The next use of the Rowid or Column or Next instruction for P1
  3582. ** will refer to the last entry in the database table or index.
  3583. ** If the table or index is empty and P2>0, then jump immediately to P2.
  3584. ** If P2 is 0 or if the table or index is not empty, fall through
  3585. ** to the following instruction.
  3586. */
  3587. case OP_Last: { /* no-push */
  3588. int i = pOp->p1;
  3589. Cursor *pC;
  3590. BtCursor *pCrsr;
  3591. assert( i>=0 && i<p->nCursor );
  3592. pC = p->apCsr[i];
  3593. assert( pC!=0 );
  3594. if( (pCrsr = pC->pCursor)!=0 ){
  3595. int res;
  3596. rc = sqlite3BtreeLast(pCrsr, &res);
  3597. pC->nullRow = res;
  3598. pC->deferredMoveto = 0;
  3599. pC->cacheStatus = CACHE_STALE;
  3600. if( res && pOp->p2>0 ){
  3601. pc = pOp->p2 - 1;
  3602. }
  3603. }else{
  3604. pC->nullRow = 0;
  3605. }
  3606. break;
  3607. }
  3608. /* Opcode: Sort P1 P2 *
  3609. **
  3610. ** This opcode does exactly the same thing as OP_Rewind except that
  3611. ** it increments an undocumented global variable used for testing.
  3612. **
  3613. ** Sorting is accomplished by writing records into a sorting index,
  3614. ** then rewinding that index and playing it back from beginning to
  3615. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  3616. ** rewinding so that the global variable will be incremented and
  3617. ** regression tests can determine whether or not the optimizer is
  3618. ** correctly optimizing out sorts.
  3619. */
  3620. case OP_Sort: { /* no-push */
  3621. #ifdef SQLITE_TEST
  3622. sqlite3_sort_count++;
  3623. sqlite3_search_count--;
  3624. #endif
  3625. /* Fall through into OP_Rewind */
  3626. }
  3627. /* Opcode: Rewind P1 P2 *
  3628. **
  3629. ** The next use of the Rowid or Column or Next instruction for P1
  3630. ** will refer to the first entry in the database table or index.
  3631. ** If the table or index is empty and P2>0, then jump immediately to P2.
  3632. ** If P2 is 0 or if the table or index is not empty, fall through
  3633. ** to the following instruction.
  3634. */
  3635. case OP_Rewind: { /* no-push */
  3636. int i = pOp->p1;
  3637. Cursor *pC;
  3638. BtCursor *pCrsr;
  3639. int res;
  3640. assert( i>=0 && i<p->nCursor );
  3641. pC = p->apCsr[i];
  3642. assert( pC!=0 );
  3643. if( (pCrsr = pC->pCursor)!=0 ){
  3644. rc = sqlite3BtreeFirst(pCrsr, &res);
  3645. pC->atFirst = res==0;
  3646. pC->deferredMoveto = 0;
  3647. pC->cacheStatus = CACHE_STALE;
  3648. }else{
  3649. res = 1;
  3650. }
  3651. pC->nullRow = res;
  3652. if( res && pOp->p2>0 ){
  3653. pc = pOp->p2 - 1;
  3654. }
  3655. break;
  3656. }
  3657. /* Opcode: Next P1 P2 *
  3658. **
  3659. ** Advance cursor P1 so that it points to the next key/data pair in its
  3660. ** table or index. If there are no more key/value pairs then fall through
  3661. ** to the following instruction. But if the cursor advance was successful,
  3662. ** jump immediately to P2.
  3663. **
  3664. ** See also: Prev
  3665. */
  3666. /* Opcode: Prev P1 P2 *
  3667. **
  3668. ** Back up cursor P1 so that it points to the previous key/data pair in its
  3669. ** table or index. If there is no previous key/value pairs then fall through
  3670. ** to the following instruction. But if the cursor backup was successful,
  3671. ** jump immediately to P2.
  3672. */
  3673. case OP_Prev: /* no-push */
  3674. case OP_Next: { /* no-push */
  3675. Cursor *pC;
  3676. BtCursor *pCrsr;
  3677. CHECK_FOR_INTERRUPT;
  3678. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  3679. pC = p->apCsr[pOp->p1];
  3680. if( pC==0 ){
  3681. break; /* See ticket #2273 */
  3682. }
  3683. if( (pCrsr = pC->pCursor)!=0 ){
  3684. int res;
  3685. if( pC->nullRow ){
  3686. res = 1;
  3687. }else{
  3688. assert( pC->deferredMoveto==0 );
  3689. rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
  3690. sqlite3BtreePrevious(pCrsr, &res);
  3691. pC->nullRow = res;
  3692. pC->cacheStatus = CACHE_STALE;
  3693. }
  3694. if( res==0 ){
  3695. pc = pOp->p2 - 1;
  3696. #ifdef SQLITE_TEST
  3697. sqlite3_search_count++;
  3698. #endif
  3699. }
  3700. }else{
  3701. pC->nullRow = 1;
  3702. }
  3703. pC->rowidIsValid = 0;
  3704. break;
  3705. }
  3706. /* Opcode: IdxInsert P1 P2 *
  3707. **
  3708. ** The top of the stack holds a SQL index key made using either the
  3709. ** MakeIdxRec or MakeRecord instructions. This opcode writes that key
  3710. ** into the index P1. Data for the entry is nil.
  3711. **
  3712. ** P2 is a flag that provides a hint to the b-tree layer that this
  3713. ** insert is likely to be an append.
  3714. **
  3715. ** This instruction only works for indices. The equivalent instruction
  3716. ** for tables is OP_Insert.
  3717. */
  3718. case OP_IdxInsert: { /* no-push */
  3719. int i = pOp->p1;
  3720. Cursor *pC;
  3721. BtCursor *pCrsr;
  3722. assert( pTos>=p->aStack );
  3723. assert( i>=0 && i<p->nCursor );
  3724. assert( p->apCsr[i]!=0 );
  3725. assert( pTos->flags & MEM_Blob );
  3726. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  3727. assert( pC->isTable==0 );
  3728. rc = ExpandBlob(pTos);
  3729. if( rc==SQLITE_OK ){
  3730. int nKey = pTos->n;
  3731. const char *zKey = pTos->z;
  3732. rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2);
  3733. assert( pC->deferredMoveto==0 );
  3734. pC->cacheStatus = CACHE_STALE;
  3735. }
  3736. }
  3737. Release(pTos);
  3738. pTos--;
  3739. break;
  3740. }
  3741. /* Opcode: IdxDelete P1 * *
  3742. **
  3743. ** The top of the stack is an index key built using the either the
  3744. ** MakeIdxRec or MakeRecord opcodes.
  3745. ** This opcode removes that entry from the index.
  3746. */
  3747. case OP_IdxDelete: { /* no-push */
  3748. int i = pOp->p1;
  3749. Cursor *pC;
  3750. BtCursor *pCrsr;
  3751. assert( pTos>=p->aStack );
  3752. assert( pTos->flags & MEM_Blob );
  3753. assert( i>=0 && i<p->nCursor );
  3754. assert( p->apCsr[i]!=0 );
  3755. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  3756. int res;
  3757. rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res);
  3758. if( rc==SQLITE_OK && res==0 ){
  3759. rc = sqlite3BtreeDelete(pCrsr);
  3760. }
  3761. assert( pC->deferredMoveto==0 );
  3762. pC->cacheStatus = CACHE_STALE;
  3763. }
  3764. Release(pTos);
  3765. pTos--;
  3766. break;
  3767. }
  3768. /* Opcode: IdxRowid P1 * *
  3769. **
  3770. ** Push onto the stack an integer which is the last entry in the record at
  3771. ** the end of the index key pointed to by cursor P1. This integer should be
  3772. ** the rowid of the table entry to which this index entry points.
  3773. **
  3774. ** See also: Rowid, MakeIdxRec.
  3775. */
  3776. case OP_IdxRowid: {
  3777. int i = pOp->p1;
  3778. BtCursor *pCrsr;
  3779. Cursor *pC;
  3780. assert( i>=0 && i<p->nCursor );
  3781. assert( p->apCsr[i]!=0 );
  3782. pTos++;
  3783. pTos->flags = MEM_Null;
  3784. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  3785. i64 rowid;
  3786. assert( pC->deferredMoveto==0 );
  3787. assert( pC->isTable==0 );
  3788. if( pC->nullRow ){
  3789. pTos->flags = MEM_Null;
  3790. }else{
  3791. rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
  3792. if( rc!=SQLITE_OK ){
  3793. goto abort_due_to_error;
  3794. }
  3795. pTos->flags = MEM_Int;
  3796. pTos->u.i = rowid;
  3797. }
  3798. }
  3799. break;
  3800. }
  3801. /* Opcode: IdxGT P1 P2 *
  3802. **
  3803. ** The top of the stack is an index entry that omits the ROWID. Compare
  3804. ** the top of stack against the index that P1 is currently pointing to.
  3805. ** Ignore the ROWID on the P1 index.
  3806. **
  3807. ** The top of the stack might have fewer columns that P1.
  3808. **
  3809. ** If the P1 index entry is greater than the top of the stack
  3810. ** then jump to P2. Otherwise fall through to the next instruction.
  3811. ** In either case, the stack is popped once.
  3812. */
  3813. /* Opcode: IdxGE P1 P2 P3
  3814. **
  3815. ** The top of the stack is an index entry that omits the ROWID. Compare
  3816. ** the top of stack against the index that P1 is currently pointing to.
  3817. ** Ignore the ROWID on the P1 index.
  3818. **
  3819. ** If the P1 index entry is greater than or equal to the top of the stack
  3820. ** then jump to P2. Otherwise fall through to the next instruction.
  3821. ** In either case, the stack is popped once.
  3822. **
  3823. ** If P3 is the "+" string (or any other non-NULL string) then the
  3824. ** index taken from the top of the stack is temporarily increased by
  3825. ** an epsilon prior to the comparison. This make the opcode work
  3826. ** like IdxGT except that if the key from the stack is a prefix of
  3827. ** the key in the cursor, the result is false whereas it would be
  3828. ** true with IdxGT.
  3829. */
  3830. /* Opcode: IdxLT P1 P2 P3
  3831. **
  3832. ** The top of the stack is an index entry that omits the ROWID. Compare
  3833. ** the top of stack against the index that P1 is currently pointing to.
  3834. ** Ignore the ROWID on the P1 index.
  3835. **
  3836. ** If the P1 index entry is less than the top of the stack
  3837. ** then jump to P2. Otherwise fall through to the next instruction.
  3838. ** In either case, the stack is popped once.
  3839. **
  3840. ** If P3 is the "+" string (or any other non-NULL string) then the
  3841. ** index taken from the top of the stack is temporarily increased by
  3842. ** an epsilon prior to the comparison. This makes the opcode work
  3843. ** like IdxLE.
  3844. */
  3845. case OP_IdxLT: /* no-push */
  3846. case OP_IdxGT: /* no-push */
  3847. case OP_IdxGE: { /* no-push */
  3848. int i= pOp->p1;
  3849. Cursor *pC;
  3850. assert( i>=0 && i<p->nCursor );
  3851. assert( p->apCsr[i]!=0 );
  3852. assert( pTos>=p->aStack );
  3853. if( (pC = p->apCsr[i])->pCursor!=0 ){
  3854. int res;
  3855. assert( pTos->flags & MEM_Blob ); /* Created using OP_MakeRecord */
  3856. assert( pC->deferredMoveto==0 );
  3857. ExpandBlob(pTos);
  3858. *pC->pIncrKey = pOp->p3!=0;
  3859. assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
  3860. rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
  3861. *pC->pIncrKey = 0;
  3862. if( rc!=SQLITE_OK ){
  3863. break;
  3864. }
  3865. if( pOp->opcode==OP_IdxLT ){
  3866. res = -res;
  3867. }else if( pOp->opcode==OP_IdxGE ){
  3868. res++;
  3869. }
  3870. if( res>0 ){
  3871. pc = pOp->p2 - 1 ;
  3872. }
  3873. }
  3874. Release(pTos);
  3875. pTos--;
  3876. break;
  3877. }
  3878. /* Opcode: Destroy P1 P2 *
  3879. **
  3880. ** Delete an entire database table or index whose root page in the database
  3881. ** file is given by P1.
  3882. **
  3883. ** The table being destroyed is in the main database file if P2==0. If
  3884. ** P2==1 then the table to be clear is in the auxiliary database file
  3885. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  3886. **
  3887. ** If AUTOVACUUM is enabled then it is possible that another root page
  3888. ** might be moved into the newly deleted root page in order to keep all
  3889. ** root pages contiguous at the beginning of the database. The former
  3890. ** value of the root page that moved - its value before the move occurred -
  3891. ** is pushed onto the stack. If no page movement was required (because
  3892. ** the table being dropped was already the last one in the database) then
  3893. ** a zero is pushed onto the stack. If AUTOVACUUM is disabled
  3894. ** then a zero is pushed onto the stack.
  3895. **
  3896. ** See also: Clear
  3897. */
  3898. case OP_Destroy: {
  3899. int iMoved;
  3900. int iCnt;
  3901. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3902. Vdbe *pVdbe;
  3903. iCnt = 0;
  3904. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  3905. if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
  3906. iCnt++;
  3907. }
  3908. }
  3909. #else
  3910. iCnt = db->activeVdbeCnt;
  3911. #endif
  3912. if( iCnt>1 ){
  3913. rc = SQLITE_LOCKED;
  3914. p->errorAction = OE_Abort;
  3915. }else{
  3916. assert( iCnt==1 );
  3917. assert( (p->btreeMask & (1<<pOp->p2))!=0 );
  3918. rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
  3919. pTos++;
  3920. pTos->flags = MEM_Int;
  3921. pTos->u.i = iMoved;
  3922. #ifndef SQLITE_OMIT_AUTOVACUUM
  3923. if( rc==SQLITE_OK && iMoved!=0 ){
  3924. sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
  3925. }
  3926. #endif
  3927. }
  3928. break;
  3929. }
  3930. /* Opcode: Clear P1 P2 *
  3931. **
  3932. ** Delete all contents of the database table or index whose root page
  3933. ** in the database file is given by P1. But, unlike Destroy, do not
  3934. ** remove the table or index from the database file.
  3935. **
  3936. ** The table being clear is in the main database file if P2==0. If
  3937. ** P2==1 then the table to be clear is in the auxiliary database file
  3938. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  3939. **
  3940. ** See also: Destroy
  3941. */
  3942. case OP_Clear: { /* no-push */
  3943. /* For consistency with the way other features of SQLite operate
  3944. ** with a truncate, we will also skip the update callback.
  3945. */
  3946. #if 0
  3947. Btree *pBt = db->aDb[pOp->p2].pBt;
  3948. if( db->xUpdateCallback && pOp->p3 ){
  3949. const char *zDb = db->aDb[pOp->p2].zName;
  3950. const char *zTbl = pOp->p3;
  3951. BtCursor *pCur = 0;
  3952. int fin = 0;
  3953. rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
  3954. if( rc!=SQLITE_OK ){
  3955. goto abort_due_to_error;
  3956. }
  3957. for(
  3958. rc=sqlite3BtreeFirst(pCur, &fin);
  3959. rc==SQLITE_OK && !fin;
  3960. rc=sqlite3BtreeNext(pCur, &fin)
  3961. ){
  3962. i64 iKey;
  3963. rc = sqlite3BtreeKeySize(pCur, &iKey);
  3964. if( rc ){
  3965. break;
  3966. }
  3967. iKey = keyToInt(iKey);
  3968. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
  3969. }
  3970. sqlite3BtreeCloseCursor(pCur);
  3971. if( rc!=SQLITE_OK ){
  3972. goto abort_due_to_error;
  3973. }
  3974. }
  3975. #endif
  3976. assert( (p->btreeMask & (1<<pOp->p2))!=0 );
  3977. rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
  3978. break;
  3979. }
  3980. /* Opcode: CreateTable P1 * *
  3981. **
  3982. ** Allocate a new table in the main database file if P2==0 or in the
  3983. ** auxiliary database file if P2==1. Push the page number
  3984. ** for the root page of the new table onto the stack.
  3985. **
  3986. ** The difference between a table and an index is this: A table must
  3987. ** have a 4-byte integer key and can have arbitrary data. An index
  3988. ** has an arbitrary key but no data.
  3989. **
  3990. ** See also: CreateIndex
  3991. */
  3992. /* Opcode: CreateIndex P1 * *
  3993. **
  3994. ** Allocate a new index in the main database file if P2==0 or in the
  3995. ** auxiliary database file if P2==1. Push the page number of the
  3996. ** root page of the new index onto the stack.
  3997. **
  3998. ** See documentation on OP_CreateTable for additional information.
  3999. */
  4000. case OP_CreateIndex:
  4001. case OP_CreateTable: {
  4002. int pgno;
  4003. int flags;
  4004. Db *pDb;
  4005. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  4006. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  4007. pDb = &db->aDb[pOp->p1];
  4008. assert( pDb->pBt!=0 );
  4009. if( pOp->opcode==OP_CreateTable ){
  4010. /* flags = BTREE_INTKEY; */
  4011. flags = BTREE_LEAFDATA|BTREE_INTKEY;
  4012. }else{
  4013. flags = BTREE_ZERODATA;
  4014. }
  4015. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  4016. pTos++;
  4017. if( rc==SQLITE_OK ){
  4018. pTos->u.i = pgno;
  4019. pTos->flags = MEM_Int;
  4020. }else{
  4021. pTos->flags = MEM_Null;
  4022. }
  4023. break;
  4024. }
  4025. /* Opcode: ParseSchema P1 P2 P3
  4026. **
  4027. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  4028. ** that match the WHERE clause P3. P2 is the "force" flag. Always do
  4029. ** the parsing if P2 is true. If P2 is false, then this routine is a
  4030. ** no-op if the schema is not currently loaded. In other words, if P2
  4031. ** is false, the SQLITE_MASTER table is only parsed if the rest of the
  4032. ** schema is already loaded into the symbol table.
  4033. **
  4034. ** This opcode invokes the parser to create a new virtual machine,
  4035. ** then runs the new virtual machine. It is thus a reentrant opcode.
  4036. */
  4037. case OP_ParseSchema: { /* no-push */
  4038. char *zSql;
  4039. int iDb = pOp->p1;
  4040. const char *zMaster;
  4041. InitData initData;
  4042. assert( iDb>=0 && iDb<db->nDb );
  4043. if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
  4044. break;
  4045. }
  4046. zMaster = SCHEMA_TABLE(iDb);
  4047. initData.db = db;
  4048. initData.iDb = pOp->p1;
  4049. initData.pzErrMsg = &p->zErrMsg;
  4050. zSql = sqlite3MPrintf(db,
  4051. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
  4052. db->aDb[iDb].zName, zMaster, pOp->p3);
  4053. if( zSql==0 ) goto no_mem;
  4054. sqlite3SafetyOff(db);
  4055. assert( db->init.busy==0 );
  4056. db->init.busy = 1;
  4057. assert( !db->mallocFailed );
  4058. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  4059. if( rc==SQLITE_ABORT ) rc = initData.rc;
  4060. sqlite3_free(zSql);
  4061. db->init.busy = 0;
  4062. sqlite3SafetyOn(db);
  4063. if( rc==SQLITE_NOMEM ){
  4064. goto no_mem;
  4065. }
  4066. break;
  4067. }
  4068. #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
  4069. /* Opcode: LoadAnalysis P1 * *
  4070. **
  4071. ** Read the sqlite_stat1 table for database P1 and load the content
  4072. ** of that table into the internal index hash table. This will cause
  4073. ** the analysis to be used when preparing all subsequent queries.
  4074. */
  4075. case OP_LoadAnalysis: { /* no-push */
  4076. int iDb = pOp->p1;
  4077. assert( iDb>=0 && iDb<db->nDb );
  4078. rc = sqlite3AnalysisLoad(db, iDb);
  4079. break;
  4080. }
  4081. #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */
  4082. /* Opcode: DropTable P1 * P3
  4083. **
  4084. ** Remove the internal (in-memory) data structures that describe
  4085. ** the table named P3 in database P1. This is called after a table
  4086. ** is dropped in order to keep the internal representation of the
  4087. ** schema consistent with what is on disk.
  4088. */
  4089. case OP_DropTable: { /* no-push */
  4090. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
  4091. break;
  4092. }
  4093. /* Opcode: DropIndex P1 * P3
  4094. **
  4095. ** Remove the internal (in-memory) data structures that describe
  4096. ** the index named P3 in database P1. This is called after an index
  4097. ** is dropped in order to keep the internal representation of the
  4098. ** schema consistent with what is on disk.
  4099. */
  4100. case OP_DropIndex: { /* no-push */
  4101. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
  4102. break;
  4103. }
  4104. /* Opcode: DropTrigger P1 * P3
  4105. **
  4106. ** Remove the internal (in-memory) data structures that describe
  4107. ** the trigger named P3 in database P1. This is called after a trigger
  4108. ** is dropped in order to keep the internal representation of the
  4109. ** schema consistent with what is on disk.
  4110. */
  4111. case OP_DropTrigger: { /* no-push */
  4112. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
  4113. break;
  4114. }
  4115. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  4116. /* Opcode: IntegrityCk P1 P2 *
  4117. **
  4118. ** Do an analysis of the currently open database. Push onto the
  4119. ** stack the text of an error message describing any problems.
  4120. ** If no problems are found, push a NULL onto the stack.
  4121. **
  4122. ** P1 is the address of a memory cell that contains the maximum
  4123. ** number of allowed errors. At most mem[P1] errors will be reported.
  4124. ** In other words, the analysis stops as soon as mem[P1] errors are
  4125. ** seen. Mem[P1] is updated with the number of errors remaining.
  4126. **
  4127. ** The root page numbers of all tables in the database are integer
  4128. ** values on the stack. This opcode pulls as many integers as it
  4129. ** can off of the stack and uses those numbers as the root pages.
  4130. **
  4131. ** If P2 is not zero, the check is done on the auxiliary database
  4132. ** file, not the main database file.
  4133. **
  4134. ** This opcode is used to implement the integrity_check pragma.
  4135. */
  4136. case OP_IntegrityCk: {
  4137. int nRoot;
  4138. int *aRoot;
  4139. int j;
  4140. int nErr;
  4141. char *z;
  4142. Mem *pnErr;
  4143. for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
  4144. if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
  4145. }
  4146. assert( nRoot>0 );
  4147. aRoot = sqlite3_malloc( sizeof(int)*(nRoot+1) );
  4148. if( aRoot==0 ) goto no_mem;
  4149. j = pOp->p1;
  4150. assert( j>=0 && j<p->nMem );
  4151. pnErr = &p->aMem[j];
  4152. assert( (pnErr->flags & MEM_Int)!=0 );
  4153. for(j=0; j<nRoot; j++){
  4154. aRoot[j] = (pTos-j)->u.i;
  4155. }
  4156. aRoot[j] = 0;
  4157. popStack(&pTos, nRoot);
  4158. pTos++;
  4159. assert( pOp->p2>=0 && pOp->p2<db->nDb );
  4160. assert( (p->btreeMask & (1<<pOp->p2))!=0 );
  4161. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
  4162. pnErr->u.i, &nErr);
  4163. pnErr->u.i -= nErr;
  4164. if( nErr==0 ){
  4165. assert( z==0 );
  4166. pTos->flags = MEM_Null;
  4167. }else{
  4168. pTos->z = z;
  4169. pTos->n = strlen(z);
  4170. pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
  4171. pTos->xDel = 0;
  4172. }
  4173. pTos->enc = SQLITE_UTF8;
  4174. sqlite3VdbeChangeEncoding(pTos, encoding);
  4175. sqlite3_free(aRoot);
  4176. break;
  4177. }
  4178. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  4179. /* Opcode: FifoWrite * * *
  4180. **
  4181. ** Write the integer on the top of the stack
  4182. ** into the Fifo.
  4183. */
  4184. case OP_FifoWrite: { /* no-push */
  4185. assert( pTos>=p->aStack );
  4186. sqlite3VdbeMemIntegerify(pTos);
  4187. if( sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i)==SQLITE_NOMEM ){
  4188. goto no_mem;
  4189. }
  4190. assert( (pTos->flags & MEM_Dyn)==0 );
  4191. pTos--;
  4192. break;
  4193. }
  4194. /* Opcode: FifoRead * P2 *
  4195. **
  4196. ** Attempt to read a single integer from the Fifo
  4197. ** and push it onto the stack. If the Fifo is empty
  4198. ** push nothing but instead jump to P2.
  4199. */
  4200. case OP_FifoRead: {
  4201. i64 v;
  4202. CHECK_FOR_INTERRUPT;
  4203. if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
  4204. pc = pOp->p2 - 1;
  4205. }else{
  4206. pTos++;
  4207. pTos->u.i = v;
  4208. pTos->flags = MEM_Int;
  4209. }
  4210. break;
  4211. }
  4212. #ifndef SQLITE_OMIT_TRIGGER
  4213. /* Opcode: ContextPush * * *
  4214. **
  4215. ** Save the current Vdbe context such that it can be restored by a ContextPop
  4216. ** opcode. The context stores the last insert row id, the last statement change
  4217. ** count, and the current statement change count.
  4218. */
  4219. case OP_ContextPush: { /* no-push */
  4220. int i = p->contextStackTop++;
  4221. Context *pContext;
  4222. assert( i>=0 );
  4223. /* FIX ME: This should be allocated as part of the vdbe at compile-time */
  4224. if( i>=p->contextStackDepth ){
  4225. p->contextStackDepth = i+1;
  4226. p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
  4227. sizeof(Context)*(i+1));
  4228. if( p->contextStack==0 ) goto no_mem;
  4229. }
  4230. pContext = &p->contextStack[i];
  4231. pContext->lastRowid = db->lastRowid;
  4232. pContext->nChange = p->nChange;
  4233. pContext->sFifo = p->sFifo;
  4234. sqlite3VdbeFifoInit(&p->sFifo);
  4235. break;
  4236. }
  4237. /* Opcode: ContextPop * * *
  4238. **
  4239. ** Restore the Vdbe context to the state it was in when contextPush was last
  4240. ** executed. The context stores the last insert row id, the last statement
  4241. ** change count, and the current statement change count.
  4242. */
  4243. case OP_ContextPop: { /* no-push */
  4244. Context *pContext = &p->contextStack[--p->contextStackTop];
  4245. assert( p->contextStackTop>=0 );
  4246. db->lastRowid = pContext->lastRowid;
  4247. p->nChange = pContext->nChange;
  4248. sqlite3VdbeFifoClear(&p->sFifo);
  4249. p->sFifo = pContext->sFifo;
  4250. break;
  4251. }
  4252. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  4253. /* Opcode: MemStore P1 P2 *
  4254. **
  4255. ** Write the top of the stack into memory location P1.
  4256. ** P1 should be a small integer since space is allocated
  4257. ** for all memory locations between 0 and P1 inclusive.
  4258. **
  4259. ** After the data is stored in the memory location, the
  4260. ** stack is popped once if P2 is 1. If P2 is zero, then
  4261. ** the original data remains on the stack.
  4262. */
  4263. case OP_MemStore: { /* no-push */
  4264. assert( pTos>=p->aStack );
  4265. assert( pOp->p1>=0 && pOp->p1<p->nMem );
  4266. rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
  4267. pTos--;
  4268. /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
  4269. ** restore the top of the stack to its original value.
  4270. */
  4271. if( pOp->p2 ){
  4272. break;
  4273. }
  4274. }
  4275. /* Opcode: MemLoad P1 * *
  4276. **
  4277. ** Push a copy of the value in memory location P1 onto the stack.
  4278. **
  4279. ** If the value is a string, then the value pushed is a pointer to
  4280. ** the string that is stored in the memory location. If the memory
  4281. ** location is subsequently changed (using OP_MemStore) then the
  4282. ** value pushed onto the stack will change too.
  4283. */
  4284. case OP_MemLoad: {
  4285. int i = pOp->p1;
  4286. assert( i>=0 && i<p->nMem );
  4287. pTos++;
  4288. sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
  4289. break;
  4290. }
  4291. #ifndef SQLITE_OMIT_AUTOINCREMENT
  4292. /* Opcode: MemMax P1 * *
  4293. **
  4294. ** Set the value of memory cell P1 to the maximum of its current value
  4295. ** and the value on the top of the stack. The stack is unchanged.
  4296. **
  4297. ** This instruction throws an error if the memory cell is not initially
  4298. ** an integer.
  4299. */
  4300. case OP_MemMax: { /* no-push */
  4301. int i = pOp->p1;
  4302. Mem *pMem;
  4303. assert( pTos>=p->aStack );
  4304. assert( i>=0 && i<p->nMem );
  4305. pMem = &p->aMem[i];
  4306. sqlite3VdbeMemIntegerify(pMem);
  4307. sqlite3VdbeMemIntegerify(pTos);
  4308. if( pMem->u.i<pTos->u.i){
  4309. pMem->u.i = pTos->u.i;
  4310. }
  4311. break;
  4312. }
  4313. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  4314. /* Opcode: MemIncr P1 P2 *
  4315. **
  4316. ** Increment the integer valued memory cell P2 by the value in P1.
  4317. **
  4318. ** It is illegal to use this instruction on a memory cell that does
  4319. ** not contain an integer. An assertion fault will result if you try.
  4320. */
  4321. case OP_MemIncr: { /* no-push */
  4322. int i = pOp->p2;
  4323. Mem *pMem;
  4324. assert( i>=0 && i<p->nMem );
  4325. pMem = &p->aMem[i];
  4326. assert( pMem->flags==MEM_Int );
  4327. pMem->u.i += pOp->p1;
  4328. break;
  4329. }
  4330. /* Opcode: IfMemPos P1 P2 *
  4331. **
  4332. ** If the value of memory cell P1 is 1 or greater, jump to P2.
  4333. **
  4334. ** It is illegal to use this instruction on a memory cell that does
  4335. ** not contain an integer. An assertion fault will result if you try.
  4336. */
  4337. case OP_IfMemPos: { /* no-push */
  4338. int i = pOp->p1;
  4339. Mem *pMem;
  4340. assert( i>=0 && i<p->nMem );
  4341. pMem = &p->aMem[i];
  4342. assert( pMem->flags==MEM_Int );
  4343. if( pMem->u.i>0 ){
  4344. pc = pOp->p2 - 1;
  4345. }
  4346. break;
  4347. }
  4348. /* Opcode: IfMemNeg P1 P2 *
  4349. **
  4350. ** If the value of memory cell P1 is less than zero, jump to P2.
  4351. **
  4352. ** It is illegal to use this instruction on a memory cell that does
  4353. ** not contain an integer. An assertion fault will result if you try.
  4354. */
  4355. case OP_IfMemNeg: { /* no-push */
  4356. int i = pOp->p1;
  4357. Mem *pMem;
  4358. assert( i>=0 && i<p->nMem );
  4359. pMem = &p->aMem[i];
  4360. assert( pMem->flags==MEM_Int );
  4361. if( pMem->u.i<0 ){
  4362. pc = pOp->p2 - 1;
  4363. }
  4364. break;
  4365. }
  4366. /* Opcode: IfMemZero P1 P2 *
  4367. **
  4368. ** If the value of memory cell P1 is exactly 0, jump to P2.
  4369. **
  4370. ** It is illegal to use this instruction on a memory cell that does
  4371. ** not contain an integer. An assertion fault will result if you try.
  4372. */
  4373. case OP_IfMemZero: { /* no-push */
  4374. int i = pOp->p1;
  4375. Mem *pMem;
  4376. assert( i>=0 && i<p->nMem );
  4377. pMem = &p->aMem[i];
  4378. assert( pMem->flags==MEM_Int );
  4379. if( pMem->u.i==0 ){
  4380. pc = pOp->p2 - 1;
  4381. }
  4382. break;
  4383. }
  4384. /* Opcode: MemNull P1 * *
  4385. **
  4386. ** Store a NULL in memory cell P1
  4387. */
  4388. case OP_MemNull: {
  4389. assert( pOp->p1>=0 && pOp->p1<p->nMem );
  4390. sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
  4391. break;
  4392. }
  4393. /* Opcode: MemInt P1 P2 *
  4394. **
  4395. ** Store the integer value P1 in memory cell P2.
  4396. */
  4397. case OP_MemInt: {
  4398. assert( pOp->p2>=0 && pOp->p2<p->nMem );
  4399. sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
  4400. break;
  4401. }
  4402. /* Opcode: MemMove P1 P2 *
  4403. **
  4404. ** Move the content of memory cell P2 over to memory cell P1.
  4405. ** Any prior content of P1 is erased. Memory cell P2 is left
  4406. ** containing a NULL.
  4407. */
  4408. case OP_MemMove: {
  4409. assert( pOp->p1>=0 && pOp->p1<p->nMem );
  4410. assert( pOp->p2>=0 && pOp->p2<p->nMem );
  4411. rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
  4412. break;
  4413. }
  4414. /* Opcode: AggStep P1 P2 P3
  4415. **
  4416. ** Execute the step function for an aggregate. The
  4417. ** function has P2 arguments. P3 is a pointer to the FuncDef
  4418. ** structure that specifies the function. Use memory location
  4419. ** P1 as the accumulator.
  4420. **
  4421. ** The P2 arguments are popped from the stack.
  4422. */
  4423. case OP_AggStep: { /* no-push */
  4424. int n = pOp->p2;
  4425. int i;
  4426. Mem *pMem, *pRec;
  4427. sqlite3_context ctx;
  4428. sqlite3_value **apVal;
  4429. assert( n>=0 );
  4430. pRec = &pTos[1-n];
  4431. assert( pRec>=p->aStack );
  4432. apVal = p->apArg;
  4433. assert( apVal || n==0 );
  4434. for(i=0; i<n; i++, pRec++){
  4435. apVal[i] = pRec;
  4436. storeTypeInfo(pRec, encoding);
  4437. }
  4438. ctx.pFunc = (FuncDef*)pOp->p3;
  4439. assert( pOp->p1>=0 && pOp->p1<p->nMem );
  4440. ctx.pMem = pMem = &p->aMem[pOp->p1];
  4441. pMem->n++;
  4442. ctx.s.flags = MEM_Null;
  4443. ctx.s.z = 0;
  4444. ctx.s.xDel = 0;
  4445. ctx.s.db = db;
  4446. ctx.isError = 0;
  4447. ctx.pColl = 0;
  4448. if( ctx.pFunc->needCollSeq ){
  4449. assert( pOp>p->aOp );
  4450. assert( pOp[-1].p3type==P3_COLLSEQ );
  4451. assert( pOp[-1].opcode==OP_CollSeq );
  4452. ctx.pColl = (CollSeq *)pOp[-1].p3;
  4453. }
  4454. (ctx.pFunc->xStep)(&ctx, n, apVal);
  4455. popStack(&pTos, n);
  4456. if( ctx.isError ){
  4457. sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
  4458. rc = SQLITE_ERROR;
  4459. }
  4460. sqlite3VdbeMemRelease(&ctx.s);
  4461. break;
  4462. }
  4463. /* Opcode: AggFinal P1 P2 P3
  4464. **
  4465. ** Execute the finalizer function for an aggregate. P1 is
  4466. ** the memory location that is the accumulator for the aggregate.
  4467. **
  4468. ** P2 is the number of arguments that the step function takes and
  4469. ** P3 is a pointer to the FuncDef for this function. The P2
  4470. ** argument is not used by this opcode. It is only there to disambiguate
  4471. ** functions that can take varying numbers of arguments. The
  4472. ** P3 argument is only needed for the degenerate case where
  4473. ** the step function was not previously called.
  4474. */
  4475. case OP_AggFinal: { /* no-push */
  4476. Mem *pMem;
  4477. assert( pOp->p1>=0 && pOp->p1<p->nMem );
  4478. pMem = &p->aMem[pOp->p1];
  4479. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  4480. rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
  4481. if( rc==SQLITE_ERROR ){
  4482. sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
  4483. }
  4484. if( sqlite3VdbeMemTooBig(pMem) ){
  4485. goto too_big;
  4486. }
  4487. break;
  4488. }
  4489. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  4490. /* Opcode: Vacuum * * *
  4491. **
  4492. ** Vacuum the entire database. This opcode will cause other virtual
  4493. ** machines to be created and run. It may not be called from within
  4494. ** a transaction.
  4495. */
  4496. case OP_Vacuum: { /* no-push */
  4497. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  4498. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  4499. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  4500. break;
  4501. }
  4502. #endif
  4503. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  4504. /* Opcode: IncrVacuum P1 P2 *
  4505. **
  4506. ** Perform a single step of the incremental vacuum procedure on
  4507. ** the P1 database. If the vacuum has finished, jump to instruction
  4508. ** P2. Otherwise, fall through to the next instruction.
  4509. */
  4510. case OP_IncrVacuum: { /* no-push */
  4511. Btree *pBt;
  4512. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  4513. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  4514. pBt = db->aDb[pOp->p1].pBt;
  4515. rc = sqlite3BtreeIncrVacuum(pBt);
  4516. if( rc==SQLITE_DONE ){
  4517. pc = pOp->p2 - 1;
  4518. rc = SQLITE_OK;
  4519. }
  4520. break;
  4521. }
  4522. #endif
  4523. /* Opcode: Expire P1 * *
  4524. **
  4525. ** Cause precompiled statements to become expired. An expired statement
  4526. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  4527. ** (via sqlite3_step()).
  4528. **
  4529. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  4530. ** then only the currently executing statement is affected.
  4531. */
  4532. case OP_Expire: { /* no-push */
  4533. if( !pOp->p1 ){
  4534. sqlite3ExpirePreparedStatements(db);
  4535. }else{
  4536. p->expired = 1;
  4537. }
  4538. break;
  4539. }
  4540. #ifndef SQLITE_OMIT_SHARED_CACHE
  4541. /* Opcode: TableLock P1 P2 P3
  4542. **
  4543. ** Obtain a lock on a particular table. This instruction is only used when
  4544. ** the shared-cache feature is enabled.
  4545. **
  4546. ** If P1 is not negative, then it is the index of the database
  4547. ** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a
  4548. ** write-lock is required. In this case the index of the database is the
  4549. ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
  4550. ** required.
  4551. **
  4552. ** P2 contains the root-page of the table to lock.
  4553. **
  4554. ** P3 contains a pointer to the name of the table being locked. This is only
  4555. ** used to generate an error message if the lock cannot be obtained.
  4556. */
  4557. case OP_TableLock: { /* no-push */
  4558. int p1 = pOp->p1;
  4559. u8 isWriteLock = (p1<0);
  4560. if( isWriteLock ){
  4561. p1 = (-1*p1)-1;
  4562. }
  4563. assert( p1>=0 && p1<db->nDb );
  4564. assert( (p->btreeMask & (1<<p1))!=0 );
  4565. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  4566. if( rc==SQLITE_LOCKED ){
  4567. const char *z = (const char *)pOp->p3;
  4568. sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
  4569. }
  4570. break;
  4571. }
  4572. #endif /* SQLITE_OMIT_SHARED_CACHE */
  4573. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4574. /* Opcode: VBegin * * P3
  4575. **
  4576. ** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method
  4577. ** for that table.
  4578. */
  4579. case OP_VBegin: { /* no-push */
  4580. rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3);
  4581. break;
  4582. }
  4583. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4584. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4585. /* Opcode: VCreate P1 * P3
  4586. **
  4587. ** P3 is the name of a virtual table in database P1. Call the xCreate method
  4588. ** for that table.
  4589. */
  4590. case OP_VCreate: { /* no-push */
  4591. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg);
  4592. break;
  4593. }
  4594. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4595. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4596. /* Opcode: VDestroy P1 * P3
  4597. **
  4598. ** P3 is the name of a virtual table in database P1. Call the xDestroy method
  4599. ** of that table.
  4600. */
  4601. case OP_VDestroy: { /* no-push */
  4602. p->inVtabMethod = 2;
  4603. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3);
  4604. p->inVtabMethod = 0;
  4605. break;
  4606. }
  4607. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4608. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4609. /* Opcode: VOpen P1 * P3
  4610. **
  4611. ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
  4612. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  4613. ** table and stores that cursor in P1.
  4614. */
  4615. case OP_VOpen: { /* no-push */
  4616. Cursor *pCur = 0;
  4617. sqlite3_vtab_cursor *pVtabCursor = 0;
  4618. sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
  4619. sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
  4620. assert(pVtab && pModule);
  4621. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  4622. rc = pModule->xOpen(pVtab, &pVtabCursor);
  4623. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  4624. if( SQLITE_OK==rc ){
  4625. /* Initialise sqlite3_vtab_cursor base class */
  4626. pVtabCursor->pVtab = pVtab;
  4627. /* Initialise vdbe cursor object */
  4628. pCur = allocateCursor(p, pOp->p1, -1);
  4629. if( pCur ){
  4630. pCur->pVtabCursor = pVtabCursor;
  4631. pCur->pModule = pVtabCursor->pVtab->pModule;
  4632. }else{
  4633. db->mallocFailed = 1;
  4634. pModule->xClose(pVtabCursor);
  4635. }
  4636. }
  4637. break;
  4638. }
  4639. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4640. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4641. /* Opcode: VFilter P1 P2 P3
  4642. **
  4643. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  4644. ** the filtered result set is empty.
  4645. **
  4646. ** P3 is either NULL or a string that was generated by the xBestIndex
  4647. ** method of the module. The interpretation of the P3 string is left
  4648. ** to the module implementation.
  4649. **
  4650. ** This opcode invokes the xFilter method on the virtual table specified
  4651. ** by P1. The integer query plan parameter to xFilter is the top of the
  4652. ** stack. Next down on the stack is the argc parameter. Beneath the
  4653. ** next of stack are argc additional parameters which are passed to
  4654. ** xFilter as argv. The topmost parameter (i.e. 3rd element popped from
  4655. ** the stack) becomes argv[argc-1] when passed to xFilter.
  4656. **
  4657. ** The integer query plan parameter, argc, and all argv stack values
  4658. ** are popped from the stack before this instruction completes.
  4659. **
  4660. ** A jump is made to P2 if the result set after filtering would be
  4661. ** empty.
  4662. */
  4663. case OP_VFilter: { /* no-push */
  4664. int nArg;
  4665. const sqlite3_module *pModule;
  4666. Cursor *pCur = p->apCsr[pOp->p1];
  4667. assert( pCur->pVtabCursor );
  4668. pModule = pCur->pVtabCursor->pVtab->pModule;
  4669. /* Grab the index number and argc parameters off the top of the stack. */
  4670. assert( (&pTos[-1])>=p->aStack );
  4671. assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int );
  4672. nArg = pTos[-1].u.i;
  4673. /* Invoke the xFilter method */
  4674. {
  4675. int res = 0;
  4676. int i;
  4677. Mem **apArg = p->apArg;
  4678. for(i = 0; i<nArg; i++){
  4679. apArg[i] = &pTos[i+1-2-nArg];
  4680. storeTypeInfo(apArg[i], 0);
  4681. }
  4682. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  4683. p->inVtabMethod = 1;
  4684. rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg);
  4685. p->inVtabMethod = 0;
  4686. if( rc==SQLITE_OK ){
  4687. res = pModule->xEof(pCur->pVtabCursor);
  4688. }
  4689. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  4690. if( res ){
  4691. pc = pOp->p2 - 1;
  4692. }
  4693. }
  4694. /* Pop the index number, argc value and parameters off the stack */
  4695. popStack(&pTos, 2+nArg);
  4696. break;
  4697. }
  4698. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4699. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4700. /* Opcode: VRowid P1 * *
  4701. **
  4702. ** Push an integer onto the stack which is the rowid of
  4703. ** the virtual-table that the P1 cursor is pointing to.
  4704. */
  4705. case OP_VRowid: {
  4706. const sqlite3_module *pModule;
  4707. Cursor *pCur = p->apCsr[pOp->p1];
  4708. assert( pCur->pVtabCursor );
  4709. pModule = pCur->pVtabCursor->pVtab->pModule;
  4710. if( pModule->xRowid==0 ){
  4711. sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0);
  4712. rc = SQLITE_ERROR;
  4713. } else {
  4714. sqlite_int64 iRow;
  4715. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  4716. rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
  4717. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  4718. pTos++;
  4719. pTos->flags = MEM_Int;
  4720. pTos->u.i = iRow;
  4721. }
  4722. break;
  4723. }
  4724. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4725. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4726. /* Opcode: VColumn P1 P2 *
  4727. **
  4728. ** Push onto the stack the value of the P2-th column of
  4729. ** the row of the virtual-table that the P1 cursor is pointing to.
  4730. */
  4731. case OP_VColumn: {
  4732. const sqlite3_module *pModule;
  4733. Cursor *pCur = p->apCsr[pOp->p1];
  4734. assert( pCur->pVtabCursor );
  4735. pModule = pCur->pVtabCursor->pVtab->pModule;
  4736. if( pModule->xColumn==0 ){
  4737. sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0);
  4738. rc = SQLITE_ERROR;
  4739. } else {
  4740. sqlite3_context sContext;
  4741. memset(&sContext, 0, sizeof(sContext));
  4742. sContext.s.flags = MEM_Null;
  4743. sContext.s.db = db;
  4744. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  4745. rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  4746. /* Copy the result of the function to the top of the stack. We
  4747. ** do this regardless of whether or not an error occured to ensure any
  4748. ** dynamic allocation in sContext.s (a Mem struct) is released.
  4749. */
  4750. sqlite3VdbeChangeEncoding(&sContext.s, encoding);
  4751. pTos++;
  4752. pTos->flags = 0;
  4753. sqlite3VdbeMemMove(pTos, &sContext.s);
  4754. if( sqlite3SafetyOn(db) ){
  4755. goto abort_due_to_misuse;
  4756. }
  4757. if( sqlite3VdbeMemTooBig(pTos) ){
  4758. goto too_big;
  4759. }
  4760. }
  4761. break;
  4762. }
  4763. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4764. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4765. /* Opcode: VNext P1 P2 *
  4766. **
  4767. ** Advance virtual table P1 to the next row in its result set and
  4768. ** jump to instruction P2. Or, if the virtual table has reached
  4769. ** the end of its result set, then fall through to the next instruction.
  4770. */
  4771. case OP_VNext: { /* no-push */
  4772. const sqlite3_module *pModule;
  4773. int res = 0;
  4774. Cursor *pCur = p->apCsr[pOp->p1];
  4775. assert( pCur->pVtabCursor );
  4776. pModule = pCur->pVtabCursor->pVtab->pModule;
  4777. if( pModule->xNext==0 ){
  4778. sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0);
  4779. rc = SQLITE_ERROR;
  4780. } else {
  4781. /* Invoke the xNext() method of the module. There is no way for the
  4782. ** underlying implementation to return an error if one occurs during
  4783. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  4784. ** data is available) and the error code returned when xColumn or
  4785. ** some other method is next invoked on the save virtual table cursor.
  4786. */
  4787. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  4788. p->inVtabMethod = 1;
  4789. rc = pModule->xNext(pCur->pVtabCursor);
  4790. p->inVtabMethod = 0;
  4791. if( rc==SQLITE_OK ){
  4792. res = pModule->xEof(pCur->pVtabCursor);
  4793. }
  4794. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  4795. if( !res ){
  4796. /* If there is data, jump to P2 */
  4797. pc = pOp->p2 - 1;
  4798. }
  4799. }
  4800. break;
  4801. }
  4802. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4803. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4804. /* Opcode: VRename * * P3
  4805. **
  4806. ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
  4807. ** This opcode invokes the corresponding xRename method. The value
  4808. ** on the top of the stack is popped and passed as the zName argument
  4809. ** to the xRename method.
  4810. */
  4811. case OP_VRename: { /* no-push */
  4812. sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
  4813. assert( pVtab->pModule->xRename );
  4814. Stringify(pTos, encoding);
  4815. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  4816. sqlite3VtabLock(pVtab);
  4817. rc = pVtab->pModule->xRename(pVtab, pTos->z);
  4818. sqlite3VtabUnlock(db, pVtab);
  4819. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  4820. popStack(&pTos, 1);
  4821. break;
  4822. }
  4823. #endif
  4824. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4825. /* Opcode: VUpdate P1 P2 P3
  4826. **
  4827. ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
  4828. ** This opcode invokes the corresponding xUpdate method. P2 values
  4829. ** are taken from the stack to pass to the xUpdate invocation. The
  4830. ** value on the top of the stack corresponds to the p2th element
  4831. ** of the argv array passed to xUpdate.
  4832. **
  4833. ** The xUpdate method will do a DELETE or an INSERT or both.
  4834. ** The argv[0] element (which corresponds to the P2-th element down
  4835. ** on the stack) is the rowid of a row to delete. If argv[0] is
  4836. ** NULL then no deletion occurs. The argv[1] element is the rowid
  4837. ** of the new row. This can be NULL to have the virtual table
  4838. ** select the new rowid for itself. The higher elements in the
  4839. ** stack are the values of columns in the new row.
  4840. **
  4841. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  4842. ** a row to delete.
  4843. **
  4844. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  4845. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  4846. ** is set to the value of the rowid for the row just inserted.
  4847. */
  4848. case OP_VUpdate: { /* no-push */
  4849. sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
  4850. sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
  4851. int nArg = pOp->p2;
  4852. assert( pOp->p3type==P3_VTAB );
  4853. if( pModule->xUpdate==0 ){
  4854. sqlite3SetString(&p->zErrMsg, "read-only table", 0);
  4855. rc = SQLITE_ERROR;
  4856. }else{
  4857. int i;
  4858. sqlite_int64 rowid;
  4859. Mem **apArg = p->apArg;
  4860. Mem *pX = &pTos[1-nArg];
  4861. for(i = 0; i<nArg; i++, pX++){
  4862. storeTypeInfo(pX, 0);
  4863. apArg[i] = pX;
  4864. }
  4865. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  4866. sqlite3VtabLock(pVtab);
  4867. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  4868. sqlite3VtabUnlock(db, pVtab);
  4869. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  4870. if( pOp->p1 && rc==SQLITE_OK ){
  4871. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  4872. db->lastRowid = rowid;
  4873. }
  4874. }
  4875. popStack(&pTos, nArg);
  4876. break;
  4877. }
  4878. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4879. /* An other opcode is illegal...
  4880. */
  4881. default: {
  4882. assert( 0 );
  4883. break;
  4884. }
  4885. /*****************************************************************************
  4886. ** The cases of the switch statement above this line should all be indented
  4887. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  4888. ** readability. From this point on down, the normal indentation rules are
  4889. ** restored.
  4890. *****************************************************************************/
  4891. }
  4892. /* Make sure the stack limit was not exceeded */
  4893. assert( pTos<=pStackLimit );
  4894. #ifdef VDBE_PROFILE
  4895. {
  4896. long long elapse = hwtime() - start;
  4897. pOp->cycles += elapse;
  4898. pOp->cnt++;
  4899. #if 0
  4900. fprintf(stdout, "%10lld ", elapse);
  4901. sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
  4902. #endif
  4903. }
  4904. #endif
  4905. #ifdef SQLITE_TEST
  4906. /* Keep track of the size of the largest BLOB or STR that has appeared
  4907. ** on the top of the VDBE stack.
  4908. */
  4909. if( pTos>=p->aStack && (pTos->flags & (MEM_Blob|MEM_Str))!=0
  4910. && pTos->n>sqlite3_max_blobsize ){
  4911. sqlite3_max_blobsize = pTos->n;
  4912. }
  4913. #endif
  4914. /* The following code adds nothing to the actual functionality
  4915. ** of the program. It is only here for testing and debugging.
  4916. ** On the other hand, it does burn CPU cycles every time through
  4917. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  4918. */
  4919. #ifndef NDEBUG
  4920. /* Sanity checking on the top element of the stack. If the previous
  4921. ** instruction was VNoChange, then the flags field of the top
  4922. ** of the stack is set to 0. This is technically invalid for a memory
  4923. ** cell, so avoid calling MemSanity() in this case.
  4924. */
  4925. if( pTos>=p->aStack && pTos->flags ){
  4926. assert( pTos->db==db );
  4927. sqlite3VdbeMemSanity(pTos);
  4928. assert( !sqlite3VdbeMemTooBig(pTos) );
  4929. }
  4930. assert( pc>=-1 && pc<p->nOp );
  4931. #ifdef SQLITE_DEBUG
  4932. /* Code for tracing the vdbe stack. */
  4933. if( p->trace && pTos>=p->aStack ){
  4934. int i;
  4935. fprintf(p->trace, "Stack:");
  4936. for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
  4937. if( pTos[i].flags & MEM_Null ){
  4938. fprintf(p->trace, " NULL");
  4939. }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  4940. fprintf(p->trace, " si:%lld", pTos[i].u.i);
  4941. }else if( pTos[i].flags & MEM_Int ){
  4942. fprintf(p->trace, " i:%lld", pTos[i].u.i);
  4943. }else if( pTos[i].flags & MEM_Real ){
  4944. fprintf(p->trace, " r:%g", pTos[i].r);
  4945. }else{
  4946. char zBuf[200];
  4947. sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
  4948. fprintf(p->trace, " ");
  4949. fprintf(p->trace, "%s", zBuf);
  4950. }
  4951. }
  4952. if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
  4953. fprintf(p->trace,"\n");
  4954. }
  4955. #endif /* SQLITE_DEBUG */
  4956. #endif /* NDEBUG */
  4957. } /* The end of the for(;;) loop the loops through opcodes */
  4958. /* If we reach this point, it means that execution is finished.
  4959. */
  4960. vdbe_halt:
  4961. if( rc ){
  4962. p->rc = rc;
  4963. rc = SQLITE_ERROR;
  4964. }else{
  4965. rc = SQLITE_DONE;
  4966. }
  4967. sqlite3VdbeHalt(p);
  4968. p->pTos = pTos;
  4969. /* This is the only way out of this procedure. We have to
  4970. ** release the mutexes on btrees that were acquired at the
  4971. ** top. */
  4972. vdbe_return:
  4973. sqlite3BtreeMutexArrayLeave(&p->aMutex);
  4974. return rc;
  4975. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  4976. ** is encountered.
  4977. */
  4978. too_big:
  4979. sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
  4980. rc = SQLITE_TOOBIG;
  4981. goto vdbe_halt;
  4982. /* Jump to here if a malloc() fails.
  4983. */
  4984. no_mem:
  4985. db->mallocFailed = 1;
  4986. sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
  4987. rc = SQLITE_NOMEM;
  4988. goto vdbe_halt;
  4989. /* Jump to here for an SQLITE_MISUSE error.
  4990. */
  4991. abort_due_to_misuse:
  4992. rc = SQLITE_MISUSE;
  4993. /* Fall thru into abort_due_to_error */
  4994. /* Jump to here for any other kind of fatal error. The "rc" variable
  4995. ** should hold the error number.
  4996. */
  4997. abort_due_to_error:
  4998. if( p->zErrMsg==0 ){
  4999. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  5000. sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
  5001. }
  5002. goto vdbe_halt;
  5003. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  5004. ** flag.
  5005. */
  5006. abort_due_to_interrupt:
  5007. assert( db->u1.isInterrupted );
  5008. if( db->magic!=SQLITE_MAGIC_BUSY ){
  5009. rc = SQLITE_MISUSE;
  5010. }else{
  5011. rc = SQLITE_INTERRUPT;
  5012. }
  5013. p->rc = rc;
  5014. sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
  5015. goto vdbe_halt;
  5016. }