where.c 226 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144
  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. ** This module contains C code that generates VDBE code used to process
  13. ** the WHERE clause of SQL statements. This module is responsible for
  14. ** generating the code that loops through a table looking for applicable
  15. ** rows. Indices are selected and used to speed the search when doing
  16. ** so is applicable. Because this module is responsible for selecting
  17. ** indices, you might also think of this module as the "query optimizer".
  18. */
  19. #include "sqliteInt.h"
  20. /*
  21. ** Trace output macros
  22. */
  23. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  24. /***/ int sqlite3WhereTrace = 0;
  25. #endif
  26. #if defined(SQLITE_DEBUG) \
  27. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  28. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  29. # define WHERETRACE_ENABLED 1
  30. #else
  31. # define WHERETRACE(K,X)
  32. #endif
  33. /* Forward references
  34. */
  35. typedef struct WhereClause WhereClause;
  36. typedef struct WhereMaskSet WhereMaskSet;
  37. typedef struct WhereOrInfo WhereOrInfo;
  38. typedef struct WhereAndInfo WhereAndInfo;
  39. typedef struct WhereLevel WhereLevel;
  40. typedef struct WhereLoop WhereLoop;
  41. typedef struct WherePath WherePath;
  42. typedef struct WhereTerm WhereTerm;
  43. typedef struct WhereLoopBuilder WhereLoopBuilder;
  44. typedef struct WhereScan WhereScan;
  45. typedef struct WhereOrCost WhereOrCost;
  46. typedef struct WhereOrSet WhereOrSet;
  47. /*
  48. ** This object contains information needed to implement a single nested
  49. ** loop in WHERE clause.
  50. **
  51. ** Contrast this object with WhereLoop. This object describes the
  52. ** implementation of the loop. WhereLoop describes the algorithm.
  53. ** This object contains a pointer to the WhereLoop algorithm as one of
  54. ** its elements.
  55. **
  56. ** The WhereInfo object contains a single instance of this object for
  57. ** each term in the FROM clause (which is to say, for each of the
  58. ** nested loops as implemented). The order of WhereLevel objects determines
  59. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  60. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  61. */
  62. struct WhereLevel {
  63. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  64. int iTabCur; /* The VDBE cursor used to access the table */
  65. int iIdxCur; /* The VDBE cursor used to access pIdx */
  66. int addrBrk; /* Jump here to break out of the loop */
  67. int addrNxt; /* Jump here to start the next IN combination */
  68. int addrCont; /* Jump here to continue with the next loop cycle */
  69. int addrFirst; /* First instruction of interior of the loop */
  70. int addrBody; /* Beginning of the body of this loop */
  71. u8 iFrom; /* Which entry in the FROM clause */
  72. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  73. int p1, p2; /* Operands of the opcode used to ends the loop */
  74. union { /* Information that depends on pWLoop->wsFlags */
  75. struct {
  76. int nIn; /* Number of entries in aInLoop[] */
  77. struct InLoop {
  78. int iCur; /* The VDBE cursor used by this IN operator */
  79. int addrInTop; /* Top of the IN loop */
  80. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  81. } *aInLoop; /* Information about each nested IN operator */
  82. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  83. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  84. } u;
  85. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  86. Bitmask notReady; /* FROM entries not usable at this level */
  87. };
  88. /*
  89. ** Each instance of this object represents an algorithm for evaluating one
  90. ** term of a join. Every term of the FROM clause will have at least
  91. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  92. ** prevent a query solution - which is an error) and many terms of the
  93. ** FROM clause will have multiple WhereLoop objects, each describing a
  94. ** potential way of implementing that FROM-clause term, together with
  95. ** dependencies and cost estimates for using the chosen algorithm.
  96. **
  97. ** Query planning consists of building up a collection of these WhereLoop
  98. ** objects, then computing a particular sequence of WhereLoop objects, with
  99. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  100. ** and that minimize the overall cost.
  101. */
  102. struct WhereLoop {
  103. Bitmask prereq; /* Bitmask of other loops that must run first */
  104. Bitmask maskSelf; /* Bitmask identifying table iTab */
  105. #ifdef SQLITE_DEBUG
  106. char cId; /* Symbolic ID of this loop for debugging use */
  107. #endif
  108. u8 iTab; /* Position in FROM clause of table for this loop */
  109. u8 iSortIdx; /* Sorting index number. 0==None */
  110. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  111. LogEst rRun; /* Cost of running each loop */
  112. LogEst nOut; /* Estimated number of output rows */
  113. union {
  114. struct { /* Information for internal btree tables */
  115. int nEq; /* Number of equality constraints */
  116. Index *pIndex; /* Index used, or NULL */
  117. } btree;
  118. struct { /* Information for virtual tables */
  119. int idxNum; /* Index number */
  120. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  121. u8 isOrdered; /* True if satisfies ORDER BY */
  122. u16 omitMask; /* Terms that may be omitted */
  123. char *idxStr; /* Index identifier string */
  124. } vtab;
  125. } u;
  126. u32 wsFlags; /* WHERE_* flags describing the plan */
  127. u16 nLTerm; /* Number of entries in aLTerm[] */
  128. /**** whereLoopXfer() copies fields above ***********************/
  129. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  130. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  131. WhereTerm **aLTerm; /* WhereTerms used */
  132. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  133. WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
  134. };
  135. /* This object holds the prerequisites and the cost of running a
  136. ** subquery on one operand of an OR operator in the WHERE clause.
  137. ** See WhereOrSet for additional information
  138. */
  139. struct WhereOrCost {
  140. Bitmask prereq; /* Prerequisites */
  141. LogEst rRun; /* Cost of running this subquery */
  142. LogEst nOut; /* Number of outputs for this subquery */
  143. };
  144. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  145. ** correspond to the subquery(s) of OR-clause processing. Only the
  146. ** best N_OR_COST elements are retained.
  147. */
  148. #define N_OR_COST 3
  149. struct WhereOrSet {
  150. u16 n; /* Number of valid a[] entries */
  151. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  152. };
  153. /* Forward declaration of methods */
  154. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  155. /*
  156. ** Each instance of this object holds a sequence of WhereLoop objects
  157. ** that implement some or all of a query plan.
  158. **
  159. ** Think of each WhereLoop object as a node in a graph with arcs
  160. ** showing dependencies and costs for travelling between nodes. (That is
  161. ** not a completely accurate description because WhereLoop costs are a
  162. ** vector, not a scalar, and because dependencies are many-to-one, not
  163. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  164. ** Then a WherePath object is a path through the graph that visits some
  165. ** or all of the WhereLoop objects once.
  166. **
  167. ** The "solver" works by creating the N best WherePath objects of length
  168. ** 1. Then using those as a basis to compute the N best WherePath objects
  169. ** of length 2. And so forth until the length of WherePaths equals the
  170. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  171. ** at the end is the choosen query plan.
  172. */
  173. struct WherePath {
  174. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  175. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  176. LogEst nRow; /* Estimated number of rows generated by this path */
  177. LogEst rCost; /* Total cost of this path */
  178. u8 isOrdered; /* True if this path satisfies ORDER BY */
  179. u8 isOrderedValid; /* True if the isOrdered field is valid */
  180. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  181. };
  182. /*
  183. ** The query generator uses an array of instances of this structure to
  184. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  185. ** clause subexpression is separated from the others by AND operators,
  186. ** usually, or sometimes subexpressions separated by OR.
  187. **
  188. ** All WhereTerms are collected into a single WhereClause structure.
  189. ** The following identity holds:
  190. **
  191. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  192. **
  193. ** When a term is of the form:
  194. **
  195. ** X <op> <expr>
  196. **
  197. ** where X is a column name and <op> is one of certain operators,
  198. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  199. ** cursor number and column number for X. WhereTerm.eOperator records
  200. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  201. ** use of a bitmask encoding for the operator allows us to search
  202. ** quickly for terms that match any of several different operators.
  203. **
  204. ** A WhereTerm might also be two or more subterms connected by OR:
  205. **
  206. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  207. **
  208. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  209. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  210. ** is collected about the OR clause.
  211. **
  212. ** If a term in the WHERE clause does not match either of the two previous
  213. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  214. ** to the original subexpression content and wtFlags is set up appropriately
  215. ** but no other fields in the WhereTerm object are meaningful.
  216. **
  217. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  218. ** but they do so indirectly. A single WhereMaskSet structure translates
  219. ** cursor number into bits and the translated bit is stored in the prereq
  220. ** fields. The translation is used in order to maximize the number of
  221. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  222. ** spread out over the non-negative integers. For example, the cursor
  223. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  224. ** translates these sparse cursor numbers into consecutive integers
  225. ** beginning with 0 in order to make the best possible use of the available
  226. ** bits in the Bitmask. So, in the example above, the cursor numbers
  227. ** would be mapped into integers 0 through 7.
  228. **
  229. ** The number of terms in a join is limited by the number of bits
  230. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  231. ** is only able to process joins with 64 or fewer tables.
  232. */
  233. struct WhereTerm {
  234. Expr *pExpr; /* Pointer to the subexpression that is this term */
  235. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  236. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  237. union {
  238. int leftColumn; /* Column number of X in "X <op> <expr>" */
  239. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  240. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  241. } u;
  242. LogEst truthProb; /* Probability of truth for this expression */
  243. u16 eOperator; /* A WO_xx value describing <op> */
  244. u8 wtFlags; /* TERM_xxx bit flags. See below */
  245. u8 nChild; /* Number of children that must disable us */
  246. WhereClause *pWC; /* The clause this term is part of */
  247. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  248. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  249. };
  250. /*
  251. ** Allowed values of WhereTerm.wtFlags
  252. */
  253. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  254. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  255. #define TERM_CODED 0x04 /* This term is already coded */
  256. #define TERM_COPIED 0x08 /* Has a child */
  257. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  258. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  259. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  260. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  261. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  262. #else
  263. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  264. #endif
  265. /*
  266. ** An instance of the WhereScan object is used as an iterator for locating
  267. ** terms in the WHERE clause that are useful to the query planner.
  268. */
  269. struct WhereScan {
  270. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  271. WhereClause *pWC; /* WhereClause currently being scanned */
  272. char *zCollName; /* Required collating sequence, if not NULL */
  273. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  274. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  275. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  276. u32 opMask; /* Acceptable operators */
  277. int k; /* Resume scanning at this->pWC->a[this->k] */
  278. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  279. };
  280. /*
  281. ** An instance of the following structure holds all information about a
  282. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  283. **
  284. ** Explanation of pOuter: For a WHERE clause of the form
  285. **
  286. ** a AND ((b AND c) OR (d AND e)) AND f
  287. **
  288. ** There are separate WhereClause objects for the whole clause and for
  289. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  290. ** subclauses points to the WhereClause object for the whole clause.
  291. */
  292. struct WhereClause {
  293. WhereInfo *pWInfo; /* WHERE clause processing context */
  294. WhereClause *pOuter; /* Outer conjunction */
  295. u8 op; /* Split operator. TK_AND or TK_OR */
  296. int nTerm; /* Number of terms */
  297. int nSlot; /* Number of entries in a[] */
  298. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  299. #if defined(SQLITE_SMALL_STACK)
  300. WhereTerm aStatic[1]; /* Initial static space for a[] */
  301. #else
  302. WhereTerm aStatic[8]; /* Initial static space for a[] */
  303. #endif
  304. };
  305. /*
  306. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  307. ** a dynamically allocated instance of the following structure.
  308. */
  309. struct WhereOrInfo {
  310. WhereClause wc; /* Decomposition into subterms */
  311. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  312. };
  313. /*
  314. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  315. ** a dynamically allocated instance of the following structure.
  316. */
  317. struct WhereAndInfo {
  318. WhereClause wc; /* The subexpression broken out */
  319. };
  320. /*
  321. ** An instance of the following structure keeps track of a mapping
  322. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  323. **
  324. ** The VDBE cursor numbers are small integers contained in
  325. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  326. ** clause, the cursor numbers might not begin with 0 and they might
  327. ** contain gaps in the numbering sequence. But we want to make maximum
  328. ** use of the bits in our bitmasks. This structure provides a mapping
  329. ** from the sparse cursor numbers into consecutive integers beginning
  330. ** with 0.
  331. **
  332. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  333. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  334. **
  335. ** For example, if the WHERE clause expression used these VDBE
  336. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  337. ** would map those cursor numbers into bits 0 through 5.
  338. **
  339. ** Note that the mapping is not necessarily ordered. In the example
  340. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  341. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  342. ** does not really matter. What is important is that sparse cursor
  343. ** numbers all get mapped into bit numbers that begin with 0 and contain
  344. ** no gaps.
  345. */
  346. struct WhereMaskSet {
  347. int n; /* Number of assigned cursor values */
  348. int ix[BMS]; /* Cursor assigned to each bit */
  349. };
  350. /*
  351. ** This object is a convenience wrapper holding all information needed
  352. ** to construct WhereLoop objects for a particular query.
  353. */
  354. struct WhereLoopBuilder {
  355. WhereInfo *pWInfo; /* Information about this WHERE */
  356. WhereClause *pWC; /* WHERE clause terms */
  357. ExprList *pOrderBy; /* ORDER BY clause */
  358. WhereLoop *pNew; /* Template WhereLoop */
  359. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  360. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  361. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  362. int nRecValid; /* Number of valid fields currently in pRec */
  363. #endif
  364. };
  365. /*
  366. ** The WHERE clause processing routine has two halves. The
  367. ** first part does the start of the WHERE loop and the second
  368. ** half does the tail of the WHERE loop. An instance of
  369. ** this structure is returned by the first half and passed
  370. ** into the second half to give some continuity.
  371. **
  372. ** An instance of this object holds the complete state of the query
  373. ** planner.
  374. */
  375. struct WhereInfo {
  376. Parse *pParse; /* Parsing and code generating context */
  377. SrcList *pTabList; /* List of tables in the join */
  378. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  379. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  380. WhereLoop *pLoops; /* List of all WhereLoop objects */
  381. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  382. LogEst nRowOut; /* Estimated number of output rows */
  383. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  384. u8 bOBSat; /* ORDER BY satisfied by indices */
  385. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  386. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  387. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  388. u8 nLevel; /* Number of nested loop */
  389. int iTop; /* The very beginning of the WHERE loop */
  390. int iContinue; /* Jump here to continue with next record */
  391. int iBreak; /* Jump here to break out of the loop */
  392. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  393. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  394. WhereClause sWC; /* Decomposition of the WHERE clause */
  395. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  396. };
  397. /*
  398. ** Bitmasks for the operators on WhereTerm objects. These are all
  399. ** operators that are of interest to the query planner. An
  400. ** OR-ed combination of these values can be used when searching for
  401. ** particular WhereTerms within a WhereClause.
  402. */
  403. #define WO_IN 0x001
  404. #define WO_EQ 0x002
  405. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  406. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  407. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  408. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  409. #define WO_MATCH 0x040
  410. #define WO_ISNULL 0x080
  411. #define WO_OR 0x100 /* Two or more OR-connected terms */
  412. #define WO_AND 0x200 /* Two or more AND-connected terms */
  413. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  414. #define WO_NOOP 0x800 /* This term does not restrict search space */
  415. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  416. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  417. /*
  418. ** These are definitions of bits in the WhereLoop.wsFlags field.
  419. ** The particular combination of bits in each WhereLoop help to
  420. ** determine the algorithm that WhereLoop represents.
  421. */
  422. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  423. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  424. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  425. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  426. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  427. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  428. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  429. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  430. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  431. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  432. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  433. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  434. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  435. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  436. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  437. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  438. /*
  439. ** Return the estimated number of output rows from a WHERE clause
  440. */
  441. u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  442. return sqlite3LogEstToInt(pWInfo->nRowOut);
  443. }
  444. /*
  445. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  446. ** WHERE clause returns outputs for DISTINCT processing.
  447. */
  448. int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  449. return pWInfo->eDistinct;
  450. }
  451. /*
  452. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  453. ** Return FALSE if the output needs to be sorted.
  454. */
  455. int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  456. return pWInfo->bOBSat!=0;
  457. }
  458. /*
  459. ** Return the VDBE address or label to jump to in order to continue
  460. ** immediately with the next row of a WHERE clause.
  461. */
  462. int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  463. return pWInfo->iContinue;
  464. }
  465. /*
  466. ** Return the VDBE address or label to jump to in order to break
  467. ** out of a WHERE loop.
  468. */
  469. int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  470. return pWInfo->iBreak;
  471. }
  472. /*
  473. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  474. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  475. ** UPDATE or DELETE might change subsequent WHERE clause results.
  476. */
  477. int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
  478. return pWInfo->okOnePass;
  479. }
  480. /*
  481. ** Move the content of pSrc into pDest
  482. */
  483. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  484. pDest->n = pSrc->n;
  485. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  486. }
  487. /*
  488. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  489. **
  490. ** The new entry might overwrite an existing entry, or it might be
  491. ** appended, or it might be discarded. Do whatever is the right thing
  492. ** so that pSet keeps the N_OR_COST best entries seen so far.
  493. */
  494. static int whereOrInsert(
  495. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  496. Bitmask prereq, /* Prerequisites of the new entry */
  497. LogEst rRun, /* Run-cost of the new entry */
  498. LogEst nOut /* Number of outputs for the new entry */
  499. ){
  500. u16 i;
  501. WhereOrCost *p;
  502. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  503. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  504. goto whereOrInsert_done;
  505. }
  506. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  507. return 0;
  508. }
  509. }
  510. if( pSet->n<N_OR_COST ){
  511. p = &pSet->a[pSet->n++];
  512. p->nOut = nOut;
  513. }else{
  514. p = pSet->a;
  515. for(i=1; i<pSet->n; i++){
  516. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  517. }
  518. if( p->rRun<=rRun ) return 0;
  519. }
  520. whereOrInsert_done:
  521. p->prereq = prereq;
  522. p->rRun = rRun;
  523. if( p->nOut>nOut ) p->nOut = nOut;
  524. return 1;
  525. }
  526. /*
  527. ** Initialize a preallocated WhereClause structure.
  528. */
  529. static void whereClauseInit(
  530. WhereClause *pWC, /* The WhereClause to be initialized */
  531. WhereInfo *pWInfo /* The WHERE processing context */
  532. ){
  533. pWC->pWInfo = pWInfo;
  534. pWC->pOuter = 0;
  535. pWC->nTerm = 0;
  536. pWC->nSlot = ArraySize(pWC->aStatic);
  537. pWC->a = pWC->aStatic;
  538. }
  539. /* Forward reference */
  540. static void whereClauseClear(WhereClause*);
  541. /*
  542. ** Deallocate all memory associated with a WhereOrInfo object.
  543. */
  544. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  545. whereClauseClear(&p->wc);
  546. sqlite3DbFree(db, p);
  547. }
  548. /*
  549. ** Deallocate all memory associated with a WhereAndInfo object.
  550. */
  551. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  552. whereClauseClear(&p->wc);
  553. sqlite3DbFree(db, p);
  554. }
  555. /*
  556. ** Deallocate a WhereClause structure. The WhereClause structure
  557. ** itself is not freed. This routine is the inverse of whereClauseInit().
  558. */
  559. static void whereClauseClear(WhereClause *pWC){
  560. int i;
  561. WhereTerm *a;
  562. sqlite3 *db = pWC->pWInfo->pParse->db;
  563. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  564. if( a->wtFlags & TERM_DYNAMIC ){
  565. sqlite3ExprDelete(db, a->pExpr);
  566. }
  567. if( a->wtFlags & TERM_ORINFO ){
  568. whereOrInfoDelete(db, a->u.pOrInfo);
  569. }else if( a->wtFlags & TERM_ANDINFO ){
  570. whereAndInfoDelete(db, a->u.pAndInfo);
  571. }
  572. }
  573. if( pWC->a!=pWC->aStatic ){
  574. sqlite3DbFree(db, pWC->a);
  575. }
  576. }
  577. /*
  578. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  579. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  580. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  581. ** 0 is returned if the new WhereTerm could not be added due to a memory
  582. ** allocation error. The memory allocation failure will be recorded in
  583. ** the db->mallocFailed flag so that higher-level functions can detect it.
  584. **
  585. ** This routine will increase the size of the pWC->a[] array as necessary.
  586. **
  587. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  588. ** for freeing the expression p is assumed by the WhereClause object pWC.
  589. ** This is true even if this routine fails to allocate a new WhereTerm.
  590. **
  591. ** WARNING: This routine might reallocate the space used to store
  592. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  593. ** calling this routine. Such pointers may be reinitialized by referencing
  594. ** the pWC->a[] array.
  595. */
  596. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  597. WhereTerm *pTerm;
  598. int idx;
  599. testcase( wtFlags & TERM_VIRTUAL );
  600. if( pWC->nTerm>=pWC->nSlot ){
  601. WhereTerm *pOld = pWC->a;
  602. sqlite3 *db = pWC->pWInfo->pParse->db;
  603. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  604. if( pWC->a==0 ){
  605. if( wtFlags & TERM_DYNAMIC ){
  606. sqlite3ExprDelete(db, p);
  607. }
  608. pWC->a = pOld;
  609. return 0;
  610. }
  611. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  612. if( pOld!=pWC->aStatic ){
  613. sqlite3DbFree(db, pOld);
  614. }
  615. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  616. }
  617. pTerm = &pWC->a[idx = pWC->nTerm++];
  618. if( p && ExprHasProperty(p, EP_Unlikely) ){
  619. pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
  620. }else{
  621. pTerm->truthProb = -1;
  622. }
  623. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  624. pTerm->wtFlags = wtFlags;
  625. pTerm->pWC = pWC;
  626. pTerm->iParent = -1;
  627. return idx;
  628. }
  629. /*
  630. ** This routine identifies subexpressions in the WHERE clause where
  631. ** each subexpression is separated by the AND operator or some other
  632. ** operator specified in the op parameter. The WhereClause structure
  633. ** is filled with pointers to subexpressions. For example:
  634. **
  635. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  636. ** \________/ \_______________/ \________________/
  637. ** slot[0] slot[1] slot[2]
  638. **
  639. ** The original WHERE clause in pExpr is unaltered. All this routine
  640. ** does is make slot[] entries point to substructure within pExpr.
  641. **
  642. ** In the previous sentence and in the diagram, "slot[]" refers to
  643. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  644. ** all terms of the WHERE clause.
  645. */
  646. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  647. pWC->op = op;
  648. if( pExpr==0 ) return;
  649. if( pExpr->op!=op ){
  650. whereClauseInsert(pWC, pExpr, 0);
  651. }else{
  652. whereSplit(pWC, pExpr->pLeft, op);
  653. whereSplit(pWC, pExpr->pRight, op);
  654. }
  655. }
  656. /*
  657. ** Initialize a WhereMaskSet object
  658. */
  659. #define initMaskSet(P) (P)->n=0
  660. /*
  661. ** Return the bitmask for the given cursor number. Return 0 if
  662. ** iCursor is not in the set.
  663. */
  664. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  665. int i;
  666. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  667. for(i=0; i<pMaskSet->n; i++){
  668. if( pMaskSet->ix[i]==iCursor ){
  669. return MASKBIT(i);
  670. }
  671. }
  672. return 0;
  673. }
  674. /*
  675. ** Create a new mask for cursor iCursor.
  676. **
  677. ** There is one cursor per table in the FROM clause. The number of
  678. ** tables in the FROM clause is limited by a test early in the
  679. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  680. ** array will never overflow.
  681. */
  682. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  683. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  684. pMaskSet->ix[pMaskSet->n++] = iCursor;
  685. }
  686. /*
  687. ** These routines walk (recursively) an expression tree and generate
  688. ** a bitmask indicating which tables are used in that expression
  689. ** tree.
  690. */
  691. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  692. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  693. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  694. Bitmask mask = 0;
  695. if( p==0 ) return 0;
  696. if( p->op==TK_COLUMN ){
  697. mask = getMask(pMaskSet, p->iTable);
  698. return mask;
  699. }
  700. mask = exprTableUsage(pMaskSet, p->pRight);
  701. mask |= exprTableUsage(pMaskSet, p->pLeft);
  702. if( ExprHasProperty(p, EP_xIsSelect) ){
  703. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  704. }else{
  705. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  706. }
  707. return mask;
  708. }
  709. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  710. int i;
  711. Bitmask mask = 0;
  712. if( pList ){
  713. for(i=0; i<pList->nExpr; i++){
  714. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  715. }
  716. }
  717. return mask;
  718. }
  719. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  720. Bitmask mask = 0;
  721. while( pS ){
  722. SrcList *pSrc = pS->pSrc;
  723. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  724. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  725. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  726. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  727. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  728. if( ALWAYS(pSrc!=0) ){
  729. int i;
  730. for(i=0; i<pSrc->nSrc; i++){
  731. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  732. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  733. }
  734. }
  735. pS = pS->pPrior;
  736. }
  737. return mask;
  738. }
  739. /*
  740. ** Return TRUE if the given operator is one of the operators that is
  741. ** allowed for an indexable WHERE clause term. The allowed operators are
  742. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  743. */
  744. static int allowedOp(int op){
  745. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  746. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  747. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  748. assert( TK_GE==TK_EQ+4 );
  749. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  750. }
  751. /*
  752. ** Swap two objects of type TYPE.
  753. */
  754. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  755. /*
  756. ** Commute a comparison operator. Expressions of the form "X op Y"
  757. ** are converted into "Y op X".
  758. **
  759. ** If left/right precedence rules come into play when determining the
  760. ** collating sequence, then COLLATE operators are adjusted to ensure
  761. ** that the collating sequence does not change. For example:
  762. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  763. ** the left hand side of a comparison overrides any collation sequence
  764. ** attached to the right. For the same reason the EP_Collate flag
  765. ** is not commuted.
  766. */
  767. static void exprCommute(Parse *pParse, Expr *pExpr){
  768. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  769. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  770. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  771. if( expRight==expLeft ){
  772. /* Either X and Y both have COLLATE operator or neither do */
  773. if( expRight ){
  774. /* Both X and Y have COLLATE operators. Make sure X is always
  775. ** used by clearing the EP_Collate flag from Y. */
  776. pExpr->pRight->flags &= ~EP_Collate;
  777. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  778. /* Neither X nor Y have COLLATE operators, but X has a non-default
  779. ** collating sequence. So add the EP_Collate marker on X to cause
  780. ** it to be searched first. */
  781. pExpr->pLeft->flags |= EP_Collate;
  782. }
  783. }
  784. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  785. if( pExpr->op>=TK_GT ){
  786. assert( TK_LT==TK_GT+2 );
  787. assert( TK_GE==TK_LE+2 );
  788. assert( TK_GT>TK_EQ );
  789. assert( TK_GT<TK_LE );
  790. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  791. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  792. }
  793. }
  794. /*
  795. ** Translate from TK_xx operator to WO_xx bitmask.
  796. */
  797. static u16 operatorMask(int op){
  798. u16 c;
  799. assert( allowedOp(op) );
  800. if( op==TK_IN ){
  801. c = WO_IN;
  802. }else if( op==TK_ISNULL ){
  803. c = WO_ISNULL;
  804. }else{
  805. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  806. c = (u16)(WO_EQ<<(op-TK_EQ));
  807. }
  808. assert( op!=TK_ISNULL || c==WO_ISNULL );
  809. assert( op!=TK_IN || c==WO_IN );
  810. assert( op!=TK_EQ || c==WO_EQ );
  811. assert( op!=TK_LT || c==WO_LT );
  812. assert( op!=TK_LE || c==WO_LE );
  813. assert( op!=TK_GT || c==WO_GT );
  814. assert( op!=TK_GE || c==WO_GE );
  815. return c;
  816. }
  817. /*
  818. ** Advance to the next WhereTerm that matches according to the criteria
  819. ** established when the pScan object was initialized by whereScanInit().
  820. ** Return NULL if there are no more matching WhereTerms.
  821. */
  822. static WhereTerm *whereScanNext(WhereScan *pScan){
  823. int iCur; /* The cursor on the LHS of the term */
  824. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  825. Expr *pX; /* An expression being tested */
  826. WhereClause *pWC; /* Shorthand for pScan->pWC */
  827. WhereTerm *pTerm; /* The term being tested */
  828. int k = pScan->k; /* Where to start scanning */
  829. while( pScan->iEquiv<=pScan->nEquiv ){
  830. iCur = pScan->aEquiv[pScan->iEquiv-2];
  831. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  832. while( (pWC = pScan->pWC)!=0 ){
  833. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  834. if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
  835. if( (pTerm->eOperator & WO_EQUIV)!=0
  836. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  837. ){
  838. int j;
  839. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  840. assert( pX->op==TK_COLUMN );
  841. for(j=0; j<pScan->nEquiv; j+=2){
  842. if( pScan->aEquiv[j]==pX->iTable
  843. && pScan->aEquiv[j+1]==pX->iColumn ){
  844. break;
  845. }
  846. }
  847. if( j==pScan->nEquiv ){
  848. pScan->aEquiv[j] = pX->iTable;
  849. pScan->aEquiv[j+1] = pX->iColumn;
  850. pScan->nEquiv += 2;
  851. }
  852. }
  853. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  854. /* Verify the affinity and collating sequence match */
  855. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  856. CollSeq *pColl;
  857. Parse *pParse = pWC->pWInfo->pParse;
  858. pX = pTerm->pExpr;
  859. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  860. continue;
  861. }
  862. assert(pX->pLeft);
  863. pColl = sqlite3BinaryCompareCollSeq(pParse,
  864. pX->pLeft, pX->pRight);
  865. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  866. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  867. continue;
  868. }
  869. }
  870. if( (pTerm->eOperator & WO_EQ)!=0
  871. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  872. && pX->iTable==pScan->aEquiv[0]
  873. && pX->iColumn==pScan->aEquiv[1]
  874. ){
  875. continue;
  876. }
  877. pScan->k = k+1;
  878. return pTerm;
  879. }
  880. }
  881. }
  882. pScan->pWC = pScan->pWC->pOuter;
  883. k = 0;
  884. }
  885. pScan->pWC = pScan->pOrigWC;
  886. k = 0;
  887. pScan->iEquiv += 2;
  888. }
  889. return 0;
  890. }
  891. /*
  892. ** Initialize a WHERE clause scanner object. Return a pointer to the
  893. ** first match. Return NULL if there are no matches.
  894. **
  895. ** The scanner will be searching the WHERE clause pWC. It will look
  896. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  897. ** iCur. The <op> must be one of the operators described by opMask.
  898. **
  899. ** If the search is for X and the WHERE clause contains terms of the
  900. ** form X=Y then this routine might also return terms of the form
  901. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  902. ** but is enough to handle most commonly occurring SQL statements.
  903. **
  904. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  905. ** index pIdx.
  906. */
  907. static WhereTerm *whereScanInit(
  908. WhereScan *pScan, /* The WhereScan object being initialized */
  909. WhereClause *pWC, /* The WHERE clause to be scanned */
  910. int iCur, /* Cursor to scan for */
  911. int iColumn, /* Column to scan for */
  912. u32 opMask, /* Operator(s) to scan for */
  913. Index *pIdx /* Must be compatible with this index */
  914. ){
  915. int j;
  916. /* memset(pScan, 0, sizeof(*pScan)); */
  917. pScan->pOrigWC = pWC;
  918. pScan->pWC = pWC;
  919. if( pIdx && iColumn>=0 ){
  920. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  921. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  922. if( NEVER(j>=pIdx->nColumn) ) return 0;
  923. }
  924. pScan->zCollName = pIdx->azColl[j];
  925. }else{
  926. pScan->idxaff = 0;
  927. pScan->zCollName = 0;
  928. }
  929. pScan->opMask = opMask;
  930. pScan->k = 0;
  931. pScan->aEquiv[0] = iCur;
  932. pScan->aEquiv[1] = iColumn;
  933. pScan->nEquiv = 2;
  934. pScan->iEquiv = 2;
  935. return whereScanNext(pScan);
  936. }
  937. /*
  938. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  939. ** where X is a reference to the iColumn of table iCur and <op> is one of
  940. ** the WO_xx operator codes specified by the op parameter.
  941. ** Return a pointer to the term. Return 0 if not found.
  942. **
  943. ** The term returned might by Y=<expr> if there is another constraint in
  944. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  945. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  946. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  947. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  948. ** and the second is for the column number. There are 22 slots in aEquiv[]
  949. ** so that means we can look for X plus up to 10 other equivalent values.
  950. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  951. ** and ... and A9=A10 and A10=<expr>.
  952. **
  953. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  954. ** then try for the one with no dependencies on <expr> - in other words where
  955. ** <expr> is a constant expression of some kind. Only return entries of
  956. ** the form "X <op> Y" where Y is a column in another table if no terms of
  957. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  958. ** exist, try to return a term that does not use WO_EQUIV.
  959. */
  960. static WhereTerm *findTerm(
  961. WhereClause *pWC, /* The WHERE clause to be searched */
  962. int iCur, /* Cursor number of LHS */
  963. int iColumn, /* Column number of LHS */
  964. Bitmask notReady, /* RHS must not overlap with this mask */
  965. u32 op, /* Mask of WO_xx values describing operator */
  966. Index *pIdx /* Must be compatible with this index, if not NULL */
  967. ){
  968. WhereTerm *pResult = 0;
  969. WhereTerm *p;
  970. WhereScan scan;
  971. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  972. while( p ){
  973. if( (p->prereqRight & notReady)==0 ){
  974. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  975. return p;
  976. }
  977. if( pResult==0 ) pResult = p;
  978. }
  979. p = whereScanNext(&scan);
  980. }
  981. return pResult;
  982. }
  983. /* Forward reference */
  984. static void exprAnalyze(SrcList*, WhereClause*, int);
  985. /*
  986. ** Call exprAnalyze on all terms in a WHERE clause.
  987. */
  988. static void exprAnalyzeAll(
  989. SrcList *pTabList, /* the FROM clause */
  990. WhereClause *pWC /* the WHERE clause to be analyzed */
  991. ){
  992. int i;
  993. for(i=pWC->nTerm-1; i>=0; i--){
  994. exprAnalyze(pTabList, pWC, i);
  995. }
  996. }
  997. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  998. /*
  999. ** Check to see if the given expression is a LIKE or GLOB operator that
  1000. ** can be optimized using inequality constraints. Return TRUE if it is
  1001. ** so and false if not.
  1002. **
  1003. ** In order for the operator to be optimizible, the RHS must be a string
  1004. ** literal that does not begin with a wildcard.
  1005. */
  1006. static int isLikeOrGlob(
  1007. Parse *pParse, /* Parsing and code generating context */
  1008. Expr *pExpr, /* Test this expression */
  1009. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  1010. int *pisComplete, /* True if the only wildcard is % in the last character */
  1011. int *pnoCase /* True if uppercase is equivalent to lowercase */
  1012. ){
  1013. const char *z = 0; /* String on RHS of LIKE operator */
  1014. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  1015. ExprList *pList; /* List of operands to the LIKE operator */
  1016. int c; /* One character in z[] */
  1017. int cnt; /* Number of non-wildcard prefix characters */
  1018. char wc[3]; /* Wildcard characters */
  1019. sqlite3 *db = pParse->db; /* Database connection */
  1020. sqlite3_value *pVal = 0;
  1021. int op; /* Opcode of pRight */
  1022. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  1023. return 0;
  1024. }
  1025. #ifdef SQLITE_EBCDIC
  1026. if( *pnoCase ) return 0;
  1027. #endif
  1028. pList = pExpr->x.pList;
  1029. pLeft = pList->a[1].pExpr;
  1030. if( pLeft->op!=TK_COLUMN
  1031. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  1032. || IsVirtual(pLeft->pTab)
  1033. ){
  1034. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  1035. ** be the name of an indexed column with TEXT affinity. */
  1036. return 0;
  1037. }
  1038. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  1039. pRight = pList->a[0].pExpr;
  1040. op = pRight->op;
  1041. if( op==TK_REGISTER ){
  1042. op = pRight->op2;
  1043. }
  1044. if( op==TK_VARIABLE ){
  1045. Vdbe *pReprepare = pParse->pReprepare;
  1046. int iCol = pRight->iColumn;
  1047. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  1048. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  1049. z = (char *)sqlite3_value_text(pVal);
  1050. }
  1051. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  1052. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  1053. }else if( op==TK_STRING ){
  1054. z = pRight->u.zToken;
  1055. }
  1056. if( z ){
  1057. cnt = 0;
  1058. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  1059. cnt++;
  1060. }
  1061. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  1062. Expr *pPrefix;
  1063. *pisComplete = c==wc[0] && z[cnt+1]==0;
  1064. pPrefix = sqlite3Expr(db, TK_STRING, z);
  1065. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  1066. *ppPrefix = pPrefix;
  1067. if( op==TK_VARIABLE ){
  1068. Vdbe *v = pParse->pVdbe;
  1069. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  1070. if( *pisComplete && pRight->u.zToken[1] ){
  1071. /* If the rhs of the LIKE expression is a variable, and the current
  1072. ** value of the variable means there is no need to invoke the LIKE
  1073. ** function, then no OP_Variable will be added to the program.
  1074. ** This causes problems for the sqlite3_bind_parameter_name()
  1075. ** API. To workaround them, add a dummy OP_Variable here.
  1076. */
  1077. int r1 = sqlite3GetTempReg(pParse);
  1078. sqlite3ExprCodeTarget(pParse, pRight, r1);
  1079. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  1080. sqlite3ReleaseTempReg(pParse, r1);
  1081. }
  1082. }
  1083. }else{
  1084. z = 0;
  1085. }
  1086. }
  1087. sqlite3ValueFree(pVal);
  1088. return (z!=0);
  1089. }
  1090. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  1091. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1092. /*
  1093. ** Check to see if the given expression is of the form
  1094. **
  1095. ** column MATCH expr
  1096. **
  1097. ** If it is then return TRUE. If not, return FALSE.
  1098. */
  1099. static int isMatchOfColumn(
  1100. Expr *pExpr /* Test this expression */
  1101. ){
  1102. ExprList *pList;
  1103. if( pExpr->op!=TK_FUNCTION ){
  1104. return 0;
  1105. }
  1106. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  1107. return 0;
  1108. }
  1109. pList = pExpr->x.pList;
  1110. if( pList->nExpr!=2 ){
  1111. return 0;
  1112. }
  1113. if( pList->a[1].pExpr->op != TK_COLUMN ){
  1114. return 0;
  1115. }
  1116. return 1;
  1117. }
  1118. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  1119. /*
  1120. ** If the pBase expression originated in the ON or USING clause of
  1121. ** a join, then transfer the appropriate markings over to derived.
  1122. */
  1123. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  1124. if( pDerived ){
  1125. pDerived->flags |= pBase->flags & EP_FromJoin;
  1126. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  1127. }
  1128. }
  1129. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  1130. /*
  1131. ** Analyze a term that consists of two or more OR-connected
  1132. ** subterms. So in:
  1133. **
  1134. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  1135. ** ^^^^^^^^^^^^^^^^^^^^
  1136. **
  1137. ** This routine analyzes terms such as the middle term in the above example.
  1138. ** A WhereOrTerm object is computed and attached to the term under
  1139. ** analysis, regardless of the outcome of the analysis. Hence:
  1140. **
  1141. ** WhereTerm.wtFlags |= TERM_ORINFO
  1142. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  1143. **
  1144. ** The term being analyzed must have two or more of OR-connected subterms.
  1145. ** A single subterm might be a set of AND-connected sub-subterms.
  1146. ** Examples of terms under analysis:
  1147. **
  1148. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  1149. ** (B) x=expr1 OR expr2=x OR x=expr3
  1150. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  1151. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  1152. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  1153. **
  1154. ** CASE 1:
  1155. **
  1156. ** If all subterms are of the form T.C=expr for some single column of C and
  1157. ** a single table T (as shown in example B above) then create a new virtual
  1158. ** term that is an equivalent IN expression. In other words, if the term
  1159. ** being analyzed is:
  1160. **
  1161. ** x = expr1 OR expr2 = x OR x = expr3
  1162. **
  1163. ** then create a new virtual term like this:
  1164. **
  1165. ** x IN (expr1,expr2,expr3)
  1166. **
  1167. ** CASE 2:
  1168. **
  1169. ** If all subterms are indexable by a single table T, then set
  1170. **
  1171. ** WhereTerm.eOperator = WO_OR
  1172. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  1173. **
  1174. ** A subterm is "indexable" if it is of the form
  1175. ** "T.C <op> <expr>" where C is any column of table T and
  1176. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  1177. ** A subterm is also indexable if it is an AND of two or more
  1178. ** subsubterms at least one of which is indexable. Indexable AND
  1179. ** subterms have their eOperator set to WO_AND and they have
  1180. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  1181. **
  1182. ** From another point of view, "indexable" means that the subterm could
  1183. ** potentially be used with an index if an appropriate index exists.
  1184. ** This analysis does not consider whether or not the index exists; that
  1185. ** is decided elsewhere. This analysis only looks at whether subterms
  1186. ** appropriate for indexing exist.
  1187. **
  1188. ** All examples A through E above satisfy case 2. But if a term
  1189. ** also statisfies case 1 (such as B) we know that the optimizer will
  1190. ** always prefer case 1, so in that case we pretend that case 2 is not
  1191. ** satisfied.
  1192. **
  1193. ** It might be the case that multiple tables are indexable. For example,
  1194. ** (E) above is indexable on tables P, Q, and R.
  1195. **
  1196. ** Terms that satisfy case 2 are candidates for lookup by using
  1197. ** separate indices to find rowids for each subterm and composing
  1198. ** the union of all rowids using a RowSet object. This is similar
  1199. ** to "bitmap indices" in other database engines.
  1200. **
  1201. ** OTHERWISE:
  1202. **
  1203. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  1204. ** zero. This term is not useful for search.
  1205. */
  1206. static void exprAnalyzeOrTerm(
  1207. SrcList *pSrc, /* the FROM clause */
  1208. WhereClause *pWC, /* the complete WHERE clause */
  1209. int idxTerm /* Index of the OR-term to be analyzed */
  1210. ){
  1211. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  1212. Parse *pParse = pWInfo->pParse; /* Parser context */
  1213. sqlite3 *db = pParse->db; /* Database connection */
  1214. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  1215. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  1216. int i; /* Loop counters */
  1217. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  1218. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  1219. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  1220. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  1221. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  1222. /*
  1223. ** Break the OR clause into its separate subterms. The subterms are
  1224. ** stored in a WhereClause structure containing within the WhereOrInfo
  1225. ** object that is attached to the original OR clause term.
  1226. */
  1227. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  1228. assert( pExpr->op==TK_OR );
  1229. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  1230. if( pOrInfo==0 ) return;
  1231. pTerm->wtFlags |= TERM_ORINFO;
  1232. pOrWc = &pOrInfo->wc;
  1233. whereClauseInit(pOrWc, pWInfo);
  1234. whereSplit(pOrWc, pExpr, TK_OR);
  1235. exprAnalyzeAll(pSrc, pOrWc);
  1236. if( db->mallocFailed ) return;
  1237. assert( pOrWc->nTerm>=2 );
  1238. /*
  1239. ** Compute the set of tables that might satisfy cases 1 or 2.
  1240. */
  1241. indexable = ~(Bitmask)0;
  1242. chngToIN = ~(Bitmask)0;
  1243. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  1244. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  1245. WhereAndInfo *pAndInfo;
  1246. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  1247. chngToIN = 0;
  1248. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  1249. if( pAndInfo ){
  1250. WhereClause *pAndWC;
  1251. WhereTerm *pAndTerm;
  1252. int j;
  1253. Bitmask b = 0;
  1254. pOrTerm->u.pAndInfo = pAndInfo;
  1255. pOrTerm->wtFlags |= TERM_ANDINFO;
  1256. pOrTerm->eOperator = WO_AND;
  1257. pAndWC = &pAndInfo->wc;
  1258. whereClauseInit(pAndWC, pWC->pWInfo);
  1259. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  1260. exprAnalyzeAll(pSrc, pAndWC);
  1261. pAndWC->pOuter = pWC;
  1262. testcase( db->mallocFailed );
  1263. if( !db->mallocFailed ){
  1264. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  1265. assert( pAndTerm->pExpr );
  1266. if( allowedOp(pAndTerm->pExpr->op) ){
  1267. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  1268. }
  1269. }
  1270. }
  1271. indexable &= b;
  1272. }
  1273. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  1274. /* Skip this term for now. We revisit it when we process the
  1275. ** corresponding TERM_VIRTUAL term */
  1276. }else{
  1277. Bitmask b;
  1278. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  1279. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  1280. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  1281. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  1282. }
  1283. indexable &= b;
  1284. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  1285. chngToIN = 0;
  1286. }else{
  1287. chngToIN &= b;
  1288. }
  1289. }
  1290. }
  1291. /*
  1292. ** Record the set of tables that satisfy case 2. The set might be
  1293. ** empty.
  1294. */
  1295. pOrInfo->indexable = indexable;
  1296. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  1297. /*
  1298. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  1299. ** we have to do some additional checking to see if case 1 really
  1300. ** is satisfied.
  1301. **
  1302. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  1303. ** that there is no possibility of transforming the OR clause into an
  1304. ** IN operator because one or more terms in the OR clause contain
  1305. ** something other than == on a column in the single table. The 1-bit
  1306. ** case means that every term of the OR clause is of the form
  1307. ** "table.column=expr" for some single table. The one bit that is set
  1308. ** will correspond to the common table. We still need to check to make
  1309. ** sure the same column is used on all terms. The 2-bit case is when
  1310. ** the all terms are of the form "table1.column=table2.column". It
  1311. ** might be possible to form an IN operator with either table1.column
  1312. ** or table2.column as the LHS if either is common to every term of
  1313. ** the OR clause.
  1314. **
  1315. ** Note that terms of the form "table.column1=table.column2" (the
  1316. ** same table on both sizes of the ==) cannot be optimized.
  1317. */
  1318. if( chngToIN ){
  1319. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  1320. int iColumn = -1; /* Column index on lhs of IN operator */
  1321. int iCursor = -1; /* Table cursor common to all terms */
  1322. int j = 0; /* Loop counter */
  1323. /* Search for a table and column that appears on one side or the
  1324. ** other of the == operator in every subterm. That table and column
  1325. ** will be recorded in iCursor and iColumn. There might not be any
  1326. ** such table and column. Set okToChngToIN if an appropriate table
  1327. ** and column is found but leave okToChngToIN false if not found.
  1328. */
  1329. for(j=0; j<2 && !okToChngToIN; j++){
  1330. pOrTerm = pOrWc->a;
  1331. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  1332. assert( pOrTerm->eOperator & WO_EQ );
  1333. pOrTerm->wtFlags &= ~TERM_OR_OK;
  1334. if( pOrTerm->leftCursor==iCursor ){
  1335. /* This is the 2-bit case and we are on the second iteration and
  1336. ** current term is from the first iteration. So skip this term. */
  1337. assert( j==1 );
  1338. continue;
  1339. }
  1340. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  1341. /* This term must be of the form t1.a==t2.b where t2 is in the
  1342. ** chngToIN set but t1 is not. This term will be either preceeded
  1343. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  1344. ** and use its inversion. */
  1345. testcase( pOrTerm->wtFlags & TERM_COPIED );
  1346. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  1347. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  1348. continue;
  1349. }
  1350. iColumn = pOrTerm->u.leftColumn;
  1351. iCursor = pOrTerm->leftCursor;
  1352. break;
  1353. }
  1354. if( i<0 ){
  1355. /* No candidate table+column was found. This can only occur
  1356. ** on the second iteration */
  1357. assert( j==1 );
  1358. assert( IsPowerOfTwo(chngToIN) );
  1359. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  1360. break;
  1361. }
  1362. testcase( j==1 );
  1363. /* We have found a candidate table and column. Check to see if that
  1364. ** table and column is common to every term in the OR clause */
  1365. okToChngToIN = 1;
  1366. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  1367. assert( pOrTerm->eOperator & WO_EQ );
  1368. if( pOrTerm->leftCursor!=iCursor ){
  1369. pOrTerm->wtFlags &= ~TERM_OR_OK;
  1370. }else if( pOrTerm->u.leftColumn!=iColumn ){
  1371. okToChngToIN = 0;
  1372. }else{
  1373. int affLeft, affRight;
  1374. /* If the right-hand side is also a column, then the affinities
  1375. ** of both right and left sides must be such that no type
  1376. ** conversions are required on the right. (Ticket #2249)
  1377. */
  1378. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  1379. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  1380. if( affRight!=0 && affRight!=affLeft ){
  1381. okToChngToIN = 0;
  1382. }else{
  1383. pOrTerm->wtFlags |= TERM_OR_OK;
  1384. }
  1385. }
  1386. }
  1387. }
  1388. /* At this point, okToChngToIN is true if original pTerm satisfies
  1389. ** case 1. In that case, construct a new virtual term that is
  1390. ** pTerm converted into an IN operator.
  1391. */
  1392. if( okToChngToIN ){
  1393. Expr *pDup; /* A transient duplicate expression */
  1394. ExprList *pList = 0; /* The RHS of the IN operator */
  1395. Expr *pLeft = 0; /* The LHS of the IN operator */
  1396. Expr *pNew; /* The complete IN operator */
  1397. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  1398. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  1399. assert( pOrTerm->eOperator & WO_EQ );
  1400. assert( pOrTerm->leftCursor==iCursor );
  1401. assert( pOrTerm->u.leftColumn==iColumn );
  1402. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  1403. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  1404. pLeft = pOrTerm->pExpr->pLeft;
  1405. }
  1406. assert( pLeft!=0 );
  1407. pDup = sqlite3ExprDup(db, pLeft, 0);
  1408. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  1409. if( pNew ){
  1410. int idxNew;
  1411. transferJoinMarkings(pNew, pExpr);
  1412. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  1413. pNew->x.pList = pList;
  1414. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  1415. testcase( idxNew==0 );
  1416. exprAnalyze(pSrc, pWC, idxNew);
  1417. pTerm = &pWC->a[idxTerm];
  1418. pWC->a[idxNew].iParent = idxTerm;
  1419. pTerm->nChild = 1;
  1420. }else{
  1421. sqlite3ExprListDelete(db, pList);
  1422. }
  1423. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  1424. }
  1425. }
  1426. }
  1427. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  1428. /*
  1429. ** The input to this routine is an WhereTerm structure with only the
  1430. ** "pExpr" field filled in. The job of this routine is to analyze the
  1431. ** subexpression and populate all the other fields of the WhereTerm
  1432. ** structure.
  1433. **
  1434. ** If the expression is of the form "<expr> <op> X" it gets commuted
  1435. ** to the standard form of "X <op> <expr>".
  1436. **
  1437. ** If the expression is of the form "X <op> Y" where both X and Y are
  1438. ** columns, then the original expression is unchanged and a new virtual
  1439. ** term of the form "Y <op> X" is added to the WHERE clause and
  1440. ** analyzed separately. The original term is marked with TERM_COPIED
  1441. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  1442. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  1443. ** is a commuted copy of a prior term.) The original term has nChild=1
  1444. ** and the copy has idxParent set to the index of the original term.
  1445. */
  1446. static void exprAnalyze(
  1447. SrcList *pSrc, /* the FROM clause */
  1448. WhereClause *pWC, /* the WHERE clause */
  1449. int idxTerm /* Index of the term to be analyzed */
  1450. ){
  1451. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  1452. WhereTerm *pTerm; /* The term to be analyzed */
  1453. WhereMaskSet *pMaskSet; /* Set of table index masks */
  1454. Expr *pExpr; /* The expression to be analyzed */
  1455. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  1456. Bitmask prereqAll; /* Prerequesites of pExpr */
  1457. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  1458. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  1459. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  1460. int noCase = 0; /* LIKE/GLOB distinguishes case */
  1461. int op; /* Top-level operator. pExpr->op */
  1462. Parse *pParse = pWInfo->pParse; /* Parsing context */
  1463. sqlite3 *db = pParse->db; /* Database connection */
  1464. if( db->mallocFailed ){
  1465. return;
  1466. }
  1467. pTerm = &pWC->a[idxTerm];
  1468. pMaskSet = &pWInfo->sMaskSet;
  1469. pExpr = pTerm->pExpr;
  1470. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  1471. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  1472. op = pExpr->op;
  1473. if( op==TK_IN ){
  1474. assert( pExpr->pRight==0 );
  1475. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  1476. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  1477. }else{
  1478. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  1479. }
  1480. }else if( op==TK_ISNULL ){
  1481. pTerm->prereqRight = 0;
  1482. }else{
  1483. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  1484. }
  1485. prereqAll = exprTableUsage(pMaskSet, pExpr);
  1486. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  1487. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  1488. prereqAll |= x;
  1489. extraRight = x-1; /* ON clause terms may not be used with an index
  1490. ** on left table of a LEFT JOIN. Ticket #3015 */
  1491. }
  1492. pTerm->prereqAll = prereqAll;
  1493. pTerm->leftCursor = -1;
  1494. pTerm->iParent = -1;
  1495. pTerm->eOperator = 0;
  1496. if( allowedOp(op) ){
  1497. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  1498. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  1499. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  1500. if( pLeft->op==TK_COLUMN ){
  1501. pTerm->leftCursor = pLeft->iTable;
  1502. pTerm->u.leftColumn = pLeft->iColumn;
  1503. pTerm->eOperator = operatorMask(op) & opMask;
  1504. }
  1505. if( pRight && pRight->op==TK_COLUMN ){
  1506. WhereTerm *pNew;
  1507. Expr *pDup;
  1508. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  1509. if( pTerm->leftCursor>=0 ){
  1510. int idxNew;
  1511. pDup = sqlite3ExprDup(db, pExpr, 0);
  1512. if( db->mallocFailed ){
  1513. sqlite3ExprDelete(db, pDup);
  1514. return;
  1515. }
  1516. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  1517. if( idxNew==0 ) return;
  1518. pNew = &pWC->a[idxNew];
  1519. pNew->iParent = idxTerm;
  1520. pTerm = &pWC->a[idxTerm];
  1521. pTerm->nChild = 1;
  1522. pTerm->wtFlags |= TERM_COPIED;
  1523. if( pExpr->op==TK_EQ
  1524. && !ExprHasProperty(pExpr, EP_FromJoin)
  1525. && OptimizationEnabled(db, SQLITE_Transitive)
  1526. ){
  1527. pTerm->eOperator |= WO_EQUIV;
  1528. eExtraOp = WO_EQUIV;
  1529. }
  1530. }else{
  1531. pDup = pExpr;
  1532. pNew = pTerm;
  1533. }
  1534. exprCommute(pParse, pDup);
  1535. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  1536. pNew->leftCursor = pLeft->iTable;
  1537. pNew->u.leftColumn = pLeft->iColumn;
  1538. testcase( (prereqLeft | extraRight) != prereqLeft );
  1539. pNew->prereqRight = prereqLeft | extraRight;
  1540. pNew->prereqAll = prereqAll;
  1541. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  1542. }
  1543. }
  1544. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  1545. /* If a term is the BETWEEN operator, create two new virtual terms
  1546. ** that define the range that the BETWEEN implements. For example:
  1547. **
  1548. ** a BETWEEN b AND c
  1549. **
  1550. ** is converted into:
  1551. **
  1552. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  1553. **
  1554. ** The two new terms are added onto the end of the WhereClause object.
  1555. ** The new terms are "dynamic" and are children of the original BETWEEN
  1556. ** term. That means that if the BETWEEN term is coded, the children are
  1557. ** skipped. Or, if the children are satisfied by an index, the original
  1558. ** BETWEEN term is skipped.
  1559. */
  1560. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  1561. ExprList *pList = pExpr->x.pList;
  1562. int i;
  1563. static const u8 ops[] = {TK_GE, TK_LE};
  1564. assert( pList!=0 );
  1565. assert( pList->nExpr==2 );
  1566. for(i=0; i<2; i++){
  1567. Expr *pNewExpr;
  1568. int idxNew;
  1569. pNewExpr = sqlite3PExpr(pParse, ops[i],
  1570. sqlite3ExprDup(db, pExpr->pLeft, 0),
  1571. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  1572. transferJoinMarkings(pNewExpr, pExpr);
  1573. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  1574. testcase( idxNew==0 );
  1575. exprAnalyze(pSrc, pWC, idxNew);
  1576. pTerm = &pWC->a[idxTerm];
  1577. pWC->a[idxNew].iParent = idxTerm;
  1578. }
  1579. pTerm->nChild = 2;
  1580. }
  1581. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  1582. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  1583. /* Analyze a term that is composed of two or more subterms connected by
  1584. ** an OR operator.
  1585. */
  1586. else if( pExpr->op==TK_OR ){
  1587. assert( pWC->op==TK_AND );
  1588. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  1589. pTerm = &pWC->a[idxTerm];
  1590. }
  1591. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  1592. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  1593. /* Add constraints to reduce the search space on a LIKE or GLOB
  1594. ** operator.
  1595. **
  1596. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  1597. **
  1598. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  1599. **
  1600. ** The last character of the prefix "abc" is incremented to form the
  1601. ** termination condition "abd".
  1602. */
  1603. if( pWC->op==TK_AND
  1604. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  1605. ){
  1606. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  1607. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  1608. Expr *pNewExpr1;
  1609. Expr *pNewExpr2;
  1610. int idxNew1;
  1611. int idxNew2;
  1612. Token sCollSeqName; /* Name of collating sequence */
  1613. pLeft = pExpr->x.pList->a[1].pExpr;
  1614. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  1615. if( !db->mallocFailed ){
  1616. u8 c, *pC; /* Last character before the first wildcard */
  1617. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  1618. c = *pC;
  1619. if( noCase ){
  1620. /* The point is to increment the last character before the first
  1621. ** wildcard. But if we increment '@', that will push it into the
  1622. ** alphabetic range where case conversions will mess up the
  1623. ** inequality. To avoid this, make sure to also run the full
  1624. ** LIKE on all candidate expressions by clearing the isComplete flag
  1625. */
  1626. if( c=='A'-1 ) isComplete = 0;
  1627. c = sqlite3UpperToLower[c];
  1628. }
  1629. *pC = c + 1;
  1630. }
  1631. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  1632. sCollSeqName.n = 6;
  1633. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  1634. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  1635. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  1636. pStr1, 0);
  1637. transferJoinMarkings(pNewExpr1, pExpr);
  1638. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  1639. testcase( idxNew1==0 );
  1640. exprAnalyze(pSrc, pWC, idxNew1);
  1641. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  1642. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  1643. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  1644. pStr2, 0);
  1645. transferJoinMarkings(pNewExpr2, pExpr);
  1646. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  1647. testcase( idxNew2==0 );
  1648. exprAnalyze(pSrc, pWC, idxNew2);
  1649. pTerm = &pWC->a[idxTerm];
  1650. if( isComplete ){
  1651. pWC->a[idxNew1].iParent = idxTerm;
  1652. pWC->a[idxNew2].iParent = idxTerm;
  1653. pTerm->nChild = 2;
  1654. }
  1655. }
  1656. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  1657. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1658. /* Add a WO_MATCH auxiliary term to the constraint set if the
  1659. ** current expression is of the form: column MATCH expr.
  1660. ** This information is used by the xBestIndex methods of
  1661. ** virtual tables. The native query optimizer does not attempt
  1662. ** to do anything with MATCH functions.
  1663. */
  1664. if( isMatchOfColumn(pExpr) ){
  1665. int idxNew;
  1666. Expr *pRight, *pLeft;
  1667. WhereTerm *pNewTerm;
  1668. Bitmask prereqColumn, prereqExpr;
  1669. pRight = pExpr->x.pList->a[0].pExpr;
  1670. pLeft = pExpr->x.pList->a[1].pExpr;
  1671. prereqExpr = exprTableUsage(pMaskSet, pRight);
  1672. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  1673. if( (prereqExpr & prereqColumn)==0 ){
  1674. Expr *pNewExpr;
  1675. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  1676. 0, sqlite3ExprDup(db, pRight, 0), 0);
  1677. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  1678. testcase( idxNew==0 );
  1679. pNewTerm = &pWC->a[idxNew];
  1680. pNewTerm->prereqRight = prereqExpr;
  1681. pNewTerm->leftCursor = pLeft->iTable;
  1682. pNewTerm->u.leftColumn = pLeft->iColumn;
  1683. pNewTerm->eOperator = WO_MATCH;
  1684. pNewTerm->iParent = idxTerm;
  1685. pTerm = &pWC->a[idxTerm];
  1686. pTerm->nChild = 1;
  1687. pTerm->wtFlags |= TERM_COPIED;
  1688. pNewTerm->prereqAll = pTerm->prereqAll;
  1689. }
  1690. }
  1691. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  1692. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  1693. /* When sqlite_stat3 histogram data is available an operator of the
  1694. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  1695. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  1696. ** virtual term of that form.
  1697. **
  1698. ** Note that the virtual term must be tagged with TERM_VNULL. This
  1699. ** TERM_VNULL tag will suppress the not-null check at the beginning
  1700. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  1701. ** the start of the loop will prevent any results from being returned.
  1702. */
  1703. if( pExpr->op==TK_NOTNULL
  1704. && pExpr->pLeft->op==TK_COLUMN
  1705. && pExpr->pLeft->iColumn>=0
  1706. && OptimizationEnabled(db, SQLITE_Stat3)
  1707. ){
  1708. Expr *pNewExpr;
  1709. Expr *pLeft = pExpr->pLeft;
  1710. int idxNew;
  1711. WhereTerm *pNewTerm;
  1712. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  1713. sqlite3ExprDup(db, pLeft, 0),
  1714. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  1715. idxNew = whereClauseInsert(pWC, pNewExpr,
  1716. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  1717. if( idxNew ){
  1718. pNewTerm = &pWC->a[idxNew];
  1719. pNewTerm->prereqRight = 0;
  1720. pNewTerm->leftCursor = pLeft->iTable;
  1721. pNewTerm->u.leftColumn = pLeft->iColumn;
  1722. pNewTerm->eOperator = WO_GT;
  1723. pNewTerm->iParent = idxTerm;
  1724. pTerm = &pWC->a[idxTerm];
  1725. pTerm->nChild = 1;
  1726. pTerm->wtFlags |= TERM_COPIED;
  1727. pNewTerm->prereqAll = pTerm->prereqAll;
  1728. }
  1729. }
  1730. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  1731. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  1732. ** an index for tables to the left of the join.
  1733. */
  1734. pTerm->prereqRight |= extraRight;
  1735. }
  1736. /*
  1737. ** This function searches pList for a entry that matches the iCol-th column
  1738. ** of index pIdx.
  1739. **
  1740. ** If such an expression is found, its index in pList->a[] is returned. If
  1741. ** no expression is found, -1 is returned.
  1742. */
  1743. static int findIndexCol(
  1744. Parse *pParse, /* Parse context */
  1745. ExprList *pList, /* Expression list to search */
  1746. int iBase, /* Cursor for table associated with pIdx */
  1747. Index *pIdx, /* Index to match column of */
  1748. int iCol /* Column of index to match */
  1749. ){
  1750. int i;
  1751. const char *zColl = pIdx->azColl[iCol];
  1752. for(i=0; i<pList->nExpr; i++){
  1753. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  1754. if( p->op==TK_COLUMN
  1755. && p->iColumn==pIdx->aiColumn[iCol]
  1756. && p->iTable==iBase
  1757. ){
  1758. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  1759. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  1760. return i;
  1761. }
  1762. }
  1763. }
  1764. return -1;
  1765. }
  1766. /*
  1767. ** Return true if the DISTINCT expression-list passed as the third argument
  1768. ** is redundant.
  1769. **
  1770. ** A DISTINCT list is redundant if the database contains some subset of
  1771. ** columns that are unique and non-null.
  1772. */
  1773. static int isDistinctRedundant(
  1774. Parse *pParse, /* Parsing context */
  1775. SrcList *pTabList, /* The FROM clause */
  1776. WhereClause *pWC, /* The WHERE clause */
  1777. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  1778. ){
  1779. Table *pTab;
  1780. Index *pIdx;
  1781. int i;
  1782. int iBase;
  1783. /* If there is more than one table or sub-select in the FROM clause of
  1784. ** this query, then it will not be possible to show that the DISTINCT
  1785. ** clause is redundant. */
  1786. if( pTabList->nSrc!=1 ) return 0;
  1787. iBase = pTabList->a[0].iCursor;
  1788. pTab = pTabList->a[0].pTab;
  1789. /* If any of the expressions is an IPK column on table iBase, then return
  1790. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  1791. ** current SELECT is a correlated sub-query.
  1792. */
  1793. for(i=0; i<pDistinct->nExpr; i++){
  1794. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  1795. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  1796. }
  1797. /* Loop through all indices on the table, checking each to see if it makes
  1798. ** the DISTINCT qualifier redundant. It does so if:
  1799. **
  1800. ** 1. The index is itself UNIQUE, and
  1801. **
  1802. ** 2. All of the columns in the index are either part of the pDistinct
  1803. ** list, or else the WHERE clause contains a term of the form "col=X",
  1804. ** where X is a constant value. The collation sequences of the
  1805. ** comparison and select-list expressions must match those of the index.
  1806. **
  1807. ** 3. All of those index columns for which the WHERE clause does not
  1808. ** contain a "col=X" term are subject to a NOT NULL constraint.
  1809. */
  1810. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1811. if( pIdx->onError==OE_None ) continue;
  1812. for(i=0; i<pIdx->nColumn; i++){
  1813. int iCol = pIdx->aiColumn[i];
  1814. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  1815. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  1816. if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
  1817. break;
  1818. }
  1819. }
  1820. }
  1821. if( i==pIdx->nColumn ){
  1822. /* This index implies that the DISTINCT qualifier is redundant. */
  1823. return 1;
  1824. }
  1825. }
  1826. return 0;
  1827. }
  1828. /*
  1829. ** Estimate the logarithm of the input value to base 2.
  1830. */
  1831. static LogEst estLog(LogEst N){
  1832. LogEst x = sqlite3LogEst(N);
  1833. return x>33 ? x - 33 : 0;
  1834. }
  1835. /*
  1836. ** Two routines for printing the content of an sqlite3_index_info
  1837. ** structure. Used for testing and debugging only. If neither
  1838. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  1839. ** are no-ops.
  1840. */
  1841. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  1842. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  1843. int i;
  1844. if( !sqlite3WhereTrace ) return;
  1845. for(i=0; i<p->nConstraint; i++){
  1846. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  1847. i,
  1848. p->aConstraint[i].iColumn,
  1849. p->aConstraint[i].iTermOffset,
  1850. p->aConstraint[i].op,
  1851. p->aConstraint[i].usable);
  1852. }
  1853. for(i=0; i<p->nOrderBy; i++){
  1854. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  1855. i,
  1856. p->aOrderBy[i].iColumn,
  1857. p->aOrderBy[i].desc);
  1858. }
  1859. }
  1860. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  1861. int i;
  1862. if( !sqlite3WhereTrace ) return;
  1863. for(i=0; i<p->nConstraint; i++){
  1864. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  1865. i,
  1866. p->aConstraintUsage[i].argvIndex,
  1867. p->aConstraintUsage[i].omit);
  1868. }
  1869. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  1870. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  1871. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  1872. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  1873. }
  1874. #else
  1875. #define TRACE_IDX_INPUTS(A)
  1876. #define TRACE_IDX_OUTPUTS(A)
  1877. #endif
  1878. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  1879. /*
  1880. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  1881. ** could be used with an index to access pSrc, assuming an appropriate
  1882. ** index existed.
  1883. */
  1884. static int termCanDriveIndex(
  1885. WhereTerm *pTerm, /* WHERE clause term to check */
  1886. struct SrcList_item *pSrc, /* Table we are trying to access */
  1887. Bitmask notReady /* Tables in outer loops of the join */
  1888. ){
  1889. char aff;
  1890. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  1891. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  1892. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  1893. if( pTerm->u.leftColumn<0 ) return 0;
  1894. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  1895. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  1896. return 1;
  1897. }
  1898. #endif
  1899. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  1900. /*
  1901. ** Generate code to construct the Index object for an automatic index
  1902. ** and to set up the WhereLevel object pLevel so that the code generator
  1903. ** makes use of the automatic index.
  1904. */
  1905. static void constructAutomaticIndex(
  1906. Parse *pParse, /* The parsing context */
  1907. WhereClause *pWC, /* The WHERE clause */
  1908. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  1909. Bitmask notReady, /* Mask of cursors that are not available */
  1910. WhereLevel *pLevel /* Write new index here */
  1911. ){
  1912. int nColumn; /* Number of columns in the constructed index */
  1913. WhereTerm *pTerm; /* A single term of the WHERE clause */
  1914. WhereTerm *pWCEnd; /* End of pWC->a[] */
  1915. int nByte; /* Byte of memory needed for pIdx */
  1916. Index *pIdx; /* Object describing the transient index */
  1917. Vdbe *v; /* Prepared statement under construction */
  1918. int addrInit; /* Address of the initialization bypass jump */
  1919. Table *pTable; /* The table being indexed */
  1920. KeyInfo *pKeyinfo; /* Key information for the index */
  1921. int addrTop; /* Top of the index fill loop */
  1922. int regRecord; /* Register holding an index record */
  1923. int n; /* Column counter */
  1924. int i; /* Loop counter */
  1925. int mxBitCol; /* Maximum column in pSrc->colUsed */
  1926. CollSeq *pColl; /* Collating sequence to on a column */
  1927. WhereLoop *pLoop; /* The Loop object */
  1928. Bitmask idxCols; /* Bitmap of columns used for indexing */
  1929. Bitmask extraCols; /* Bitmap of additional columns */
  1930. u8 sentWarning = 0; /* True if a warnning has been issued */
  1931. /* Generate code to skip over the creation and initialization of the
  1932. ** transient index on 2nd and subsequent iterations of the loop. */
  1933. v = pParse->pVdbe;
  1934. assert( v!=0 );
  1935. addrInit = sqlite3CodeOnce(pParse);
  1936. /* Count the number of columns that will be added to the index
  1937. ** and used to match WHERE clause constraints */
  1938. nColumn = 0;
  1939. pTable = pSrc->pTab;
  1940. pWCEnd = &pWC->a[pWC->nTerm];
  1941. pLoop = pLevel->pWLoop;
  1942. idxCols = 0;
  1943. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  1944. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  1945. int iCol = pTerm->u.leftColumn;
  1946. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  1947. testcase( iCol==BMS );
  1948. testcase( iCol==BMS-1 );
  1949. if( !sentWarning ){
  1950. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  1951. "automatic index on %s(%s)", pTable->zName,
  1952. pTable->aCol[iCol].zName);
  1953. sentWarning = 1;
  1954. }
  1955. if( (idxCols & cMask)==0 ){
  1956. if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
  1957. pLoop->aLTerm[nColumn++] = pTerm;
  1958. idxCols |= cMask;
  1959. }
  1960. }
  1961. }
  1962. assert( nColumn>0 );
  1963. pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
  1964. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  1965. | WHERE_AUTO_INDEX;
  1966. /* Count the number of additional columns needed to create a
  1967. ** covering index. A "covering index" is an index that contains all
  1968. ** columns that are needed by the query. With a covering index, the
  1969. ** original table never needs to be accessed. Automatic indices must
  1970. ** be a covering index because the index will not be updated if the
  1971. ** original table changes and the index and table cannot both be used
  1972. ** if they go out of sync.
  1973. */
  1974. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  1975. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  1976. testcase( pTable->nCol==BMS-1 );
  1977. testcase( pTable->nCol==BMS-2 );
  1978. for(i=0; i<mxBitCol; i++){
  1979. if( extraCols & MASKBIT(i) ) nColumn++;
  1980. }
  1981. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  1982. nColumn += pTable->nCol - BMS + 1;
  1983. }
  1984. pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
  1985. /* Construct the Index object to describe this index */
  1986. nByte = sizeof(Index);
  1987. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  1988. nByte += nColumn*sizeof(char*); /* Index.azColl */
  1989. nByte += nColumn; /* Index.aSortOrder */
  1990. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  1991. if( pIdx==0 ) return;
  1992. pLoop->u.btree.pIndex = pIdx;
  1993. pIdx->azColl = (char**)&pIdx[1];
  1994. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  1995. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  1996. pIdx->zName = "auto-index";
  1997. pIdx->nColumn = nColumn;
  1998. pIdx->pTable = pTable;
  1999. n = 0;
  2000. idxCols = 0;
  2001. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  2002. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  2003. int iCol = pTerm->u.leftColumn;
  2004. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  2005. testcase( iCol==BMS-1 );
  2006. testcase( iCol==BMS );
  2007. if( (idxCols & cMask)==0 ){
  2008. Expr *pX = pTerm->pExpr;
  2009. idxCols |= cMask;
  2010. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  2011. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  2012. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  2013. n++;
  2014. }
  2015. }
  2016. }
  2017. assert( (u32)n==pLoop->u.btree.nEq );
  2018. /* Add additional columns needed to make the automatic index into
  2019. ** a covering index */
  2020. for(i=0; i<mxBitCol; i++){
  2021. if( extraCols & MASKBIT(i) ){
  2022. pIdx->aiColumn[n] = i;
  2023. pIdx->azColl[n] = "BINARY";
  2024. n++;
  2025. }
  2026. }
  2027. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  2028. for(i=BMS-1; i<pTable->nCol; i++){
  2029. pIdx->aiColumn[n] = i;
  2030. pIdx->azColl[n] = "BINARY";
  2031. n++;
  2032. }
  2033. }
  2034. assert( n==nColumn );
  2035. /* Create the automatic index */
  2036. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  2037. assert( pLevel->iIdxCur>=0 );
  2038. pLevel->iIdxCur = pParse->nTab++;
  2039. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  2040. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  2041. VdbeComment((v, "for %s", pTable->zName));
  2042. /* Fill the automatic index with content */
  2043. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  2044. regRecord = sqlite3GetTempReg(pParse);
  2045. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
  2046. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  2047. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  2048. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  2049. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  2050. sqlite3VdbeJumpHere(v, addrTop);
  2051. sqlite3ReleaseTempReg(pParse, regRecord);
  2052. /* Jump here when skipping the initialization */
  2053. sqlite3VdbeJumpHere(v, addrInit);
  2054. }
  2055. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  2056. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2057. /*
  2058. ** Allocate and populate an sqlite3_index_info structure. It is the
  2059. ** responsibility of the caller to eventually release the structure
  2060. ** by passing the pointer returned by this function to sqlite3_free().
  2061. */
  2062. static sqlite3_index_info *allocateIndexInfo(
  2063. Parse *pParse,
  2064. WhereClause *pWC,
  2065. struct SrcList_item *pSrc,
  2066. ExprList *pOrderBy
  2067. ){
  2068. int i, j;
  2069. int nTerm;
  2070. struct sqlite3_index_constraint *pIdxCons;
  2071. struct sqlite3_index_orderby *pIdxOrderBy;
  2072. struct sqlite3_index_constraint_usage *pUsage;
  2073. WhereTerm *pTerm;
  2074. int nOrderBy;
  2075. sqlite3_index_info *pIdxInfo;
  2076. /* Count the number of possible WHERE clause constraints referring
  2077. ** to this virtual table */
  2078. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  2079. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  2080. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  2081. testcase( pTerm->eOperator & WO_IN );
  2082. testcase( pTerm->eOperator & WO_ISNULL );
  2083. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  2084. if( pTerm->wtFlags & TERM_VNULL ) continue;
  2085. nTerm++;
  2086. }
  2087. /* If the ORDER BY clause contains only columns in the current
  2088. ** virtual table then allocate space for the aOrderBy part of
  2089. ** the sqlite3_index_info structure.
  2090. */
  2091. nOrderBy = 0;
  2092. if( pOrderBy ){
  2093. int n = pOrderBy->nExpr;
  2094. for(i=0; i<n; i++){
  2095. Expr *pExpr = pOrderBy->a[i].pExpr;
  2096. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  2097. }
  2098. if( i==n){
  2099. nOrderBy = n;
  2100. }
  2101. }
  2102. /* Allocate the sqlite3_index_info structure
  2103. */
  2104. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  2105. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  2106. + sizeof(*pIdxOrderBy)*nOrderBy );
  2107. if( pIdxInfo==0 ){
  2108. sqlite3ErrorMsg(pParse, "out of memory");
  2109. return 0;
  2110. }
  2111. /* Initialize the structure. The sqlite3_index_info structure contains
  2112. ** many fields that are declared "const" to prevent xBestIndex from
  2113. ** changing them. We have to do some funky casting in order to
  2114. ** initialize those fields.
  2115. */
  2116. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  2117. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  2118. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  2119. *(int*)&pIdxInfo->nConstraint = nTerm;
  2120. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  2121. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  2122. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  2123. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  2124. pUsage;
  2125. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  2126. u8 op;
  2127. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  2128. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  2129. testcase( pTerm->eOperator & WO_IN );
  2130. testcase( pTerm->eOperator & WO_ISNULL );
  2131. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  2132. if( pTerm->wtFlags & TERM_VNULL ) continue;
  2133. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  2134. pIdxCons[j].iTermOffset = i;
  2135. op = (u8)pTerm->eOperator & WO_ALL;
  2136. if( op==WO_IN ) op = WO_EQ;
  2137. pIdxCons[j].op = op;
  2138. /* The direct assignment in the previous line is possible only because
  2139. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  2140. ** following asserts verify this fact. */
  2141. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  2142. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  2143. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  2144. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  2145. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  2146. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  2147. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  2148. j++;
  2149. }
  2150. for(i=0; i<nOrderBy; i++){
  2151. Expr *pExpr = pOrderBy->a[i].pExpr;
  2152. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  2153. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  2154. }
  2155. return pIdxInfo;
  2156. }
  2157. /*
  2158. ** The table object reference passed as the second argument to this function
  2159. ** must represent a virtual table. This function invokes the xBestIndex()
  2160. ** method of the virtual table with the sqlite3_index_info object that
  2161. ** comes in as the 3rd argument to this function.
  2162. **
  2163. ** If an error occurs, pParse is populated with an error message and a
  2164. ** non-zero value is returned. Otherwise, 0 is returned and the output
  2165. ** part of the sqlite3_index_info structure is left populated.
  2166. **
  2167. ** Whether or not an error is returned, it is the responsibility of the
  2168. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  2169. ** that this is required.
  2170. */
  2171. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  2172. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  2173. int i;
  2174. int rc;
  2175. TRACE_IDX_INPUTS(p);
  2176. rc = pVtab->pModule->xBestIndex(pVtab, p);
  2177. TRACE_IDX_OUTPUTS(p);
  2178. if( rc!=SQLITE_OK ){
  2179. if( rc==SQLITE_NOMEM ){
  2180. pParse->db->mallocFailed = 1;
  2181. }else if( !pVtab->zErrMsg ){
  2182. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  2183. }else{
  2184. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  2185. }
  2186. }
  2187. sqlite3_free(pVtab->zErrMsg);
  2188. pVtab->zErrMsg = 0;
  2189. for(i=0; i<p->nConstraint; i++){
  2190. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  2191. sqlite3ErrorMsg(pParse,
  2192. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  2193. }
  2194. }
  2195. return pParse->nErr;
  2196. }
  2197. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  2198. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  2199. /*
  2200. ** Estimate the location of a particular key among all keys in an
  2201. ** index. Store the results in aStat as follows:
  2202. **
  2203. ** aStat[0] Est. number of rows less than pVal
  2204. ** aStat[1] Est. number of rows equal to pVal
  2205. **
  2206. ** Return SQLITE_OK on success.
  2207. */
  2208. static void whereKeyStats(
  2209. Parse *pParse, /* Database connection */
  2210. Index *pIdx, /* Index to consider domain of */
  2211. UnpackedRecord *pRec, /* Vector of values to consider */
  2212. int roundUp, /* Round up if true. Round down if false */
  2213. tRowcnt *aStat /* OUT: stats written here */
  2214. ){
  2215. IndexSample *aSample = pIdx->aSample;
  2216. int iCol; /* Index of required stats in anEq[] etc. */
  2217. int iMin = 0; /* Smallest sample not yet tested */
  2218. int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
  2219. int iTest; /* Next sample to test */
  2220. int res; /* Result of comparison operation */
  2221. #ifndef SQLITE_DEBUG
  2222. UNUSED_PARAMETER( pParse );
  2223. #endif
  2224. assert( pRec!=0 || pParse->db->mallocFailed );
  2225. if( pRec==0 ) return;
  2226. iCol = pRec->nField - 1;
  2227. assert( pIdx->nSample>0 );
  2228. assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  2229. do{
  2230. iTest = (iMin+i)/2;
  2231. res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
  2232. if( res<0 ){
  2233. iMin = iTest+1;
  2234. }else{
  2235. i = iTest;
  2236. }
  2237. }while( res && iMin<i );
  2238. #ifdef SQLITE_DEBUG
  2239. /* The following assert statements check that the binary search code
  2240. ** above found the right answer. This block serves no purpose other
  2241. ** than to invoke the asserts. */
  2242. if( res==0 ){
  2243. /* If (res==0) is true, then sample $i must be equal to pRec */
  2244. assert( i<pIdx->nSample );
  2245. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  2246. || pParse->db->mallocFailed );
  2247. }else{
  2248. /* Otherwise, pRec must be smaller than sample $i and larger than
  2249. ** sample ($i-1). */
  2250. assert( i==pIdx->nSample
  2251. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  2252. || pParse->db->mallocFailed );
  2253. assert( i==0
  2254. || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  2255. || pParse->db->mallocFailed );
  2256. }
  2257. #endif /* ifdef SQLITE_DEBUG */
  2258. /* At this point, aSample[i] is the first sample that is greater than
  2259. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  2260. ** than pVal. If aSample[i]==pVal, then res==0.
  2261. */
  2262. if( res==0 ){
  2263. aStat[0] = aSample[i].anLt[iCol];
  2264. aStat[1] = aSample[i].anEq[iCol];
  2265. }else{
  2266. tRowcnt iLower, iUpper, iGap;
  2267. if( i==0 ){
  2268. iLower = 0;
  2269. iUpper = aSample[0].anLt[iCol];
  2270. }else{
  2271. iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
  2272. iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
  2273. }
  2274. aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1);
  2275. if( iLower>=iUpper ){
  2276. iGap = 0;
  2277. }else{
  2278. iGap = iUpper - iLower;
  2279. }
  2280. if( roundUp ){
  2281. iGap = (iGap*2)/3;
  2282. }else{
  2283. iGap = iGap/3;
  2284. }
  2285. aStat[0] = iLower + iGap;
  2286. }
  2287. }
  2288. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  2289. /*
  2290. ** This function is used to estimate the number of rows that will be visited
  2291. ** by scanning an index for a range of values. The range may have an upper
  2292. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  2293. ** and lower bounds are represented by pLower and pUpper respectively. For
  2294. ** example, assuming that index p is on t1(a):
  2295. **
  2296. ** ... FROM t1 WHERE a > ? AND a < ? ...
  2297. ** |_____| |_____|
  2298. ** | |
  2299. ** pLower pUpper
  2300. **
  2301. ** If either of the upper or lower bound is not present, then NULL is passed in
  2302. ** place of the corresponding WhereTerm.
  2303. **
  2304. ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
  2305. ** column subject to the range constraint. Or, equivalently, the number of
  2306. ** equality constraints optimized by the proposed index scan. For example,
  2307. ** assuming index p is on t1(a, b), and the SQL query is:
  2308. **
  2309. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  2310. **
  2311. ** then nEq is set to 1 (as the range restricted column, b, is the second
  2312. ** left-most column of the index). Or, if the query is:
  2313. **
  2314. ** ... FROM t1 WHERE a > ? AND a < ? ...
  2315. **
  2316. ** then nEq is set to 0.
  2317. **
  2318. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  2319. ** number of rows that the index scan is expected to visit without
  2320. ** considering the range constraints. If nEq is 0, this is the number of
  2321. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  2322. ** to account for the range contraints pLower and pUpper.
  2323. **
  2324. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  2325. ** used, each range inequality reduces the search space by a factor of 4.
  2326. ** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
  2327. ** rows visited by a factor of 16.
  2328. */
  2329. static int whereRangeScanEst(
  2330. Parse *pParse, /* Parsing & code generating context */
  2331. WhereLoopBuilder *pBuilder,
  2332. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  2333. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  2334. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  2335. ){
  2336. int rc = SQLITE_OK;
  2337. int nOut = pLoop->nOut;
  2338. LogEst nNew;
  2339. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  2340. Index *p = pLoop->u.btree.pIndex;
  2341. int nEq = pLoop->u.btree.nEq;
  2342. if( p->nSample>0
  2343. && nEq==pBuilder->nRecValid
  2344. && nEq<p->nSampleCol
  2345. && OptimizationEnabled(pParse->db, SQLITE_Stat3)
  2346. ){
  2347. UnpackedRecord *pRec = pBuilder->pRec;
  2348. tRowcnt a[2];
  2349. u8 aff;
  2350. /* Variable iLower will be set to the estimate of the number of rows in
  2351. ** the index that are less than the lower bound of the range query. The
  2352. ** lower bound being the concatenation of $P and $L, where $P is the
  2353. ** key-prefix formed by the nEq values matched against the nEq left-most
  2354. ** columns of the index, and $L is the value in pLower.
  2355. **
  2356. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  2357. ** is not a simple variable or literal value), the lower bound of the
  2358. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  2359. ** if $L is available, whereKeyStats() is called for both ($P) and
  2360. ** ($P:$L) and the larger of the two returned values used.
  2361. **
  2362. ** Similarly, iUpper is to be set to the estimate of the number of rows
  2363. ** less than the upper bound of the range query. Where the upper bound
  2364. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  2365. ** of iUpper are requested of whereKeyStats() and the smaller used.
  2366. */
  2367. tRowcnt iLower;
  2368. tRowcnt iUpper;
  2369. if( nEq==p->nColumn ){
  2370. aff = SQLITE_AFF_INTEGER;
  2371. }else{
  2372. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  2373. }
  2374. /* Determine iLower and iUpper using ($P) only. */
  2375. if( nEq==0 ){
  2376. iLower = 0;
  2377. iUpper = p->aiRowEst[0];
  2378. }else{
  2379. /* Note: this call could be optimized away - since the same values must
  2380. ** have been requested when testing key $P in whereEqualScanEst(). */
  2381. whereKeyStats(pParse, p, pRec, 0, a);
  2382. iLower = a[0];
  2383. iUpper = a[0] + a[1];
  2384. }
  2385. /* If possible, improve on the iLower estimate using ($P:$L). */
  2386. if( pLower ){
  2387. int bOk; /* True if value is extracted from pExpr */
  2388. Expr *pExpr = pLower->pExpr->pRight;
  2389. assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  2390. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  2391. if( rc==SQLITE_OK && bOk ){
  2392. tRowcnt iNew;
  2393. whereKeyStats(pParse, p, pRec, 0, a);
  2394. iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
  2395. if( iNew>iLower ) iLower = iNew;
  2396. nOut--;
  2397. }
  2398. }
  2399. /* If possible, improve on the iUpper estimate using ($P:$U). */
  2400. if( pUpper ){
  2401. int bOk; /* True if value is extracted from pExpr */
  2402. Expr *pExpr = pUpper->pExpr->pRight;
  2403. assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  2404. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  2405. if( rc==SQLITE_OK && bOk ){
  2406. tRowcnt iNew;
  2407. whereKeyStats(pParse, p, pRec, 1, a);
  2408. iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
  2409. if( iNew<iUpper ) iUpper = iNew;
  2410. nOut--;
  2411. }
  2412. }
  2413. pBuilder->pRec = pRec;
  2414. if( rc==SQLITE_OK ){
  2415. if( iUpper>iLower ){
  2416. nNew = sqlite3LogEst(iUpper - iLower);
  2417. }else{
  2418. nNew = 10; assert( 10==sqlite3LogEst(2) );
  2419. }
  2420. if( nNew<nOut ){
  2421. nOut = nNew;
  2422. }
  2423. pLoop->nOut = (LogEst)nOut;
  2424. WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n",
  2425. (u32)iLower, (u32)iUpper, nOut));
  2426. return SQLITE_OK;
  2427. }
  2428. }
  2429. #else
  2430. UNUSED_PARAMETER(pParse);
  2431. UNUSED_PARAMETER(pBuilder);
  2432. #endif
  2433. assert( pLower || pUpper );
  2434. /* TUNING: Each inequality constraint reduces the search space 4-fold.
  2435. ** A BETWEEN operator, therefore, reduces the search space 16-fold */
  2436. nNew = nOut;
  2437. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
  2438. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  2439. nOut--;
  2440. }
  2441. if( pUpper ){
  2442. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  2443. nOut--;
  2444. }
  2445. if( nNew<10 ) nNew = 10;
  2446. if( nNew<nOut ) nOut = nNew;
  2447. pLoop->nOut = (LogEst)nOut;
  2448. return rc;
  2449. }
  2450. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  2451. /*
  2452. ** Estimate the number of rows that will be returned based on
  2453. ** an equality constraint x=VALUE and where that VALUE occurs in
  2454. ** the histogram data. This only works when x is the left-most
  2455. ** column of an index and sqlite_stat3 histogram data is available
  2456. ** for that index. When pExpr==NULL that means the constraint is
  2457. ** "x IS NULL" instead of "x=VALUE".
  2458. **
  2459. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  2460. ** If unable to make an estimate, leave *pnRow unchanged and return
  2461. ** non-zero.
  2462. **
  2463. ** This routine can fail if it is unable to load a collating sequence
  2464. ** required for string comparison, or if unable to allocate memory
  2465. ** for a UTF conversion required for comparison. The error is stored
  2466. ** in the pParse structure.
  2467. */
  2468. static int whereEqualScanEst(
  2469. Parse *pParse, /* Parsing & code generating context */
  2470. WhereLoopBuilder *pBuilder,
  2471. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  2472. tRowcnt *pnRow /* Write the revised row estimate here */
  2473. ){
  2474. Index *p = pBuilder->pNew->u.btree.pIndex;
  2475. int nEq = pBuilder->pNew->u.btree.nEq;
  2476. UnpackedRecord *pRec = pBuilder->pRec;
  2477. u8 aff; /* Column affinity */
  2478. int rc; /* Subfunction return code */
  2479. tRowcnt a[2]; /* Statistics */
  2480. int bOk;
  2481. assert( nEq>=1 );
  2482. assert( nEq<=(p->nColumn+1) );
  2483. assert( p->aSample!=0 );
  2484. assert( p->nSample>0 );
  2485. assert( pBuilder->nRecValid<nEq );
  2486. /* If values are not available for all fields of the index to the left
  2487. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  2488. if( pBuilder->nRecValid<(nEq-1) ){
  2489. return SQLITE_NOTFOUND;
  2490. }
  2491. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  2492. ** below would return the same value. */
  2493. if( nEq>p->nColumn ){
  2494. *pnRow = 1;
  2495. return SQLITE_OK;
  2496. }
  2497. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  2498. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  2499. pBuilder->pRec = pRec;
  2500. if( rc!=SQLITE_OK ) return rc;
  2501. if( bOk==0 ) return SQLITE_NOTFOUND;
  2502. pBuilder->nRecValid = nEq;
  2503. whereKeyStats(pParse, p, pRec, 0, a);
  2504. WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
  2505. *pnRow = a[1];
  2506. return rc;
  2507. }
  2508. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  2509. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  2510. /*
  2511. ** Estimate the number of rows that will be returned based on
  2512. ** an IN constraint where the right-hand side of the IN operator
  2513. ** is a list of values. Example:
  2514. **
  2515. ** WHERE x IN (1,2,3,4)
  2516. **
  2517. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  2518. ** If unable to make an estimate, leave *pnRow unchanged and return
  2519. ** non-zero.
  2520. **
  2521. ** This routine can fail if it is unable to load a collating sequence
  2522. ** required for string comparison, or if unable to allocate memory
  2523. ** for a UTF conversion required for comparison. The error is stored
  2524. ** in the pParse structure.
  2525. */
  2526. static int whereInScanEst(
  2527. Parse *pParse, /* Parsing & code generating context */
  2528. WhereLoopBuilder *pBuilder,
  2529. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  2530. tRowcnt *pnRow /* Write the revised row estimate here */
  2531. ){
  2532. Index *p = pBuilder->pNew->u.btree.pIndex;
  2533. int nRecValid = pBuilder->nRecValid;
  2534. int rc = SQLITE_OK; /* Subfunction return code */
  2535. tRowcnt nEst; /* Number of rows for a single term */
  2536. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  2537. int i; /* Loop counter */
  2538. assert( p->aSample!=0 );
  2539. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  2540. nEst = p->aiRowEst[0];
  2541. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  2542. nRowEst += nEst;
  2543. pBuilder->nRecValid = nRecValid;
  2544. }
  2545. if( rc==SQLITE_OK ){
  2546. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  2547. *pnRow = nRowEst;
  2548. WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
  2549. }
  2550. assert( pBuilder->nRecValid==nRecValid );
  2551. return rc;
  2552. }
  2553. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  2554. /*
  2555. ** Disable a term in the WHERE clause. Except, do not disable the term
  2556. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  2557. ** or USING clause of that join.
  2558. **
  2559. ** Consider the term t2.z='ok' in the following queries:
  2560. **
  2561. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  2562. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  2563. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  2564. **
  2565. ** The t2.z='ok' is disabled in the in (2) because it originates
  2566. ** in the ON clause. The term is disabled in (3) because it is not part
  2567. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  2568. **
  2569. ** Disabling a term causes that term to not be tested in the inner loop
  2570. ** of the join. Disabling is an optimization. When terms are satisfied
  2571. ** by indices, we disable them to prevent redundant tests in the inner
  2572. ** loop. We would get the correct results if nothing were ever disabled,
  2573. ** but joins might run a little slower. The trick is to disable as much
  2574. ** as we can without disabling too much. If we disabled in (1), we'd get
  2575. ** the wrong answer. See ticket #813.
  2576. */
  2577. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  2578. if( pTerm
  2579. && (pTerm->wtFlags & TERM_CODED)==0
  2580. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  2581. && (pLevel->notReady & pTerm->prereqAll)==0
  2582. ){
  2583. pTerm->wtFlags |= TERM_CODED;
  2584. if( pTerm->iParent>=0 ){
  2585. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  2586. if( (--pOther->nChild)==0 ){
  2587. disableTerm(pLevel, pOther);
  2588. }
  2589. }
  2590. }
  2591. }
  2592. /*
  2593. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  2594. ** to the n registers starting at base.
  2595. **
  2596. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  2597. ** beginning and end of zAff are ignored. If all entries in zAff are
  2598. ** SQLITE_AFF_NONE, then no code gets generated.
  2599. **
  2600. ** This routine makes its own copy of zAff so that the caller is free
  2601. ** to modify zAff after this routine returns.
  2602. */
  2603. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  2604. Vdbe *v = pParse->pVdbe;
  2605. if( zAff==0 ){
  2606. assert( pParse->db->mallocFailed );
  2607. return;
  2608. }
  2609. assert( v!=0 );
  2610. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  2611. ** and end of the affinity string.
  2612. */
  2613. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  2614. n--;
  2615. base++;
  2616. zAff++;
  2617. }
  2618. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  2619. n--;
  2620. }
  2621. /* Code the OP_Affinity opcode if there is anything left to do. */
  2622. if( n>0 ){
  2623. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  2624. sqlite3VdbeChangeP4(v, -1, zAff, n);
  2625. sqlite3ExprCacheAffinityChange(pParse, base, n);
  2626. }
  2627. }
  2628. /*
  2629. ** Generate code for a single equality term of the WHERE clause. An equality
  2630. ** term can be either X=expr or X IN (...). pTerm is the term to be
  2631. ** coded.
  2632. **
  2633. ** The current value for the constraint is left in register iReg.
  2634. **
  2635. ** For a constraint of the form X=expr, the expression is evaluated and its
  2636. ** result is left on the stack. For constraints of the form X IN (...)
  2637. ** this routine sets up a loop that will iterate over all values of X.
  2638. */
  2639. static int codeEqualityTerm(
  2640. Parse *pParse, /* The parsing context */
  2641. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  2642. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  2643. int iEq, /* Index of the equality term within this level */
  2644. int bRev, /* True for reverse-order IN operations */
  2645. int iTarget /* Attempt to leave results in this register */
  2646. ){
  2647. Expr *pX = pTerm->pExpr;
  2648. Vdbe *v = pParse->pVdbe;
  2649. int iReg; /* Register holding results */
  2650. assert( iTarget>0 );
  2651. if( pX->op==TK_EQ ){
  2652. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  2653. }else if( pX->op==TK_ISNULL ){
  2654. iReg = iTarget;
  2655. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  2656. #ifndef SQLITE_OMIT_SUBQUERY
  2657. }else{
  2658. int eType;
  2659. int iTab;
  2660. struct InLoop *pIn;
  2661. WhereLoop *pLoop = pLevel->pWLoop;
  2662. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  2663. && pLoop->u.btree.pIndex!=0
  2664. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  2665. ){
  2666. testcase( iEq==0 );
  2667. testcase( bRev );
  2668. bRev = !bRev;
  2669. }
  2670. assert( pX->op==TK_IN );
  2671. iReg = iTarget;
  2672. eType = sqlite3FindInIndex(pParse, pX, 0);
  2673. if( eType==IN_INDEX_INDEX_DESC ){
  2674. testcase( bRev );
  2675. bRev = !bRev;
  2676. }
  2677. iTab = pX->iTable;
  2678. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  2679. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  2680. pLoop->wsFlags |= WHERE_IN_ABLE;
  2681. if( pLevel->u.in.nIn==0 ){
  2682. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  2683. }
  2684. pLevel->u.in.nIn++;
  2685. pLevel->u.in.aInLoop =
  2686. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  2687. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  2688. pIn = pLevel->u.in.aInLoop;
  2689. if( pIn ){
  2690. pIn += pLevel->u.in.nIn - 1;
  2691. pIn->iCur = iTab;
  2692. if( eType==IN_INDEX_ROWID ){
  2693. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  2694. }else{
  2695. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  2696. }
  2697. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  2698. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  2699. }else{
  2700. pLevel->u.in.nIn = 0;
  2701. }
  2702. #endif
  2703. }
  2704. disableTerm(pLevel, pTerm);
  2705. return iReg;
  2706. }
  2707. /*
  2708. ** Generate code that will evaluate all == and IN constraints for an
  2709. ** index.
  2710. **
  2711. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  2712. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  2713. ** The index has as many as three equality constraints, but in this
  2714. ** example, the third "c" value is an inequality. So only two
  2715. ** constraints are coded. This routine will generate code to evaluate
  2716. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  2717. ** in consecutive registers and the index of the first register is returned.
  2718. **
  2719. ** In the example above nEq==2. But this subroutine works for any value
  2720. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  2721. ** The only thing it does is allocate the pLevel->iMem memory cell and
  2722. ** compute the affinity string.
  2723. **
  2724. ** This routine always allocates at least one memory cell and returns
  2725. ** the index of that memory cell. The code that
  2726. ** calls this routine will use that memory cell to store the termination
  2727. ** key value of the loop. If one or more IN operators appear, then
  2728. ** this routine allocates an additional nEq memory cells for internal
  2729. ** use.
  2730. **
  2731. ** Before returning, *pzAff is set to point to a buffer containing a
  2732. ** copy of the column affinity string of the index allocated using
  2733. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  2734. ** with equality constraints that use NONE affinity are set to
  2735. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  2736. **
  2737. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  2738. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  2739. **
  2740. ** In the example above, the index on t1(a) has TEXT affinity. But since
  2741. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  2742. ** no conversion should be attempted before using a t2.b value as part of
  2743. ** a key to search the index. Hence the first byte in the returned affinity
  2744. ** string in this example would be set to SQLITE_AFF_NONE.
  2745. */
  2746. static int codeAllEqualityTerms(
  2747. Parse *pParse, /* Parsing context */
  2748. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  2749. int bRev, /* Reverse the order of IN operators */
  2750. int nExtraReg, /* Number of extra registers to allocate */
  2751. char **pzAff /* OUT: Set to point to affinity string */
  2752. ){
  2753. int nEq; /* The number of == or IN constraints to code */
  2754. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  2755. Index *pIdx; /* The index being used for this loop */
  2756. WhereTerm *pTerm; /* A single constraint term */
  2757. WhereLoop *pLoop; /* The WhereLoop object */
  2758. int j; /* Loop counter */
  2759. int regBase; /* Base register */
  2760. int nReg; /* Number of registers to allocate */
  2761. char *zAff; /* Affinity string to return */
  2762. /* This module is only called on query plans that use an index. */
  2763. pLoop = pLevel->pWLoop;
  2764. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  2765. nEq = pLoop->u.btree.nEq;
  2766. pIdx = pLoop->u.btree.pIndex;
  2767. assert( pIdx!=0 );
  2768. /* Figure out how many memory cells we will need then allocate them.
  2769. */
  2770. regBase = pParse->nMem + 1;
  2771. nReg = pLoop->u.btree.nEq + nExtraReg;
  2772. pParse->nMem += nReg;
  2773. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  2774. if( !zAff ){
  2775. pParse->db->mallocFailed = 1;
  2776. }
  2777. /* Evaluate the equality constraints
  2778. */
  2779. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  2780. for(j=0; j<nEq; j++){
  2781. int r1;
  2782. pTerm = pLoop->aLTerm[j];
  2783. assert( pTerm!=0 );
  2784. /* The following true for indices with redundant columns.
  2785. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  2786. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  2787. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  2788. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  2789. if( r1!=regBase+j ){
  2790. if( nReg==1 ){
  2791. sqlite3ReleaseTempReg(pParse, regBase);
  2792. regBase = r1;
  2793. }else{
  2794. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  2795. }
  2796. }
  2797. testcase( pTerm->eOperator & WO_ISNULL );
  2798. testcase( pTerm->eOperator & WO_IN );
  2799. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  2800. Expr *pRight = pTerm->pExpr->pRight;
  2801. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  2802. if( zAff ){
  2803. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  2804. zAff[j] = SQLITE_AFF_NONE;
  2805. }
  2806. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  2807. zAff[j] = SQLITE_AFF_NONE;
  2808. }
  2809. }
  2810. }
  2811. }
  2812. *pzAff = zAff;
  2813. return regBase;
  2814. }
  2815. #ifndef SQLITE_OMIT_EXPLAIN
  2816. /*
  2817. ** This routine is a helper for explainIndexRange() below
  2818. **
  2819. ** pStr holds the text of an expression that we are building up one term
  2820. ** at a time. This routine adds a new term to the end of the expression.
  2821. ** Terms are separated by AND so add the "AND" text for second and subsequent
  2822. ** terms only.
  2823. */
  2824. static void explainAppendTerm(
  2825. StrAccum *pStr, /* The text expression being built */
  2826. int iTerm, /* Index of this term. First is zero */
  2827. const char *zColumn, /* Name of the column */
  2828. const char *zOp /* Name of the operator */
  2829. ){
  2830. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  2831. sqlite3StrAccumAppend(pStr, zColumn, -1);
  2832. sqlite3StrAccumAppend(pStr, zOp, 1);
  2833. sqlite3StrAccumAppend(pStr, "?", 1);
  2834. }
  2835. /*
  2836. ** Argument pLevel describes a strategy for scanning table pTab. This
  2837. ** function returns a pointer to a string buffer containing a description
  2838. ** of the subset of table rows scanned by the strategy in the form of an
  2839. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  2840. **
  2841. ** For example, if the query:
  2842. **
  2843. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  2844. **
  2845. ** is run and there is an index on (a, b), then this function returns a
  2846. ** string similar to:
  2847. **
  2848. ** "a=? AND b>?"
  2849. **
  2850. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  2851. ** It is the responsibility of the caller to free the buffer when it is
  2852. ** no longer required.
  2853. */
  2854. static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
  2855. Index *pIndex = pLoop->u.btree.pIndex;
  2856. int nEq = pLoop->u.btree.nEq;
  2857. int i, j;
  2858. Column *aCol = pTab->aCol;
  2859. int *aiColumn = pIndex->aiColumn;
  2860. StrAccum txt;
  2861. if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  2862. return 0;
  2863. }
  2864. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  2865. txt.db = db;
  2866. sqlite3StrAccumAppend(&txt, " (", 2);
  2867. for(i=0; i<nEq; i++){
  2868. char *z = (i==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[i]].zName;
  2869. explainAppendTerm(&txt, i, z, "=");
  2870. }
  2871. j = i;
  2872. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  2873. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  2874. explainAppendTerm(&txt, i++, z, ">");
  2875. }
  2876. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  2877. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  2878. explainAppendTerm(&txt, i, z, "<");
  2879. }
  2880. sqlite3StrAccumAppend(&txt, ")", 1);
  2881. return sqlite3StrAccumFinish(&txt);
  2882. }
  2883. /*
  2884. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  2885. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  2886. ** record is added to the output to describe the table scan strategy in
  2887. ** pLevel.
  2888. */
  2889. static void explainOneScan(
  2890. Parse *pParse, /* Parse context */
  2891. SrcList *pTabList, /* Table list this loop refers to */
  2892. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  2893. int iLevel, /* Value for "level" column of output */
  2894. int iFrom, /* Value for "from" column of output */
  2895. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  2896. ){
  2897. if( pParse->explain==2 ){
  2898. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  2899. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  2900. sqlite3 *db = pParse->db; /* Database handle */
  2901. char *zMsg; /* Text to add to EQP output */
  2902. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  2903. int isSearch; /* True for a SEARCH. False for SCAN. */
  2904. WhereLoop *pLoop; /* The controlling WhereLoop object */
  2905. u32 flags; /* Flags that describe this loop */
  2906. pLoop = pLevel->pWLoop;
  2907. flags = pLoop->wsFlags;
  2908. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  2909. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  2910. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  2911. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  2912. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  2913. if( pItem->pSelect ){
  2914. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  2915. }else{
  2916. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  2917. }
  2918. if( pItem->zAlias ){
  2919. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  2920. }
  2921. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
  2922. && ALWAYS(pLoop->u.btree.pIndex!=0)
  2923. ){
  2924. char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
  2925. zMsg = sqlite3MAppendf(db, zMsg,
  2926. ((flags & WHERE_AUTO_INDEX) ?
  2927. "%s USING AUTOMATIC %sINDEX%.0s%s" :
  2928. "%s USING %sINDEX %s%s"),
  2929. zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
  2930. pLoop->u.btree.pIndex->zName, zWhere);
  2931. sqlite3DbFree(db, zWhere);
  2932. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  2933. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  2934. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  2935. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  2936. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  2937. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  2938. }else if( flags&WHERE_BTM_LIMIT ){
  2939. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  2940. }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
  2941. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  2942. }
  2943. }
  2944. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2945. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  2946. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  2947. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  2948. }
  2949. #endif
  2950. zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
  2951. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  2952. }
  2953. }
  2954. #else
  2955. # define explainOneScan(u,v,w,x,y,z)
  2956. #endif /* SQLITE_OMIT_EXPLAIN */
  2957. /*
  2958. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  2959. ** implementation described by pWInfo.
  2960. */
  2961. static Bitmask codeOneLoopStart(
  2962. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  2963. int iLevel, /* Which level of pWInfo->a[] should be coded */
  2964. Bitmask notReady /* Which tables are currently available */
  2965. ){
  2966. int j, k; /* Loop counters */
  2967. int iCur; /* The VDBE cursor for the table */
  2968. int addrNxt; /* Where to jump to continue with the next IN case */
  2969. int omitTable; /* True if we use the index only */
  2970. int bRev; /* True if we need to scan in reverse order */
  2971. WhereLevel *pLevel; /* The where level to be coded */
  2972. WhereLoop *pLoop; /* The WhereLoop object being coded */
  2973. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  2974. WhereTerm *pTerm; /* A WHERE clause term */
  2975. Parse *pParse; /* Parsing context */
  2976. sqlite3 *db; /* Database connection */
  2977. Vdbe *v; /* The prepared stmt under constructions */
  2978. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  2979. int addrBrk; /* Jump here to break out of the loop */
  2980. int addrCont; /* Jump here to continue with next cycle */
  2981. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  2982. int iReleaseReg = 0; /* Temp register to free before returning */
  2983. pParse = pWInfo->pParse;
  2984. v = pParse->pVdbe;
  2985. pWC = &pWInfo->sWC;
  2986. db = pParse->db;
  2987. pLevel = &pWInfo->a[iLevel];
  2988. pLoop = pLevel->pWLoop;
  2989. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  2990. iCur = pTabItem->iCursor;
  2991. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  2992. bRev = (pWInfo->revMask>>iLevel)&1;
  2993. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  2994. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  2995. VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
  2996. /* Create labels for the "break" and "continue" instructions
  2997. ** for the current loop. Jump to addrBrk to break out of a loop.
  2998. ** Jump to cont to go immediately to the next iteration of the
  2999. ** loop.
  3000. **
  3001. ** When there is an IN operator, we also have a "addrNxt" label that
  3002. ** means to continue with the next IN value combination. When
  3003. ** there are no IN operators in the constraints, the "addrNxt" label
  3004. ** is the same as "addrBrk".
  3005. */
  3006. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  3007. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  3008. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  3009. ** initialize a memory cell that records if this table matches any
  3010. ** row of the left table of the join.
  3011. */
  3012. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  3013. pLevel->iLeftJoin = ++pParse->nMem;
  3014. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  3015. VdbeComment((v, "init LEFT JOIN no-match flag"));
  3016. }
  3017. /* Special case of a FROM clause subquery implemented as a co-routine */
  3018. if( pTabItem->viaCoroutine ){
  3019. int regYield = pTabItem->regReturn;
  3020. sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
  3021. pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  3022. VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
  3023. sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
  3024. pLevel->op = OP_Goto;
  3025. }else
  3026. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3027. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  3028. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  3029. ** to access the data.
  3030. */
  3031. int iReg; /* P3 Value for OP_VFilter */
  3032. int addrNotFound;
  3033. int nConstraint = pLoop->nLTerm;
  3034. sqlite3ExprCachePush(pParse);
  3035. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  3036. addrNotFound = pLevel->addrBrk;
  3037. for(j=0; j<nConstraint; j++){
  3038. int iTarget = iReg+j+2;
  3039. pTerm = pLoop->aLTerm[j];
  3040. if( pTerm==0 ) continue;
  3041. if( pTerm->eOperator & WO_IN ){
  3042. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  3043. addrNotFound = pLevel->addrNxt;
  3044. }else{
  3045. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  3046. }
  3047. }
  3048. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  3049. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  3050. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  3051. pLoop->u.vtab.idxStr,
  3052. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  3053. pLoop->u.vtab.needFree = 0;
  3054. for(j=0; j<nConstraint && j<16; j++){
  3055. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  3056. disableTerm(pLevel, pLoop->aLTerm[j]);
  3057. }
  3058. }
  3059. pLevel->op = OP_VNext;
  3060. pLevel->p1 = iCur;
  3061. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  3062. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  3063. sqlite3ExprCachePop(pParse, 1);
  3064. }else
  3065. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  3066. if( (pLoop->wsFlags & WHERE_IPK)!=0
  3067. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  3068. ){
  3069. /* Case 2: We can directly reference a single row using an
  3070. ** equality comparison against the ROWID field. Or
  3071. ** we reference multiple rows using a "rowid IN (...)"
  3072. ** construct.
  3073. */
  3074. assert( pLoop->u.btree.nEq==1 );
  3075. iReleaseReg = sqlite3GetTempReg(pParse);
  3076. pTerm = pLoop->aLTerm[0];
  3077. assert( pTerm!=0 );
  3078. assert( pTerm->pExpr!=0 );
  3079. assert( omitTable==0 );
  3080. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  3081. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  3082. addrNxt = pLevel->addrNxt;
  3083. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  3084. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  3085. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  3086. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  3087. VdbeComment((v, "pk"));
  3088. pLevel->op = OP_Noop;
  3089. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  3090. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  3091. ){
  3092. /* Case 3: We have an inequality comparison against the ROWID field.
  3093. */
  3094. int testOp = OP_Noop;
  3095. int start;
  3096. int memEndValue = 0;
  3097. WhereTerm *pStart, *pEnd;
  3098. assert( omitTable==0 );
  3099. j = 0;
  3100. pStart = pEnd = 0;
  3101. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  3102. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  3103. assert( pStart!=0 || pEnd!=0 );
  3104. if( bRev ){
  3105. pTerm = pStart;
  3106. pStart = pEnd;
  3107. pEnd = pTerm;
  3108. }
  3109. if( pStart ){
  3110. Expr *pX; /* The expression that defines the start bound */
  3111. int r1, rTemp; /* Registers for holding the start boundary */
  3112. /* The following constant maps TK_xx codes into corresponding
  3113. ** seek opcodes. It depends on a particular ordering of TK_xx
  3114. */
  3115. const u8 aMoveOp[] = {
  3116. /* TK_GT */ OP_SeekGt,
  3117. /* TK_LE */ OP_SeekLe,
  3118. /* TK_LT */ OP_SeekLt,
  3119. /* TK_GE */ OP_SeekGe
  3120. };
  3121. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  3122. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  3123. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  3124. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  3125. testcase( pStart->wtFlags & TERM_VIRTUAL );
  3126. pX = pStart->pExpr;
  3127. assert( pX!=0 );
  3128. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  3129. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  3130. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  3131. VdbeComment((v, "pk"));
  3132. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  3133. sqlite3ReleaseTempReg(pParse, rTemp);
  3134. disableTerm(pLevel, pStart);
  3135. }else{
  3136. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  3137. }
  3138. if( pEnd ){
  3139. Expr *pX;
  3140. pX = pEnd->pExpr;
  3141. assert( pX!=0 );
  3142. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  3143. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  3144. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  3145. memEndValue = ++pParse->nMem;
  3146. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  3147. if( pX->op==TK_LT || pX->op==TK_GT ){
  3148. testOp = bRev ? OP_Le : OP_Ge;
  3149. }else{
  3150. testOp = bRev ? OP_Lt : OP_Gt;
  3151. }
  3152. disableTerm(pLevel, pEnd);
  3153. }
  3154. start = sqlite3VdbeCurrentAddr(v);
  3155. pLevel->op = bRev ? OP_Prev : OP_Next;
  3156. pLevel->p1 = iCur;
  3157. pLevel->p2 = start;
  3158. assert( pLevel->p5==0 );
  3159. if( testOp!=OP_Noop ){
  3160. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  3161. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  3162. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  3163. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  3164. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  3165. }
  3166. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  3167. /* Case 4: A scan using an index.
  3168. **
  3169. ** The WHERE clause may contain zero or more equality
  3170. ** terms ("==" or "IN" operators) that refer to the N
  3171. ** left-most columns of the index. It may also contain
  3172. ** inequality constraints (>, <, >= or <=) on the indexed
  3173. ** column that immediately follows the N equalities. Only
  3174. ** the right-most column can be an inequality - the rest must
  3175. ** use the "==" and "IN" operators. For example, if the
  3176. ** index is on (x,y,z), then the following clauses are all
  3177. ** optimized:
  3178. **
  3179. ** x=5
  3180. ** x=5 AND y=10
  3181. ** x=5 AND y<10
  3182. ** x=5 AND y>5 AND y<10
  3183. ** x=5 AND y=5 AND z<=10
  3184. **
  3185. ** The z<10 term of the following cannot be used, only
  3186. ** the x=5 term:
  3187. **
  3188. ** x=5 AND z<10
  3189. **
  3190. ** N may be zero if there are inequality constraints.
  3191. ** If there are no inequality constraints, then N is at
  3192. ** least one.
  3193. **
  3194. ** This case is also used when there are no WHERE clause
  3195. ** constraints but an index is selected anyway, in order
  3196. ** to force the output order to conform to an ORDER BY.
  3197. */
  3198. static const u8 aStartOp[] = {
  3199. 0,
  3200. 0,
  3201. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  3202. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  3203. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  3204. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  3205. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  3206. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  3207. };
  3208. static const u8 aEndOp[] = {
  3209. OP_Noop, /* 0: (!end_constraints) */
  3210. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  3211. OP_IdxLT /* 2: (end_constraints && bRev) */
  3212. };
  3213. int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  3214. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  3215. int regBase; /* Base register holding constraint values */
  3216. int r1; /* Temp register */
  3217. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  3218. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  3219. int startEq; /* True if range start uses ==, >= or <= */
  3220. int endEq; /* True if range end uses ==, >= or <= */
  3221. int start_constraints; /* Start of range is constrained */
  3222. int nConstraint; /* Number of constraint terms */
  3223. Index *pIdx; /* The index we will be using */
  3224. int iIdxCur; /* The VDBE cursor for the index */
  3225. int nExtraReg = 0; /* Number of extra registers needed */
  3226. int op; /* Instruction opcode */
  3227. char *zStartAff; /* Affinity for start of range constraint */
  3228. char *zEndAff; /* Affinity for end of range constraint */
  3229. pIdx = pLoop->u.btree.pIndex;
  3230. iIdxCur = pLevel->iIdxCur;
  3231. /* If this loop satisfies a sort order (pOrderBy) request that
  3232. ** was passed to this function to implement a "SELECT min(x) ..."
  3233. ** query, then the caller will only allow the loop to run for
  3234. ** a single iteration. This means that the first row returned
  3235. ** should not have a NULL value stored in 'x'. If column 'x' is
  3236. ** the first one after the nEq equality constraints in the index,
  3237. ** this requires some special handling.
  3238. */
  3239. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  3240. && (pWInfo->bOBSat!=0)
  3241. && (pIdx->nColumn>nEq)
  3242. ){
  3243. /* assert( pOrderBy->nExpr==1 ); */
  3244. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  3245. isMinQuery = 1;
  3246. nExtraReg = 1;
  3247. }
  3248. /* Find any inequality constraint terms for the start and end
  3249. ** of the range.
  3250. */
  3251. j = nEq;
  3252. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  3253. pRangeStart = pLoop->aLTerm[j++];
  3254. nExtraReg = 1;
  3255. }
  3256. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  3257. pRangeEnd = pLoop->aLTerm[j++];
  3258. nExtraReg = 1;
  3259. }
  3260. /* Generate code to evaluate all constraint terms using == or IN
  3261. ** and store the values of those terms in an array of registers
  3262. ** starting at regBase.
  3263. */
  3264. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  3265. zEndAff = sqlite3DbStrDup(db, zStartAff);
  3266. addrNxt = pLevel->addrNxt;
  3267. /* If we are doing a reverse order scan on an ascending index, or
  3268. ** a forward order scan on a descending index, interchange the
  3269. ** start and end terms (pRangeStart and pRangeEnd).
  3270. */
  3271. if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  3272. || (bRev && pIdx->nColumn==nEq)
  3273. ){
  3274. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  3275. }
  3276. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  3277. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  3278. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  3279. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  3280. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  3281. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  3282. start_constraints = pRangeStart || nEq>0;
  3283. /* Seek the index cursor to the start of the range. */
  3284. nConstraint = nEq;
  3285. if( pRangeStart ){
  3286. Expr *pRight = pRangeStart->pExpr->pRight;
  3287. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  3288. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  3289. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  3290. }
  3291. if( zStartAff ){
  3292. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  3293. /* Since the comparison is to be performed with no conversions
  3294. ** applied to the operands, set the affinity to apply to pRight to
  3295. ** SQLITE_AFF_NONE. */
  3296. zStartAff[nEq] = SQLITE_AFF_NONE;
  3297. }
  3298. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  3299. zStartAff[nEq] = SQLITE_AFF_NONE;
  3300. }
  3301. }
  3302. nConstraint++;
  3303. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  3304. }else if( isMinQuery ){
  3305. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  3306. nConstraint++;
  3307. startEq = 0;
  3308. start_constraints = 1;
  3309. }
  3310. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  3311. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  3312. assert( op!=0 );
  3313. testcase( op==OP_Rewind );
  3314. testcase( op==OP_Last );
  3315. testcase( op==OP_SeekGt );
  3316. testcase( op==OP_SeekGe );
  3317. testcase( op==OP_SeekLe );
  3318. testcase( op==OP_SeekLt );
  3319. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  3320. /* Load the value for the inequality constraint at the end of the
  3321. ** range (if any).
  3322. */
  3323. nConstraint = nEq;
  3324. if( pRangeEnd ){
  3325. Expr *pRight = pRangeEnd->pExpr->pRight;
  3326. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  3327. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  3328. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  3329. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  3330. }
  3331. if( zEndAff ){
  3332. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  3333. /* Since the comparison is to be performed with no conversions
  3334. ** applied to the operands, set the affinity to apply to pRight to
  3335. ** SQLITE_AFF_NONE. */
  3336. zEndAff[nEq] = SQLITE_AFF_NONE;
  3337. }
  3338. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  3339. zEndAff[nEq] = SQLITE_AFF_NONE;
  3340. }
  3341. }
  3342. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  3343. nConstraint++;
  3344. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  3345. }
  3346. sqlite3DbFree(db, zStartAff);
  3347. sqlite3DbFree(db, zEndAff);
  3348. /* Top of the loop body */
  3349. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  3350. /* Check if the index cursor is past the end of the range. */
  3351. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  3352. testcase( op==OP_Noop );
  3353. testcase( op==OP_IdxGE );
  3354. testcase( op==OP_IdxLT );
  3355. if( op!=OP_Noop ){
  3356. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  3357. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  3358. }
  3359. /* If there are inequality constraints, check that the value
  3360. ** of the table column that the inequality contrains is not NULL.
  3361. ** If it is, jump to the next iteration of the loop.
  3362. */
  3363. r1 = sqlite3GetTempReg(pParse);
  3364. testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
  3365. testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
  3366. if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  3367. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  3368. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  3369. }
  3370. sqlite3ReleaseTempReg(pParse, r1);
  3371. /* Seek the table cursor, if required */
  3372. disableTerm(pLevel, pRangeStart);
  3373. disableTerm(pLevel, pRangeEnd);
  3374. if( !omitTable ){
  3375. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  3376. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  3377. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  3378. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  3379. }
  3380. /* Record the instruction used to terminate the loop. Disable
  3381. ** WHERE clause terms made redundant by the index range scan.
  3382. */
  3383. if( pLoop->wsFlags & WHERE_ONEROW ){
  3384. pLevel->op = OP_Noop;
  3385. }else if( bRev ){
  3386. pLevel->op = OP_Prev;
  3387. }else{
  3388. pLevel->op = OP_Next;
  3389. }
  3390. pLevel->p1 = iIdxCur;
  3391. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  3392. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  3393. }else{
  3394. assert( pLevel->p5==0 );
  3395. }
  3396. }else
  3397. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  3398. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  3399. /* Case 5: Two or more separately indexed terms connected by OR
  3400. **
  3401. ** Example:
  3402. **
  3403. ** CREATE TABLE t1(a,b,c,d);
  3404. ** CREATE INDEX i1 ON t1(a);
  3405. ** CREATE INDEX i2 ON t1(b);
  3406. ** CREATE INDEX i3 ON t1(c);
  3407. **
  3408. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  3409. **
  3410. ** In the example, there are three indexed terms connected by OR.
  3411. ** The top of the loop looks like this:
  3412. **
  3413. ** Null 1 # Zero the rowset in reg 1
  3414. **
  3415. ** Then, for each indexed term, the following. The arguments to
  3416. ** RowSetTest are such that the rowid of the current row is inserted
  3417. ** into the RowSet. If it is already present, control skips the
  3418. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  3419. **
  3420. ** sqlite3WhereBegin(<term>)
  3421. ** RowSetTest # Insert rowid into rowset
  3422. ** Gosub 2 A
  3423. ** sqlite3WhereEnd()
  3424. **
  3425. ** Following the above, code to terminate the loop. Label A, the target
  3426. ** of the Gosub above, jumps to the instruction right after the Goto.
  3427. **
  3428. ** Null 1 # Zero the rowset in reg 1
  3429. ** Goto B # The loop is finished.
  3430. **
  3431. ** A: <loop body> # Return data, whatever.
  3432. **
  3433. ** Return 2 # Jump back to the Gosub
  3434. **
  3435. ** B: <after the loop>
  3436. **
  3437. */
  3438. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  3439. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  3440. Index *pCov = 0; /* Potential covering index (or NULL) */
  3441. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  3442. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  3443. int regRowset = 0; /* Register for RowSet object */
  3444. int regRowid = 0; /* Register holding rowid */
  3445. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  3446. int iRetInit; /* Address of regReturn init */
  3447. int untestedTerms = 0; /* Some terms not completely tested */
  3448. int ii; /* Loop counter */
  3449. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  3450. pTerm = pLoop->aLTerm[0];
  3451. assert( pTerm!=0 );
  3452. assert( pTerm->eOperator & WO_OR );
  3453. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  3454. pOrWc = &pTerm->u.pOrInfo->wc;
  3455. pLevel->op = OP_Return;
  3456. pLevel->p1 = regReturn;
  3457. /* Set up a new SrcList in pOrTab containing the table being scanned
  3458. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  3459. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  3460. */
  3461. if( pWInfo->nLevel>1 ){
  3462. int nNotReady; /* The number of notReady tables */
  3463. struct SrcList_item *origSrc; /* Original list of tables */
  3464. nNotReady = pWInfo->nLevel - iLevel - 1;
  3465. pOrTab = sqlite3StackAllocRaw(db,
  3466. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  3467. if( pOrTab==0 ) return notReady;
  3468. pOrTab->nAlloc = (u8)(nNotReady + 1);
  3469. pOrTab->nSrc = pOrTab->nAlloc;
  3470. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  3471. origSrc = pWInfo->pTabList->a;
  3472. for(k=1; k<=nNotReady; k++){
  3473. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  3474. }
  3475. }else{
  3476. pOrTab = pWInfo->pTabList;
  3477. }
  3478. /* Initialize the rowset register to contain NULL. An SQL NULL is
  3479. ** equivalent to an empty rowset.
  3480. **
  3481. ** Also initialize regReturn to contain the address of the instruction
  3482. ** immediately following the OP_Return at the bottom of the loop. This
  3483. ** is required in a few obscure LEFT JOIN cases where control jumps
  3484. ** over the top of the loop into the body of it. In this case the
  3485. ** correct response for the end-of-loop code (the OP_Return) is to
  3486. ** fall through to the next instruction, just as an OP_Next does if
  3487. ** called on an uninitialized cursor.
  3488. */
  3489. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  3490. regRowset = ++pParse->nMem;
  3491. regRowid = ++pParse->nMem;
  3492. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  3493. }
  3494. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  3495. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  3496. ** Then for every term xN, evaluate as the subexpression: xN AND z
  3497. ** That way, terms in y that are factored into the disjunction will
  3498. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  3499. **
  3500. ** Actually, each subexpression is converted to "xN AND w" where w is
  3501. ** the "interesting" terms of z - terms that did not originate in the
  3502. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  3503. ** indices.
  3504. **
  3505. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  3506. ** is not contained in the ON clause of a LEFT JOIN.
  3507. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  3508. */
  3509. if( pWC->nTerm>1 ){
  3510. int iTerm;
  3511. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  3512. Expr *pExpr = pWC->a[iTerm].pExpr;
  3513. if( &pWC->a[iTerm] == pTerm ) continue;
  3514. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  3515. if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
  3516. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  3517. pExpr = sqlite3ExprDup(db, pExpr, 0);
  3518. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  3519. }
  3520. if( pAndExpr ){
  3521. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  3522. }
  3523. }
  3524. for(ii=0; ii<pOrWc->nTerm; ii++){
  3525. WhereTerm *pOrTerm = &pOrWc->a[ii];
  3526. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  3527. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  3528. Expr *pOrExpr = pOrTerm->pExpr;
  3529. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  3530. pAndExpr->pLeft = pOrExpr;
  3531. pOrExpr = pAndExpr;
  3532. }
  3533. /* Loop through table entries that match term pOrTerm. */
  3534. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  3535. WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  3536. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  3537. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  3538. if( pSubWInfo ){
  3539. WhereLoop *pSubLoop;
  3540. explainOneScan(
  3541. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  3542. );
  3543. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  3544. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  3545. int r;
  3546. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  3547. regRowid, 0);
  3548. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  3549. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  3550. }
  3551. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  3552. /* The pSubWInfo->untestedTerms flag means that this OR term
  3553. ** contained one or more AND term from a notReady table. The
  3554. ** terms from the notReady table could not be tested and will
  3555. ** need to be tested later.
  3556. */
  3557. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  3558. /* If all of the OR-connected terms are optimized using the same
  3559. ** index, and the index is opened using the same cursor number
  3560. ** by each call to sqlite3WhereBegin() made by this loop, it may
  3561. ** be possible to use that index as a covering index.
  3562. **
  3563. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  3564. ** uses an index, and this is either the first OR-connected term
  3565. ** processed or the index is the same as that used by all previous
  3566. ** terms, set pCov to the candidate covering index. Otherwise, set
  3567. ** pCov to NULL to indicate that no candidate covering index will
  3568. ** be available.
  3569. */
  3570. pSubLoop = pSubWInfo->a[0].pWLoop;
  3571. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  3572. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  3573. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  3574. ){
  3575. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  3576. pCov = pSubLoop->u.btree.pIndex;
  3577. }else{
  3578. pCov = 0;
  3579. }
  3580. /* Finish the loop through table entries that match term pOrTerm. */
  3581. sqlite3WhereEnd(pSubWInfo);
  3582. }
  3583. }
  3584. }
  3585. pLevel->u.pCovidx = pCov;
  3586. if( pCov ) pLevel->iIdxCur = iCovCur;
  3587. if( pAndExpr ){
  3588. pAndExpr->pLeft = 0;
  3589. sqlite3ExprDelete(db, pAndExpr);
  3590. }
  3591. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  3592. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  3593. sqlite3VdbeResolveLabel(v, iLoopBody);
  3594. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  3595. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  3596. }else
  3597. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  3598. {
  3599. /* Case 6: There is no usable index. We must do a complete
  3600. ** scan of the entire table.
  3601. */
  3602. static const u8 aStep[] = { OP_Next, OP_Prev };
  3603. static const u8 aStart[] = { OP_Rewind, OP_Last };
  3604. assert( bRev==0 || bRev==1 );
  3605. pLevel->op = aStep[bRev];
  3606. pLevel->p1 = iCur;
  3607. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  3608. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  3609. }
  3610. /* Insert code to test every subexpression that can be completely
  3611. ** computed using the current set of tables.
  3612. */
  3613. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  3614. Expr *pE;
  3615. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  3616. testcase( pTerm->wtFlags & TERM_CODED );
  3617. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  3618. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  3619. testcase( pWInfo->untestedTerms==0
  3620. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  3621. pWInfo->untestedTerms = 1;
  3622. continue;
  3623. }
  3624. pE = pTerm->pExpr;
  3625. assert( pE!=0 );
  3626. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  3627. continue;
  3628. }
  3629. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  3630. pTerm->wtFlags |= TERM_CODED;
  3631. }
  3632. /* Insert code to test for implied constraints based on transitivity
  3633. ** of the "==" operator.
  3634. **
  3635. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  3636. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  3637. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  3638. ** the implied "t1.a=123" constraint.
  3639. */
  3640. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  3641. Expr *pE, *pEAlt;
  3642. WhereTerm *pAlt;
  3643. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  3644. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  3645. if( pTerm->leftCursor!=iCur ) continue;
  3646. if( pLevel->iLeftJoin ) continue;
  3647. pE = pTerm->pExpr;
  3648. assert( !ExprHasProperty(pE, EP_FromJoin) );
  3649. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  3650. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  3651. if( pAlt==0 ) continue;
  3652. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  3653. testcase( pAlt->eOperator & WO_EQ );
  3654. testcase( pAlt->eOperator & WO_IN );
  3655. VdbeNoopComment((v, "begin transitive constraint"));
  3656. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  3657. if( pEAlt ){
  3658. *pEAlt = *pAlt->pExpr;
  3659. pEAlt->pLeft = pE->pLeft;
  3660. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  3661. sqlite3StackFree(db, pEAlt);
  3662. }
  3663. }
  3664. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  3665. ** at least one row of the right table has matched the left table.
  3666. */
  3667. if( pLevel->iLeftJoin ){
  3668. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  3669. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  3670. VdbeComment((v, "record LEFT JOIN hit"));
  3671. sqlite3ExprCacheClear(pParse);
  3672. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  3673. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  3674. testcase( pTerm->wtFlags & TERM_CODED );
  3675. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  3676. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  3677. assert( pWInfo->untestedTerms );
  3678. continue;
  3679. }
  3680. assert( pTerm->pExpr );
  3681. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  3682. pTerm->wtFlags |= TERM_CODED;
  3683. }
  3684. }
  3685. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  3686. return pLevel->notReady;
  3687. }
  3688. #ifdef WHERETRACE_ENABLED
  3689. /*
  3690. ** Print a WhereLoop object for debugging purposes
  3691. */
  3692. static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
  3693. int nb = 1+(pTabList->nSrc+7)/8;
  3694. struct SrcList_item *pItem = pTabList->a + p->iTab;
  3695. Table *pTab = pItem->pTab;
  3696. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  3697. p->iTab, nb, p->maskSelf, nb, p->prereq);
  3698. sqlite3DebugPrintf(" %12s",
  3699. pItem->zAlias ? pItem->zAlias : pTab->zName);
  3700. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  3701. if( p->u.btree.pIndex ){
  3702. const char *zName = p->u.btree.pIndex->zName;
  3703. if( zName==0 ) zName = "ipk";
  3704. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  3705. int i = sqlite3Strlen30(zName) - 1;
  3706. while( zName[i]!='_' ) i--;
  3707. zName += i;
  3708. }
  3709. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  3710. }else{
  3711. sqlite3DebugPrintf("%20s","");
  3712. }
  3713. }else{
  3714. char *z;
  3715. if( p->u.vtab.idxStr ){
  3716. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  3717. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  3718. }else{
  3719. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  3720. }
  3721. sqlite3DebugPrintf(" %-19s", z);
  3722. sqlite3_free(z);
  3723. }
  3724. sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
  3725. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  3726. }
  3727. #endif
  3728. /*
  3729. ** Convert bulk memory into a valid WhereLoop that can be passed
  3730. ** to whereLoopClear harmlessly.
  3731. */
  3732. static void whereLoopInit(WhereLoop *p){
  3733. p->aLTerm = p->aLTermSpace;
  3734. p->nLTerm = 0;
  3735. p->nLSlot = ArraySize(p->aLTermSpace);
  3736. p->wsFlags = 0;
  3737. }
  3738. /*
  3739. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  3740. */
  3741. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  3742. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  3743. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  3744. sqlite3_free(p->u.vtab.idxStr);
  3745. p->u.vtab.needFree = 0;
  3746. p->u.vtab.idxStr = 0;
  3747. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  3748. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  3749. sqlite3DbFree(db, p->u.btree.pIndex);
  3750. p->u.btree.pIndex = 0;
  3751. }
  3752. }
  3753. }
  3754. /*
  3755. ** Deallocate internal memory used by a WhereLoop object
  3756. */
  3757. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  3758. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  3759. whereLoopClearUnion(db, p);
  3760. whereLoopInit(p);
  3761. }
  3762. /*
  3763. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  3764. */
  3765. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  3766. WhereTerm **paNew;
  3767. if( p->nLSlot>=n ) return SQLITE_OK;
  3768. n = (n+7)&~7;
  3769. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  3770. if( paNew==0 ) return SQLITE_NOMEM;
  3771. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  3772. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  3773. p->aLTerm = paNew;
  3774. p->nLSlot = n;
  3775. return SQLITE_OK;
  3776. }
  3777. /*
  3778. ** Transfer content from the second pLoop into the first.
  3779. */
  3780. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  3781. whereLoopClearUnion(db, pTo);
  3782. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  3783. memset(&pTo->u, 0, sizeof(pTo->u));
  3784. return SQLITE_NOMEM;
  3785. }
  3786. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  3787. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  3788. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  3789. pFrom->u.vtab.needFree = 0;
  3790. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  3791. pFrom->u.btree.pIndex = 0;
  3792. }
  3793. return SQLITE_OK;
  3794. }
  3795. /*
  3796. ** Delete a WhereLoop object
  3797. */
  3798. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  3799. whereLoopClear(db, p);
  3800. sqlite3DbFree(db, p);
  3801. }
  3802. /*
  3803. ** Free a WhereInfo structure
  3804. */
  3805. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  3806. if( ALWAYS(pWInfo) ){
  3807. whereClauseClear(&pWInfo->sWC);
  3808. while( pWInfo->pLoops ){
  3809. WhereLoop *p = pWInfo->pLoops;
  3810. pWInfo->pLoops = p->pNextLoop;
  3811. whereLoopDelete(db, p);
  3812. }
  3813. sqlite3DbFree(db, pWInfo);
  3814. }
  3815. }
  3816. /*
  3817. ** Insert or replace a WhereLoop entry using the template supplied.
  3818. **
  3819. ** An existing WhereLoop entry might be overwritten if the new template
  3820. ** is better and has fewer dependencies. Or the template will be ignored
  3821. ** and no insert will occur if an existing WhereLoop is faster and has
  3822. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  3823. ** added based on the template.
  3824. **
  3825. ** If pBuilder->pOrSet is not NULL then we only care about only the
  3826. ** prerequisites and rRun and nOut costs of the N best loops. That
  3827. ** information is gathered in the pBuilder->pOrSet object. This special
  3828. ** processing mode is used only for OR clause processing.
  3829. **
  3830. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  3831. ** still might overwrite similar loops with the new template if the
  3832. ** template is better. Loops may be overwritten if the following
  3833. ** conditions are met:
  3834. **
  3835. ** (1) They have the same iTab.
  3836. ** (2) They have the same iSortIdx.
  3837. ** (3) The template has same or fewer dependencies than the current loop
  3838. ** (4) The template has the same or lower cost than the current loop
  3839. ** (5) The template uses more terms of the same index but has no additional
  3840. ** dependencies
  3841. */
  3842. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  3843. WhereLoop **ppPrev, *p, *pNext = 0;
  3844. WhereInfo *pWInfo = pBuilder->pWInfo;
  3845. sqlite3 *db = pWInfo->pParse->db;
  3846. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  3847. ** and prereqs.
  3848. */
  3849. if( pBuilder->pOrSet!=0 ){
  3850. #if WHERETRACE_ENABLED
  3851. u16 n = pBuilder->pOrSet->n;
  3852. int x =
  3853. #endif
  3854. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  3855. pTemplate->nOut);
  3856. #if WHERETRACE_ENABLED
  3857. if( sqlite3WhereTrace & 0x8 ){
  3858. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  3859. whereLoopPrint(pTemplate, pWInfo->pTabList);
  3860. }
  3861. #endif
  3862. return SQLITE_OK;
  3863. }
  3864. /* Search for an existing WhereLoop to overwrite, or which takes
  3865. ** priority over pTemplate.
  3866. */
  3867. for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
  3868. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  3869. /* If either the iTab or iSortIdx values for two WhereLoop are different
  3870. ** then those WhereLoops need to be considered separately. Neither is
  3871. ** a candidate to replace the other. */
  3872. continue;
  3873. }
  3874. /* In the current implementation, the rSetup value is either zero
  3875. ** or the cost of building an automatic index (NlogN) and the NlogN
  3876. ** is the same for compatible WhereLoops. */
  3877. assert( p->rSetup==0 || pTemplate->rSetup==0
  3878. || p->rSetup==pTemplate->rSetup );
  3879. /* whereLoopAddBtree() always generates and inserts the automatic index
  3880. ** case first. Hence compatible candidate WhereLoops never have a larger
  3881. ** rSetup. Call this SETUP-INVARIANT */
  3882. assert( p->rSetup>=pTemplate->rSetup );
  3883. if( (p->prereq & pTemplate->prereq)==p->prereq
  3884. && p->rSetup<=pTemplate->rSetup
  3885. && p->rRun<=pTemplate->rRun
  3886. && p->nOut<=pTemplate->nOut
  3887. ){
  3888. /* This branch taken when p is equal or better than pTemplate in
  3889. ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
  3890. ** (4) number of output rows. */
  3891. assert( p->rSetup==pTemplate->rSetup );
  3892. if( p->prereq==pTemplate->prereq
  3893. && p->nLTerm<pTemplate->nLTerm
  3894. && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
  3895. && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
  3896. || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
  3897. ){
  3898. /* Overwrite an existing WhereLoop with an similar one that uses
  3899. ** more terms of the index */
  3900. pNext = p->pNextLoop;
  3901. break;
  3902. }else{
  3903. /* pTemplate is not helpful.
  3904. ** Return without changing or adding anything */
  3905. goto whereLoopInsert_noop;
  3906. }
  3907. }
  3908. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
  3909. && p->rRun>=pTemplate->rRun
  3910. && p->nOut>=pTemplate->nOut
  3911. ){
  3912. /* Overwrite an existing WhereLoop with a better one: one that is
  3913. ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
  3914. ** or (4) number of output rows, and is no worse in any of those
  3915. ** categories. */
  3916. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  3917. pNext = p->pNextLoop;
  3918. break;
  3919. }
  3920. }
  3921. /* If we reach this point it means that either p[] should be overwritten
  3922. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  3923. ** WhereLoop and insert it.
  3924. */
  3925. #if WHERETRACE_ENABLED
  3926. if( sqlite3WhereTrace & 0x8 ){
  3927. if( p!=0 ){
  3928. sqlite3DebugPrintf("ins-del: ");
  3929. whereLoopPrint(p, pWInfo->pTabList);
  3930. }
  3931. sqlite3DebugPrintf("ins-new: ");
  3932. whereLoopPrint(pTemplate, pWInfo->pTabList);
  3933. }
  3934. #endif
  3935. if( p==0 ){
  3936. p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  3937. if( p==0 ) return SQLITE_NOMEM;
  3938. whereLoopInit(p);
  3939. }
  3940. whereLoopXfer(db, p, pTemplate);
  3941. p->pNextLoop = pNext;
  3942. *ppPrev = p;
  3943. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  3944. Index *pIndex = p->u.btree.pIndex;
  3945. if( pIndex && pIndex->tnum==0 ){
  3946. p->u.btree.pIndex = 0;
  3947. }
  3948. }
  3949. return SQLITE_OK;
  3950. /* Jump here if the insert is a no-op */
  3951. whereLoopInsert_noop:
  3952. #if WHERETRACE_ENABLED
  3953. if( sqlite3WhereTrace & 0x8 ){
  3954. sqlite3DebugPrintf("ins-noop: ");
  3955. whereLoopPrint(pTemplate, pWInfo->pTabList);
  3956. }
  3957. #endif
  3958. return SQLITE_OK;
  3959. }
  3960. /*
  3961. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  3962. ** WHERE clause that reference the loop but which are not used by an
  3963. ** index.
  3964. **
  3965. ** In the current implementation, the first extra WHERE clause term reduces
  3966. ** the number of output rows by a factor of 10 and each additional term
  3967. ** reduces the number of output rows by sqrt(2).
  3968. */
  3969. static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
  3970. WhereTerm *pTerm, *pX;
  3971. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  3972. int i, j;
  3973. if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
  3974. return;
  3975. }
  3976. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  3977. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  3978. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  3979. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  3980. for(j=pLoop->nLTerm-1; j>=0; j--){
  3981. pX = pLoop->aLTerm[j];
  3982. if( pX==pTerm ) break;
  3983. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  3984. }
  3985. if( j<0 ) pLoop->nOut += pTerm->truthProb;
  3986. }
  3987. }
  3988. /*
  3989. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
  3990. ** Try to match one more.
  3991. **
  3992. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  3993. ** INTEGER PRIMARY KEY.
  3994. */
  3995. static int whereLoopAddBtreeIndex(
  3996. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  3997. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  3998. Index *pProbe, /* An index on pSrc */
  3999. LogEst nInMul /* log(Number of iterations due to IN) */
  4000. ){
  4001. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  4002. Parse *pParse = pWInfo->pParse; /* Parsing context */
  4003. sqlite3 *db = pParse->db; /* Database connection malloc context */
  4004. WhereLoop *pNew; /* Template WhereLoop under construction */
  4005. WhereTerm *pTerm; /* A WhereTerm under consideration */
  4006. int opMask; /* Valid operators for constraints */
  4007. WhereScan scan; /* Iterator for WHERE terms */
  4008. Bitmask saved_prereq; /* Original value of pNew->prereq */
  4009. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  4010. int saved_nEq; /* Original value of pNew->u.btree.nEq */
  4011. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  4012. LogEst saved_nOut; /* Original value of pNew->nOut */
  4013. int iCol; /* Index of the column in the table */
  4014. int rc = SQLITE_OK; /* Return code */
  4015. LogEst nRowEst; /* Estimated index selectivity */
  4016. LogEst rLogSize; /* Logarithm of table size */
  4017. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  4018. pNew = pBuilder->pNew;
  4019. if( db->mallocFailed ) return SQLITE_NOMEM;
  4020. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  4021. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  4022. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  4023. opMask = WO_LT|WO_LE;
  4024. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  4025. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  4026. }else{
  4027. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  4028. }
  4029. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  4030. assert( pNew->u.btree.nEq<=pProbe->nColumn );
  4031. if( pNew->u.btree.nEq < pProbe->nColumn ){
  4032. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  4033. nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
  4034. if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
  4035. }else{
  4036. iCol = -1;
  4037. nRowEst = 0;
  4038. }
  4039. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  4040. opMask, pProbe);
  4041. saved_nEq = pNew->u.btree.nEq;
  4042. saved_nLTerm = pNew->nLTerm;
  4043. saved_wsFlags = pNew->wsFlags;
  4044. saved_prereq = pNew->prereq;
  4045. saved_nOut = pNew->nOut;
  4046. pNew->rSetup = 0;
  4047. rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
  4048. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  4049. int nIn = 0;
  4050. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  4051. int nRecValid = pBuilder->nRecValid;
  4052. #endif
  4053. if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  4054. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  4055. ){
  4056. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  4057. }
  4058. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  4059. assert( pNew->nOut==saved_nOut );
  4060. pNew->wsFlags = saved_wsFlags;
  4061. pNew->u.btree.nEq = saved_nEq;
  4062. pNew->nLTerm = saved_nLTerm;
  4063. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  4064. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  4065. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  4066. pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
  4067. if( pTerm->eOperator & WO_IN ){
  4068. Expr *pExpr = pTerm->pExpr;
  4069. pNew->wsFlags |= WHERE_COLUMN_IN;
  4070. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  4071. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  4072. nIn = 46; assert( 46==sqlite3LogEst(25) );
  4073. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  4074. /* "x IN (value, value, ...)" */
  4075. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  4076. }
  4077. pNew->rRun += nIn;
  4078. pNew->u.btree.nEq++;
  4079. pNew->nOut = nRowEst + nInMul + nIn;
  4080. }else if( pTerm->eOperator & (WO_EQ) ){
  4081. assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
  4082. || nInMul==0 );
  4083. pNew->wsFlags |= WHERE_COLUMN_EQ;
  4084. if( iCol<0
  4085. || (pProbe->onError!=OE_None && nInMul==0
  4086. && pNew->u.btree.nEq==pProbe->nColumn-1)
  4087. ){
  4088. assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
  4089. pNew->wsFlags |= WHERE_ONEROW;
  4090. }
  4091. pNew->u.btree.nEq++;
  4092. pNew->nOut = nRowEst + nInMul;
  4093. }else if( pTerm->eOperator & (WO_ISNULL) ){
  4094. pNew->wsFlags |= WHERE_COLUMN_NULL;
  4095. pNew->u.btree.nEq++;
  4096. /* TUNING: IS NULL selects 2 rows */
  4097. nIn = 10; assert( 10==sqlite3LogEst(2) );
  4098. pNew->nOut = nRowEst + nInMul + nIn;
  4099. }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
  4100. testcase( pTerm->eOperator & WO_GT );
  4101. testcase( pTerm->eOperator & WO_GE );
  4102. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  4103. pBtm = pTerm;
  4104. pTop = 0;
  4105. }else{
  4106. assert( pTerm->eOperator & (WO_LT|WO_LE) );
  4107. testcase( pTerm->eOperator & WO_LT );
  4108. testcase( pTerm->eOperator & WO_LE );
  4109. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  4110. pTop = pTerm;
  4111. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  4112. pNew->aLTerm[pNew->nLTerm-2] : 0;
  4113. }
  4114. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  4115. /* Adjust nOut and rRun for STAT3 range values */
  4116. assert( pNew->nOut==saved_nOut );
  4117. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  4118. }
  4119. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  4120. if( nInMul==0
  4121. && pProbe->nSample
  4122. && pNew->u.btree.nEq<=pProbe->nSampleCol
  4123. && OptimizationEnabled(db, SQLITE_Stat3)
  4124. ){
  4125. Expr *pExpr = pTerm->pExpr;
  4126. tRowcnt nOut = 0;
  4127. if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
  4128. testcase( pTerm->eOperator & WO_EQ );
  4129. testcase( pTerm->eOperator & WO_ISNULL );
  4130. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  4131. }else if( (pTerm->eOperator & WO_IN)
  4132. && !ExprHasProperty(pExpr, EP_xIsSelect) ){
  4133. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  4134. }
  4135. assert( nOut==0 || rc==SQLITE_OK );
  4136. if( nOut ){
  4137. pNew->nOut = sqlite3LogEst(nOut);
  4138. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  4139. }
  4140. }
  4141. #endif
  4142. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  4143. /* Each row involves a step of the index, then a binary search of
  4144. ** the main table */
  4145. pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
  4146. }
  4147. /* Step cost for each output row */
  4148. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
  4149. whereLoopOutputAdjust(pBuilder->pWC, pNew);
  4150. rc = whereLoopInsert(pBuilder, pNew);
  4151. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  4152. && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
  4153. ){
  4154. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  4155. }
  4156. pNew->nOut = saved_nOut;
  4157. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  4158. pBuilder->nRecValid = nRecValid;
  4159. #endif
  4160. }
  4161. pNew->prereq = saved_prereq;
  4162. pNew->u.btree.nEq = saved_nEq;
  4163. pNew->wsFlags = saved_wsFlags;
  4164. pNew->nOut = saved_nOut;
  4165. pNew->nLTerm = saved_nLTerm;
  4166. return rc;
  4167. }
  4168. /*
  4169. ** Return True if it is possible that pIndex might be useful in
  4170. ** implementing the ORDER BY clause in pBuilder.
  4171. **
  4172. ** Return False if pBuilder does not contain an ORDER BY clause or
  4173. ** if there is no way for pIndex to be useful in implementing that
  4174. ** ORDER BY clause.
  4175. */
  4176. static int indexMightHelpWithOrderBy(
  4177. WhereLoopBuilder *pBuilder,
  4178. Index *pIndex,
  4179. int iCursor
  4180. ){
  4181. ExprList *pOB;
  4182. int ii, jj;
  4183. if( pIndex->bUnordered ) return 0;
  4184. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  4185. for(ii=0; ii<pOB->nExpr; ii++){
  4186. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  4187. if( pExpr->op!=TK_COLUMN ) return 0;
  4188. if( pExpr->iTable==iCursor ){
  4189. for(jj=0; jj<pIndex->nColumn; jj++){
  4190. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  4191. }
  4192. }
  4193. }
  4194. return 0;
  4195. }
  4196. /*
  4197. ** Return a bitmask where 1s indicate that the corresponding column of
  4198. ** the table is used by an index. Only the first 63 columns are considered.
  4199. */
  4200. static Bitmask columnsInIndex(Index *pIdx){
  4201. Bitmask m = 0;
  4202. int j;
  4203. for(j=pIdx->nColumn-1; j>=0; j--){
  4204. int x = pIdx->aiColumn[j];
  4205. assert( x>=0 );
  4206. testcase( x==BMS-1 );
  4207. testcase( x==BMS-2 );
  4208. if( x<BMS-1 ) m |= MASKBIT(x);
  4209. }
  4210. return m;
  4211. }
  4212. /* Check to see if a partial index with pPartIndexWhere can be used
  4213. ** in the current query. Return true if it can be and false if not.
  4214. */
  4215. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  4216. int i;
  4217. WhereTerm *pTerm;
  4218. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  4219. if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
  4220. }
  4221. return 0;
  4222. }
  4223. /*
  4224. ** Add all WhereLoop objects for a single table of the join where the table
  4225. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  4226. ** a b-tree table, not a virtual table.
  4227. */
  4228. static int whereLoopAddBtree(
  4229. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  4230. Bitmask mExtra /* Extra prerequesites for using this table */
  4231. ){
  4232. WhereInfo *pWInfo; /* WHERE analysis context */
  4233. Index *pProbe; /* An index we are evaluating */
  4234. Index sPk; /* A fake index object for the primary key */
  4235. tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  4236. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  4237. SrcList *pTabList; /* The FROM clause */
  4238. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  4239. WhereLoop *pNew; /* Template WhereLoop object */
  4240. int rc = SQLITE_OK; /* Return code */
  4241. int iSortIdx = 1; /* Index number */
  4242. int b; /* A boolean value */
  4243. LogEst rSize; /* number of rows in the table */
  4244. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  4245. WhereClause *pWC; /* The parsed WHERE clause */
  4246. Table *pTab; /* Table being queried */
  4247. pNew = pBuilder->pNew;
  4248. pWInfo = pBuilder->pWInfo;
  4249. pTabList = pWInfo->pTabList;
  4250. pSrc = pTabList->a + pNew->iTab;
  4251. pTab = pSrc->pTab;
  4252. pWC = pBuilder->pWC;
  4253. assert( !IsVirtual(pSrc->pTab) );
  4254. if( pSrc->pIndex ){
  4255. /* An INDEXED BY clause specifies a particular index to use */
  4256. pProbe = pSrc->pIndex;
  4257. }else{
  4258. /* There is no INDEXED BY clause. Create a fake Index object in local
  4259. ** variable sPk to represent the rowid primary key index. Make this
  4260. ** fake index the first in a chain of Index objects with all of the real
  4261. ** indices to follow */
  4262. Index *pFirst; /* First of real indices on the table */
  4263. memset(&sPk, 0, sizeof(Index));
  4264. sPk.nColumn = 1;
  4265. sPk.aiColumn = &aiColumnPk;
  4266. sPk.aiRowEst = aiRowEstPk;
  4267. sPk.onError = OE_Replace;
  4268. sPk.pTable = pTab;
  4269. aiRowEstPk[0] = pTab->nRowEst;
  4270. aiRowEstPk[1] = 1;
  4271. pFirst = pSrc->pTab->pIndex;
  4272. if( pSrc->notIndexed==0 ){
  4273. /* The real indices of the table are only considered if the
  4274. ** NOT INDEXED qualifier is omitted from the FROM clause */
  4275. sPk.pNext = pFirst;
  4276. }
  4277. pProbe = &sPk;
  4278. }
  4279. rSize = sqlite3LogEst(pTab->nRowEst);
  4280. rLogSize = estLog(rSize);
  4281. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  4282. /* Automatic indexes */
  4283. if( !pBuilder->pOrSet
  4284. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  4285. && pSrc->pIndex==0
  4286. && !pSrc->viaCoroutine
  4287. && !pSrc->notIndexed
  4288. && !pSrc->isCorrelated
  4289. ){
  4290. /* Generate auto-index WhereLoops */
  4291. WhereTerm *pTerm;
  4292. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  4293. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  4294. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  4295. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  4296. pNew->u.btree.nEq = 1;
  4297. pNew->u.btree.pIndex = 0;
  4298. pNew->nLTerm = 1;
  4299. pNew->aLTerm[0] = pTerm;
  4300. /* TUNING: One-time cost for computing the automatic index is
  4301. ** approximately 7*N*log2(N) where N is the number of rows in
  4302. ** the table being indexed. */
  4303. pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
  4304. /* TUNING: Each index lookup yields 20 rows in the table. This
  4305. ** is more than the usual guess of 10 rows, since we have no way
  4306. ** of knowning how selective the index will ultimately be. It would
  4307. ** not be unreasonable to make this value much larger. */
  4308. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  4309. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  4310. pNew->wsFlags = WHERE_AUTO_INDEX;
  4311. pNew->prereq = mExtra | pTerm->prereqRight;
  4312. rc = whereLoopInsert(pBuilder, pNew);
  4313. }
  4314. }
  4315. }
  4316. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  4317. /* Loop over all indices
  4318. */
  4319. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  4320. if( pProbe->pPartIdxWhere!=0
  4321. && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
  4322. continue; /* Partial index inappropriate for this query */
  4323. }
  4324. pNew->u.btree.nEq = 0;
  4325. pNew->nLTerm = 0;
  4326. pNew->iSortIdx = 0;
  4327. pNew->rSetup = 0;
  4328. pNew->prereq = mExtra;
  4329. pNew->nOut = rSize;
  4330. pNew->u.btree.pIndex = pProbe;
  4331. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  4332. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  4333. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  4334. if( pProbe->tnum<=0 ){
  4335. /* Integer primary key index */
  4336. pNew->wsFlags = WHERE_IPK;
  4337. /* Full table scan */
  4338. pNew->iSortIdx = b ? iSortIdx : 0;
  4339. /* TUNING: Cost of full table scan is 3*(N + log2(N)).
  4340. ** + The extra 3 factor is to encourage the use of indexed lookups
  4341. ** over full scans. FIXME */
  4342. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
  4343. whereLoopOutputAdjust(pWC, pNew);
  4344. rc = whereLoopInsert(pBuilder, pNew);
  4345. pNew->nOut = rSize;
  4346. if( rc ) break;
  4347. }else{
  4348. Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
  4349. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  4350. /* Full scan via index */
  4351. if( b
  4352. || ( m==0
  4353. && pProbe->bUnordered==0
  4354. && pProbe->szIdxRow<pTab->szTabRow
  4355. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  4356. && sqlite3GlobalConfig.bUseCis
  4357. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  4358. )
  4359. ){
  4360. pNew->iSortIdx = b ? iSortIdx : 0;
  4361. if( m==0 ){
  4362. /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
  4363. ** + The extra factor K of between 1.1 and 3.0 that depends
  4364. ** on the relative sizes of the table and the index. K
  4365. ** is smaller for smaller indices, thus favoring them.
  4366. */
  4367. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
  4368. (15*pProbe->szIdxRow)/pTab->szTabRow;
  4369. }else{
  4370. assert( b!=0 );
  4371. /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
  4372. ** which we will simplify to just N*log2(N) */
  4373. pNew->rRun = rSize + rLogSize;
  4374. }
  4375. whereLoopOutputAdjust(pWC, pNew);
  4376. rc = whereLoopInsert(pBuilder, pNew);
  4377. pNew->nOut = rSize;
  4378. if( rc ) break;
  4379. }
  4380. }
  4381. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  4382. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  4383. sqlite3Stat4ProbeFree(pBuilder->pRec);
  4384. pBuilder->nRecValid = 0;
  4385. pBuilder->pRec = 0;
  4386. #endif
  4387. /* If there was an INDEXED BY clause, then only that one index is
  4388. ** considered. */
  4389. if( pSrc->pIndex ) break;
  4390. }
  4391. return rc;
  4392. }
  4393. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4394. /*
  4395. ** Add all WhereLoop objects for a table of the join identified by
  4396. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  4397. */
  4398. static int whereLoopAddVirtual(
  4399. WhereLoopBuilder *pBuilder /* WHERE clause information */
  4400. ){
  4401. WhereInfo *pWInfo; /* WHERE analysis context */
  4402. Parse *pParse; /* The parsing context */
  4403. WhereClause *pWC; /* The WHERE clause */
  4404. struct SrcList_item *pSrc; /* The FROM clause term to search */
  4405. Table *pTab;
  4406. sqlite3 *db;
  4407. sqlite3_index_info *pIdxInfo;
  4408. struct sqlite3_index_constraint *pIdxCons;
  4409. struct sqlite3_index_constraint_usage *pUsage;
  4410. WhereTerm *pTerm;
  4411. int i, j;
  4412. int iTerm, mxTerm;
  4413. int nConstraint;
  4414. int seenIn = 0; /* True if an IN operator is seen */
  4415. int seenVar = 0; /* True if a non-constant constraint is seen */
  4416. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  4417. WhereLoop *pNew;
  4418. int rc = SQLITE_OK;
  4419. pWInfo = pBuilder->pWInfo;
  4420. pParse = pWInfo->pParse;
  4421. db = pParse->db;
  4422. pWC = pBuilder->pWC;
  4423. pNew = pBuilder->pNew;
  4424. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  4425. pTab = pSrc->pTab;
  4426. assert( IsVirtual(pTab) );
  4427. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  4428. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  4429. pNew->prereq = 0;
  4430. pNew->rSetup = 0;
  4431. pNew->wsFlags = WHERE_VIRTUALTABLE;
  4432. pNew->nLTerm = 0;
  4433. pNew->u.vtab.needFree = 0;
  4434. pUsage = pIdxInfo->aConstraintUsage;
  4435. nConstraint = pIdxInfo->nConstraint;
  4436. if( whereLoopResize(db, pNew, nConstraint) ){
  4437. sqlite3DbFree(db, pIdxInfo);
  4438. return SQLITE_NOMEM;
  4439. }
  4440. for(iPhase=0; iPhase<=3; iPhase++){
  4441. if( !seenIn && (iPhase&1)!=0 ){
  4442. iPhase++;
  4443. if( iPhase>3 ) break;
  4444. }
  4445. if( !seenVar && iPhase>1 ) break;
  4446. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  4447. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  4448. j = pIdxCons->iTermOffset;
  4449. pTerm = &pWC->a[j];
  4450. switch( iPhase ){
  4451. case 0: /* Constants without IN operator */
  4452. pIdxCons->usable = 0;
  4453. if( (pTerm->eOperator & WO_IN)!=0 ){
  4454. seenIn = 1;
  4455. }
  4456. if( pTerm->prereqRight!=0 ){
  4457. seenVar = 1;
  4458. }else if( (pTerm->eOperator & WO_IN)==0 ){
  4459. pIdxCons->usable = 1;
  4460. }
  4461. break;
  4462. case 1: /* Constants with IN operators */
  4463. assert( seenIn );
  4464. pIdxCons->usable = (pTerm->prereqRight==0);
  4465. break;
  4466. case 2: /* Variables without IN */
  4467. assert( seenVar );
  4468. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  4469. break;
  4470. default: /* Variables with IN */
  4471. assert( seenVar && seenIn );
  4472. pIdxCons->usable = 1;
  4473. break;
  4474. }
  4475. }
  4476. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  4477. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  4478. pIdxInfo->idxStr = 0;
  4479. pIdxInfo->idxNum = 0;
  4480. pIdxInfo->needToFreeIdxStr = 0;
  4481. pIdxInfo->orderByConsumed = 0;
  4482. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  4483. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  4484. if( rc ) goto whereLoopAddVtab_exit;
  4485. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  4486. pNew->prereq = 0;
  4487. mxTerm = -1;
  4488. assert( pNew->nLSlot>=nConstraint );
  4489. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  4490. pNew->u.vtab.omitMask = 0;
  4491. for(i=0; i<nConstraint; i++, pIdxCons++){
  4492. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  4493. j = pIdxCons->iTermOffset;
  4494. if( iTerm>=nConstraint
  4495. || j<0
  4496. || j>=pWC->nTerm
  4497. || pNew->aLTerm[iTerm]!=0
  4498. ){
  4499. rc = SQLITE_ERROR;
  4500. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  4501. goto whereLoopAddVtab_exit;
  4502. }
  4503. testcase( iTerm==nConstraint-1 );
  4504. testcase( j==0 );
  4505. testcase( j==pWC->nTerm-1 );
  4506. pTerm = &pWC->a[j];
  4507. pNew->prereq |= pTerm->prereqRight;
  4508. assert( iTerm<pNew->nLSlot );
  4509. pNew->aLTerm[iTerm] = pTerm;
  4510. if( iTerm>mxTerm ) mxTerm = iTerm;
  4511. testcase( iTerm==15 );
  4512. testcase( iTerm==16 );
  4513. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  4514. if( (pTerm->eOperator & WO_IN)!=0 ){
  4515. if( pUsage[i].omit==0 ){
  4516. /* Do not attempt to use an IN constraint if the virtual table
  4517. ** says that the equivalent EQ constraint cannot be safely omitted.
  4518. ** If we do attempt to use such a constraint, some rows might be
  4519. ** repeated in the output. */
  4520. break;
  4521. }
  4522. /* A virtual table that is constrained by an IN clause may not
  4523. ** consume the ORDER BY clause because (1) the order of IN terms
  4524. ** is not necessarily related to the order of output terms and
  4525. ** (2) Multiple outputs from a single IN value will not merge
  4526. ** together. */
  4527. pIdxInfo->orderByConsumed = 0;
  4528. }
  4529. }
  4530. }
  4531. if( i>=nConstraint ){
  4532. pNew->nLTerm = mxTerm+1;
  4533. assert( pNew->nLTerm<=pNew->nLSlot );
  4534. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  4535. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  4536. pIdxInfo->needToFreeIdxStr = 0;
  4537. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  4538. pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
  4539. && pIdxInfo->orderByConsumed);
  4540. pNew->rSetup = 0;
  4541. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  4542. /* TUNING: Every virtual table query returns 25 rows */
  4543. pNew->nOut = 46; assert( 46==sqlite3LogEst(25) );
  4544. whereLoopInsert(pBuilder, pNew);
  4545. if( pNew->u.vtab.needFree ){
  4546. sqlite3_free(pNew->u.vtab.idxStr);
  4547. pNew->u.vtab.needFree = 0;
  4548. }
  4549. }
  4550. }
  4551. whereLoopAddVtab_exit:
  4552. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  4553. sqlite3DbFree(db, pIdxInfo);
  4554. return rc;
  4555. }
  4556. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  4557. /*
  4558. ** Add WhereLoop entries to handle OR terms. This works for either
  4559. ** btrees or virtual tables.
  4560. */
  4561. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  4562. WhereInfo *pWInfo = pBuilder->pWInfo;
  4563. WhereClause *pWC;
  4564. WhereLoop *pNew;
  4565. WhereTerm *pTerm, *pWCEnd;
  4566. int rc = SQLITE_OK;
  4567. int iCur;
  4568. WhereClause tempWC;
  4569. WhereLoopBuilder sSubBuild;
  4570. WhereOrSet sSum, sCur, sPrev;
  4571. struct SrcList_item *pItem;
  4572. pWC = pBuilder->pWC;
  4573. if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
  4574. pWCEnd = pWC->a + pWC->nTerm;
  4575. pNew = pBuilder->pNew;
  4576. memset(&sSum, 0, sizeof(sSum));
  4577. pItem = pWInfo->pTabList->a + pNew->iTab;
  4578. iCur = pItem->iCursor;
  4579. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  4580. if( (pTerm->eOperator & WO_OR)!=0
  4581. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  4582. ){
  4583. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  4584. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  4585. WhereTerm *pOrTerm;
  4586. int once = 1;
  4587. int i, j;
  4588. sSubBuild = *pBuilder;
  4589. sSubBuild.pOrderBy = 0;
  4590. sSubBuild.pOrSet = &sCur;
  4591. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  4592. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  4593. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  4594. }else if( pOrTerm->leftCursor==iCur ){
  4595. tempWC.pWInfo = pWC->pWInfo;
  4596. tempWC.pOuter = pWC;
  4597. tempWC.op = TK_AND;
  4598. tempWC.nTerm = 1;
  4599. tempWC.a = pOrTerm;
  4600. sSubBuild.pWC = &tempWC;
  4601. }else{
  4602. continue;
  4603. }
  4604. sCur.n = 0;
  4605. #ifndef SQLITE_OMIT_VIRTUALTABLE
  4606. if( IsVirtual(pItem->pTab) ){
  4607. rc = whereLoopAddVirtual(&sSubBuild);
  4608. for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
  4609. }else
  4610. #endif
  4611. {
  4612. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  4613. }
  4614. assert( rc==SQLITE_OK || sCur.n==0 );
  4615. if( sCur.n==0 ){
  4616. sSum.n = 0;
  4617. break;
  4618. }else if( once ){
  4619. whereOrMove(&sSum, &sCur);
  4620. once = 0;
  4621. }else{
  4622. whereOrMove(&sPrev, &sSum);
  4623. sSum.n = 0;
  4624. for(i=0; i<sPrev.n; i++){
  4625. for(j=0; j<sCur.n; j++){
  4626. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  4627. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  4628. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  4629. }
  4630. }
  4631. }
  4632. }
  4633. pNew->nLTerm = 1;
  4634. pNew->aLTerm[0] = pTerm;
  4635. pNew->wsFlags = WHERE_MULTI_OR;
  4636. pNew->rSetup = 0;
  4637. pNew->iSortIdx = 0;
  4638. memset(&pNew->u, 0, sizeof(pNew->u));
  4639. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  4640. /* TUNING: Multiple by 3.5 for the secondary table lookup */
  4641. pNew->rRun = sSum.a[i].rRun + 18;
  4642. pNew->nOut = sSum.a[i].nOut;
  4643. pNew->prereq = sSum.a[i].prereq;
  4644. rc = whereLoopInsert(pBuilder, pNew);
  4645. }
  4646. }
  4647. }
  4648. return rc;
  4649. }
  4650. /*
  4651. ** Add all WhereLoop objects for all tables
  4652. */
  4653. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  4654. WhereInfo *pWInfo = pBuilder->pWInfo;
  4655. Bitmask mExtra = 0;
  4656. Bitmask mPrior = 0;
  4657. int iTab;
  4658. SrcList *pTabList = pWInfo->pTabList;
  4659. struct SrcList_item *pItem;
  4660. sqlite3 *db = pWInfo->pParse->db;
  4661. int nTabList = pWInfo->nLevel;
  4662. int rc = SQLITE_OK;
  4663. u8 priorJoinType = 0;
  4664. WhereLoop *pNew;
  4665. /* Loop over the tables in the join, from left to right */
  4666. pNew = pBuilder->pNew;
  4667. whereLoopInit(pNew);
  4668. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  4669. pNew->iTab = iTab;
  4670. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  4671. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  4672. mExtra = mPrior;
  4673. }
  4674. priorJoinType = pItem->jointype;
  4675. if( IsVirtual(pItem->pTab) ){
  4676. rc = whereLoopAddVirtual(pBuilder);
  4677. }else{
  4678. rc = whereLoopAddBtree(pBuilder, mExtra);
  4679. }
  4680. if( rc==SQLITE_OK ){
  4681. rc = whereLoopAddOr(pBuilder, mExtra);
  4682. }
  4683. mPrior |= pNew->maskSelf;
  4684. if( rc || db->mallocFailed ) break;
  4685. }
  4686. whereLoopClear(db, pNew);
  4687. return rc;
  4688. }
  4689. /*
  4690. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  4691. ** parameters) to see if it outputs rows in the requested ORDER BY
  4692. ** (or GROUP BY) without requiring a separate sort operation. Return:
  4693. **
  4694. ** 0: ORDER BY is not satisfied. Sorting required
  4695. ** 1: ORDER BY is satisfied. Omit sorting
  4696. ** -1: Unknown at this time
  4697. **
  4698. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  4699. ** strict. With GROUP BY and DISTINCT the only requirement is that
  4700. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  4701. ** and DISTINT do not require rows to appear in any particular order as long
  4702. ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
  4703. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  4704. ** pOrderBy terms must be matched in strict left-to-right order.
  4705. */
  4706. static int wherePathSatisfiesOrderBy(
  4707. WhereInfo *pWInfo, /* The WHERE clause */
  4708. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  4709. WherePath *pPath, /* The WherePath to check */
  4710. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  4711. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  4712. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  4713. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  4714. ){
  4715. u8 revSet; /* True if rev is known */
  4716. u8 rev; /* Composite sort order */
  4717. u8 revIdx; /* Index sort order */
  4718. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  4719. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  4720. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  4721. u16 nColumn; /* Number of columns in pIndex */
  4722. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  4723. int iLoop; /* Index of WhereLoop in pPath being processed */
  4724. int i, j; /* Loop counters */
  4725. int iCur; /* Cursor number for current WhereLoop */
  4726. int iColumn; /* A column number within table iCur */
  4727. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  4728. WhereTerm *pTerm; /* A single term of the WHERE clause */
  4729. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  4730. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  4731. Index *pIndex; /* The index associated with pLoop */
  4732. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  4733. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  4734. Bitmask obDone; /* Mask of all ORDER BY terms */
  4735. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  4736. Bitmask ready; /* Mask of inner loops */
  4737. /*
  4738. ** We say the WhereLoop is "one-row" if it generates no more than one
  4739. ** row of output. A WhereLoop is one-row if all of the following are true:
  4740. ** (a) All index columns match with WHERE_COLUMN_EQ.
  4741. ** (b) The index is unique
  4742. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  4743. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  4744. **
  4745. ** We say the WhereLoop is "order-distinct" if the set of columns from
  4746. ** that WhereLoop that are in the ORDER BY clause are different for every
  4747. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  4748. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  4749. ** is not order-distinct. To be order-distinct is not quite the same as being
  4750. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  4751. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  4752. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  4753. **
  4754. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  4755. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  4756. ** automatically order-distinct.
  4757. */
  4758. assert( pOrderBy!=0 );
  4759. /* Sortability of virtual tables is determined by the xBestIndex method
  4760. ** of the virtual table itself */
  4761. if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
  4762. testcase( nLoop>0 ); /* True when outer loops are one-row and match
  4763. ** no ORDER BY terms */
  4764. return pLast->u.vtab.isOrdered;
  4765. }
  4766. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  4767. nOrderBy = pOrderBy->nExpr;
  4768. testcase( nOrderBy==BMS-1 );
  4769. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  4770. isOrderDistinct = 1;
  4771. obDone = MASKBIT(nOrderBy)-1;
  4772. orderDistinctMask = 0;
  4773. ready = 0;
  4774. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  4775. if( iLoop>0 ) ready |= pLoop->maskSelf;
  4776. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  4777. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  4778. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  4779. /* Mark off any ORDER BY term X that is a column in the table of
  4780. ** the current loop for which there is term in the WHERE
  4781. ** clause of the form X IS NULL or X=? that reference only outer
  4782. ** loops.
  4783. */
  4784. for(i=0; i<nOrderBy; i++){
  4785. if( MASKBIT(i) & obSat ) continue;
  4786. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  4787. if( pOBExpr->op!=TK_COLUMN ) continue;
  4788. if( pOBExpr->iTable!=iCur ) continue;
  4789. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  4790. ~ready, WO_EQ|WO_ISNULL, 0);
  4791. if( pTerm==0 ) continue;
  4792. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  4793. const char *z1, *z2;
  4794. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  4795. if( !pColl ) pColl = db->pDfltColl;
  4796. z1 = pColl->zName;
  4797. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  4798. if( !pColl ) pColl = db->pDfltColl;
  4799. z2 = pColl->zName;
  4800. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  4801. }
  4802. obSat |= MASKBIT(i);
  4803. }
  4804. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  4805. if( pLoop->wsFlags & WHERE_IPK ){
  4806. pIndex = 0;
  4807. nColumn = 0;
  4808. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  4809. return 0;
  4810. }else{
  4811. nColumn = pIndex->nColumn;
  4812. isOrderDistinct = pIndex->onError!=OE_None;
  4813. }
  4814. /* Loop through all columns of the index and deal with the ones
  4815. ** that are not constrained by == or IN.
  4816. */
  4817. rev = revSet = 0;
  4818. distinctColumns = 0;
  4819. for(j=0; j<=nColumn; j++){
  4820. u8 bOnce; /* True to run the ORDER BY search loop */
  4821. /* Skip over == and IS NULL terms */
  4822. if( j<pLoop->u.btree.nEq
  4823. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  4824. ){
  4825. if( i & WO_ISNULL ){
  4826. testcase( isOrderDistinct );
  4827. isOrderDistinct = 0;
  4828. }
  4829. continue;
  4830. }
  4831. /* Get the column number in the table (iColumn) and sort order
  4832. ** (revIdx) for the j-th column of the index.
  4833. */
  4834. if( j<nColumn ){
  4835. /* Normal index columns */
  4836. iColumn = pIndex->aiColumn[j];
  4837. revIdx = pIndex->aSortOrder[j];
  4838. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  4839. }else{
  4840. /* The ROWID column at the end */
  4841. assert( j==nColumn );
  4842. iColumn = -1;
  4843. revIdx = 0;
  4844. }
  4845. /* An unconstrained column that might be NULL means that this
  4846. ** WhereLoop is not well-ordered
  4847. */
  4848. if( isOrderDistinct
  4849. && iColumn>=0
  4850. && j>=pLoop->u.btree.nEq
  4851. && pIndex->pTable->aCol[iColumn].notNull==0
  4852. ){
  4853. isOrderDistinct = 0;
  4854. }
  4855. /* Find the ORDER BY term that corresponds to the j-th column
  4856. ** of the index and and mark that ORDER BY term off
  4857. */
  4858. bOnce = 1;
  4859. isMatch = 0;
  4860. for(i=0; bOnce && i<nOrderBy; i++){
  4861. if( MASKBIT(i) & obSat ) continue;
  4862. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  4863. testcase( wctrlFlags & WHERE_GROUPBY );
  4864. testcase( wctrlFlags & WHERE_DISTINCTBY );
  4865. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  4866. if( pOBExpr->op!=TK_COLUMN ) continue;
  4867. if( pOBExpr->iTable!=iCur ) continue;
  4868. if( pOBExpr->iColumn!=iColumn ) continue;
  4869. if( iColumn>=0 ){
  4870. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  4871. if( !pColl ) pColl = db->pDfltColl;
  4872. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  4873. }
  4874. isMatch = 1;
  4875. break;
  4876. }
  4877. if( isMatch ){
  4878. if( iColumn<0 ){
  4879. testcase( distinctColumns==0 );
  4880. distinctColumns = 1;
  4881. }
  4882. obSat |= MASKBIT(i);
  4883. if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
  4884. /* Make sure the sort order is compatible in an ORDER BY clause.
  4885. ** Sort order is irrelevant for a GROUP BY clause. */
  4886. if( revSet ){
  4887. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
  4888. }else{
  4889. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  4890. if( rev ) *pRevMask |= MASKBIT(iLoop);
  4891. revSet = 1;
  4892. }
  4893. }
  4894. }else{
  4895. /* No match found */
  4896. if( j==0 || j<nColumn ){
  4897. testcase( isOrderDistinct!=0 );
  4898. isOrderDistinct = 0;
  4899. }
  4900. break;
  4901. }
  4902. } /* end Loop over all index columns */
  4903. if( distinctColumns ){
  4904. testcase( isOrderDistinct==0 );
  4905. isOrderDistinct = 1;
  4906. }
  4907. } /* end-if not one-row */
  4908. /* Mark off any other ORDER BY terms that reference pLoop */
  4909. if( isOrderDistinct ){
  4910. orderDistinctMask |= pLoop->maskSelf;
  4911. for(i=0; i<nOrderBy; i++){
  4912. Expr *p;
  4913. if( MASKBIT(i) & obSat ) continue;
  4914. p = pOrderBy->a[i].pExpr;
  4915. if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
  4916. obSat |= MASKBIT(i);
  4917. }
  4918. }
  4919. }
  4920. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  4921. if( obSat==obDone ) return 1;
  4922. if( !isOrderDistinct ) return 0;
  4923. return -1;
  4924. }
  4925. #ifdef WHERETRACE_ENABLED
  4926. /* For debugging use only: */
  4927. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  4928. static char zName[65];
  4929. int i;
  4930. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  4931. if( pLast ) zName[i++] = pLast->cId;
  4932. zName[i] = 0;
  4933. return zName;
  4934. }
  4935. #endif
  4936. /*
  4937. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  4938. ** attempts to find the lowest cost path that visits each WhereLoop
  4939. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  4940. **
  4941. ** Assume that the total number of output rows that will need to be sorted
  4942. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  4943. ** costs if nRowEst==0.
  4944. **
  4945. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  4946. ** error occurs.
  4947. */
  4948. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  4949. int mxChoice; /* Maximum number of simultaneous paths tracked */
  4950. int nLoop; /* Number of terms in the join */
  4951. Parse *pParse; /* Parsing context */
  4952. sqlite3 *db; /* The database connection */
  4953. int iLoop; /* Loop counter over the terms of the join */
  4954. int ii, jj; /* Loop counters */
  4955. int mxI = 0; /* Index of next entry to replace */
  4956. LogEst rCost; /* Cost of a path */
  4957. LogEst nOut; /* Number of outputs */
  4958. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  4959. LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
  4960. LogEst rSortCost; /* Cost to do a sort */
  4961. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  4962. WherePath *aFrom; /* All nFrom paths at the previous level */
  4963. WherePath *aTo; /* The nTo best paths at the current level */
  4964. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  4965. WherePath *pTo; /* An element of aTo[] that we are working on */
  4966. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  4967. WhereLoop **pX; /* Used to divy up the pSpace memory */
  4968. char *pSpace; /* Temporary memory used by this routine */
  4969. pParse = pWInfo->pParse;
  4970. db = pParse->db;
  4971. nLoop = pWInfo->nLevel;
  4972. /* TUNING: For simple queries, only the best path is tracked.
  4973. ** For 2-way joins, the 5 best paths are followed.
  4974. ** For joins of 3 or more tables, track the 10 best paths */
  4975. mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
  4976. assert( nLoop<=pWInfo->pTabList->nSrc );
  4977. WHERETRACE(0x002, ("---- begin solver\n"));
  4978. /* Allocate and initialize space for aTo and aFrom */
  4979. ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  4980. pSpace = sqlite3DbMallocRaw(db, ii);
  4981. if( pSpace==0 ) return SQLITE_NOMEM;
  4982. aTo = (WherePath*)pSpace;
  4983. aFrom = aTo+mxChoice;
  4984. memset(aFrom, 0, sizeof(aFrom[0]));
  4985. pX = (WhereLoop**)(aFrom+mxChoice);
  4986. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  4987. pFrom->aLoop = pX;
  4988. }
  4989. /* Seed the search with a single WherePath containing zero WhereLoops.
  4990. **
  4991. ** TUNING: Do not let the number of iterations go above 25. If the cost
  4992. ** of computing an automatic index is not paid back within the first 25
  4993. ** rows, then do not use the automatic index. */
  4994. aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
  4995. nFrom = 1;
  4996. /* Precompute the cost of sorting the final result set, if the caller
  4997. ** to sqlite3WhereBegin() was concerned about sorting */
  4998. rSortCost = 0;
  4999. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  5000. aFrom[0].isOrderedValid = 1;
  5001. }else{
  5002. /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
  5003. ** number of output rows. The 48 is the expected size of a row to sort.
  5004. ** FIXME: compute a better estimate of the 48 multiplier based on the
  5005. ** result set expressions. */
  5006. rSortCost = nRowEst + estLog(nRowEst);
  5007. WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
  5008. }
  5009. /* Compute successively longer WherePaths using the previous generation
  5010. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  5011. ** best paths at each generation */
  5012. for(iLoop=0; iLoop<nLoop; iLoop++){
  5013. nTo = 0;
  5014. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  5015. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  5016. Bitmask maskNew;
  5017. Bitmask revMask = 0;
  5018. u8 isOrderedValid = pFrom->isOrderedValid;
  5019. u8 isOrdered = pFrom->isOrdered;
  5020. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  5021. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  5022. /* At this point, pWLoop is a candidate to be the next loop.
  5023. ** Compute its cost */
  5024. rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  5025. rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
  5026. nOut = pFrom->nRow + pWLoop->nOut;
  5027. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  5028. if( !isOrderedValid ){
  5029. switch( wherePathSatisfiesOrderBy(pWInfo,
  5030. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  5031. iLoop, pWLoop, &revMask) ){
  5032. case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
  5033. isOrdered = 1;
  5034. isOrderedValid = 1;
  5035. break;
  5036. case 0: /* No. pFrom+pWLoop will require a separate sort */
  5037. isOrdered = 0;
  5038. isOrderedValid = 1;
  5039. rCost = sqlite3LogEstAdd(rCost, rSortCost);
  5040. break;
  5041. default: /* Cannot tell yet. Try again on the next iteration */
  5042. break;
  5043. }
  5044. }else{
  5045. revMask = pFrom->revLoop;
  5046. }
  5047. /* Check to see if pWLoop should be added to the mxChoice best so far */
  5048. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  5049. if( pTo->maskLoop==maskNew
  5050. && pTo->isOrderedValid==isOrderedValid
  5051. && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
  5052. (pTo->rCost>=rCost && pTo->nRow>=nOut))
  5053. ){
  5054. testcase( jj==nTo-1 );
  5055. break;
  5056. }
  5057. }
  5058. if( jj>=nTo ){
  5059. if( nTo>=mxChoice && rCost>=mxCost ){
  5060. #ifdef WHERETRACE_ENABLED
  5061. if( sqlite3WhereTrace&0x4 ){
  5062. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  5063. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  5064. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  5065. }
  5066. #endif
  5067. continue;
  5068. }
  5069. /* Add a new Path to the aTo[] set */
  5070. if( nTo<mxChoice ){
  5071. /* Increase the size of the aTo set by one */
  5072. jj = nTo++;
  5073. }else{
  5074. /* New path replaces the prior worst to keep count below mxChoice */
  5075. jj = mxI;
  5076. }
  5077. pTo = &aTo[jj];
  5078. #ifdef WHERETRACE_ENABLED
  5079. if( sqlite3WhereTrace&0x4 ){
  5080. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  5081. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  5082. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  5083. }
  5084. #endif
  5085. }else{
  5086. if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
  5087. #ifdef WHERETRACE_ENABLED
  5088. if( sqlite3WhereTrace&0x4 ){
  5089. sqlite3DebugPrintf(
  5090. "Skip %s cost=%-3d,%3d order=%c",
  5091. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  5092. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  5093. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  5094. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  5095. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  5096. }
  5097. #endif
  5098. testcase( pTo->rCost==rCost );
  5099. continue;
  5100. }
  5101. testcase( pTo->rCost==rCost+1 );
  5102. /* A new and better score for a previously created equivalent path */
  5103. #ifdef WHERETRACE_ENABLED
  5104. if( sqlite3WhereTrace&0x4 ){
  5105. sqlite3DebugPrintf(
  5106. "Update %s cost=%-3d,%3d order=%c",
  5107. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  5108. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  5109. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  5110. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  5111. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  5112. }
  5113. #endif
  5114. }
  5115. /* pWLoop is a winner. Add it to the set of best so far */
  5116. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  5117. pTo->revLoop = revMask;
  5118. pTo->nRow = nOut;
  5119. pTo->rCost = rCost;
  5120. pTo->isOrderedValid = isOrderedValid;
  5121. pTo->isOrdered = isOrdered;
  5122. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  5123. pTo->aLoop[iLoop] = pWLoop;
  5124. if( nTo>=mxChoice ){
  5125. mxI = 0;
  5126. mxCost = aTo[0].rCost;
  5127. mxOut = aTo[0].nRow;
  5128. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  5129. if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
  5130. mxCost = pTo->rCost;
  5131. mxOut = pTo->nRow;
  5132. mxI = jj;
  5133. }
  5134. }
  5135. }
  5136. }
  5137. }
  5138. #ifdef WHERETRACE_ENABLED
  5139. if( sqlite3WhereTrace>=2 ){
  5140. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  5141. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  5142. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  5143. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  5144. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  5145. if( pTo->isOrderedValid && pTo->isOrdered ){
  5146. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  5147. }else{
  5148. sqlite3DebugPrintf("\n");
  5149. }
  5150. }
  5151. }
  5152. #endif
  5153. /* Swap the roles of aFrom and aTo for the next generation */
  5154. pFrom = aTo;
  5155. aTo = aFrom;
  5156. aFrom = pFrom;
  5157. nFrom = nTo;
  5158. }
  5159. if( nFrom==0 ){
  5160. sqlite3ErrorMsg(pParse, "no query solution");
  5161. sqlite3DbFree(db, pSpace);
  5162. return SQLITE_ERROR;
  5163. }
  5164. /* Find the lowest cost path. pFrom will be left pointing to that path */
  5165. pFrom = aFrom;
  5166. for(ii=1; ii<nFrom; ii++){
  5167. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  5168. }
  5169. assert( pWInfo->nLevel==nLoop );
  5170. /* Load the lowest cost path into pWInfo */
  5171. for(iLoop=0; iLoop<nLoop; iLoop++){
  5172. WhereLevel *pLevel = pWInfo->a + iLoop;
  5173. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  5174. pLevel->iFrom = pWLoop->iTab;
  5175. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  5176. }
  5177. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  5178. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  5179. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  5180. && nRowEst
  5181. ){
  5182. Bitmask notUsed;
  5183. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  5184. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  5185. if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  5186. }
  5187. if( pFrom->isOrdered ){
  5188. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  5189. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  5190. }else{
  5191. pWInfo->bOBSat = 1;
  5192. pWInfo->revMask = pFrom->revLoop;
  5193. }
  5194. }
  5195. pWInfo->nRowOut = pFrom->nRow;
  5196. /* Free temporary memory and return success */
  5197. sqlite3DbFree(db, pSpace);
  5198. return SQLITE_OK;
  5199. }
  5200. /*
  5201. ** Most queries use only a single table (they are not joins) and have
  5202. ** simple == constraints against indexed fields. This routine attempts
  5203. ** to plan those simple cases using much less ceremony than the
  5204. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  5205. ** times for the common case.
  5206. **
  5207. ** Return non-zero on success, if this query can be handled by this
  5208. ** no-frills query planner. Return zero if this query needs the
  5209. ** general-purpose query planner.
  5210. */
  5211. static int whereShortCut(WhereLoopBuilder *pBuilder){
  5212. WhereInfo *pWInfo;
  5213. struct SrcList_item *pItem;
  5214. WhereClause *pWC;
  5215. WhereTerm *pTerm;
  5216. WhereLoop *pLoop;
  5217. int iCur;
  5218. int j;
  5219. Table *pTab;
  5220. Index *pIdx;
  5221. pWInfo = pBuilder->pWInfo;
  5222. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  5223. assert( pWInfo->pTabList->nSrc>=1 );
  5224. pItem = pWInfo->pTabList->a;
  5225. pTab = pItem->pTab;
  5226. if( IsVirtual(pTab) ) return 0;
  5227. if( pItem->zIndex ) return 0;
  5228. iCur = pItem->iCursor;
  5229. pWC = &pWInfo->sWC;
  5230. pLoop = pBuilder->pNew;
  5231. pLoop->wsFlags = 0;
  5232. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  5233. if( pTerm ){
  5234. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  5235. pLoop->aLTerm[0] = pTerm;
  5236. pLoop->nLTerm = 1;
  5237. pLoop->u.btree.nEq = 1;
  5238. /* TUNING: Cost of a rowid lookup is 10 */
  5239. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  5240. }else{
  5241. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  5242. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  5243. assert( ArraySize(pLoop->aLTermSpace)==4 );
  5244. if( pIdx->onError==OE_None
  5245. || pIdx->pPartIdxWhere!=0
  5246. || pIdx->nColumn>ArraySize(pLoop->aLTermSpace)
  5247. ) continue;
  5248. for(j=0; j<pIdx->nColumn; j++){
  5249. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  5250. if( pTerm==0 ) break;
  5251. pLoop->aLTerm[j] = pTerm;
  5252. }
  5253. if( j!=pIdx->nColumn ) continue;
  5254. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  5255. if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  5256. pLoop->wsFlags |= WHERE_IDX_ONLY;
  5257. }
  5258. pLoop->nLTerm = j;
  5259. pLoop->u.btree.nEq = j;
  5260. pLoop->u.btree.pIndex = pIdx;
  5261. /* TUNING: Cost of a unique index lookup is 15 */
  5262. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  5263. break;
  5264. }
  5265. }
  5266. if( pLoop->wsFlags ){
  5267. pLoop->nOut = (LogEst)1;
  5268. pWInfo->a[0].pWLoop = pLoop;
  5269. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  5270. pWInfo->a[0].iTabCur = iCur;
  5271. pWInfo->nRowOut = 1;
  5272. if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
  5273. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  5274. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  5275. }
  5276. #ifdef SQLITE_DEBUG
  5277. pLoop->cId = '0';
  5278. #endif
  5279. return 1;
  5280. }
  5281. return 0;
  5282. }
  5283. /*
  5284. ** Generate the beginning of the loop used for WHERE clause processing.
  5285. ** The return value is a pointer to an opaque structure that contains
  5286. ** information needed to terminate the loop. Later, the calling routine
  5287. ** should invoke sqlite3WhereEnd() with the return value of this function
  5288. ** in order to complete the WHERE clause processing.
  5289. **
  5290. ** If an error occurs, this routine returns NULL.
  5291. **
  5292. ** The basic idea is to do a nested loop, one loop for each table in
  5293. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  5294. ** same as a SELECT with only a single table in the FROM clause.) For
  5295. ** example, if the SQL is this:
  5296. **
  5297. ** SELECT * FROM t1, t2, t3 WHERE ...;
  5298. **
  5299. ** Then the code generated is conceptually like the following:
  5300. **
  5301. ** foreach row1 in t1 do \ Code generated
  5302. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  5303. ** foreach row3 in t3 do /
  5304. ** ...
  5305. ** end \ Code generated
  5306. ** end |-- by sqlite3WhereEnd()
  5307. ** end /
  5308. **
  5309. ** Note that the loops might not be nested in the order in which they
  5310. ** appear in the FROM clause if a different order is better able to make
  5311. ** use of indices. Note also that when the IN operator appears in
  5312. ** the WHERE clause, it might result in additional nested loops for
  5313. ** scanning through all values on the right-hand side of the IN.
  5314. **
  5315. ** There are Btree cursors associated with each table. t1 uses cursor
  5316. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  5317. ** And so forth. This routine generates code to open those VDBE cursors
  5318. ** and sqlite3WhereEnd() generates the code to close them.
  5319. **
  5320. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  5321. ** in pTabList pointing at their appropriate entries. The [...] code
  5322. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  5323. ** data from the various tables of the loop.
  5324. **
  5325. ** If the WHERE clause is empty, the foreach loops must each scan their
  5326. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  5327. ** the tables have indices and there are terms in the WHERE clause that
  5328. ** refer to those indices, a complete table scan can be avoided and the
  5329. ** code will run much faster. Most of the work of this routine is checking
  5330. ** to see if there are indices that can be used to speed up the loop.
  5331. **
  5332. ** Terms of the WHERE clause are also used to limit which rows actually
  5333. ** make it to the "..." in the middle of the loop. After each "foreach",
  5334. ** terms of the WHERE clause that use only terms in that loop and outer
  5335. ** loops are evaluated and if false a jump is made around all subsequent
  5336. ** inner loops (or around the "..." if the test occurs within the inner-
  5337. ** most loop)
  5338. **
  5339. ** OUTER JOINS
  5340. **
  5341. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  5342. **
  5343. ** foreach row1 in t1 do
  5344. ** flag = 0
  5345. ** foreach row2 in t2 do
  5346. ** start:
  5347. ** ...
  5348. ** flag = 1
  5349. ** end
  5350. ** if flag==0 then
  5351. ** move the row2 cursor to a null row
  5352. ** goto start
  5353. ** fi
  5354. ** end
  5355. **
  5356. ** ORDER BY CLAUSE PROCESSING
  5357. **
  5358. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  5359. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  5360. ** if there is one. If there is no ORDER BY clause or if this routine
  5361. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  5362. */
  5363. WhereInfo *sqlite3WhereBegin(
  5364. Parse *pParse, /* The parser context */
  5365. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  5366. Expr *pWhere, /* The WHERE clause */
  5367. ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
  5368. ExprList *pResultSet, /* Result set of the query */
  5369. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  5370. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  5371. ){
  5372. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  5373. int nTabList; /* Number of elements in pTabList */
  5374. WhereInfo *pWInfo; /* Will become the return value of this function */
  5375. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  5376. Bitmask notReady; /* Cursors that are not yet positioned */
  5377. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  5378. WhereMaskSet *pMaskSet; /* The expression mask set */
  5379. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  5380. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  5381. int ii; /* Loop counter */
  5382. sqlite3 *db; /* Database connection */
  5383. int rc; /* Return code */
  5384. /* Variable initialization */
  5385. db = pParse->db;
  5386. memset(&sWLB, 0, sizeof(sWLB));
  5387. sWLB.pOrderBy = pOrderBy;
  5388. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  5389. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  5390. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  5391. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  5392. }
  5393. /* The number of tables in the FROM clause is limited by the number of
  5394. ** bits in a Bitmask
  5395. */
  5396. testcase( pTabList->nSrc==BMS );
  5397. if( pTabList->nSrc>BMS ){
  5398. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  5399. return 0;
  5400. }
  5401. /* This function normally generates a nested loop for all tables in
  5402. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  5403. ** only generate code for the first table in pTabList and assume that
  5404. ** any cursors associated with subsequent tables are uninitialized.
  5405. */
  5406. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  5407. /* Allocate and initialize the WhereInfo structure that will become the
  5408. ** return value. A single allocation is used to store the WhereInfo
  5409. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  5410. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  5411. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  5412. ** some architectures. Hence the ROUND8() below.
  5413. */
  5414. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  5415. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  5416. if( db->mallocFailed ){
  5417. sqlite3DbFree(db, pWInfo);
  5418. pWInfo = 0;
  5419. goto whereBeginError;
  5420. }
  5421. pWInfo->nLevel = nTabList;
  5422. pWInfo->pParse = pParse;
  5423. pWInfo->pTabList = pTabList;
  5424. pWInfo->pOrderBy = pOrderBy;
  5425. pWInfo->pResultSet = pResultSet;
  5426. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  5427. pWInfo->wctrlFlags = wctrlFlags;
  5428. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  5429. pMaskSet = &pWInfo->sMaskSet;
  5430. sWLB.pWInfo = pWInfo;
  5431. sWLB.pWC = &pWInfo->sWC;
  5432. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  5433. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  5434. whereLoopInit(sWLB.pNew);
  5435. #ifdef SQLITE_DEBUG
  5436. sWLB.pNew->cId = '*';
  5437. #endif
  5438. /* Split the WHERE clause into separate subexpressions where each
  5439. ** subexpression is separated by an AND operator.
  5440. */
  5441. initMaskSet(pMaskSet);
  5442. whereClauseInit(&pWInfo->sWC, pWInfo);
  5443. sqlite3ExprCodeConstants(pParse, pWhere);
  5444. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  5445. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  5446. /* Special case: a WHERE clause that is constant. Evaluate the
  5447. ** expression and either jump over all of the code or fall thru.
  5448. */
  5449. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  5450. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  5451. pWhere = 0;
  5452. }
  5453. /* Special case: No FROM clause
  5454. */
  5455. if( nTabList==0 ){
  5456. if( pOrderBy ) pWInfo->bOBSat = 1;
  5457. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  5458. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  5459. }
  5460. }
  5461. /* Assign a bit from the bitmask to every term in the FROM clause.
  5462. **
  5463. ** When assigning bitmask values to FROM clause cursors, it must be
  5464. ** the case that if X is the bitmask for the N-th FROM clause term then
  5465. ** the bitmask for all FROM clause terms to the left of the N-th term
  5466. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  5467. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  5468. ** of the join. Subtracting one from the right table bitmask gives a
  5469. ** bitmask for all tables to the left of the join. Knowing the bitmask
  5470. ** for all tables to the left of a left join is important. Ticket #3015.
  5471. **
  5472. ** Note that bitmasks are created for all pTabList->nSrc tables in
  5473. ** pTabList, not just the first nTabList tables. nTabList is normally
  5474. ** equal to pTabList->nSrc but might be shortened to 1 if the
  5475. ** WHERE_ONETABLE_ONLY flag is set.
  5476. */
  5477. for(ii=0; ii<pTabList->nSrc; ii++){
  5478. createMask(pMaskSet, pTabList->a[ii].iCursor);
  5479. }
  5480. #ifndef NDEBUG
  5481. {
  5482. Bitmask toTheLeft = 0;
  5483. for(ii=0; ii<pTabList->nSrc; ii++){
  5484. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  5485. assert( (m-1)==toTheLeft );
  5486. toTheLeft |= m;
  5487. }
  5488. }
  5489. #endif
  5490. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  5491. ** add new virtual terms onto the end of the WHERE clause. We do not
  5492. ** want to analyze these virtual terms, so start analyzing at the end
  5493. ** and work forward so that the added virtual terms are never processed.
  5494. */
  5495. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  5496. if( db->mallocFailed ){
  5497. goto whereBeginError;
  5498. }
  5499. /* If the ORDER BY (or GROUP BY) clause contains references to general
  5500. ** expressions, then we won't be able to satisfy it using indices, so
  5501. ** go ahead and disable it now.
  5502. */
  5503. if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
  5504. for(ii=0; ii<pOrderBy->nExpr; ii++){
  5505. Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
  5506. if( pExpr->op!=TK_COLUMN ){
  5507. pWInfo->pOrderBy = pOrderBy = 0;
  5508. break;
  5509. }else if( pExpr->iColumn<0 ){
  5510. break;
  5511. }
  5512. }
  5513. }
  5514. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  5515. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  5516. /* The DISTINCT marking is pointless. Ignore it. */
  5517. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  5518. }else if( pOrderBy==0 ){
  5519. /* Try to ORDER BY the result set to make distinct processing easier */
  5520. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  5521. pWInfo->pOrderBy = pResultSet;
  5522. }
  5523. }
  5524. /* Construct the WhereLoop objects */
  5525. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  5526. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  5527. rc = whereLoopAddAll(&sWLB);
  5528. if( rc ) goto whereBeginError;
  5529. /* Display all of the WhereLoop objects if wheretrace is enabled */
  5530. #ifdef WHERETRACE_ENABLED
  5531. if( sqlite3WhereTrace ){
  5532. WhereLoop *p;
  5533. int i;
  5534. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  5535. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  5536. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  5537. p->cId = zLabel[i%sizeof(zLabel)];
  5538. whereLoopPrint(p, pTabList);
  5539. }
  5540. }
  5541. #endif
  5542. wherePathSolver(pWInfo, 0);
  5543. if( db->mallocFailed ) goto whereBeginError;
  5544. if( pWInfo->pOrderBy ){
  5545. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  5546. if( db->mallocFailed ) goto whereBeginError;
  5547. }
  5548. }
  5549. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  5550. pWInfo->revMask = (Bitmask)(-1);
  5551. }
  5552. if( pParse->nErr || NEVER(db->mallocFailed) ){
  5553. goto whereBeginError;
  5554. }
  5555. #ifdef WHERETRACE_ENABLED
  5556. if( sqlite3WhereTrace ){
  5557. int ii;
  5558. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  5559. if( pWInfo->bOBSat ){
  5560. sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
  5561. }
  5562. switch( pWInfo->eDistinct ){
  5563. case WHERE_DISTINCT_UNIQUE: {
  5564. sqlite3DebugPrintf(" DISTINCT=unique");
  5565. break;
  5566. }
  5567. case WHERE_DISTINCT_ORDERED: {
  5568. sqlite3DebugPrintf(" DISTINCT=ordered");
  5569. break;
  5570. }
  5571. case WHERE_DISTINCT_UNORDERED: {
  5572. sqlite3DebugPrintf(" DISTINCT=unordered");
  5573. break;
  5574. }
  5575. }
  5576. sqlite3DebugPrintf("\n");
  5577. for(ii=0; ii<pWInfo->nLevel; ii++){
  5578. whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
  5579. }
  5580. }
  5581. #endif
  5582. /* Attempt to omit tables from the join that do not effect the result */
  5583. if( pWInfo->nLevel>=2
  5584. && pResultSet!=0
  5585. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  5586. ){
  5587. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  5588. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  5589. while( pWInfo->nLevel>=2 ){
  5590. WhereTerm *pTerm, *pEnd;
  5591. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  5592. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  5593. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  5594. && (pLoop->wsFlags & WHERE_ONEROW)==0
  5595. ){
  5596. break;
  5597. }
  5598. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  5599. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  5600. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  5601. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  5602. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  5603. ){
  5604. break;
  5605. }
  5606. }
  5607. if( pTerm<pEnd ) break;
  5608. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  5609. pWInfo->nLevel--;
  5610. nTabList--;
  5611. }
  5612. }
  5613. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  5614. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  5615. /* If the caller is an UPDATE or DELETE statement that is requesting
  5616. ** to use a one-pass algorithm, determine if this is appropriate.
  5617. ** The one-pass algorithm only works if the WHERE clause constrains
  5618. ** the statement to update a single row.
  5619. */
  5620. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  5621. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  5622. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  5623. pWInfo->okOnePass = 1;
  5624. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  5625. }
  5626. /* Open all tables in the pTabList and any indices selected for
  5627. ** searching those tables.
  5628. */
  5629. notReady = ~(Bitmask)0;
  5630. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  5631. Table *pTab; /* Table to open */
  5632. int iDb; /* Index of database containing table/index */
  5633. struct SrcList_item *pTabItem;
  5634. pTabItem = &pTabList->a[pLevel->iFrom];
  5635. pTab = pTabItem->pTab;
  5636. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  5637. pLoop = pLevel->pWLoop;
  5638. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  5639. /* Do nothing */
  5640. }else
  5641. #ifndef SQLITE_OMIT_VIRTUALTABLE
  5642. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  5643. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  5644. int iCur = pTabItem->iCursor;
  5645. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  5646. }else if( IsVirtual(pTab) ){
  5647. /* noop */
  5648. }else
  5649. #endif
  5650. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  5651. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  5652. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  5653. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  5654. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  5655. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  5656. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  5657. Bitmask b = pTabItem->colUsed;
  5658. int n = 0;
  5659. for(; b; b=b>>1, n++){}
  5660. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  5661. SQLITE_INT_TO_PTR(n), P4_INT32);
  5662. assert( n<=pTab->nCol );
  5663. }
  5664. }else{
  5665. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  5666. }
  5667. if( pLoop->wsFlags & WHERE_INDEXED ){
  5668. Index *pIx = pLoop->u.btree.pIndex;
  5669. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  5670. /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
  5671. int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
  5672. assert( pIx->pSchema==pTab->pSchema );
  5673. assert( iIndexCur>=0 );
  5674. sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
  5675. (char*)pKey, P4_KEYINFO_HANDOFF);
  5676. VdbeComment((v, "%s", pIx->zName));
  5677. }
  5678. sqlite3CodeVerifySchema(pParse, iDb);
  5679. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  5680. }
  5681. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  5682. if( db->mallocFailed ) goto whereBeginError;
  5683. /* Generate the code to do the search. Each iteration of the for
  5684. ** loop below generates code for a single nested loop of the VM
  5685. ** program.
  5686. */
  5687. notReady = ~(Bitmask)0;
  5688. for(ii=0; ii<nTabList; ii++){
  5689. pLevel = &pWInfo->a[ii];
  5690. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  5691. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  5692. constructAutomaticIndex(pParse, &pWInfo->sWC,
  5693. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  5694. if( db->mallocFailed ) goto whereBeginError;
  5695. }
  5696. #endif
  5697. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  5698. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  5699. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  5700. pWInfo->iContinue = pLevel->addrCont;
  5701. }
  5702. /* Done. */
  5703. return pWInfo;
  5704. /* Jump here if malloc fails */
  5705. whereBeginError:
  5706. if( pWInfo ){
  5707. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  5708. whereInfoFree(db, pWInfo);
  5709. }
  5710. return 0;
  5711. }
  5712. /*
  5713. ** Generate the end of the WHERE loop. See comments on
  5714. ** sqlite3WhereBegin() for additional information.
  5715. */
  5716. void sqlite3WhereEnd(WhereInfo *pWInfo){
  5717. Parse *pParse = pWInfo->pParse;
  5718. Vdbe *v = pParse->pVdbe;
  5719. int i;
  5720. WhereLevel *pLevel;
  5721. WhereLoop *pLoop;
  5722. SrcList *pTabList = pWInfo->pTabList;
  5723. sqlite3 *db = pParse->db;
  5724. /* Generate loop termination code.
  5725. */
  5726. sqlite3ExprCacheClear(pParse);
  5727. for(i=pWInfo->nLevel-1; i>=0; i--){
  5728. pLevel = &pWInfo->a[i];
  5729. pLoop = pLevel->pWLoop;
  5730. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  5731. if( pLevel->op!=OP_Noop ){
  5732. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  5733. sqlite3VdbeChangeP5(v, pLevel->p5);
  5734. }
  5735. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  5736. struct InLoop *pIn;
  5737. int j;
  5738. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  5739. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  5740. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  5741. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  5742. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  5743. }
  5744. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  5745. }
  5746. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  5747. if( pLevel->iLeftJoin ){
  5748. int addr;
  5749. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  5750. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  5751. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  5752. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  5753. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  5754. }
  5755. if( pLoop->wsFlags & WHERE_INDEXED ){
  5756. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  5757. }
  5758. if( pLevel->op==OP_Return ){
  5759. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  5760. }else{
  5761. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  5762. }
  5763. sqlite3VdbeJumpHere(v, addr);
  5764. }
  5765. }
  5766. /* The "break" point is here, just past the end of the outer loop.
  5767. ** Set it.
  5768. */
  5769. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  5770. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  5771. */
  5772. assert( pWInfo->nLevel<=pTabList->nSrc );
  5773. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  5774. Index *pIdx = 0;
  5775. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  5776. Table *pTab = pTabItem->pTab;
  5777. assert( pTab!=0 );
  5778. pLoop = pLevel->pWLoop;
  5779. if( (pTab->tabFlags & TF_Ephemeral)==0
  5780. && pTab->pSelect==0
  5781. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  5782. ){
  5783. int ws = pLoop->wsFlags;
  5784. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  5785. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  5786. }
  5787. if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
  5788. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  5789. }
  5790. }
  5791. /* If this scan uses an index, make VDBE code substitutions to read data
  5792. ** from the index instead of from the table where possible. In some cases
  5793. ** this optimization prevents the table from ever being read, which can
  5794. ** yield a significant performance boost.
  5795. **
  5796. ** Calls to the code generator in between sqlite3WhereBegin and
  5797. ** sqlite3WhereEnd will have created code that references the table
  5798. ** directly. This loop scans all that code looking for opcodes
  5799. ** that reference the table and converts them into opcodes that
  5800. ** reference the index.
  5801. */
  5802. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  5803. pIdx = pLoop->u.btree.pIndex;
  5804. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  5805. pIdx = pLevel->u.pCovidx;
  5806. }
  5807. if( pIdx && !db->mallocFailed ){
  5808. int k, j, last;
  5809. VdbeOp *pOp;
  5810. last = sqlite3VdbeCurrentAddr(v);
  5811. k = pLevel->addrBody;
  5812. pOp = sqlite3VdbeGetOp(v, k);
  5813. for(; k<last; k++, pOp++){
  5814. if( pOp->p1!=pLevel->iTabCur ) continue;
  5815. if( pOp->opcode==OP_Column ){
  5816. for(j=0; j<pIdx->nColumn; j++){
  5817. if( pOp->p2==pIdx->aiColumn[j] ){
  5818. pOp->p2 = j;
  5819. pOp->p1 = pLevel->iIdxCur;
  5820. break;
  5821. }
  5822. }
  5823. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
  5824. }else if( pOp->opcode==OP_Rowid ){
  5825. pOp->p1 = pLevel->iIdxCur;
  5826. pOp->opcode = OP_IdxRowid;
  5827. }
  5828. }
  5829. }
  5830. }
  5831. /* Final cleanup
  5832. */
  5833. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  5834. whereInfoFree(db, pWInfo);
  5835. return;
  5836. }