expr.c 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270
  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 file contains routines used for analyzing expressions and
  13. ** for generating VDBE code that evaluates expressions in SQLite.
  14. */
  15. #include "sqliteInt.h"
  16. /*
  17. ** Return the 'affinity' of the expression pExpr if any.
  18. **
  19. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  20. ** or a sub-select with a column as the return value, then the
  21. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  22. ** indicating no affinity for the expression.
  23. **
  24. ** i.e. the WHERE clause expresssions in the following statements all
  25. ** have an affinity:
  26. **
  27. ** CREATE TABLE t1(a);
  28. ** SELECT * FROM t1 WHERE a;
  29. ** SELECT a AS b FROM t1 WHERE b;
  30. ** SELECT * FROM t1 WHERE (select a from t1);
  31. */
  32. char sqlite3ExprAffinity(Expr *pExpr){
  33. int op;
  34. pExpr = sqlite3ExprSkipCollate(pExpr);
  35. op = pExpr->op;
  36. if( op==TK_SELECT ){
  37. assert( pExpr->flags&EP_xIsSelect );
  38. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  39. }
  40. #ifndef SQLITE_OMIT_CAST
  41. if( op==TK_CAST ){
  42. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  43. return sqlite3AffinityType(pExpr->u.zToken, 0);
  44. }
  45. #endif
  46. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  47. && pExpr->pTab!=0
  48. ){
  49. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  50. ** a TK_COLUMN but was previously evaluated and cached in a register */
  51. int j = pExpr->iColumn;
  52. if( j<0 ) return SQLITE_AFF_INTEGER;
  53. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  54. return pExpr->pTab->aCol[j].affinity;
  55. }
  56. return pExpr->affinity;
  57. }
  58. /*
  59. ** Set the collating sequence for expression pExpr to be the collating
  60. ** sequence named by pToken. Return a pointer to a new Expr node that
  61. ** implements the COLLATE operator.
  62. **
  63. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  64. ** and the pExpr parameter is returned unchanged.
  65. */
  66. Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  67. if( pCollName->n>0 ){
  68. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  69. if( pNew ){
  70. pNew->pLeft = pExpr;
  71. pNew->flags |= EP_Collate|EP_Skip;
  72. pExpr = pNew;
  73. }
  74. }
  75. return pExpr;
  76. }
  77. Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  78. Token s;
  79. assert( zC!=0 );
  80. s.z = zC;
  81. s.n = sqlite3Strlen30(s.z);
  82. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  83. }
  84. /*
  85. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  86. ** or likelihood() function at the root of an expression.
  87. */
  88. Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  89. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  90. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  91. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  92. assert( pExpr->x.pList->nExpr>0 );
  93. assert( pExpr->op==TK_FUNCTION );
  94. pExpr = pExpr->x.pList->a[0].pExpr;
  95. }else{
  96. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  97. pExpr = pExpr->pLeft;
  98. }
  99. }
  100. return pExpr;
  101. }
  102. /*
  103. ** Return the collation sequence for the expression pExpr. If
  104. ** there is no defined collating sequence, return NULL.
  105. **
  106. ** The collating sequence might be determined by a COLLATE operator
  107. ** or by the presence of a column with a defined collating sequence.
  108. ** COLLATE operators take first precedence. Left operands take
  109. ** precedence over right operands.
  110. */
  111. CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  112. sqlite3 *db = pParse->db;
  113. CollSeq *pColl = 0;
  114. Expr *p = pExpr;
  115. while( p ){
  116. int op = p->op;
  117. if( op==TK_CAST || op==TK_UPLUS ){
  118. p = p->pLeft;
  119. continue;
  120. }
  121. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  122. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  123. break;
  124. }
  125. if( p->pTab!=0
  126. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  127. || op==TK_REGISTER || op==TK_TRIGGER)
  128. ){
  129. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  130. ** a TK_COLUMN but was previously evaluated and cached in a register */
  131. int j = p->iColumn;
  132. if( j>=0 ){
  133. const char *zColl = p->pTab->aCol[j].zColl;
  134. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  135. }
  136. break;
  137. }
  138. if( p->flags & EP_Collate ){
  139. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  140. p = p->pLeft;
  141. }else{
  142. p = p->pRight;
  143. }
  144. }else{
  145. break;
  146. }
  147. }
  148. if( sqlite3CheckCollSeq(pParse, pColl) ){
  149. pColl = 0;
  150. }
  151. return pColl;
  152. }
  153. /*
  154. ** pExpr is an operand of a comparison operator. aff2 is the
  155. ** type affinity of the other operand. This routine returns the
  156. ** type affinity that should be used for the comparison operator.
  157. */
  158. char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  159. char aff1 = sqlite3ExprAffinity(pExpr);
  160. if( aff1 && aff2 ){
  161. /* Both sides of the comparison are columns. If one has numeric
  162. ** affinity, use that. Otherwise use no affinity.
  163. */
  164. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  165. return SQLITE_AFF_NUMERIC;
  166. }else{
  167. return SQLITE_AFF_NONE;
  168. }
  169. }else if( !aff1 && !aff2 ){
  170. /* Neither side of the comparison is a column. Compare the
  171. ** results directly.
  172. */
  173. return SQLITE_AFF_NONE;
  174. }else{
  175. /* One side is a column, the other is not. Use the columns affinity. */
  176. assert( aff1==0 || aff2==0 );
  177. return (aff1 + aff2);
  178. }
  179. }
  180. /*
  181. ** pExpr is a comparison operator. Return the type affinity that should
  182. ** be applied to both operands prior to doing the comparison.
  183. */
  184. static char comparisonAffinity(Expr *pExpr){
  185. char aff;
  186. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  187. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  188. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  189. assert( pExpr->pLeft );
  190. aff = sqlite3ExprAffinity(pExpr->pLeft);
  191. if( pExpr->pRight ){
  192. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  193. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  194. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  195. }else if( !aff ){
  196. aff = SQLITE_AFF_NONE;
  197. }
  198. return aff;
  199. }
  200. /*
  201. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  202. ** idx_affinity is the affinity of an indexed column. Return true
  203. ** if the index with affinity idx_affinity may be used to implement
  204. ** the comparison in pExpr.
  205. */
  206. int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  207. char aff = comparisonAffinity(pExpr);
  208. switch( aff ){
  209. case SQLITE_AFF_NONE:
  210. return 1;
  211. case SQLITE_AFF_TEXT:
  212. return idx_affinity==SQLITE_AFF_TEXT;
  213. default:
  214. return sqlite3IsNumericAffinity(idx_affinity);
  215. }
  216. }
  217. /*
  218. ** Return the P5 value that should be used for a binary comparison
  219. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  220. */
  221. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  222. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  223. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  224. return aff;
  225. }
  226. /*
  227. ** Return a pointer to the collation sequence that should be used by
  228. ** a binary comparison operator comparing pLeft and pRight.
  229. **
  230. ** If the left hand expression has a collating sequence type, then it is
  231. ** used. Otherwise the collation sequence for the right hand expression
  232. ** is used, or the default (BINARY) if neither expression has a collating
  233. ** type.
  234. **
  235. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  236. ** it is not considered.
  237. */
  238. CollSeq *sqlite3BinaryCompareCollSeq(
  239. Parse *pParse,
  240. Expr *pLeft,
  241. Expr *pRight
  242. ){
  243. CollSeq *pColl;
  244. assert( pLeft );
  245. if( pLeft->flags & EP_Collate ){
  246. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  247. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  248. pColl = sqlite3ExprCollSeq(pParse, pRight);
  249. }else{
  250. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  251. if( !pColl ){
  252. pColl = sqlite3ExprCollSeq(pParse, pRight);
  253. }
  254. }
  255. return pColl;
  256. }
  257. /*
  258. ** Generate code for a comparison operator.
  259. */
  260. static int codeCompare(
  261. Parse *pParse, /* The parsing (and code generating) context */
  262. Expr *pLeft, /* The left operand */
  263. Expr *pRight, /* The right operand */
  264. int opcode, /* The comparison opcode */
  265. int in1, int in2, /* Register holding operands */
  266. int dest, /* Jump here if true. */
  267. int jumpIfNull /* If true, jump if either operand is NULL */
  268. ){
  269. int p5;
  270. int addr;
  271. CollSeq *p4;
  272. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  273. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  274. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  275. (void*)p4, P4_COLLSEQ);
  276. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  277. return addr;
  278. }
  279. #if SQLITE_MAX_EXPR_DEPTH>0
  280. /*
  281. ** Check that argument nHeight is less than or equal to the maximum
  282. ** expression depth allowed. If it is not, leave an error message in
  283. ** pParse.
  284. */
  285. int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  286. int rc = SQLITE_OK;
  287. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  288. if( nHeight>mxHeight ){
  289. sqlite3ErrorMsg(pParse,
  290. "Expression tree is too large (maximum depth %d)", mxHeight
  291. );
  292. rc = SQLITE_ERROR;
  293. }
  294. return rc;
  295. }
  296. /* The following three functions, heightOfExpr(), heightOfExprList()
  297. ** and heightOfSelect(), are used to determine the maximum height
  298. ** of any expression tree referenced by the structure passed as the
  299. ** first argument.
  300. **
  301. ** If this maximum height is greater than the current value pointed
  302. ** to by pnHeight, the second parameter, then set *pnHeight to that
  303. ** value.
  304. */
  305. static void heightOfExpr(Expr *p, int *pnHeight){
  306. if( p ){
  307. if( p->nHeight>*pnHeight ){
  308. *pnHeight = p->nHeight;
  309. }
  310. }
  311. }
  312. static void heightOfExprList(ExprList *p, int *pnHeight){
  313. if( p ){
  314. int i;
  315. for(i=0; i<p->nExpr; i++){
  316. heightOfExpr(p->a[i].pExpr, pnHeight);
  317. }
  318. }
  319. }
  320. static void heightOfSelect(Select *p, int *pnHeight){
  321. if( p ){
  322. heightOfExpr(p->pWhere, pnHeight);
  323. heightOfExpr(p->pHaving, pnHeight);
  324. heightOfExpr(p->pLimit, pnHeight);
  325. heightOfExpr(p->pOffset, pnHeight);
  326. heightOfExprList(p->pEList, pnHeight);
  327. heightOfExprList(p->pGroupBy, pnHeight);
  328. heightOfExprList(p->pOrderBy, pnHeight);
  329. heightOfSelect(p->pPrior, pnHeight);
  330. }
  331. }
  332. /*
  333. ** Set the Expr.nHeight variable in the structure passed as an
  334. ** argument. An expression with no children, Expr.pList or
  335. ** Expr.pSelect member has a height of 1. Any other expression
  336. ** has a height equal to the maximum height of any other
  337. ** referenced Expr plus one.
  338. */
  339. static void exprSetHeight(Expr *p){
  340. int nHeight = 0;
  341. heightOfExpr(p->pLeft, &nHeight);
  342. heightOfExpr(p->pRight, &nHeight);
  343. if( ExprHasProperty(p, EP_xIsSelect) ){
  344. heightOfSelect(p->x.pSelect, &nHeight);
  345. }else{
  346. heightOfExprList(p->x.pList, &nHeight);
  347. }
  348. p->nHeight = nHeight + 1;
  349. }
  350. /*
  351. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  352. ** the height is greater than the maximum allowed expression depth,
  353. ** leave an error in pParse.
  354. */
  355. void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  356. exprSetHeight(p);
  357. sqlite3ExprCheckHeight(pParse, p->nHeight);
  358. }
  359. /*
  360. ** Return the maximum height of any expression tree referenced
  361. ** by the select statement passed as an argument.
  362. */
  363. int sqlite3SelectExprHeight(Select *p){
  364. int nHeight = 0;
  365. heightOfSelect(p, &nHeight);
  366. return nHeight;
  367. }
  368. #else
  369. #define exprSetHeight(y)
  370. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  371. /*
  372. ** This routine is the core allocator for Expr nodes.
  373. **
  374. ** Construct a new expression node and return a pointer to it. Memory
  375. ** for this node and for the pToken argument is a single allocation
  376. ** obtained from sqlite3DbMalloc(). The calling function
  377. ** is responsible for making sure the node eventually gets freed.
  378. **
  379. ** If dequote is true, then the token (if it exists) is dequoted.
  380. ** If dequote is false, no dequoting is performance. The deQuote
  381. ** parameter is ignored if pToken is NULL or if the token does not
  382. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  383. ** then the EP_DblQuoted flag is set on the expression node.
  384. **
  385. ** Special case: If op==TK_INTEGER and pToken points to a string that
  386. ** can be translated into a 32-bit integer, then the token is not
  387. ** stored in u.zToken. Instead, the integer values is written
  388. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  389. ** is allocated to hold the integer text and the dequote flag is ignored.
  390. */
  391. Expr *sqlite3ExprAlloc(
  392. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  393. int op, /* Expression opcode */
  394. const Token *pToken, /* Token argument. Might be NULL */
  395. int dequote /* True to dequote */
  396. ){
  397. Expr *pNew;
  398. int nExtra = 0;
  399. int iValue = 0;
  400. if( pToken ){
  401. if( op!=TK_INTEGER || pToken->z==0
  402. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  403. nExtra = pToken->n+1;
  404. assert( iValue>=0 );
  405. }
  406. }
  407. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  408. if( pNew ){
  409. pNew->op = (u8)op;
  410. pNew->iAgg = -1;
  411. if( pToken ){
  412. if( nExtra==0 ){
  413. pNew->flags |= EP_IntValue;
  414. pNew->u.iValue = iValue;
  415. }else{
  416. int c;
  417. pNew->u.zToken = (char*)&pNew[1];
  418. assert( pToken->z!=0 || pToken->n==0 );
  419. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  420. pNew->u.zToken[pToken->n] = 0;
  421. if( dequote && nExtra>=3
  422. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  423. sqlite3Dequote(pNew->u.zToken);
  424. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  425. }
  426. }
  427. }
  428. #if SQLITE_MAX_EXPR_DEPTH>0
  429. pNew->nHeight = 1;
  430. #endif
  431. }
  432. return pNew;
  433. }
  434. /*
  435. ** Allocate a new expression node from a zero-terminated token that has
  436. ** already been dequoted.
  437. */
  438. Expr *sqlite3Expr(
  439. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  440. int op, /* Expression opcode */
  441. const char *zToken /* Token argument. Might be NULL */
  442. ){
  443. Token x;
  444. x.z = zToken;
  445. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  446. return sqlite3ExprAlloc(db, op, &x, 0);
  447. }
  448. /*
  449. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  450. **
  451. ** If pRoot==NULL that means that a memory allocation error has occurred.
  452. ** In that case, delete the subtrees pLeft and pRight.
  453. */
  454. void sqlite3ExprAttachSubtrees(
  455. sqlite3 *db,
  456. Expr *pRoot,
  457. Expr *pLeft,
  458. Expr *pRight
  459. ){
  460. if( pRoot==0 ){
  461. assert( db->mallocFailed );
  462. sqlite3ExprDelete(db, pLeft);
  463. sqlite3ExprDelete(db, pRight);
  464. }else{
  465. if( pRight ){
  466. pRoot->pRight = pRight;
  467. pRoot->flags |= EP_Collate & pRight->flags;
  468. }
  469. if( pLeft ){
  470. pRoot->pLeft = pLeft;
  471. pRoot->flags |= EP_Collate & pLeft->flags;
  472. }
  473. exprSetHeight(pRoot);
  474. }
  475. }
  476. /*
  477. ** Allocate a Expr node which joins as many as two subtrees.
  478. **
  479. ** One or both of the subtrees can be NULL. Return a pointer to the new
  480. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  481. ** free the subtrees and return NULL.
  482. */
  483. Expr *sqlite3PExpr(
  484. Parse *pParse, /* Parsing context */
  485. int op, /* Expression opcode */
  486. Expr *pLeft, /* Left operand */
  487. Expr *pRight, /* Right operand */
  488. const Token *pToken /* Argument token */
  489. ){
  490. Expr *p;
  491. if( op==TK_AND && pLeft && pRight ){
  492. /* Take advantage of short-circuit false optimization for AND */
  493. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  494. }else{
  495. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  496. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  497. }
  498. if( p ) {
  499. sqlite3ExprCheckHeight(pParse, p->nHeight);
  500. }
  501. return p;
  502. }
  503. /*
  504. ** Return 1 if an expression must be FALSE in all cases and 0 if the
  505. ** expression might be true. This is an optimization. If is OK to
  506. ** return 0 here even if the expression really is always false (a
  507. ** false negative). But it is a bug to return 1 if the expression
  508. ** might be true in some rare circumstances (a false positive.)
  509. **
  510. ** Note that if the expression is part of conditional for a
  511. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  512. ** is it true or false, so always return 0.
  513. */
  514. static int exprAlwaysFalse(Expr *p){
  515. int v = 0;
  516. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  517. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  518. return v==0;
  519. }
  520. /*
  521. ** Join two expressions using an AND operator. If either expression is
  522. ** NULL, then just return the other expression.
  523. **
  524. ** If one side or the other of the AND is known to be false, then instead
  525. ** of returning an AND expression, just return a constant expression with
  526. ** a value of false.
  527. */
  528. Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  529. if( pLeft==0 ){
  530. return pRight;
  531. }else if( pRight==0 ){
  532. return pLeft;
  533. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  534. sqlite3ExprDelete(db, pLeft);
  535. sqlite3ExprDelete(db, pRight);
  536. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  537. }else{
  538. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  539. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  540. return pNew;
  541. }
  542. }
  543. /*
  544. ** Construct a new expression node for a function with multiple
  545. ** arguments.
  546. */
  547. Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  548. Expr *pNew;
  549. sqlite3 *db = pParse->db;
  550. assert( pToken );
  551. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  552. if( pNew==0 ){
  553. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  554. return 0;
  555. }
  556. pNew->x.pList = pList;
  557. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  558. sqlite3ExprSetHeight(pParse, pNew);
  559. return pNew;
  560. }
  561. /*
  562. ** Assign a variable number to an expression that encodes a wildcard
  563. ** in the original SQL statement.
  564. **
  565. ** Wildcards consisting of a single "?" are assigned the next sequential
  566. ** variable number.
  567. **
  568. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  569. ** sure "nnn" is not too be to avoid a denial of service attack when
  570. ** the SQL statement comes from an external source.
  571. **
  572. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  573. ** as the previous instance of the same wildcard. Or if this is the first
  574. ** instance of the wildcard, the next sequenial variable number is
  575. ** assigned.
  576. */
  577. void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  578. sqlite3 *db = pParse->db;
  579. const char *z;
  580. if( pExpr==0 ) return;
  581. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  582. z = pExpr->u.zToken;
  583. assert( z!=0 );
  584. assert( z[0]!=0 );
  585. if( z[1]==0 ){
  586. /* Wildcard of the form "?". Assign the next variable number */
  587. assert( z[0]=='?' );
  588. pExpr->iColumn = (ynVar)(++pParse->nVar);
  589. }else{
  590. ynVar x = 0;
  591. u32 n = sqlite3Strlen30(z);
  592. if( z[0]=='?' ){
  593. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  594. ** use it as the variable number */
  595. i64 i;
  596. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  597. pExpr->iColumn = x = (ynVar)i;
  598. testcase( i==0 );
  599. testcase( i==1 );
  600. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  601. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  602. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  603. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  604. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  605. x = 0;
  606. }
  607. if( i>pParse->nVar ){
  608. pParse->nVar = (int)i;
  609. }
  610. }else{
  611. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  612. ** number as the prior appearance of the same name, or if the name
  613. ** has never appeared before, reuse the same variable number
  614. */
  615. ynVar i;
  616. for(i=0; i<pParse->nzVar; i++){
  617. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  618. pExpr->iColumn = x = (ynVar)i+1;
  619. break;
  620. }
  621. }
  622. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  623. }
  624. if( x>0 ){
  625. if( x>pParse->nzVar ){
  626. char **a;
  627. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  628. if( a==0 ) return; /* Error reported through db->mallocFailed */
  629. pParse->azVar = a;
  630. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  631. pParse->nzVar = x;
  632. }
  633. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  634. sqlite3DbFree(db, pParse->azVar[x-1]);
  635. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  636. }
  637. }
  638. }
  639. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  640. sqlite3ErrorMsg(pParse, "too many SQL variables");
  641. }
  642. }
  643. /*
  644. ** Recursively delete an expression tree.
  645. */
  646. void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  647. if( p==0 ) return;
  648. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  649. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  650. if( !ExprHasProperty(p, EP_TokenOnly) ){
  651. /* The Expr.x union is never used at the same time as Expr.pRight */
  652. assert( p->x.pList==0 || p->pRight==0 );
  653. sqlite3ExprDelete(db, p->pLeft);
  654. sqlite3ExprDelete(db, p->pRight);
  655. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  656. if( ExprHasProperty(p, EP_xIsSelect) ){
  657. sqlite3SelectDelete(db, p->x.pSelect);
  658. }else{
  659. sqlite3ExprListDelete(db, p->x.pList);
  660. }
  661. }
  662. if( !ExprHasProperty(p, EP_Static) ){
  663. sqlite3DbFree(db, p);
  664. }
  665. }
  666. /*
  667. ** Return the number of bytes allocated for the expression structure
  668. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  669. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  670. */
  671. static int exprStructSize(Expr *p){
  672. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  673. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  674. return EXPR_FULLSIZE;
  675. }
  676. /*
  677. ** The dupedExpr*Size() routines each return the number of bytes required
  678. ** to store a copy of an expression or expression tree. They differ in
  679. ** how much of the tree is measured.
  680. **
  681. ** dupedExprStructSize() Size of only the Expr structure
  682. ** dupedExprNodeSize() Size of Expr + space for token
  683. ** dupedExprSize() Expr + token + subtree components
  684. **
  685. ***************************************************************************
  686. **
  687. ** The dupedExprStructSize() function returns two values OR-ed together:
  688. ** (1) the space required for a copy of the Expr structure only and
  689. ** (2) the EP_xxx flags that indicate what the structure size should be.
  690. ** The return values is always one of:
  691. **
  692. ** EXPR_FULLSIZE
  693. ** EXPR_REDUCEDSIZE | EP_Reduced
  694. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  695. **
  696. ** The size of the structure can be found by masking the return value
  697. ** of this routine with 0xfff. The flags can be found by masking the
  698. ** return value with EP_Reduced|EP_TokenOnly.
  699. **
  700. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  701. ** (unreduced) Expr objects as they or originally constructed by the parser.
  702. ** During expression analysis, extra information is computed and moved into
  703. ** later parts of teh Expr object and that extra information might get chopped
  704. ** off if the expression is reduced. Note also that it does not work to
  705. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  706. ** to reduce a pristine expression tree from the parser. The implementation
  707. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  708. ** to enforce this constraint.
  709. */
  710. static int dupedExprStructSize(Expr *p, int flags){
  711. int nSize;
  712. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  713. assert( EXPR_FULLSIZE<=0xfff );
  714. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  715. if( 0==(flags&EXPRDUP_REDUCE) ){
  716. nSize = EXPR_FULLSIZE;
  717. }else{
  718. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  719. assert( !ExprHasProperty(p, EP_FromJoin) );
  720. assert( !ExprHasProperty(p, EP_MemToken) );
  721. assert( !ExprHasProperty(p, EP_NoReduce) );
  722. if( p->pLeft || p->x.pList ){
  723. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  724. }else{
  725. assert( p->pRight==0 );
  726. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  727. }
  728. }
  729. return nSize;
  730. }
  731. /*
  732. ** This function returns the space in bytes required to store the copy
  733. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  734. ** string is defined.)
  735. */
  736. static int dupedExprNodeSize(Expr *p, int flags){
  737. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  738. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  739. nByte += sqlite3Strlen30(p->u.zToken)+1;
  740. }
  741. return ROUND8(nByte);
  742. }
  743. /*
  744. ** Return the number of bytes required to create a duplicate of the
  745. ** expression passed as the first argument. The second argument is a
  746. ** mask containing EXPRDUP_XXX flags.
  747. **
  748. ** The value returned includes space to create a copy of the Expr struct
  749. ** itself and the buffer referred to by Expr.u.zToken, if any.
  750. **
  751. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  752. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  753. ** and Expr.pRight variables (but not for any structures pointed to or
  754. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  755. */
  756. static int dupedExprSize(Expr *p, int flags){
  757. int nByte = 0;
  758. if( p ){
  759. nByte = dupedExprNodeSize(p, flags);
  760. if( flags&EXPRDUP_REDUCE ){
  761. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  762. }
  763. }
  764. return nByte;
  765. }
  766. /*
  767. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  768. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  769. ** to store the copy of expression p, the copies of p->u.zToken
  770. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  771. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  772. ** portion of the buffer copied into by this function.
  773. */
  774. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  775. Expr *pNew = 0; /* Value to return */
  776. if( p ){
  777. const int isReduced = (flags&EXPRDUP_REDUCE);
  778. u8 *zAlloc;
  779. u32 staticFlag = 0;
  780. assert( pzBuffer==0 || isReduced );
  781. /* Figure out where to write the new Expr structure. */
  782. if( pzBuffer ){
  783. zAlloc = *pzBuffer;
  784. staticFlag = EP_Static;
  785. }else{
  786. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  787. }
  788. pNew = (Expr *)zAlloc;
  789. if( pNew ){
  790. /* Set nNewSize to the size allocated for the structure pointed to
  791. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  792. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  793. ** by the copy of the p->u.zToken string (if any).
  794. */
  795. const unsigned nStructSize = dupedExprStructSize(p, flags);
  796. const int nNewSize = nStructSize & 0xfff;
  797. int nToken;
  798. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  799. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  800. }else{
  801. nToken = 0;
  802. }
  803. if( isReduced ){
  804. assert( ExprHasProperty(p, EP_Reduced)==0 );
  805. memcpy(zAlloc, p, nNewSize);
  806. }else{
  807. int nSize = exprStructSize(p);
  808. memcpy(zAlloc, p, nSize);
  809. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  810. }
  811. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  812. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  813. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  814. pNew->flags |= staticFlag;
  815. /* Copy the p->u.zToken string, if any. */
  816. if( nToken ){
  817. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  818. memcpy(zToken, p->u.zToken, nToken);
  819. }
  820. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  821. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  822. if( ExprHasProperty(p, EP_xIsSelect) ){
  823. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  824. }else{
  825. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  826. }
  827. }
  828. /* Fill in pNew->pLeft and pNew->pRight. */
  829. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  830. zAlloc += dupedExprNodeSize(p, flags);
  831. if( ExprHasProperty(pNew, EP_Reduced) ){
  832. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  833. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  834. }
  835. if( pzBuffer ){
  836. *pzBuffer = zAlloc;
  837. }
  838. }else{
  839. if( !ExprHasProperty(p, EP_TokenOnly) ){
  840. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  841. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  842. }
  843. }
  844. }
  845. }
  846. return pNew;
  847. }
  848. /*
  849. ** The following group of routines make deep copies of expressions,
  850. ** expression lists, ID lists, and select statements. The copies can
  851. ** be deleted (by being passed to their respective ...Delete() routines)
  852. ** without effecting the originals.
  853. **
  854. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  855. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  856. ** by subsequent calls to sqlite*ListAppend() routines.
  857. **
  858. ** Any tables that the SrcList might point to are not duplicated.
  859. **
  860. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  861. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  862. ** truncated version of the usual Expr structure that will be stored as
  863. ** part of the in-memory representation of the database schema.
  864. */
  865. Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  866. return exprDup(db, p, flags, 0);
  867. }
  868. ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  869. ExprList *pNew;
  870. struct ExprList_item *pItem, *pOldItem;
  871. int i;
  872. if( p==0 ) return 0;
  873. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  874. if( pNew==0 ) return 0;
  875. pNew->iECursor = 0;
  876. pNew->nExpr = i = p->nExpr;
  877. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  878. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  879. if( pItem==0 ){
  880. sqlite3DbFree(db, pNew);
  881. return 0;
  882. }
  883. pOldItem = p->a;
  884. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  885. Expr *pOldExpr = pOldItem->pExpr;
  886. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  887. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  888. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  889. pItem->sortOrder = pOldItem->sortOrder;
  890. pItem->done = 0;
  891. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  892. pItem->iOrderByCol = pOldItem->iOrderByCol;
  893. pItem->iAlias = pOldItem->iAlias;
  894. }
  895. return pNew;
  896. }
  897. /*
  898. ** If cursors, triggers, views and subqueries are all omitted from
  899. ** the build, then none of the following routines, except for
  900. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  901. ** called with a NULL argument.
  902. */
  903. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  904. || !defined(SQLITE_OMIT_SUBQUERY)
  905. SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  906. SrcList *pNew;
  907. int i;
  908. int nByte;
  909. if( p==0 ) return 0;
  910. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  911. pNew = sqlite3DbMallocRaw(db, nByte );
  912. if( pNew==0 ) return 0;
  913. pNew->nSrc = pNew->nAlloc = p->nSrc;
  914. for(i=0; i<p->nSrc; i++){
  915. struct SrcList_item *pNewItem = &pNew->a[i];
  916. struct SrcList_item *pOldItem = &p->a[i];
  917. Table *pTab;
  918. pNewItem->pSchema = pOldItem->pSchema;
  919. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  920. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  921. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  922. pNewItem->jointype = pOldItem->jointype;
  923. pNewItem->iCursor = pOldItem->iCursor;
  924. pNewItem->addrFillSub = pOldItem->addrFillSub;
  925. pNewItem->regReturn = pOldItem->regReturn;
  926. pNewItem->isCorrelated = pOldItem->isCorrelated;
  927. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  928. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  929. pNewItem->notIndexed = pOldItem->notIndexed;
  930. pNewItem->pIndex = pOldItem->pIndex;
  931. pTab = pNewItem->pTab = pOldItem->pTab;
  932. if( pTab ){
  933. pTab->nRef++;
  934. }
  935. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  936. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  937. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  938. pNewItem->colUsed = pOldItem->colUsed;
  939. }
  940. return pNew;
  941. }
  942. IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  943. IdList *pNew;
  944. int i;
  945. if( p==0 ) return 0;
  946. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  947. if( pNew==0 ) return 0;
  948. pNew->nId = p->nId;
  949. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  950. if( pNew->a==0 ){
  951. sqlite3DbFree(db, pNew);
  952. return 0;
  953. }
  954. /* Note that because the size of the allocation for p->a[] is not
  955. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  956. ** on the duplicate created by this function. */
  957. for(i=0; i<p->nId; i++){
  958. struct IdList_item *pNewItem = &pNew->a[i];
  959. struct IdList_item *pOldItem = &p->a[i];
  960. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  961. pNewItem->idx = pOldItem->idx;
  962. }
  963. return pNew;
  964. }
  965. Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  966. Select *pNew, *pPrior;
  967. if( p==0 ) return 0;
  968. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  969. if( pNew==0 ) return 0;
  970. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  971. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  972. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  973. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  974. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  975. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  976. pNew->op = p->op;
  977. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  978. if( pPrior ) pPrior->pNext = pNew;
  979. pNew->pNext = 0;
  980. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  981. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  982. pNew->iLimit = 0;
  983. pNew->iOffset = 0;
  984. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  985. pNew->pRightmost = 0;
  986. pNew->addrOpenEphm[0] = -1;
  987. pNew->addrOpenEphm[1] = -1;
  988. pNew->addrOpenEphm[2] = -1;
  989. return pNew;
  990. }
  991. #else
  992. Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  993. assert( p==0 );
  994. return 0;
  995. }
  996. #endif
  997. /*
  998. ** Add a new element to the end of an expression list. If pList is
  999. ** initially NULL, then create a new expression list.
  1000. **
  1001. ** If a memory allocation error occurs, the entire list is freed and
  1002. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  1003. ** that the new entry was successfully appended.
  1004. */
  1005. ExprList *sqlite3ExprListAppend(
  1006. Parse *pParse, /* Parsing context */
  1007. ExprList *pList, /* List to which to append. Might be NULL */
  1008. Expr *pExpr /* Expression to be appended. Might be NULL */
  1009. ){
  1010. sqlite3 *db = pParse->db;
  1011. if( pList==0 ){
  1012. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  1013. if( pList==0 ){
  1014. goto no_mem;
  1015. }
  1016. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  1017. if( pList->a==0 ) goto no_mem;
  1018. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  1019. struct ExprList_item *a;
  1020. assert( pList->nExpr>0 );
  1021. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  1022. if( a==0 ){
  1023. goto no_mem;
  1024. }
  1025. pList->a = a;
  1026. }
  1027. assert( pList->a!=0 );
  1028. if( 1 ){
  1029. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  1030. memset(pItem, 0, sizeof(*pItem));
  1031. pItem->pExpr = pExpr;
  1032. }
  1033. return pList;
  1034. no_mem:
  1035. /* Avoid leaking memory if malloc has failed. */
  1036. sqlite3ExprDelete(db, pExpr);
  1037. sqlite3ExprListDelete(db, pList);
  1038. return 0;
  1039. }
  1040. /*
  1041. ** Set the ExprList.a[].zName element of the most recently added item
  1042. ** on the expression list.
  1043. **
  1044. ** pList might be NULL following an OOM error. But pName should never be
  1045. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  1046. ** is set.
  1047. */
  1048. void sqlite3ExprListSetName(
  1049. Parse *pParse, /* Parsing context */
  1050. ExprList *pList, /* List to which to add the span. */
  1051. Token *pName, /* Name to be added */
  1052. int dequote /* True to cause the name to be dequoted */
  1053. ){
  1054. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  1055. if( pList ){
  1056. struct ExprList_item *pItem;
  1057. assert( pList->nExpr>0 );
  1058. pItem = &pList->a[pList->nExpr-1];
  1059. assert( pItem->zName==0 );
  1060. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  1061. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  1062. }
  1063. }
  1064. /*
  1065. ** Set the ExprList.a[].zSpan element of the most recently added item
  1066. ** on the expression list.
  1067. **
  1068. ** pList might be NULL following an OOM error. But pSpan should never be
  1069. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  1070. ** is set.
  1071. */
  1072. void sqlite3ExprListSetSpan(
  1073. Parse *pParse, /* Parsing context */
  1074. ExprList *pList, /* List to which to add the span. */
  1075. ExprSpan *pSpan /* The span to be added */
  1076. ){
  1077. sqlite3 *db = pParse->db;
  1078. assert( pList!=0 || db->mallocFailed!=0 );
  1079. if( pList ){
  1080. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  1081. assert( pList->nExpr>0 );
  1082. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  1083. sqlite3DbFree(db, pItem->zSpan);
  1084. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  1085. (int)(pSpan->zEnd - pSpan->zStart));
  1086. }
  1087. }
  1088. /*
  1089. ** If the expression list pEList contains more than iLimit elements,
  1090. ** leave an error message in pParse.
  1091. */
  1092. void sqlite3ExprListCheckLength(
  1093. Parse *pParse,
  1094. ExprList *pEList,
  1095. const char *zObject
  1096. ){
  1097. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  1098. testcase( pEList && pEList->nExpr==mx );
  1099. testcase( pEList && pEList->nExpr==mx+1 );
  1100. if( pEList && pEList->nExpr>mx ){
  1101. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  1102. }
  1103. }
  1104. /*
  1105. ** Delete an entire expression list.
  1106. */
  1107. void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  1108. int i;
  1109. struct ExprList_item *pItem;
  1110. if( pList==0 ) return;
  1111. assert( pList->a!=0 || pList->nExpr==0 );
  1112. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  1113. sqlite3ExprDelete(db, pItem->pExpr);
  1114. sqlite3DbFree(db, pItem->zName);
  1115. sqlite3DbFree(db, pItem->zSpan);
  1116. }
  1117. sqlite3DbFree(db, pList->a);
  1118. sqlite3DbFree(db, pList);
  1119. }
  1120. /*
  1121. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  1122. ** to an integer. These routines are checking an expression to see
  1123. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  1124. ** not constant.
  1125. **
  1126. ** These callback routines are used to implement the following:
  1127. **
  1128. ** sqlite3ExprIsConstant()
  1129. ** sqlite3ExprIsConstantNotJoin()
  1130. ** sqlite3ExprIsConstantOrFunction()
  1131. **
  1132. */
  1133. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  1134. /* If pWalker->u.i is 3 then any term of the expression that comes from
  1135. ** the ON or USING clauses of a join disqualifies the expression
  1136. ** from being considered constant. */
  1137. if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
  1138. pWalker->u.i = 0;
  1139. return WRC_Abort;
  1140. }
  1141. switch( pExpr->op ){
  1142. /* Consider functions to be constant if all their arguments are constant
  1143. ** and pWalker->u.i==2 */
  1144. case TK_FUNCTION:
  1145. if( pWalker->u.i==2 ) return 0;
  1146. /* Fall through */
  1147. case TK_ID:
  1148. case TK_COLUMN:
  1149. case TK_AGG_FUNCTION:
  1150. case TK_AGG_COLUMN:
  1151. testcase( pExpr->op==TK_ID );
  1152. testcase( pExpr->op==TK_COLUMN );
  1153. testcase( pExpr->op==TK_AGG_FUNCTION );
  1154. testcase( pExpr->op==TK_AGG_COLUMN );
  1155. pWalker->u.i = 0;
  1156. return WRC_Abort;
  1157. default:
  1158. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  1159. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  1160. return WRC_Continue;
  1161. }
  1162. }
  1163. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  1164. UNUSED_PARAMETER(NotUsed);
  1165. pWalker->u.i = 0;
  1166. return WRC_Abort;
  1167. }
  1168. static int exprIsConst(Expr *p, int initFlag){
  1169. Walker w;
  1170. memset(&w, 0, sizeof(w));
  1171. w.u.i = initFlag;
  1172. w.xExprCallback = exprNodeIsConstant;
  1173. w.xSelectCallback = selectNodeIsConstant;
  1174. sqlite3WalkExpr(&w, p);
  1175. return w.u.i;
  1176. }
  1177. /*
  1178. ** Walk an expression tree. Return 1 if the expression is constant
  1179. ** and 0 if it involves variables or function calls.
  1180. **
  1181. ** For the purposes of this function, a double-quoted string (ex: "abc")
  1182. ** is considered a variable but a single-quoted string (ex: 'abc') is
  1183. ** a constant.
  1184. */
  1185. int sqlite3ExprIsConstant(Expr *p){
  1186. return exprIsConst(p, 1);
  1187. }
  1188. /*
  1189. ** Walk an expression tree. Return 1 if the expression is constant
  1190. ** that does no originate from the ON or USING clauses of a join.
  1191. ** Return 0 if it involves variables or function calls or terms from
  1192. ** an ON or USING clause.
  1193. */
  1194. int sqlite3ExprIsConstantNotJoin(Expr *p){
  1195. return exprIsConst(p, 3);
  1196. }
  1197. /*
  1198. ** Walk an expression tree. Return 1 if the expression is constant
  1199. ** or a function call with constant arguments. Return and 0 if there
  1200. ** are any variables.
  1201. **
  1202. ** For the purposes of this function, a double-quoted string (ex: "abc")
  1203. ** is considered a variable but a single-quoted string (ex: 'abc') is
  1204. ** a constant.
  1205. */
  1206. int sqlite3ExprIsConstantOrFunction(Expr *p){
  1207. return exprIsConst(p, 2);
  1208. }
  1209. /*
  1210. ** If the expression p codes a constant integer that is small enough
  1211. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  1212. ** in *pValue. If the expression is not an integer or if it is too big
  1213. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  1214. */
  1215. int sqlite3ExprIsInteger(Expr *p, int *pValue){
  1216. int rc = 0;
  1217. /* If an expression is an integer literal that fits in a signed 32-bit
  1218. ** integer, then the EP_IntValue flag will have already been set */
  1219. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  1220. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  1221. if( p->flags & EP_IntValue ){
  1222. *pValue = p->u.iValue;
  1223. return 1;
  1224. }
  1225. switch( p->op ){
  1226. case TK_UPLUS: {
  1227. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  1228. break;
  1229. }
  1230. case TK_UMINUS: {
  1231. int v;
  1232. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  1233. assert( v!=(-2147483647-1) );
  1234. *pValue = -v;
  1235. rc = 1;
  1236. }
  1237. break;
  1238. }
  1239. default: break;
  1240. }
  1241. return rc;
  1242. }
  1243. /*
  1244. ** Return FALSE if there is no chance that the expression can be NULL.
  1245. **
  1246. ** If the expression might be NULL or if the expression is too complex
  1247. ** to tell return TRUE.
  1248. **
  1249. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  1250. ** when we know that a value cannot be NULL. Hence, a false positive
  1251. ** (returning TRUE when in fact the expression can never be NULL) might
  1252. ** be a small performance hit but is otherwise harmless. On the other
  1253. ** hand, a false negative (returning FALSE when the result could be NULL)
  1254. ** will likely result in an incorrect answer. So when in doubt, return
  1255. ** TRUE.
  1256. */
  1257. int sqlite3ExprCanBeNull(const Expr *p){
  1258. u8 op;
  1259. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  1260. op = p->op;
  1261. if( op==TK_REGISTER ) op = p->op2;
  1262. switch( op ){
  1263. case TK_INTEGER:
  1264. case TK_STRING:
  1265. case TK_FLOAT:
  1266. case TK_BLOB:
  1267. return 0;
  1268. default:
  1269. return 1;
  1270. }
  1271. }
  1272. /*
  1273. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  1274. ** to location iDest if the value in iReg is NULL. The value in iReg
  1275. ** was computed by pExpr. If we can look at pExpr at compile-time and
  1276. ** determine that it can never generate a NULL, then the OP_IsNull operation
  1277. ** can be omitted.
  1278. */
  1279. void sqlite3ExprCodeIsNullJump(
  1280. Vdbe *v, /* The VDBE under construction */
  1281. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  1282. int iReg, /* Test the value in this register for NULL */
  1283. int iDest /* Jump here if the value is null */
  1284. ){
  1285. if( sqlite3ExprCanBeNull(pExpr) ){
  1286. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  1287. }
  1288. }
  1289. /*
  1290. ** Return TRUE if the given expression is a constant which would be
  1291. ** unchanged by OP_Affinity with the affinity given in the second
  1292. ** argument.
  1293. **
  1294. ** This routine is used to determine if the OP_Affinity operation
  1295. ** can be omitted. When in doubt return FALSE. A false negative
  1296. ** is harmless. A false positive, however, can result in the wrong
  1297. ** answer.
  1298. */
  1299. int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  1300. u8 op;
  1301. if( aff==SQLITE_AFF_NONE ) return 1;
  1302. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  1303. op = p->op;
  1304. if( op==TK_REGISTER ) op = p->op2;
  1305. switch( op ){
  1306. case TK_INTEGER: {
  1307. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  1308. }
  1309. case TK_FLOAT: {
  1310. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  1311. }
  1312. case TK_STRING: {
  1313. return aff==SQLITE_AFF_TEXT;
  1314. }
  1315. case TK_BLOB: {
  1316. return 1;
  1317. }
  1318. case TK_COLUMN: {
  1319. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  1320. return p->iColumn<0
  1321. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  1322. }
  1323. default: {
  1324. return 0;
  1325. }
  1326. }
  1327. }
  1328. /*
  1329. ** Return TRUE if the given string is a row-id column name.
  1330. */
  1331. int sqlite3IsRowid(const char *z){
  1332. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  1333. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  1334. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  1335. return 0;
  1336. }
  1337. /*
  1338. ** Return true if we are able to the IN operator optimization on a
  1339. ** query of the form
  1340. **
  1341. ** x IN (SELECT ...)
  1342. **
  1343. ** Where the SELECT... clause is as specified by the parameter to this
  1344. ** routine.
  1345. **
  1346. ** The Select object passed in has already been preprocessed and no
  1347. ** errors have been found.
  1348. */
  1349. #ifndef SQLITE_OMIT_SUBQUERY
  1350. static int isCandidateForInOpt(Select *p){
  1351. SrcList *pSrc;
  1352. ExprList *pEList;
  1353. Table *pTab;
  1354. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  1355. if( p->pPrior ) return 0; /* Not a compound SELECT */
  1356. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  1357. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  1358. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  1359. return 0; /* No DISTINCT keyword and no aggregate functions */
  1360. }
  1361. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  1362. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  1363. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  1364. if( p->pWhere ) return 0; /* Has no WHERE clause */
  1365. pSrc = p->pSrc;
  1366. assert( pSrc!=0 );
  1367. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  1368. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  1369. pTab = pSrc->a[0].pTab;
  1370. if( NEVER(pTab==0) ) return 0;
  1371. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  1372. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  1373. pEList = p->pEList;
  1374. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  1375. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  1376. return 1;
  1377. }
  1378. #endif /* SQLITE_OMIT_SUBQUERY */
  1379. /*
  1380. ** Code an OP_Once instruction and allocate space for its flag. Return the
  1381. ** address of the new instruction.
  1382. */
  1383. int sqlite3CodeOnce(Parse *pParse){
  1384. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  1385. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  1386. }
  1387. /*
  1388. ** This function is used by the implementation of the IN (...) operator.
  1389. ** The pX parameter is the expression on the RHS of the IN operator, which
  1390. ** might be either a list of expressions or a subquery.
  1391. **
  1392. ** The job of this routine is to find or create a b-tree object that can
  1393. ** be used either to test for membership in the RHS set or to iterate through
  1394. ** all members of the RHS set, skipping duplicates.
  1395. **
  1396. ** A cursor is opened on the b-tree object that the RHS of the IN operator
  1397. ** and pX->iTable is set to the index of that cursor.
  1398. **
  1399. ** The returned value of this function indicates the b-tree type, as follows:
  1400. **
  1401. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  1402. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  1403. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  1404. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  1405. ** populated epheremal table.
  1406. **
  1407. ** An existing b-tree might be used if the RHS expression pX is a simple
  1408. ** subquery such as:
  1409. **
  1410. ** SELECT <column> FROM <table>
  1411. **
  1412. ** If the RHS of the IN operator is a list or a more complex subquery, then
  1413. ** an ephemeral table might need to be generated from the RHS and then
  1414. ** pX->iTable made to point to the ephermeral table instead of an
  1415. ** existing table.
  1416. **
  1417. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  1418. ** through the set members, skipping any duplicates. In this case an
  1419. ** epheremal table must be used unless the selected <column> is guaranteed
  1420. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  1421. ** has a UNIQUE constraint or UNIQUE index.
  1422. **
  1423. ** If the prNotFound parameter is not 0, then the b-tree will be used
  1424. ** for fast set membership tests. In this case an epheremal table must
  1425. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  1426. ** be found with <column> as its left-most column.
  1427. **
  1428. ** When the b-tree is being used for membership tests, the calling function
  1429. ** needs to know whether or not the structure contains an SQL NULL
  1430. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  1431. ** If there is any chance that the (...) might contain a NULL value at
  1432. ** runtime, then a register is allocated and the register number written
  1433. ** to *prNotFound. If there is no chance that the (...) contains a
  1434. ** NULL value, then *prNotFound is left unchanged.
  1435. **
  1436. ** If a register is allocated and its location stored in *prNotFound, then
  1437. ** its initial value is NULL. If the (...) does not remain constant
  1438. ** for the duration of the query (i.e. the SELECT within the (...)
  1439. ** is a correlated subquery) then the value of the allocated register is
  1440. ** reset to NULL each time the subquery is rerun. This allows the
  1441. ** caller to use vdbe code equivalent to the following:
  1442. **
  1443. ** if( register==NULL ){
  1444. ** has_null = <test if data structure contains null>
  1445. ** register = 1
  1446. ** }
  1447. **
  1448. ** in order to avoid running the <test if data structure contains null>
  1449. ** test more often than is necessary.
  1450. */
  1451. #ifndef SQLITE_OMIT_SUBQUERY
  1452. int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  1453. Select *p; /* SELECT to the right of IN operator */
  1454. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  1455. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  1456. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  1457. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  1458. assert( pX->op==TK_IN );
  1459. /* Check to see if an existing table or index can be used to
  1460. ** satisfy the query. This is preferable to generating a new
  1461. ** ephemeral table.
  1462. */
  1463. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  1464. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  1465. sqlite3 *db = pParse->db; /* Database connection */
  1466. Table *pTab; /* Table <table>. */
  1467. Expr *pExpr; /* Expression <column> */
  1468. int iCol; /* Index of column <column> */
  1469. int iDb; /* Database idx for pTab */
  1470. assert( p ); /* Because of isCandidateForInOpt(p) */
  1471. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  1472. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  1473. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  1474. pTab = p->pSrc->a[0].pTab;
  1475. pExpr = p->pEList->a[0].pExpr;
  1476. iCol = pExpr->iColumn;
  1477. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  1478. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  1479. sqlite3CodeVerifySchema(pParse, iDb);
  1480. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  1481. /* This function is only called from two places. In both cases the vdbe
  1482. ** has already been allocated. So assume sqlite3GetVdbe() is always
  1483. ** successful here.
  1484. */
  1485. assert(v);
  1486. if( iCol<0 ){
  1487. int iAddr;
  1488. iAddr = sqlite3CodeOnce(pParse);
  1489. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  1490. eType = IN_INDEX_ROWID;
  1491. sqlite3VdbeJumpHere(v, iAddr);
  1492. }else{
  1493. Index *pIdx; /* Iterator variable */
  1494. /* The collation sequence used by the comparison. If an index is to
  1495. ** be used in place of a temp-table, it must be ordered according
  1496. ** to this collation sequence. */
  1497. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  1498. /* Check that the affinity that will be used to perform the
  1499. ** comparison is the same as the affinity of the column. If
  1500. ** it is not, it is not possible to use any index.
  1501. */
  1502. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  1503. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  1504. if( (pIdx->aiColumn[0]==iCol)
  1505. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  1506. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  1507. ){
  1508. int iAddr;
  1509. char *pKey;
  1510. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  1511. iAddr = sqlite3CodeOnce(pParse);
  1512. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  1513. pKey,P4_KEYINFO_HANDOFF);
  1514. VdbeComment((v, "%s", pIdx->zName));
  1515. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  1516. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  1517. sqlite3VdbeJumpHere(v, iAddr);
  1518. if( prNotFound && !pTab->aCol[iCol].notNull ){
  1519. *prNotFound = ++pParse->nMem;
  1520. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  1521. }
  1522. }
  1523. }
  1524. }
  1525. }
  1526. if( eType==0 ){
  1527. /* Could not found an existing table or index to use as the RHS b-tree.
  1528. ** We will have to generate an ephemeral table to do the job.
  1529. */
  1530. u32 savedNQueryLoop = pParse->nQueryLoop;
  1531. int rMayHaveNull = 0;
  1532. eType = IN_INDEX_EPH;
  1533. if( prNotFound ){
  1534. *prNotFound = rMayHaveNull = ++pParse->nMem;
  1535. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  1536. }else{
  1537. testcase( pParse->nQueryLoop>0 );
  1538. pParse->nQueryLoop = 0;
  1539. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  1540. eType = IN_INDEX_ROWID;
  1541. }
  1542. }
  1543. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  1544. pParse->nQueryLoop = savedNQueryLoop;
  1545. }else{
  1546. pX->iTable = iTab;
  1547. }
  1548. return eType;
  1549. }
  1550. #endif
  1551. /*
  1552. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  1553. ** or IN operators. Examples:
  1554. **
  1555. ** (SELECT a FROM b) -- subquery
  1556. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  1557. ** x IN (4,5,11) -- IN operator with list on right-hand side
  1558. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  1559. **
  1560. ** The pExpr parameter describes the expression that contains the IN
  1561. ** operator or subquery.
  1562. **
  1563. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  1564. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  1565. ** to some integer key column of a table B-Tree. In this case, use an
  1566. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  1567. ** (slower) variable length keys B-Tree.
  1568. **
  1569. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  1570. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  1571. ** Furthermore, the IN is in a WHERE clause and that we really want
  1572. ** to iterate over the RHS of the IN operator in order to quickly locate
  1573. ** all corresponding LHS elements. All this routine does is initialize
  1574. ** the register given by rMayHaveNull to NULL. Calling routines will take
  1575. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  1576. **
  1577. ** If rMayHaveNull is zero, that means that the subquery is being used
  1578. ** for membership testing only. There is no need to initialize any
  1579. ** registers to indicate the presence or absence of NULLs on the RHS.
  1580. **
  1581. ** For a SELECT or EXISTS operator, return the register that holds the
  1582. ** result. For IN operators or if an error occurs, the return value is 0.
  1583. */
  1584. #ifndef SQLITE_OMIT_SUBQUERY
  1585. int sqlite3CodeSubselect(
  1586. Parse *pParse, /* Parsing context */
  1587. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  1588. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  1589. int isRowid /* If true, LHS of IN operator is a rowid */
  1590. ){
  1591. int testAddr = -1; /* One-time test address */
  1592. int rReg = 0; /* Register storing resulting */
  1593. Vdbe *v = sqlite3GetVdbe(pParse);
  1594. if( NEVER(v==0) ) return 0;
  1595. sqlite3ExprCachePush(pParse);
  1596. /* This code must be run in its entirety every time it is encountered
  1597. ** if any of the following is true:
  1598. **
  1599. ** * The right-hand side is a correlated subquery
  1600. ** * The right-hand side is an expression list containing variables
  1601. ** * We are inside a trigger
  1602. **
  1603. ** If all of the above are false, then we can run this code just once
  1604. ** save the results, and reuse the same result on subsequent invocations.
  1605. */
  1606. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  1607. testAddr = sqlite3CodeOnce(pParse);
  1608. }
  1609. #ifndef SQLITE_OMIT_EXPLAIN
  1610. if( pParse->explain==2 ){
  1611. char *zMsg = sqlite3MPrintf(
  1612. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  1613. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  1614. );
  1615. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  1616. }
  1617. #endif
  1618. switch( pExpr->op ){
  1619. case TK_IN: {
  1620. char affinity; /* Affinity of the LHS of the IN */
  1621. int addr; /* Address of OP_OpenEphemeral instruction */
  1622. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  1623. KeyInfo *pKeyInfo = 0; /* Key information */
  1624. if( rMayHaveNull ){
  1625. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  1626. }
  1627. affinity = sqlite3ExprAffinity(pLeft);
  1628. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  1629. ** expression it is handled the same way. An ephemeral table is
  1630. ** filled with single-field index keys representing the results
  1631. ** from the SELECT or the <exprlist>.
  1632. **
  1633. ** If the 'x' expression is a column value, or the SELECT...
  1634. ** statement returns a column value, then the affinity of that
  1635. ** column is used to build the index keys. If both 'x' and the
  1636. ** SELECT... statement are columns, then numeric affinity is used
  1637. ** if either column has NUMERIC or INTEGER affinity. If neither
  1638. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  1639. ** is used.
  1640. */
  1641. pExpr->iTable = pParse->nTab++;
  1642. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  1643. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  1644. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1);
  1645. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  1646. /* Case 1: expr IN (SELECT ...)
  1647. **
  1648. ** Generate code to write the results of the select into the temporary
  1649. ** table allocated and opened above.
  1650. */
  1651. SelectDest dest;
  1652. ExprList *pEList;
  1653. assert( !isRowid );
  1654. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  1655. dest.affSdst = (u8)affinity;
  1656. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  1657. pExpr->x.pSelect->iLimit = 0;
  1658. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  1659. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  1660. sqlite3DbFree(pParse->db, pKeyInfo);
  1661. return 0;
  1662. }
  1663. pEList = pExpr->x.pSelect->pEList;
  1664. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  1665. assert( pEList!=0 );
  1666. assert( pEList->nExpr>0 );
  1667. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  1668. pEList->a[0].pExpr);
  1669. }else if( ALWAYS(pExpr->x.pList!=0) ){
  1670. /* Case 2: expr IN (exprlist)
  1671. **
  1672. ** For each expression, build an index key from the evaluation and
  1673. ** store it in the temporary table. If <expr> is a column, then use
  1674. ** that columns affinity when building index keys. If <expr> is not
  1675. ** a column, use numeric affinity.
  1676. */
  1677. int i;
  1678. ExprList *pList = pExpr->x.pList;
  1679. struct ExprList_item *pItem;
  1680. int r1, r2, r3;
  1681. if( !affinity ){
  1682. affinity = SQLITE_AFF_NONE;
  1683. }
  1684. if( pKeyInfo ){
  1685. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  1686. }
  1687. /* Loop through each expression in <exprlist>. */
  1688. r1 = sqlite3GetTempReg(pParse);
  1689. r2 = sqlite3GetTempReg(pParse);
  1690. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  1691. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  1692. Expr *pE2 = pItem->pExpr;
  1693. int iValToIns;
  1694. /* If the expression is not constant then we will need to
  1695. ** disable the test that was generated above that makes sure
  1696. ** this code only executes once. Because for a non-constant
  1697. ** expression we need to rerun this code each time.
  1698. */
  1699. if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
  1700. sqlite3VdbeChangeToNoop(v, testAddr);
  1701. testAddr = -1;
  1702. }
  1703. /* Evaluate the expression and insert it into the temp table */
  1704. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  1705. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  1706. }else{
  1707. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  1708. if( isRowid ){
  1709. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  1710. sqlite3VdbeCurrentAddr(v)+2);
  1711. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  1712. }else{
  1713. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  1714. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  1715. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  1716. }
  1717. }
  1718. }
  1719. sqlite3ReleaseTempReg(pParse, r1);
  1720. sqlite3ReleaseTempReg(pParse, r2);
  1721. }
  1722. if( pKeyInfo ){
  1723. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF);
  1724. }
  1725. break;
  1726. }
  1727. case TK_EXISTS:
  1728. case TK_SELECT:
  1729. default: {
  1730. /* If this has to be a scalar SELECT. Generate code to put the
  1731. ** value of this select in a memory cell and record the number
  1732. ** of the memory cell in iColumn. If this is an EXISTS, write
  1733. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  1734. ** and record that memory cell in iColumn.
  1735. */
  1736. Select *pSel; /* SELECT statement to encode */
  1737. SelectDest dest; /* How to deal with SELECt result */
  1738. testcase( pExpr->op==TK_EXISTS );
  1739. testcase( pExpr->op==TK_SELECT );
  1740. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  1741. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  1742. pSel = pExpr->x.pSelect;
  1743. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  1744. if( pExpr->op==TK_SELECT ){
  1745. dest.eDest = SRT_Mem;
  1746. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  1747. VdbeComment((v, "Init subquery result"));
  1748. }else{
  1749. dest.eDest = SRT_Exists;
  1750. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  1751. VdbeComment((v, "Init EXISTS result"));
  1752. }
  1753. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  1754. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  1755. &sqlite3IntTokens[1]);
  1756. pSel->iLimit = 0;
  1757. if( sqlite3Select(pParse, pSel, &dest) ){
  1758. return 0;
  1759. }
  1760. rReg = dest.iSDParm;
  1761. ExprSetVVAProperty(pExpr, EP_NoReduce);
  1762. break;
  1763. }
  1764. }
  1765. if( testAddr>=0 ){
  1766. sqlite3VdbeJumpHere(v, testAddr);
  1767. }
  1768. sqlite3ExprCachePop(pParse, 1);
  1769. return rReg;
  1770. }
  1771. #endif /* SQLITE_OMIT_SUBQUERY */
  1772. #ifndef SQLITE_OMIT_SUBQUERY
  1773. /*
  1774. ** Generate code for an IN expression.
  1775. **
  1776. ** x IN (SELECT ...)
  1777. ** x IN (value, value, ...)
  1778. **
  1779. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  1780. ** is an array of zero or more values. The expression is true if the LHS is
  1781. ** contained within the RHS. The value of the expression is unknown (NULL)
  1782. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  1783. ** RHS contains one or more NULL values.
  1784. **
  1785. ** This routine generates code will jump to destIfFalse if the LHS is not
  1786. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  1787. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  1788. ** within the RHS then fall through.
  1789. */
  1790. static void sqlite3ExprCodeIN(
  1791. Parse *pParse, /* Parsing and code generating context */
  1792. Expr *pExpr, /* The IN expression */
  1793. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  1794. int destIfNull /* Jump here if the results are unknown due to NULLs */
  1795. ){
  1796. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  1797. char affinity; /* Comparison affinity to use */
  1798. int eType; /* Type of the RHS */
  1799. int r1; /* Temporary use register */
  1800. Vdbe *v; /* Statement under construction */
  1801. /* Compute the RHS. After this step, the table with cursor
  1802. ** pExpr->iTable will contains the values that make up the RHS.
  1803. */
  1804. v = pParse->pVdbe;
  1805. assert( v!=0 ); /* OOM detected prior to this routine */
  1806. VdbeNoopComment((v, "begin IN expr"));
  1807. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  1808. /* Figure out the affinity to use to create a key from the results
  1809. ** of the expression. affinityStr stores a static string suitable for
  1810. ** P4 of OP_MakeRecord.
  1811. */
  1812. affinity = comparisonAffinity(pExpr);
  1813. /* Code the LHS, the <expr> from "<expr> IN (...)".
  1814. */
  1815. sqlite3ExprCachePush(pParse);
  1816. r1 = sqlite3GetTempReg(pParse);
  1817. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  1818. /* If the LHS is NULL, then the result is either false or NULL depending
  1819. ** on whether the RHS is empty or not, respectively.
  1820. */
  1821. if( destIfNull==destIfFalse ){
  1822. /* Shortcut for the common case where the false and NULL outcomes are
  1823. ** the same. */
  1824. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  1825. }else{
  1826. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  1827. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  1828. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  1829. sqlite3VdbeJumpHere(v, addr1);
  1830. }
  1831. if( eType==IN_INDEX_ROWID ){
  1832. /* In this case, the RHS is the ROWID of table b-tree
  1833. */
  1834. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  1835. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  1836. }else{
  1837. /* In this case, the RHS is an index b-tree.
  1838. */
  1839. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  1840. /* If the set membership test fails, then the result of the
  1841. ** "x IN (...)" expression must be either 0 or NULL. If the set
  1842. ** contains no NULL values, then the result is 0. If the set
  1843. ** contains one or more NULL values, then the result of the
  1844. ** expression is also NULL.
  1845. */
  1846. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  1847. /* This branch runs if it is known at compile time that the RHS
  1848. ** cannot contain NULL values. This happens as the result
  1849. ** of a "NOT NULL" constraint in the database schema.
  1850. **
  1851. ** Also run this branch if NULL is equivalent to FALSE
  1852. ** for this particular IN operator.
  1853. */
  1854. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  1855. }else{
  1856. /* In this branch, the RHS of the IN might contain a NULL and
  1857. ** the presence of a NULL on the RHS makes a difference in the
  1858. ** outcome.
  1859. */
  1860. int j1, j2, j3;
  1861. /* First check to see if the LHS is contained in the RHS. If so,
  1862. ** then the presence of NULLs in the RHS does not matter, so jump
  1863. ** over all of the code that follows.
  1864. */
  1865. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  1866. /* Here we begin generating code that runs if the LHS is not
  1867. ** contained within the RHS. Generate additional code that
  1868. ** tests the RHS for NULLs. If the RHS contains a NULL then
  1869. ** jump to destIfNull. If there are no NULLs in the RHS then
  1870. ** jump to destIfFalse.
  1871. */
  1872. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  1873. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  1874. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  1875. sqlite3VdbeJumpHere(v, j3);
  1876. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  1877. sqlite3VdbeJumpHere(v, j2);
  1878. /* Jump to the appropriate target depending on whether or not
  1879. ** the RHS contains a NULL
  1880. */
  1881. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  1882. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  1883. /* The OP_Found at the top of this branch jumps here when true,
  1884. ** causing the overall IN expression evaluation to fall through.
  1885. */
  1886. sqlite3VdbeJumpHere(v, j1);
  1887. }
  1888. }
  1889. sqlite3ReleaseTempReg(pParse, r1);
  1890. sqlite3ExprCachePop(pParse, 1);
  1891. VdbeComment((v, "end IN expr"));
  1892. }
  1893. #endif /* SQLITE_OMIT_SUBQUERY */
  1894. /*
  1895. ** Duplicate an 8-byte value
  1896. */
  1897. static char *dup8bytes(Vdbe *v, const char *in){
  1898. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  1899. if( out ){
  1900. memcpy(out, in, 8);
  1901. }
  1902. return out;
  1903. }
  1904. #ifndef SQLITE_OMIT_FLOATING_POINT
  1905. /*
  1906. ** Generate an instruction that will put the floating point
  1907. ** value described by z[0..n-1] into register iMem.
  1908. **
  1909. ** The z[] string will probably not be zero-terminated. But the
  1910. ** z[n] character is guaranteed to be something that does not look
  1911. ** like the continuation of the number.
  1912. */
  1913. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  1914. if( ALWAYS(z!=0) ){
  1915. double value;
  1916. char *zV;
  1917. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  1918. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  1919. if( negateFlag ) value = -value;
  1920. zV = dup8bytes(v, (char*)&value);
  1921. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  1922. }
  1923. }
  1924. #endif
  1925. /*
  1926. ** Generate an instruction that will put the integer describe by
  1927. ** text z[0..n-1] into register iMem.
  1928. **
  1929. ** Expr.u.zToken is always UTF8 and zero-terminated.
  1930. */
  1931. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  1932. Vdbe *v = pParse->pVdbe;
  1933. if( pExpr->flags & EP_IntValue ){
  1934. int i = pExpr->u.iValue;
  1935. assert( i>=0 );
  1936. if( negFlag ) i = -i;
  1937. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  1938. }else{
  1939. int c;
  1940. i64 value;
  1941. const char *z = pExpr->u.zToken;
  1942. assert( z!=0 );
  1943. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  1944. if( c==0 || (c==2 && negFlag) ){
  1945. char *zV;
  1946. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  1947. zV = dup8bytes(v, (char*)&value);
  1948. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  1949. }else{
  1950. #ifdef SQLITE_OMIT_FLOATING_POINT
  1951. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  1952. #else
  1953. codeReal(v, z, negFlag, iMem);
  1954. #endif
  1955. }
  1956. }
  1957. }
  1958. /*
  1959. ** Clear a cache entry.
  1960. */
  1961. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  1962. if( p->tempReg ){
  1963. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  1964. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  1965. }
  1966. p->tempReg = 0;
  1967. }
  1968. }
  1969. /*
  1970. ** Record in the column cache that a particular column from a
  1971. ** particular table is stored in a particular register.
  1972. */
  1973. void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  1974. int i;
  1975. int minLru;
  1976. int idxLru;
  1977. struct yColCache *p;
  1978. assert( iReg>0 ); /* Register numbers are always positive */
  1979. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  1980. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  1981. ** for testing only - to verify that SQLite always gets the same answer
  1982. ** with and without the column cache.
  1983. */
  1984. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  1985. /* First replace any existing entry.
  1986. **
  1987. ** Actually, the way the column cache is currently used, we are guaranteed
  1988. ** that the object will never already be in cache. Verify this guarantee.
  1989. */
  1990. #ifndef NDEBUG
  1991. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  1992. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  1993. }
  1994. #endif
  1995. /* Find an empty slot and replace it */
  1996. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  1997. if( p->iReg==0 ){
  1998. p->iLevel = pParse->iCacheLevel;
  1999. p->iTable = iTab;
  2000. p->iColumn = iCol;
  2001. p->iReg = iReg;
  2002. p->tempReg = 0;
  2003. p->lru = pParse->iCacheCnt++;
  2004. return;
  2005. }
  2006. }
  2007. /* Replace the last recently used */
  2008. minLru = 0x7fffffff;
  2009. idxLru = -1;
  2010. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  2011. if( p->lru<minLru ){
  2012. idxLru = i;
  2013. minLru = p->lru;
  2014. }
  2015. }
  2016. if( ALWAYS(idxLru>=0) ){
  2017. p = &pParse->aColCache[idxLru];
  2018. p->iLevel = pParse->iCacheLevel;
  2019. p->iTable = iTab;
  2020. p->iColumn = iCol;
  2021. p->iReg = iReg;
  2022. p->tempReg = 0;
  2023. p->lru = pParse->iCacheCnt++;
  2024. return;
  2025. }
  2026. }
  2027. /*
  2028. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  2029. ** Purge the range of registers from the column cache.
  2030. */
  2031. void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  2032. int i;
  2033. int iLast = iReg + nReg - 1;
  2034. struct yColCache *p;
  2035. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  2036. int r = p->iReg;
  2037. if( r>=iReg && r<=iLast ){
  2038. cacheEntryClear(pParse, p);
  2039. p->iReg = 0;
  2040. }
  2041. }
  2042. }
  2043. /*
  2044. ** Remember the current column cache context. Any new entries added
  2045. ** added to the column cache after this call are removed when the
  2046. ** corresponding pop occurs.
  2047. */
  2048. void sqlite3ExprCachePush(Parse *pParse){
  2049. pParse->iCacheLevel++;
  2050. }
  2051. /*
  2052. ** Remove from the column cache any entries that were added since the
  2053. ** the previous N Push operations. In other words, restore the cache
  2054. ** to the state it was in N Pushes ago.
  2055. */
  2056. void sqlite3ExprCachePop(Parse *pParse, int N){
  2057. int i;
  2058. struct yColCache *p;
  2059. assert( N>0 );
  2060. assert( pParse->iCacheLevel>=N );
  2061. pParse->iCacheLevel -= N;
  2062. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  2063. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  2064. cacheEntryClear(pParse, p);
  2065. p->iReg = 0;
  2066. }
  2067. }
  2068. }
  2069. /*
  2070. ** When a cached column is reused, make sure that its register is
  2071. ** no longer available as a temp register. ticket #3879: that same
  2072. ** register might be in the cache in multiple places, so be sure to
  2073. ** get them all.
  2074. */
  2075. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  2076. int i;
  2077. struct yColCache *p;
  2078. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  2079. if( p->iReg==iReg ){
  2080. p->tempReg = 0;
  2081. }
  2082. }
  2083. }
  2084. /*
  2085. ** Generate code to extract the value of the iCol-th column of a table.
  2086. */
  2087. void sqlite3ExprCodeGetColumnOfTable(
  2088. Vdbe *v, /* The VDBE under construction */
  2089. Table *pTab, /* The table containing the value */
  2090. int iTabCur, /* The cursor for this table */
  2091. int iCol, /* Index of the column to extract */
  2092. int regOut /* Extract the valud into this register */
  2093. ){
  2094. if( iCol<0 || iCol==pTab->iPKey ){
  2095. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  2096. }else{
  2097. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  2098. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  2099. }
  2100. if( iCol>=0 ){
  2101. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  2102. }
  2103. }
  2104. /*
  2105. ** Generate code that will extract the iColumn-th column from
  2106. ** table pTab and store the column value in a register. An effort
  2107. ** is made to store the column value in register iReg, but this is
  2108. ** not guaranteed. The location of the column value is returned.
  2109. **
  2110. ** There must be an open cursor to pTab in iTable when this routine
  2111. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  2112. */
  2113. int sqlite3ExprCodeGetColumn(
  2114. Parse *pParse, /* Parsing and code generating context */
  2115. Table *pTab, /* Description of the table we are reading from */
  2116. int iColumn, /* Index of the table column */
  2117. int iTable, /* The cursor pointing to the table */
  2118. int iReg, /* Store results here */
  2119. u8 p5 /* P5 value for OP_Column */
  2120. ){
  2121. Vdbe *v = pParse->pVdbe;
  2122. int i;
  2123. struct yColCache *p;
  2124. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  2125. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  2126. p->lru = pParse->iCacheCnt++;
  2127. sqlite3ExprCachePinRegister(pParse, p->iReg);
  2128. return p->iReg;
  2129. }
  2130. }
  2131. assert( v!=0 );
  2132. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  2133. if( p5 ){
  2134. sqlite3VdbeChangeP5(v, p5);
  2135. }else{
  2136. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  2137. }
  2138. return iReg;
  2139. }
  2140. /*
  2141. ** Clear all column cache entries.
  2142. */
  2143. void sqlite3ExprCacheClear(Parse *pParse){
  2144. int i;
  2145. struct yColCache *p;
  2146. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  2147. if( p->iReg ){
  2148. cacheEntryClear(pParse, p);
  2149. p->iReg = 0;
  2150. }
  2151. }
  2152. }
  2153. /*
  2154. ** Record the fact that an affinity change has occurred on iCount
  2155. ** registers starting with iStart.
  2156. */
  2157. void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  2158. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  2159. }
  2160. /*
  2161. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  2162. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  2163. */
  2164. void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  2165. int i;
  2166. struct yColCache *p;
  2167. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  2168. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
  2169. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  2170. int x = p->iReg;
  2171. if( x>=iFrom && x<iFrom+nReg ){
  2172. p->iReg += iTo-iFrom;
  2173. }
  2174. }
  2175. }
  2176. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  2177. /*
  2178. ** Return true if any register in the range iFrom..iTo (inclusive)
  2179. ** is used as part of the column cache.
  2180. **
  2181. ** This routine is used within assert() and testcase() macros only
  2182. ** and does not appear in a normal build.
  2183. */
  2184. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  2185. int i;
  2186. struct yColCache *p;
  2187. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  2188. int r = p->iReg;
  2189. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  2190. }
  2191. return 0;
  2192. }
  2193. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  2194. /*
  2195. ** Convert an expression node to a TK_REGISTER
  2196. */
  2197. static void exprToRegister(Expr *p, int iReg){
  2198. p->op2 = p->op;
  2199. p->op = TK_REGISTER;
  2200. p->iTable = iReg;
  2201. ExprClearProperty(p, EP_Skip);
  2202. }
  2203. /*
  2204. ** Generate code into the current Vdbe to evaluate the given
  2205. ** expression. Attempt to store the results in register "target".
  2206. ** Return the register where results are stored.
  2207. **
  2208. ** With this routine, there is no guarantee that results will
  2209. ** be stored in target. The result might be stored in some other
  2210. ** register if it is convenient to do so. The calling function
  2211. ** must check the return code and move the results to the desired
  2212. ** register.
  2213. */
  2214. int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  2215. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  2216. int op; /* The opcode being coded */
  2217. int inReg = target; /* Results stored in register inReg */
  2218. int regFree1 = 0; /* If non-zero free this temporary register */
  2219. int regFree2 = 0; /* If non-zero free this temporary register */
  2220. int r1, r2, r3, r4; /* Various register numbers */
  2221. sqlite3 *db = pParse->db; /* The database connection */
  2222. assert( target>0 && target<=pParse->nMem );
  2223. if( v==0 ){
  2224. assert( pParse->db->mallocFailed );
  2225. return 0;
  2226. }
  2227. if( pExpr==0 ){
  2228. op = TK_NULL;
  2229. }else{
  2230. op = pExpr->op;
  2231. }
  2232. switch( op ){
  2233. case TK_AGG_COLUMN: {
  2234. AggInfo *pAggInfo = pExpr->pAggInfo;
  2235. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  2236. if( !pAggInfo->directMode ){
  2237. assert( pCol->iMem>0 );
  2238. inReg = pCol->iMem;
  2239. break;
  2240. }else if( pAggInfo->useSortingIdx ){
  2241. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  2242. pCol->iSorterColumn, target);
  2243. break;
  2244. }
  2245. /* Otherwise, fall thru into the TK_COLUMN case */
  2246. }
  2247. case TK_COLUMN: {
  2248. int iTab = pExpr->iTable;
  2249. if( iTab<0 ){
  2250. if( pParse->ckBase>0 ){
  2251. /* Generating CHECK constraints or inserting into partial index */
  2252. inReg = pExpr->iColumn + pParse->ckBase;
  2253. break;
  2254. }else{
  2255. /* Deleting from a partial index */
  2256. iTab = pParse->iPartIdxTab;
  2257. }
  2258. }
  2259. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  2260. pExpr->iColumn, iTab, target,
  2261. pExpr->op2);
  2262. break;
  2263. }
  2264. case TK_INTEGER: {
  2265. codeInteger(pParse, pExpr, 0, target);
  2266. break;
  2267. }
  2268. #ifndef SQLITE_OMIT_FLOATING_POINT
  2269. case TK_FLOAT: {
  2270. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2271. codeReal(v, pExpr->u.zToken, 0, target);
  2272. break;
  2273. }
  2274. #endif
  2275. case TK_STRING: {
  2276. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2277. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  2278. break;
  2279. }
  2280. case TK_NULL: {
  2281. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  2282. break;
  2283. }
  2284. #ifndef SQLITE_OMIT_BLOB_LITERAL
  2285. case TK_BLOB: {
  2286. int n;
  2287. const char *z;
  2288. char *zBlob;
  2289. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2290. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  2291. assert( pExpr->u.zToken[1]=='\'' );
  2292. z = &pExpr->u.zToken[2];
  2293. n = sqlite3Strlen30(z) - 1;
  2294. assert( z[n]=='\'' );
  2295. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  2296. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  2297. break;
  2298. }
  2299. #endif
  2300. case TK_VARIABLE: {
  2301. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2302. assert( pExpr->u.zToken!=0 );
  2303. assert( pExpr->u.zToken[0]!=0 );
  2304. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  2305. if( pExpr->u.zToken[1]!=0 ){
  2306. assert( pExpr->u.zToken[0]=='?'
  2307. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  2308. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  2309. }
  2310. break;
  2311. }
  2312. case TK_REGISTER: {
  2313. inReg = pExpr->iTable;
  2314. break;
  2315. }
  2316. case TK_AS: {
  2317. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  2318. break;
  2319. }
  2320. #ifndef SQLITE_OMIT_CAST
  2321. case TK_CAST: {
  2322. /* Expressions of the form: CAST(pLeft AS token) */
  2323. int aff, to_op;
  2324. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  2325. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2326. aff = sqlite3AffinityType(pExpr->u.zToken, 0);
  2327. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  2328. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  2329. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  2330. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  2331. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  2332. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  2333. testcase( to_op==OP_ToText );
  2334. testcase( to_op==OP_ToBlob );
  2335. testcase( to_op==OP_ToNumeric );
  2336. testcase( to_op==OP_ToInt );
  2337. testcase( to_op==OP_ToReal );
  2338. if( inReg!=target ){
  2339. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  2340. inReg = target;
  2341. }
  2342. sqlite3VdbeAddOp1(v, to_op, inReg);
  2343. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  2344. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  2345. break;
  2346. }
  2347. #endif /* SQLITE_OMIT_CAST */
  2348. case TK_LT:
  2349. case TK_LE:
  2350. case TK_GT:
  2351. case TK_GE:
  2352. case TK_NE:
  2353. case TK_EQ: {
  2354. assert( TK_LT==OP_Lt );
  2355. assert( TK_LE==OP_Le );
  2356. assert( TK_GT==OP_Gt );
  2357. assert( TK_GE==OP_Ge );
  2358. assert( TK_EQ==OP_Eq );
  2359. assert( TK_NE==OP_Ne );
  2360. testcase( op==TK_LT );
  2361. testcase( op==TK_LE );
  2362. testcase( op==TK_GT );
  2363. testcase( op==TK_GE );
  2364. testcase( op==TK_EQ );
  2365. testcase( op==TK_NE );
  2366. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2367. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  2368. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  2369. r1, r2, inReg, SQLITE_STOREP2);
  2370. testcase( regFree1==0 );
  2371. testcase( regFree2==0 );
  2372. break;
  2373. }
  2374. case TK_IS:
  2375. case TK_ISNOT: {
  2376. testcase( op==TK_IS );
  2377. testcase( op==TK_ISNOT );
  2378. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2379. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  2380. op = (op==TK_IS) ? TK_EQ : TK_NE;
  2381. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  2382. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  2383. testcase( regFree1==0 );
  2384. testcase( regFree2==0 );
  2385. break;
  2386. }
  2387. case TK_AND:
  2388. case TK_OR:
  2389. case TK_PLUS:
  2390. case TK_STAR:
  2391. case TK_MINUS:
  2392. case TK_REM:
  2393. case TK_BITAND:
  2394. case TK_BITOR:
  2395. case TK_SLASH:
  2396. case TK_LSHIFT:
  2397. case TK_RSHIFT:
  2398. case TK_CONCAT: {
  2399. assert( TK_AND==OP_And );
  2400. assert( TK_OR==OP_Or );
  2401. assert( TK_PLUS==OP_Add );
  2402. assert( TK_MINUS==OP_Subtract );
  2403. assert( TK_REM==OP_Remainder );
  2404. assert( TK_BITAND==OP_BitAnd );
  2405. assert( TK_BITOR==OP_BitOr );
  2406. assert( TK_SLASH==OP_Divide );
  2407. assert( TK_LSHIFT==OP_ShiftLeft );
  2408. assert( TK_RSHIFT==OP_ShiftRight );
  2409. assert( TK_CONCAT==OP_Concat );
  2410. testcase( op==TK_AND );
  2411. testcase( op==TK_OR );
  2412. testcase( op==TK_PLUS );
  2413. testcase( op==TK_MINUS );
  2414. testcase( op==TK_REM );
  2415. testcase( op==TK_BITAND );
  2416. testcase( op==TK_BITOR );
  2417. testcase( op==TK_SLASH );
  2418. testcase( op==TK_LSHIFT );
  2419. testcase( op==TK_RSHIFT );
  2420. testcase( op==TK_CONCAT );
  2421. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2422. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  2423. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  2424. testcase( regFree1==0 );
  2425. testcase( regFree2==0 );
  2426. break;
  2427. }
  2428. case TK_UMINUS: {
  2429. Expr *pLeft = pExpr->pLeft;
  2430. assert( pLeft );
  2431. if( pLeft->op==TK_INTEGER ){
  2432. codeInteger(pParse, pLeft, 1, target);
  2433. #ifndef SQLITE_OMIT_FLOATING_POINT
  2434. }else if( pLeft->op==TK_FLOAT ){
  2435. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2436. codeReal(v, pLeft->u.zToken, 1, target);
  2437. #endif
  2438. }else{
  2439. regFree1 = r1 = sqlite3GetTempReg(pParse);
  2440. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  2441. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  2442. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  2443. testcase( regFree2==0 );
  2444. }
  2445. inReg = target;
  2446. break;
  2447. }
  2448. case TK_BITNOT:
  2449. case TK_NOT: {
  2450. assert( TK_BITNOT==OP_BitNot );
  2451. assert( TK_NOT==OP_Not );
  2452. testcase( op==TK_BITNOT );
  2453. testcase( op==TK_NOT );
  2454. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2455. testcase( regFree1==0 );
  2456. inReg = target;
  2457. sqlite3VdbeAddOp2(v, op, r1, inReg);
  2458. break;
  2459. }
  2460. case TK_ISNULL:
  2461. case TK_NOTNULL: {
  2462. int addr;
  2463. assert( TK_ISNULL==OP_IsNull );
  2464. assert( TK_NOTNULL==OP_NotNull );
  2465. testcase( op==TK_ISNULL );
  2466. testcase( op==TK_NOTNULL );
  2467. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  2468. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2469. testcase( regFree1==0 );
  2470. addr = sqlite3VdbeAddOp1(v, op, r1);
  2471. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  2472. sqlite3VdbeJumpHere(v, addr);
  2473. break;
  2474. }
  2475. case TK_AGG_FUNCTION: {
  2476. AggInfo *pInfo = pExpr->pAggInfo;
  2477. if( pInfo==0 ){
  2478. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2479. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  2480. }else{
  2481. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  2482. }
  2483. break;
  2484. }
  2485. case TK_CONST_FUNC:
  2486. case TK_FUNCTION: {
  2487. ExprList *pFarg; /* List of function arguments */
  2488. int nFarg; /* Number of function arguments */
  2489. FuncDef *pDef; /* The function definition object */
  2490. int nId; /* Length of the function name in bytes */
  2491. const char *zId; /* The function name */
  2492. int constMask = 0; /* Mask of function arguments that are constant */
  2493. int i; /* Loop counter */
  2494. u8 enc = ENC(db); /* The text encoding used by this database */
  2495. CollSeq *pColl = 0; /* A collating sequence */
  2496. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  2497. testcase( op==TK_CONST_FUNC );
  2498. testcase( op==TK_FUNCTION );
  2499. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  2500. pFarg = 0;
  2501. }else{
  2502. pFarg = pExpr->x.pList;
  2503. }
  2504. nFarg = pFarg ? pFarg->nExpr : 0;
  2505. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2506. zId = pExpr->u.zToken;
  2507. nId = sqlite3Strlen30(zId);
  2508. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  2509. if( pDef==0 ){
  2510. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  2511. break;
  2512. }
  2513. /* Attempt a direct implementation of the built-in COALESCE() and
  2514. ** IFNULL() functions. This avoids unnecessary evalation of
  2515. ** arguments past the first non-NULL argument.
  2516. */
  2517. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  2518. int endCoalesce = sqlite3VdbeMakeLabel(v);
  2519. assert( nFarg>=2 );
  2520. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  2521. for(i=1; i<nFarg; i++){
  2522. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  2523. sqlite3ExprCacheRemove(pParse, target, 1);
  2524. sqlite3ExprCachePush(pParse);
  2525. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  2526. sqlite3ExprCachePop(pParse, 1);
  2527. }
  2528. sqlite3VdbeResolveLabel(v, endCoalesce);
  2529. break;
  2530. }
  2531. /* The UNLIKELY() function is a no-op. The result is the value
  2532. ** of the first argument.
  2533. */
  2534. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  2535. assert( nFarg>=1 );
  2536. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  2537. break;
  2538. }
  2539. if( pFarg ){
  2540. r1 = sqlite3GetTempRange(pParse, nFarg);
  2541. /* For length() and typeof() functions with a column argument,
  2542. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  2543. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  2544. ** loading.
  2545. */
  2546. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  2547. u8 exprOp;
  2548. assert( nFarg==1 );
  2549. assert( pFarg->a[0].pExpr!=0 );
  2550. exprOp = pFarg->a[0].pExpr->op;
  2551. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  2552. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  2553. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  2554. testcase( (pDef->funcFlags&~SQLITE_FUNC_ENCMASK)
  2555. ==SQLITE_FUNC_LENGTH );
  2556. pFarg->a[0].pExpr->op2 = pDef->funcFlags&~SQLITE_FUNC_ENCMASK;
  2557. }
  2558. }
  2559. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  2560. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  2561. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  2562. }else{
  2563. r1 = 0;
  2564. }
  2565. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2566. /* Possibly overload the function if the first argument is
  2567. ** a virtual table column.
  2568. **
  2569. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  2570. ** second argument, not the first, as the argument to test to
  2571. ** see if it is a column in a virtual table. This is done because
  2572. ** the left operand of infix functions (the operand we want to
  2573. ** control overloading) ends up as the second argument to the
  2574. ** function. The expression "A glob B" is equivalent to
  2575. ** "glob(B,A). We want to use the A in "A glob B" to test
  2576. ** for function overloading. But we use the B term in "glob(B,A)".
  2577. */
  2578. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  2579. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  2580. }else if( nFarg>0 ){
  2581. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  2582. }
  2583. #endif
  2584. for(i=0; i<nFarg; i++){
  2585. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  2586. constMask |= (1<<i);
  2587. }
  2588. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  2589. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  2590. }
  2591. }
  2592. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  2593. if( !pColl ) pColl = db->pDfltColl;
  2594. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  2595. }
  2596. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  2597. (char*)pDef, P4_FUNCDEF);
  2598. sqlite3VdbeChangeP5(v, (u8)nFarg);
  2599. if( nFarg ){
  2600. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  2601. }
  2602. break;
  2603. }
  2604. #ifndef SQLITE_OMIT_SUBQUERY
  2605. case TK_EXISTS:
  2606. case TK_SELECT: {
  2607. testcase( op==TK_EXISTS );
  2608. testcase( op==TK_SELECT );
  2609. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  2610. break;
  2611. }
  2612. case TK_IN: {
  2613. int destIfFalse = sqlite3VdbeMakeLabel(v);
  2614. int destIfNull = sqlite3VdbeMakeLabel(v);
  2615. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  2616. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  2617. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  2618. sqlite3VdbeResolveLabel(v, destIfFalse);
  2619. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  2620. sqlite3VdbeResolveLabel(v, destIfNull);
  2621. break;
  2622. }
  2623. #endif /* SQLITE_OMIT_SUBQUERY */
  2624. /*
  2625. ** x BETWEEN y AND z
  2626. **
  2627. ** This is equivalent to
  2628. **
  2629. ** x>=y AND x<=z
  2630. **
  2631. ** X is stored in pExpr->pLeft.
  2632. ** Y is stored in pExpr->pList->a[0].pExpr.
  2633. ** Z is stored in pExpr->pList->a[1].pExpr.
  2634. */
  2635. case TK_BETWEEN: {
  2636. Expr *pLeft = pExpr->pLeft;
  2637. struct ExprList_item *pLItem = pExpr->x.pList->a;
  2638. Expr *pRight = pLItem->pExpr;
  2639. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  2640. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  2641. testcase( regFree1==0 );
  2642. testcase( regFree2==0 );
  2643. r3 = sqlite3GetTempReg(pParse);
  2644. r4 = sqlite3GetTempReg(pParse);
  2645. codeCompare(pParse, pLeft, pRight, OP_Ge,
  2646. r1, r2, r3, SQLITE_STOREP2);
  2647. pLItem++;
  2648. pRight = pLItem->pExpr;
  2649. sqlite3ReleaseTempReg(pParse, regFree2);
  2650. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  2651. testcase( regFree2==0 );
  2652. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  2653. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  2654. sqlite3ReleaseTempReg(pParse, r3);
  2655. sqlite3ReleaseTempReg(pParse, r4);
  2656. break;
  2657. }
  2658. case TK_COLLATE:
  2659. case TK_UPLUS: {
  2660. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  2661. break;
  2662. }
  2663. case TK_TRIGGER: {
  2664. /* If the opcode is TK_TRIGGER, then the expression is a reference
  2665. ** to a column in the new.* or old.* pseudo-tables available to
  2666. ** trigger programs. In this case Expr.iTable is set to 1 for the
  2667. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  2668. ** is set to the column of the pseudo-table to read, or to -1 to
  2669. ** read the rowid field.
  2670. **
  2671. ** The expression is implemented using an OP_Param opcode. The p1
  2672. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  2673. ** to reference another column of the old.* pseudo-table, where
  2674. ** i is the index of the column. For a new.rowid reference, p1 is
  2675. ** set to (n+1), where n is the number of columns in each pseudo-table.
  2676. ** For a reference to any other column in the new.* pseudo-table, p1
  2677. ** is set to (n+2+i), where n and i are as defined previously. For
  2678. ** example, if the table on which triggers are being fired is
  2679. ** declared as:
  2680. **
  2681. ** CREATE TABLE t1(a, b);
  2682. **
  2683. ** Then p1 is interpreted as follows:
  2684. **
  2685. ** p1==0 -> old.rowid p1==3 -> new.rowid
  2686. ** p1==1 -> old.a p1==4 -> new.a
  2687. ** p1==2 -> old.b p1==5 -> new.b
  2688. */
  2689. Table *pTab = pExpr->pTab;
  2690. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  2691. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  2692. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  2693. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  2694. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  2695. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  2696. VdbeComment((v, "%s.%s -> $%d",
  2697. (pExpr->iTable ? "new" : "old"),
  2698. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  2699. target
  2700. ));
  2701. #ifndef SQLITE_OMIT_FLOATING_POINT
  2702. /* If the column has REAL affinity, it may currently be stored as an
  2703. ** integer. Use OP_RealAffinity to make sure it is really real. */
  2704. if( pExpr->iColumn>=0
  2705. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  2706. ){
  2707. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  2708. }
  2709. #endif
  2710. break;
  2711. }
  2712. /*
  2713. ** Form A:
  2714. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  2715. **
  2716. ** Form B:
  2717. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  2718. **
  2719. ** Form A is can be transformed into the equivalent form B as follows:
  2720. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  2721. ** WHEN x=eN THEN rN ELSE y END
  2722. **
  2723. ** X (if it exists) is in pExpr->pLeft.
  2724. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  2725. ** odd. The Y is also optional. If the number of elements in x.pList
  2726. ** is even, then Y is omitted and the "otherwise" result is NULL.
  2727. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  2728. **
  2729. ** The result of the expression is the Ri for the first matching Ei,
  2730. ** or if there is no matching Ei, the ELSE term Y, or if there is
  2731. ** no ELSE term, NULL.
  2732. */
  2733. default: assert( op==TK_CASE ); {
  2734. int endLabel; /* GOTO label for end of CASE stmt */
  2735. int nextCase; /* GOTO label for next WHEN clause */
  2736. int nExpr; /* 2x number of WHEN terms */
  2737. int i; /* Loop counter */
  2738. ExprList *pEList; /* List of WHEN terms */
  2739. struct ExprList_item *aListelem; /* Array of WHEN terms */
  2740. Expr opCompare; /* The X==Ei expression */
  2741. Expr cacheX; /* Cached expression X */
  2742. Expr *pX; /* The X expression */
  2743. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  2744. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  2745. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  2746. assert(pExpr->x.pList->nExpr > 0);
  2747. pEList = pExpr->x.pList;
  2748. aListelem = pEList->a;
  2749. nExpr = pEList->nExpr;
  2750. endLabel = sqlite3VdbeMakeLabel(v);
  2751. if( (pX = pExpr->pLeft)!=0 ){
  2752. cacheX = *pX;
  2753. testcase( pX->op==TK_COLUMN );
  2754. testcase( pX->op==TK_REGISTER );
  2755. exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  2756. testcase( regFree1==0 );
  2757. opCompare.op = TK_EQ;
  2758. opCompare.pLeft = &cacheX;
  2759. pTest = &opCompare;
  2760. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  2761. ** The value in regFree1 might get SCopy-ed into the file result.
  2762. ** So make sure that the regFree1 register is not reused for other
  2763. ** purposes and possibly overwritten. */
  2764. regFree1 = 0;
  2765. }
  2766. for(i=0; i<nExpr-1; i=i+2){
  2767. sqlite3ExprCachePush(pParse);
  2768. if( pX ){
  2769. assert( pTest!=0 );
  2770. opCompare.pRight = aListelem[i].pExpr;
  2771. }else{
  2772. pTest = aListelem[i].pExpr;
  2773. }
  2774. nextCase = sqlite3VdbeMakeLabel(v);
  2775. testcase( pTest->op==TK_COLUMN );
  2776. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  2777. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  2778. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  2779. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  2780. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  2781. sqlite3ExprCachePop(pParse, 1);
  2782. sqlite3VdbeResolveLabel(v, nextCase);
  2783. }
  2784. if( (nExpr&1)!=0 ){
  2785. sqlite3ExprCachePush(pParse);
  2786. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  2787. sqlite3ExprCachePop(pParse, 1);
  2788. }else{
  2789. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  2790. }
  2791. assert( db->mallocFailed || pParse->nErr>0
  2792. || pParse->iCacheLevel==iCacheLevel );
  2793. sqlite3VdbeResolveLabel(v, endLabel);
  2794. break;
  2795. }
  2796. #ifndef SQLITE_OMIT_TRIGGER
  2797. case TK_RAISE: {
  2798. assert( pExpr->affinity==OE_Rollback
  2799. || pExpr->affinity==OE_Abort
  2800. || pExpr->affinity==OE_Fail
  2801. || pExpr->affinity==OE_Ignore
  2802. );
  2803. if( !pParse->pTriggerTab ){
  2804. sqlite3ErrorMsg(pParse,
  2805. "RAISE() may only be used within a trigger-program");
  2806. return 0;
  2807. }
  2808. if( pExpr->affinity==OE_Abort ){
  2809. sqlite3MayAbort(pParse);
  2810. }
  2811. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2812. if( pExpr->affinity==OE_Ignore ){
  2813. sqlite3VdbeAddOp4(
  2814. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  2815. }else{
  2816. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  2817. pExpr->affinity, pExpr->u.zToken, 0);
  2818. }
  2819. break;
  2820. }
  2821. #endif
  2822. }
  2823. sqlite3ReleaseTempReg(pParse, regFree1);
  2824. sqlite3ReleaseTempReg(pParse, regFree2);
  2825. return inReg;
  2826. }
  2827. /*
  2828. ** Generate code to evaluate an expression and store the results
  2829. ** into a register. Return the register number where the results
  2830. ** are stored.
  2831. **
  2832. ** If the register is a temporary register that can be deallocated,
  2833. ** then write its number into *pReg. If the result register is not
  2834. ** a temporary, then set *pReg to zero.
  2835. */
  2836. int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  2837. int r1 = sqlite3GetTempReg(pParse);
  2838. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  2839. if( r2==r1 ){
  2840. *pReg = r1;
  2841. }else{
  2842. sqlite3ReleaseTempReg(pParse, r1);
  2843. *pReg = 0;
  2844. }
  2845. return r2;
  2846. }
  2847. /*
  2848. ** Generate code that will evaluate expression pExpr and store the
  2849. ** results in register target. The results are guaranteed to appear
  2850. ** in register target.
  2851. */
  2852. int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  2853. int inReg;
  2854. assert( target>0 && target<=pParse->nMem );
  2855. if( pExpr && pExpr->op==TK_REGISTER ){
  2856. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  2857. }else{
  2858. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  2859. assert( pParse->pVdbe || pParse->db->mallocFailed );
  2860. if( inReg!=target && pParse->pVdbe ){
  2861. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  2862. }
  2863. }
  2864. return target;
  2865. }
  2866. /*
  2867. ** Generate code that evalutes the given expression and puts the result
  2868. ** in register target.
  2869. **
  2870. ** Also make a copy of the expression results into another "cache" register
  2871. ** and modify the expression so that the next time it is evaluated,
  2872. ** the result is a copy of the cache register.
  2873. **
  2874. ** This routine is used for expressions that are used multiple
  2875. ** times. They are evaluated once and the results of the expression
  2876. ** are reused.
  2877. */
  2878. int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  2879. Vdbe *v = pParse->pVdbe;
  2880. int inReg;
  2881. inReg = sqlite3ExprCode(pParse, pExpr, target);
  2882. assert( target>0 );
  2883. /* This routine is called for terms to INSERT or UPDATE. And the only
  2884. ** other place where expressions can be converted into TK_REGISTER is
  2885. ** in WHERE clause processing. So as currently implemented, there is
  2886. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  2887. ** keep the ALWAYS() in case the conditions above change with future
  2888. ** modifications or enhancements. */
  2889. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  2890. int iMem;
  2891. iMem = ++pParse->nMem;
  2892. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  2893. exprToRegister(pExpr, iMem);
  2894. }
  2895. return inReg;
  2896. }
  2897. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  2898. /*
  2899. ** Generate a human-readable explanation of an expression tree.
  2900. */
  2901. void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
  2902. int op; /* The opcode being coded */
  2903. const char *zBinOp = 0; /* Binary operator */
  2904. const char *zUniOp = 0; /* Unary operator */
  2905. if( pExpr==0 ){
  2906. op = TK_NULL;
  2907. }else{
  2908. op = pExpr->op;
  2909. }
  2910. switch( op ){
  2911. case TK_AGG_COLUMN: {
  2912. sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
  2913. pExpr->iTable, pExpr->iColumn);
  2914. break;
  2915. }
  2916. case TK_COLUMN: {
  2917. if( pExpr->iTable<0 ){
  2918. /* This only happens when coding check constraints */
  2919. sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
  2920. }else{
  2921. sqlite3ExplainPrintf(pOut, "{%d:%d}",
  2922. pExpr->iTable, pExpr->iColumn);
  2923. }
  2924. break;
  2925. }
  2926. case TK_INTEGER: {
  2927. if( pExpr->flags & EP_IntValue ){
  2928. sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
  2929. }else{
  2930. sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
  2931. }
  2932. break;
  2933. }
  2934. #ifndef SQLITE_OMIT_FLOATING_POINT
  2935. case TK_FLOAT: {
  2936. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  2937. break;
  2938. }
  2939. #endif
  2940. case TK_STRING: {
  2941. sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
  2942. break;
  2943. }
  2944. case TK_NULL: {
  2945. sqlite3ExplainPrintf(pOut,"NULL");
  2946. break;
  2947. }
  2948. #ifndef SQLITE_OMIT_BLOB_LITERAL
  2949. case TK_BLOB: {
  2950. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  2951. break;
  2952. }
  2953. #endif
  2954. case TK_VARIABLE: {
  2955. sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
  2956. pExpr->u.zToken, pExpr->iColumn);
  2957. break;
  2958. }
  2959. case TK_REGISTER: {
  2960. sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
  2961. break;
  2962. }
  2963. case TK_AS: {
  2964. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  2965. break;
  2966. }
  2967. #ifndef SQLITE_OMIT_CAST
  2968. case TK_CAST: {
  2969. /* Expressions of the form: CAST(pLeft AS token) */
  2970. const char *zAff = "unk";
  2971. switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
  2972. case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
  2973. case SQLITE_AFF_NONE: zAff = "NONE"; break;
  2974. case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
  2975. case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
  2976. case SQLITE_AFF_REAL: zAff = "REAL"; break;
  2977. }
  2978. sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
  2979. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  2980. sqlite3ExplainPrintf(pOut, ")");
  2981. break;
  2982. }
  2983. #endif /* SQLITE_OMIT_CAST */
  2984. case TK_LT: zBinOp = "LT"; break;
  2985. case TK_LE: zBinOp = "LE"; break;
  2986. case TK_GT: zBinOp = "GT"; break;
  2987. case TK_GE: zBinOp = "GE"; break;
  2988. case TK_NE: zBinOp = "NE"; break;
  2989. case TK_EQ: zBinOp = "EQ"; break;
  2990. case TK_IS: zBinOp = "IS"; break;
  2991. case TK_ISNOT: zBinOp = "ISNOT"; break;
  2992. case TK_AND: zBinOp = "AND"; break;
  2993. case TK_OR: zBinOp = "OR"; break;
  2994. case TK_PLUS: zBinOp = "ADD"; break;
  2995. case TK_STAR: zBinOp = "MUL"; break;
  2996. case TK_MINUS: zBinOp = "SUB"; break;
  2997. case TK_REM: zBinOp = "REM"; break;
  2998. case TK_BITAND: zBinOp = "BITAND"; break;
  2999. case TK_BITOR: zBinOp = "BITOR"; break;
  3000. case TK_SLASH: zBinOp = "DIV"; break;
  3001. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  3002. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  3003. case TK_CONCAT: zBinOp = "CONCAT"; break;
  3004. case TK_UMINUS: zUniOp = "UMINUS"; break;
  3005. case TK_UPLUS: zUniOp = "UPLUS"; break;
  3006. case TK_BITNOT: zUniOp = "BITNOT"; break;
  3007. case TK_NOT: zUniOp = "NOT"; break;
  3008. case TK_ISNULL: zUniOp = "ISNULL"; break;
  3009. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  3010. case TK_COLLATE: {
  3011. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  3012. sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
  3013. break;
  3014. }
  3015. case TK_AGG_FUNCTION:
  3016. case TK_CONST_FUNC:
  3017. case TK_FUNCTION: {
  3018. ExprList *pFarg; /* List of function arguments */
  3019. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  3020. pFarg = 0;
  3021. }else{
  3022. pFarg = pExpr->x.pList;
  3023. }
  3024. if( op==TK_AGG_FUNCTION ){
  3025. sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
  3026. pExpr->op2, pExpr->u.zToken);
  3027. }else{
  3028. sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
  3029. }
  3030. if( pFarg ){
  3031. sqlite3ExplainExprList(pOut, pFarg);
  3032. }
  3033. sqlite3ExplainPrintf(pOut, ")");
  3034. break;
  3035. }
  3036. #ifndef SQLITE_OMIT_SUBQUERY
  3037. case TK_EXISTS: {
  3038. sqlite3ExplainPrintf(pOut, "EXISTS(");
  3039. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  3040. sqlite3ExplainPrintf(pOut,")");
  3041. break;
  3042. }
  3043. case TK_SELECT: {
  3044. sqlite3ExplainPrintf(pOut, "(");
  3045. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  3046. sqlite3ExplainPrintf(pOut, ")");
  3047. break;
  3048. }
  3049. case TK_IN: {
  3050. sqlite3ExplainPrintf(pOut, "IN(");
  3051. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  3052. sqlite3ExplainPrintf(pOut, ",");
  3053. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  3054. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  3055. }else{
  3056. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  3057. }
  3058. sqlite3ExplainPrintf(pOut, ")");
  3059. break;
  3060. }
  3061. #endif /* SQLITE_OMIT_SUBQUERY */
  3062. /*
  3063. ** x BETWEEN y AND z
  3064. **
  3065. ** This is equivalent to
  3066. **
  3067. ** x>=y AND x<=z
  3068. **
  3069. ** X is stored in pExpr->pLeft.
  3070. ** Y is stored in pExpr->pList->a[0].pExpr.
  3071. ** Z is stored in pExpr->pList->a[1].pExpr.
  3072. */
  3073. case TK_BETWEEN: {
  3074. Expr *pX = pExpr->pLeft;
  3075. Expr *pY = pExpr->x.pList->a[0].pExpr;
  3076. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  3077. sqlite3ExplainPrintf(pOut, "BETWEEN(");
  3078. sqlite3ExplainExpr(pOut, pX);
  3079. sqlite3ExplainPrintf(pOut, ",");
  3080. sqlite3ExplainExpr(pOut, pY);
  3081. sqlite3ExplainPrintf(pOut, ",");
  3082. sqlite3ExplainExpr(pOut, pZ);
  3083. sqlite3ExplainPrintf(pOut, ")");
  3084. break;
  3085. }
  3086. case TK_TRIGGER: {
  3087. /* If the opcode is TK_TRIGGER, then the expression is a reference
  3088. ** to a column in the new.* or old.* pseudo-tables available to
  3089. ** trigger programs. In this case Expr.iTable is set to 1 for the
  3090. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  3091. ** is set to the column of the pseudo-table to read, or to -1 to
  3092. ** read the rowid field.
  3093. */
  3094. sqlite3ExplainPrintf(pOut, "%s(%d)",
  3095. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  3096. break;
  3097. }
  3098. case TK_CASE: {
  3099. sqlite3ExplainPrintf(pOut, "CASE(");
  3100. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  3101. sqlite3ExplainPrintf(pOut, ",");
  3102. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  3103. break;
  3104. }
  3105. #ifndef SQLITE_OMIT_TRIGGER
  3106. case TK_RAISE: {
  3107. const char *zType = "unk";
  3108. switch( pExpr->affinity ){
  3109. case OE_Rollback: zType = "rollback"; break;
  3110. case OE_Abort: zType = "abort"; break;
  3111. case OE_Fail: zType = "fail"; break;
  3112. case OE_Ignore: zType = "ignore"; break;
  3113. }
  3114. sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
  3115. break;
  3116. }
  3117. #endif
  3118. }
  3119. if( zBinOp ){
  3120. sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
  3121. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  3122. sqlite3ExplainPrintf(pOut,",");
  3123. sqlite3ExplainExpr(pOut, pExpr->pRight);
  3124. sqlite3ExplainPrintf(pOut,")");
  3125. }else if( zUniOp ){
  3126. sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
  3127. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  3128. sqlite3ExplainPrintf(pOut,")");
  3129. }
  3130. }
  3131. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  3132. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  3133. /*
  3134. ** Generate a human-readable explanation of an expression list.
  3135. */
  3136. void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
  3137. int i;
  3138. if( pList==0 || pList->nExpr==0 ){
  3139. sqlite3ExplainPrintf(pOut, "(empty-list)");
  3140. return;
  3141. }else if( pList->nExpr==1 ){
  3142. sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
  3143. }else{
  3144. sqlite3ExplainPush(pOut);
  3145. for(i=0; i<pList->nExpr; i++){
  3146. sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
  3147. sqlite3ExplainPush(pOut);
  3148. sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
  3149. sqlite3ExplainPop(pOut);
  3150. if( pList->a[i].zName ){
  3151. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  3152. }
  3153. if( pList->a[i].bSpanIsTab ){
  3154. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  3155. }
  3156. if( i<pList->nExpr-1 ){
  3157. sqlite3ExplainNL(pOut);
  3158. }
  3159. }
  3160. sqlite3ExplainPop(pOut);
  3161. }
  3162. }
  3163. #endif /* SQLITE_DEBUG */
  3164. /*
  3165. ** Return TRUE if pExpr is an constant expression that is appropriate
  3166. ** for factoring out of a loop. Appropriate expressions are:
  3167. **
  3168. ** * Any expression that evaluates to two or more opcodes.
  3169. **
  3170. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  3171. ** or OP_Variable that does not need to be placed in a
  3172. ** specific register.
  3173. **
  3174. ** There is no point in factoring out single-instruction constant
  3175. ** expressions that need to be placed in a particular register.
  3176. ** We could factor them out, but then we would end up adding an
  3177. ** OP_SCopy instruction to move the value into the correct register
  3178. ** later. We might as well just use the original instruction and
  3179. ** avoid the OP_SCopy.
  3180. */
  3181. static int isAppropriateForFactoring(Expr *p){
  3182. if( !sqlite3ExprIsConstantNotJoin(p) ){
  3183. return 0; /* Only constant expressions are appropriate for factoring */
  3184. }
  3185. if( (p->flags & EP_FixedDest)==0 ){
  3186. return 1; /* Any constant without a fixed destination is appropriate */
  3187. }
  3188. while( p->op==TK_UPLUS ) p = p->pLeft;
  3189. switch( p->op ){
  3190. #ifndef SQLITE_OMIT_BLOB_LITERAL
  3191. case TK_BLOB:
  3192. #endif
  3193. case TK_VARIABLE:
  3194. case TK_INTEGER:
  3195. case TK_FLOAT:
  3196. case TK_NULL:
  3197. case TK_STRING: {
  3198. testcase( p->op==TK_BLOB );
  3199. testcase( p->op==TK_VARIABLE );
  3200. testcase( p->op==TK_INTEGER );
  3201. testcase( p->op==TK_FLOAT );
  3202. testcase( p->op==TK_NULL );
  3203. testcase( p->op==TK_STRING );
  3204. /* Single-instruction constants with a fixed destination are
  3205. ** better done in-line. If we factor them, they will just end
  3206. ** up generating an OP_SCopy to move the value to the destination
  3207. ** register. */
  3208. return 0;
  3209. }
  3210. case TK_UMINUS: {
  3211. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  3212. return 0;
  3213. }
  3214. break;
  3215. }
  3216. default: {
  3217. break;
  3218. }
  3219. }
  3220. return 1;
  3221. }
  3222. /*
  3223. ** If pExpr is a constant expression that is appropriate for
  3224. ** factoring out of a loop, then evaluate the expression
  3225. ** into a register and convert the expression into a TK_REGISTER
  3226. ** expression.
  3227. */
  3228. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  3229. Parse *pParse = pWalker->pParse;
  3230. switch( pExpr->op ){
  3231. case TK_IN:
  3232. case TK_REGISTER: {
  3233. return WRC_Prune;
  3234. }
  3235. case TK_COLLATE: {
  3236. return WRC_Continue;
  3237. }
  3238. case TK_FUNCTION:
  3239. case TK_AGG_FUNCTION:
  3240. case TK_CONST_FUNC: {
  3241. /* The arguments to a function have a fixed destination.
  3242. ** Mark them this way to avoid generated unneeded OP_SCopy
  3243. ** instructions.
  3244. */
  3245. ExprList *pList = pExpr->x.pList;
  3246. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  3247. if( pList ){
  3248. int i = pList->nExpr;
  3249. struct ExprList_item *pItem = pList->a;
  3250. for(; i>0; i--, pItem++){
  3251. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  3252. }
  3253. }
  3254. break;
  3255. }
  3256. }
  3257. if( isAppropriateForFactoring(pExpr) ){
  3258. int r1 = ++pParse->nMem;
  3259. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  3260. /* If r2!=r1, it means that register r1 is never used. That is harmless
  3261. ** but suboptimal, so we want to know about the situation to fix it.
  3262. ** Hence the following assert: */
  3263. assert( r2==r1 );
  3264. exprToRegister(pExpr, r2);
  3265. return WRC_Prune;
  3266. }
  3267. return WRC_Continue;
  3268. }
  3269. /*
  3270. ** Preevaluate constant subexpressions within pExpr and store the
  3271. ** results in registers. Modify pExpr so that the constant subexpresions
  3272. ** are TK_REGISTER opcodes that refer to the precomputed values.
  3273. **
  3274. ** This routine is a no-op if the jump to the cookie-check code has
  3275. ** already occur. Since the cookie-check jump is generated prior to
  3276. ** any other serious processing, this check ensures that there is no
  3277. ** way to accidently bypass the constant initializations.
  3278. **
  3279. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  3280. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  3281. ** interface. This allows test logic to verify that the same answer is
  3282. ** obtained for queries regardless of whether or not constants are
  3283. ** precomputed into registers or if they are inserted in-line.
  3284. */
  3285. void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  3286. Walker w;
  3287. if( pParse->cookieGoto ) return;
  3288. if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  3289. memset(&w, 0, sizeof(w));
  3290. w.xExprCallback = evalConstExpr;
  3291. w.pParse = pParse;
  3292. sqlite3WalkExpr(&w, pExpr);
  3293. }
  3294. /*
  3295. ** Generate code that pushes the value of every element of the given
  3296. ** expression list into a sequence of registers beginning at target.
  3297. **
  3298. ** Return the number of elements evaluated.
  3299. */
  3300. int sqlite3ExprCodeExprList(
  3301. Parse *pParse, /* Parsing context */
  3302. ExprList *pList, /* The expression list to be coded */
  3303. int target, /* Where to write results */
  3304. int doHardCopy /* Make a hard copy of every element */
  3305. ){
  3306. struct ExprList_item *pItem;
  3307. int i, n;
  3308. assert( pList!=0 );
  3309. assert( target>0 );
  3310. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  3311. n = pList->nExpr;
  3312. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  3313. Expr *pExpr = pItem->pExpr;
  3314. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  3315. if( inReg!=target+i ){
  3316. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  3317. inReg, target+i);
  3318. }
  3319. }
  3320. return n;
  3321. }
  3322. /*
  3323. ** Generate code for a BETWEEN operator.
  3324. **
  3325. ** x BETWEEN y AND z
  3326. **
  3327. ** The above is equivalent to
  3328. **
  3329. ** x>=y AND x<=z
  3330. **
  3331. ** Code it as such, taking care to do the common subexpression
  3332. ** elementation of x.
  3333. */
  3334. static void exprCodeBetween(
  3335. Parse *pParse, /* Parsing and code generating context */
  3336. Expr *pExpr, /* The BETWEEN expression */
  3337. int dest, /* Jump here if the jump is taken */
  3338. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  3339. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  3340. ){
  3341. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  3342. Expr compLeft; /* The x>=y term */
  3343. Expr compRight; /* The x<=z term */
  3344. Expr exprX; /* The x subexpression */
  3345. int regFree1 = 0; /* Temporary use register */
  3346. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  3347. exprX = *pExpr->pLeft;
  3348. exprAnd.op = TK_AND;
  3349. exprAnd.pLeft = &compLeft;
  3350. exprAnd.pRight = &compRight;
  3351. compLeft.op = TK_GE;
  3352. compLeft.pLeft = &exprX;
  3353. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  3354. compRight.op = TK_LE;
  3355. compRight.pLeft = &exprX;
  3356. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  3357. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  3358. if( jumpIfTrue ){
  3359. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  3360. }else{
  3361. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  3362. }
  3363. sqlite3ReleaseTempReg(pParse, regFree1);
  3364. /* Ensure adequate test coverage */
  3365. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  3366. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  3367. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  3368. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  3369. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  3370. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  3371. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  3372. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  3373. }
  3374. /*
  3375. ** Generate code for a boolean expression such that a jump is made
  3376. ** to the label "dest" if the expression is true but execution
  3377. ** continues straight thru if the expression is false.
  3378. **
  3379. ** If the expression evaluates to NULL (neither true nor false), then
  3380. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  3381. **
  3382. ** This code depends on the fact that certain token values (ex: TK_EQ)
  3383. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  3384. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  3385. ** the make process cause these values to align. Assert()s in the code
  3386. ** below verify that the numbers are aligned correctly.
  3387. */
  3388. void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  3389. Vdbe *v = pParse->pVdbe;
  3390. int op = 0;
  3391. int regFree1 = 0;
  3392. int regFree2 = 0;
  3393. int r1, r2;
  3394. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  3395. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  3396. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  3397. op = pExpr->op;
  3398. switch( op ){
  3399. case TK_AND: {
  3400. int d2 = sqlite3VdbeMakeLabel(v);
  3401. testcase( jumpIfNull==0 );
  3402. sqlite3ExprCachePush(pParse);
  3403. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  3404. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  3405. sqlite3VdbeResolveLabel(v, d2);
  3406. sqlite3ExprCachePop(pParse, 1);
  3407. break;
  3408. }
  3409. case TK_OR: {
  3410. testcase( jumpIfNull==0 );
  3411. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  3412. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  3413. break;
  3414. }
  3415. case TK_NOT: {
  3416. testcase( jumpIfNull==0 );
  3417. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  3418. break;
  3419. }
  3420. case TK_LT:
  3421. case TK_LE:
  3422. case TK_GT:
  3423. case TK_GE:
  3424. case TK_NE:
  3425. case TK_EQ: {
  3426. assert( TK_LT==OP_Lt );
  3427. assert( TK_LE==OP_Le );
  3428. assert( TK_GT==OP_Gt );
  3429. assert( TK_GE==OP_Ge );
  3430. assert( TK_EQ==OP_Eq );
  3431. assert( TK_NE==OP_Ne );
  3432. testcase( op==TK_LT );
  3433. testcase( op==TK_LE );
  3434. testcase( op==TK_GT );
  3435. testcase( op==TK_GE );
  3436. testcase( op==TK_EQ );
  3437. testcase( op==TK_NE );
  3438. testcase( jumpIfNull==0 );
  3439. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3440. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  3441. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  3442. r1, r2, dest, jumpIfNull);
  3443. testcase( regFree1==0 );
  3444. testcase( regFree2==0 );
  3445. break;
  3446. }
  3447. case TK_IS:
  3448. case TK_ISNOT: {
  3449. testcase( op==TK_IS );
  3450. testcase( op==TK_ISNOT );
  3451. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3452. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  3453. op = (op==TK_IS) ? TK_EQ : TK_NE;
  3454. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  3455. r1, r2, dest, SQLITE_NULLEQ);
  3456. testcase( regFree1==0 );
  3457. testcase( regFree2==0 );
  3458. break;
  3459. }
  3460. case TK_ISNULL:
  3461. case TK_NOTNULL: {
  3462. assert( TK_ISNULL==OP_IsNull );
  3463. assert( TK_NOTNULL==OP_NotNull );
  3464. testcase( op==TK_ISNULL );
  3465. testcase( op==TK_NOTNULL );
  3466. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3467. sqlite3VdbeAddOp2(v, op, r1, dest);
  3468. testcase( regFree1==0 );
  3469. break;
  3470. }
  3471. case TK_BETWEEN: {
  3472. testcase( jumpIfNull==0 );
  3473. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  3474. break;
  3475. }
  3476. #ifndef SQLITE_OMIT_SUBQUERY
  3477. case TK_IN: {
  3478. int destIfFalse = sqlite3VdbeMakeLabel(v);
  3479. int destIfNull = jumpIfNull ? dest : destIfFalse;
  3480. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  3481. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  3482. sqlite3VdbeResolveLabel(v, destIfFalse);
  3483. break;
  3484. }
  3485. #endif
  3486. default: {
  3487. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  3488. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  3489. testcase( regFree1==0 );
  3490. testcase( jumpIfNull==0 );
  3491. break;
  3492. }
  3493. }
  3494. sqlite3ReleaseTempReg(pParse, regFree1);
  3495. sqlite3ReleaseTempReg(pParse, regFree2);
  3496. }
  3497. /*
  3498. ** Generate code for a boolean expression such that a jump is made
  3499. ** to the label "dest" if the expression is false but execution
  3500. ** continues straight thru if the expression is true.
  3501. **
  3502. ** If the expression evaluates to NULL (neither true nor false) then
  3503. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  3504. ** is 0.
  3505. */
  3506. void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  3507. Vdbe *v = pParse->pVdbe;
  3508. int op = 0;
  3509. int regFree1 = 0;
  3510. int regFree2 = 0;
  3511. int r1, r2;
  3512. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  3513. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  3514. if( pExpr==0 ) return;
  3515. /* The value of pExpr->op and op are related as follows:
  3516. **
  3517. ** pExpr->op op
  3518. ** --------- ----------
  3519. ** TK_ISNULL OP_NotNull
  3520. ** TK_NOTNULL OP_IsNull
  3521. ** TK_NE OP_Eq
  3522. ** TK_EQ OP_Ne
  3523. ** TK_GT OP_Le
  3524. ** TK_LE OP_Gt
  3525. ** TK_GE OP_Lt
  3526. ** TK_LT OP_Ge
  3527. **
  3528. ** For other values of pExpr->op, op is undefined and unused.
  3529. ** The value of TK_ and OP_ constants are arranged such that we
  3530. ** can compute the mapping above using the following expression.
  3531. ** Assert()s verify that the computation is correct.
  3532. */
  3533. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  3534. /* Verify correct alignment of TK_ and OP_ constants
  3535. */
  3536. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  3537. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  3538. assert( pExpr->op!=TK_NE || op==OP_Eq );
  3539. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  3540. assert( pExpr->op!=TK_LT || op==OP_Ge );
  3541. assert( pExpr->op!=TK_LE || op==OP_Gt );
  3542. assert( pExpr->op!=TK_GT || op==OP_Le );
  3543. assert( pExpr->op!=TK_GE || op==OP_Lt );
  3544. switch( pExpr->op ){
  3545. case TK_AND: {
  3546. testcase( jumpIfNull==0 );
  3547. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  3548. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  3549. break;
  3550. }
  3551. case TK_OR: {
  3552. int d2 = sqlite3VdbeMakeLabel(v);
  3553. testcase( jumpIfNull==0 );
  3554. sqlite3ExprCachePush(pParse);
  3555. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  3556. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  3557. sqlite3VdbeResolveLabel(v, d2);
  3558. sqlite3ExprCachePop(pParse, 1);
  3559. break;
  3560. }
  3561. case TK_NOT: {
  3562. testcase( jumpIfNull==0 );
  3563. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  3564. break;
  3565. }
  3566. case TK_LT:
  3567. case TK_LE:
  3568. case TK_GT:
  3569. case TK_GE:
  3570. case TK_NE:
  3571. case TK_EQ: {
  3572. testcase( op==TK_LT );
  3573. testcase( op==TK_LE );
  3574. testcase( op==TK_GT );
  3575. testcase( op==TK_GE );
  3576. testcase( op==TK_EQ );
  3577. testcase( op==TK_NE );
  3578. testcase( jumpIfNull==0 );
  3579. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3580. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  3581. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  3582. r1, r2, dest, jumpIfNull);
  3583. testcase( regFree1==0 );
  3584. testcase( regFree2==0 );
  3585. break;
  3586. }
  3587. case TK_IS:
  3588. case TK_ISNOT: {
  3589. testcase( pExpr->op==TK_IS );
  3590. testcase( pExpr->op==TK_ISNOT );
  3591. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3592. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  3593. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  3594. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  3595. r1, r2, dest, SQLITE_NULLEQ);
  3596. testcase( regFree1==0 );
  3597. testcase( regFree2==0 );
  3598. break;
  3599. }
  3600. case TK_ISNULL:
  3601. case TK_NOTNULL: {
  3602. testcase( op==TK_ISNULL );
  3603. testcase( op==TK_NOTNULL );
  3604. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3605. sqlite3VdbeAddOp2(v, op, r1, dest);
  3606. testcase( regFree1==0 );
  3607. break;
  3608. }
  3609. case TK_BETWEEN: {
  3610. testcase( jumpIfNull==0 );
  3611. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  3612. break;
  3613. }
  3614. #ifndef SQLITE_OMIT_SUBQUERY
  3615. case TK_IN: {
  3616. if( jumpIfNull ){
  3617. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  3618. }else{
  3619. int destIfNull = sqlite3VdbeMakeLabel(v);
  3620. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  3621. sqlite3VdbeResolveLabel(v, destIfNull);
  3622. }
  3623. break;
  3624. }
  3625. #endif
  3626. default: {
  3627. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  3628. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  3629. testcase( regFree1==0 );
  3630. testcase( jumpIfNull==0 );
  3631. break;
  3632. }
  3633. }
  3634. sqlite3ReleaseTempReg(pParse, regFree1);
  3635. sqlite3ReleaseTempReg(pParse, regFree2);
  3636. }
  3637. /*
  3638. ** Do a deep comparison of two expression trees. Return 0 if the two
  3639. ** expressions are completely identical. Return 1 if they differ only
  3640. ** by a COLLATE operator at the top level. Return 2 if there are differences
  3641. ** other than the top-level COLLATE operator.
  3642. **
  3643. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  3644. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  3645. **
  3646. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  3647. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  3648. **
  3649. ** Sometimes this routine will return 2 even if the two expressions
  3650. ** really are equivalent. If we cannot prove that the expressions are
  3651. ** identical, we return 2 just to be safe. So if this routine
  3652. ** returns 2, then you do not really know for certain if the two
  3653. ** expressions are the same. But if you get a 0 or 1 return, then you
  3654. ** can be sure the expressions are the same. In the places where
  3655. ** this routine is used, it does not hurt to get an extra 2 - that
  3656. ** just might result in some slightly slower code. But returning
  3657. ** an incorrect 0 or 1 could lead to a malfunction.
  3658. */
  3659. int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  3660. if( pA==0||pB==0 ){
  3661. return pB==pA ? 0 : 2;
  3662. }
  3663. assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) );
  3664. assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) );
  3665. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  3666. return 2;
  3667. }
  3668. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  3669. if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
  3670. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  3671. return 1;
  3672. }
  3673. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  3674. return 1;
  3675. }
  3676. return 2;
  3677. }
  3678. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  3679. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  3680. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  3681. if( pA->iColumn!=pB->iColumn ) return 2;
  3682. if( pA->iTable!=pB->iTable
  3683. && pA->op!=TK_REGISTER
  3684. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  3685. if( ExprHasProperty(pA, EP_IntValue) ){
  3686. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  3687. return 2;
  3688. }
  3689. }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  3690. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  3691. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  3692. return pA->op==TK_COLLATE ? 1 : 2;
  3693. }
  3694. }
  3695. return 0;
  3696. }
  3697. /*
  3698. ** Compare two ExprList objects. Return 0 if they are identical and
  3699. ** non-zero if they differ in any way.
  3700. **
  3701. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  3702. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  3703. **
  3704. ** This routine might return non-zero for equivalent ExprLists. The
  3705. ** only consequence will be disabled optimizations. But this routine
  3706. ** must never return 0 if the two ExprList objects are different, or
  3707. ** a malfunction will result.
  3708. **
  3709. ** Two NULL pointers are considered to be the same. But a NULL pointer
  3710. ** always differs from a non-NULL pointer.
  3711. */
  3712. int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  3713. int i;
  3714. if( pA==0 && pB==0 ) return 0;
  3715. if( pA==0 || pB==0 ) return 1;
  3716. if( pA->nExpr!=pB->nExpr ) return 1;
  3717. for(i=0; i<pA->nExpr; i++){
  3718. Expr *pExprA = pA->a[i].pExpr;
  3719. Expr *pExprB = pB->a[i].pExpr;
  3720. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  3721. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  3722. }
  3723. return 0;
  3724. }
  3725. /*
  3726. ** Return true if we can prove the pE2 will always be true if pE1 is
  3727. ** true. Return false if we cannot complete the proof or if pE2 might
  3728. ** be false. Examples:
  3729. **
  3730. ** pE1: x==5 pE2: x==5 Result: true
  3731. ** pE1: x>0 pE2: x==5 Result: false
  3732. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  3733. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  3734. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  3735. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  3736. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  3737. **
  3738. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  3739. ** Expr.iTable<0 then assume a table number given by iTab.
  3740. **
  3741. ** When in doubt, return false. Returning true might give a performance
  3742. ** improvement. Returning false might cause a performance reduction, but
  3743. ** it will always give the correct answer and is hence always safe.
  3744. */
  3745. int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  3746. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  3747. return 1;
  3748. }
  3749. if( pE2->op==TK_OR
  3750. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  3751. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  3752. ){
  3753. return 1;
  3754. }
  3755. if( pE2->op==TK_NOTNULL
  3756. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  3757. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  3758. ){
  3759. return 1;
  3760. }
  3761. return 0;
  3762. }
  3763. /*
  3764. ** An instance of the following structure is used by the tree walker
  3765. ** to count references to table columns in the arguments of an
  3766. ** aggregate function, in order to implement the
  3767. ** sqlite3FunctionThisSrc() routine.
  3768. */
  3769. struct SrcCount {
  3770. SrcList *pSrc; /* One particular FROM clause in a nested query */
  3771. int nThis; /* Number of references to columns in pSrcList */
  3772. int nOther; /* Number of references to columns in other FROM clauses */
  3773. };
  3774. /*
  3775. ** Count the number of references to columns.
  3776. */
  3777. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  3778. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  3779. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  3780. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  3781. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  3782. ** NEVER() will need to be removed. */
  3783. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  3784. int i;
  3785. struct SrcCount *p = pWalker->u.pSrcCount;
  3786. SrcList *pSrc = p->pSrc;
  3787. for(i=0; i<pSrc->nSrc; i++){
  3788. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  3789. }
  3790. if( i<pSrc->nSrc ){
  3791. p->nThis++;
  3792. }else{
  3793. p->nOther++;
  3794. }
  3795. }
  3796. return WRC_Continue;
  3797. }
  3798. /*
  3799. ** Determine if any of the arguments to the pExpr Function reference
  3800. ** pSrcList. Return true if they do. Also return true if the function
  3801. ** has no arguments or has only constant arguments. Return false if pExpr
  3802. ** references columns but not columns of tables found in pSrcList.
  3803. */
  3804. int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  3805. Walker w;
  3806. struct SrcCount cnt;
  3807. assert( pExpr->op==TK_AGG_FUNCTION );
  3808. memset(&w, 0, sizeof(w));
  3809. w.xExprCallback = exprSrcCount;
  3810. w.u.pSrcCount = &cnt;
  3811. cnt.pSrc = pSrcList;
  3812. cnt.nThis = 0;
  3813. cnt.nOther = 0;
  3814. sqlite3WalkExprList(&w, pExpr->x.pList);
  3815. return cnt.nThis>0 || cnt.nOther==0;
  3816. }
  3817. /*
  3818. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  3819. ** the new element. Return a negative number if malloc fails.
  3820. */
  3821. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  3822. int i;
  3823. pInfo->aCol = sqlite3ArrayAllocate(
  3824. db,
  3825. pInfo->aCol,
  3826. sizeof(pInfo->aCol[0]),
  3827. &pInfo->nColumn,
  3828. &i
  3829. );
  3830. return i;
  3831. }
  3832. /*
  3833. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  3834. ** the new element. Return a negative number if malloc fails.
  3835. */
  3836. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  3837. int i;
  3838. pInfo->aFunc = sqlite3ArrayAllocate(
  3839. db,
  3840. pInfo->aFunc,
  3841. sizeof(pInfo->aFunc[0]),
  3842. &pInfo->nFunc,
  3843. &i
  3844. );
  3845. return i;
  3846. }
  3847. /*
  3848. ** This is the xExprCallback for a tree walker. It is used to
  3849. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  3850. ** for additional information.
  3851. */
  3852. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  3853. int i;
  3854. NameContext *pNC = pWalker->u.pNC;
  3855. Parse *pParse = pNC->pParse;
  3856. SrcList *pSrcList = pNC->pSrcList;
  3857. AggInfo *pAggInfo = pNC->pAggInfo;
  3858. switch( pExpr->op ){
  3859. case TK_AGG_COLUMN:
  3860. case TK_COLUMN: {
  3861. testcase( pExpr->op==TK_AGG_COLUMN );
  3862. testcase( pExpr->op==TK_COLUMN );
  3863. /* Check to see if the column is in one of the tables in the FROM
  3864. ** clause of the aggregate query */
  3865. if( ALWAYS(pSrcList!=0) ){
  3866. struct SrcList_item *pItem = pSrcList->a;
  3867. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  3868. struct AggInfo_col *pCol;
  3869. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  3870. if( pExpr->iTable==pItem->iCursor ){
  3871. /* If we reach this point, it means that pExpr refers to a table
  3872. ** that is in the FROM clause of the aggregate query.
  3873. **
  3874. ** Make an entry for the column in pAggInfo->aCol[] if there
  3875. ** is not an entry there already.
  3876. */
  3877. int k;
  3878. pCol = pAggInfo->aCol;
  3879. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  3880. if( pCol->iTable==pExpr->iTable &&
  3881. pCol->iColumn==pExpr->iColumn ){
  3882. break;
  3883. }
  3884. }
  3885. if( (k>=pAggInfo->nColumn)
  3886. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  3887. ){
  3888. pCol = &pAggInfo->aCol[k];
  3889. pCol->pTab = pExpr->pTab;
  3890. pCol->iTable = pExpr->iTable;
  3891. pCol->iColumn = pExpr->iColumn;
  3892. pCol->iMem = ++pParse->nMem;
  3893. pCol->iSorterColumn = -1;
  3894. pCol->pExpr = pExpr;
  3895. if( pAggInfo->pGroupBy ){
  3896. int j, n;
  3897. ExprList *pGB = pAggInfo->pGroupBy;
  3898. struct ExprList_item *pTerm = pGB->a;
  3899. n = pGB->nExpr;
  3900. for(j=0; j<n; j++, pTerm++){
  3901. Expr *pE = pTerm->pExpr;
  3902. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  3903. pE->iColumn==pExpr->iColumn ){
  3904. pCol->iSorterColumn = j;
  3905. break;
  3906. }
  3907. }
  3908. }
  3909. if( pCol->iSorterColumn<0 ){
  3910. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  3911. }
  3912. }
  3913. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  3914. ** because it was there before or because we just created it).
  3915. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  3916. ** pAggInfo->aCol[] entry.
  3917. */
  3918. ExprSetVVAProperty(pExpr, EP_NoReduce);
  3919. pExpr->pAggInfo = pAggInfo;
  3920. pExpr->op = TK_AGG_COLUMN;
  3921. pExpr->iAgg = (i16)k;
  3922. break;
  3923. } /* endif pExpr->iTable==pItem->iCursor */
  3924. } /* end loop over pSrcList */
  3925. }
  3926. return WRC_Prune;
  3927. }
  3928. case TK_AGG_FUNCTION: {
  3929. if( (pNC->ncFlags & NC_InAggFunc)==0
  3930. && pWalker->walkerDepth==pExpr->op2
  3931. ){
  3932. /* Check to see if pExpr is a duplicate of another aggregate
  3933. ** function that is already in the pAggInfo structure
  3934. */
  3935. struct AggInfo_func *pItem = pAggInfo->aFunc;
  3936. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  3937. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  3938. break;
  3939. }
  3940. }
  3941. if( i>=pAggInfo->nFunc ){
  3942. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  3943. */
  3944. u8 enc = ENC(pParse->db);
  3945. i = addAggInfoFunc(pParse->db, pAggInfo);
  3946. if( i>=0 ){
  3947. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  3948. pItem = &pAggInfo->aFunc[i];
  3949. pItem->pExpr = pExpr;
  3950. pItem->iMem = ++pParse->nMem;
  3951. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  3952. pItem->pFunc = sqlite3FindFunction(pParse->db,
  3953. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  3954. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  3955. if( pExpr->flags & EP_Distinct ){
  3956. pItem->iDistinct = pParse->nTab++;
  3957. }else{
  3958. pItem->iDistinct = -1;
  3959. }
  3960. }
  3961. }
  3962. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  3963. */
  3964. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  3965. ExprSetVVAProperty(pExpr, EP_NoReduce);
  3966. pExpr->iAgg = (i16)i;
  3967. pExpr->pAggInfo = pAggInfo;
  3968. return WRC_Prune;
  3969. }else{
  3970. return WRC_Continue;
  3971. }
  3972. }
  3973. }
  3974. return WRC_Continue;
  3975. }
  3976. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  3977. UNUSED_PARAMETER(pWalker);
  3978. UNUSED_PARAMETER(pSelect);
  3979. return WRC_Continue;
  3980. }
  3981. /*
  3982. ** Analyze the pExpr expression looking for aggregate functions and
  3983. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  3984. ** points to. Additional entries are made on the AggInfo object as
  3985. ** necessary.
  3986. **
  3987. ** This routine should only be called after the expression has been
  3988. ** analyzed by sqlite3ResolveExprNames().
  3989. */
  3990. void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  3991. Walker w;
  3992. memset(&w, 0, sizeof(w));
  3993. w.xExprCallback = analyzeAggregate;
  3994. w.xSelectCallback = analyzeAggregatesInSelect;
  3995. w.u.pNC = pNC;
  3996. assert( pNC->pSrcList!=0 );
  3997. sqlite3WalkExpr(&w, pExpr);
  3998. }
  3999. /*
  4000. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  4001. ** expression list. Return the number of errors.
  4002. **
  4003. ** If an error is found, the analysis is cut short.
  4004. */
  4005. void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  4006. struct ExprList_item *pItem;
  4007. int i;
  4008. if( pList ){
  4009. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  4010. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  4011. }
  4012. }
  4013. }
  4014. /*
  4015. ** Allocate a single new register for use to hold some intermediate result.
  4016. */
  4017. int sqlite3GetTempReg(Parse *pParse){
  4018. if( pParse->nTempReg==0 ){
  4019. return ++pParse->nMem;
  4020. }
  4021. return pParse->aTempReg[--pParse->nTempReg];
  4022. }
  4023. /*
  4024. ** Deallocate a register, making available for reuse for some other
  4025. ** purpose.
  4026. **
  4027. ** If a register is currently being used by the column cache, then
  4028. ** the dallocation is deferred until the column cache line that uses
  4029. ** the register becomes stale.
  4030. */
  4031. void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  4032. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  4033. int i;
  4034. struct yColCache *p;
  4035. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  4036. if( p->iReg==iReg ){
  4037. p->tempReg = 1;
  4038. return;
  4039. }
  4040. }
  4041. pParse->aTempReg[pParse->nTempReg++] = iReg;
  4042. }
  4043. }
  4044. /*
  4045. ** Allocate or deallocate a block of nReg consecutive registers
  4046. */
  4047. int sqlite3GetTempRange(Parse *pParse, int nReg){
  4048. int i, n;
  4049. i = pParse->iRangeReg;
  4050. n = pParse->nRangeReg;
  4051. if( nReg<=n ){
  4052. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  4053. pParse->iRangeReg += nReg;
  4054. pParse->nRangeReg -= nReg;
  4055. }else{
  4056. i = pParse->nMem+1;
  4057. pParse->nMem += nReg;
  4058. }
  4059. return i;
  4060. }
  4061. void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  4062. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  4063. if( nReg>pParse->nRangeReg ){
  4064. pParse->nRangeReg = nReg;
  4065. pParse->iRangeReg = iReg;
  4066. }
  4067. }
  4068. /*
  4069. ** Mark all temporary registers as being unavailable for reuse.
  4070. */
  4071. void sqlite3ClearTempRegCache(Parse *pParse){
  4072. pParse->nTempReg = 0;
  4073. pParse->nRangeReg = 0;
  4074. }