select.c 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668
  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 C code routines that are called by the parser
  13. ** to handle SELECT statements in SQLite.
  14. **
  15. ** $Id: select.c,v 1.372 2007/12/14 17:24:40 drh Exp $
  16. */
  17. #include "sqliteInt.h"
  18. /*
  19. ** Delete all the content of a Select structure but do not deallocate
  20. ** the select structure itself.
  21. */
  22. static void clearSelect(Select *p){
  23. sqlite3ExprListDelete(p->pEList);
  24. sqlite3SrcListDelete(p->pSrc);
  25. sqlite3ExprDelete(p->pWhere);
  26. sqlite3ExprListDelete(p->pGroupBy);
  27. sqlite3ExprDelete(p->pHaving);
  28. sqlite3ExprListDelete(p->pOrderBy);
  29. sqlite3SelectDelete(p->pPrior);
  30. sqlite3ExprDelete(p->pLimit);
  31. sqlite3ExprDelete(p->pOffset);
  32. }
  33. /*
  34. ** Allocate a new Select structure and return a pointer to that
  35. ** structure.
  36. */
  37. Select *sqlite3SelectNew(
  38. Parse *pParse, /* Parsing context */
  39. ExprList *pEList, /* which columns to include in the result */
  40. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  41. Expr *pWhere, /* the WHERE clause */
  42. ExprList *pGroupBy, /* the GROUP BY clause */
  43. Expr *pHaving, /* the HAVING clause */
  44. ExprList *pOrderBy, /* the ORDER BY clause */
  45. int isDistinct, /* true if the DISTINCT keyword is present */
  46. Expr *pLimit, /* LIMIT value. NULL means not used */
  47. Expr *pOffset /* OFFSET value. NULL means no offset */
  48. ){
  49. Select *pNew;
  50. Select standin;
  51. sqlite3 *db = pParse->db;
  52. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  53. assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */
  54. if( pNew==0 ){
  55. pNew = &standin;
  56. memset(pNew, 0, sizeof(*pNew));
  57. }
  58. if( pEList==0 ){
  59. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
  60. }
  61. pNew->pEList = pEList;
  62. pNew->pSrc = pSrc;
  63. pNew->pWhere = pWhere;
  64. pNew->pGroupBy = pGroupBy;
  65. pNew->pHaving = pHaving;
  66. pNew->pOrderBy = pOrderBy;
  67. pNew->isDistinct = isDistinct;
  68. pNew->op = TK_SELECT;
  69. assert( pOffset==0 || pLimit!=0 );
  70. pNew->pLimit = pLimit;
  71. pNew->pOffset = pOffset;
  72. pNew->iLimit = -1;
  73. pNew->iOffset = -1;
  74. pNew->addrOpenEphm[0] = -1;
  75. pNew->addrOpenEphm[1] = -1;
  76. pNew->addrOpenEphm[2] = -1;
  77. if( pNew==&standin) {
  78. clearSelect(pNew);
  79. pNew = 0;
  80. }
  81. return pNew;
  82. }
  83. /*
  84. ** Delete the given Select structure and all of its substructures.
  85. */
  86. void sqlite3SelectDelete(Select *p){
  87. if( p ){
  88. clearSelect(p);
  89. sqlite3_free(p);
  90. }
  91. }
  92. /*
  93. ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
  94. ** type of join. Return an integer constant that expresses that type
  95. ** in terms of the following bit values:
  96. **
  97. ** JT_INNER
  98. ** JT_CROSS
  99. ** JT_OUTER
  100. ** JT_NATURAL
  101. ** JT_LEFT
  102. ** JT_RIGHT
  103. **
  104. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  105. **
  106. ** If an illegal or unsupported join type is seen, then still return
  107. ** a join type, but put an error in the pParse structure.
  108. */
  109. int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  110. int jointype = 0;
  111. Token *apAll[3];
  112. Token *p;
  113. static const struct {
  114. const char zKeyword[8];
  115. u8 nChar;
  116. u8 code;
  117. } keywords[] = {
  118. { "natural", 7, JT_NATURAL },
  119. { "left", 4, JT_LEFT|JT_OUTER },
  120. { "right", 5, JT_RIGHT|JT_OUTER },
  121. { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  122. { "outer", 5, JT_OUTER },
  123. { "inner", 5, JT_INNER },
  124. { "cross", 5, JT_INNER|JT_CROSS },
  125. };
  126. int i, j;
  127. apAll[0] = pA;
  128. apAll[1] = pB;
  129. apAll[2] = pC;
  130. for(i=0; i<3 && apAll[i]; i++){
  131. p = apAll[i];
  132. for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
  133. if( p->n==keywords[j].nChar
  134. && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
  135. jointype |= keywords[j].code;
  136. break;
  137. }
  138. }
  139. if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
  140. jointype |= JT_ERROR;
  141. break;
  142. }
  143. }
  144. if(
  145. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  146. (jointype & JT_ERROR)!=0
  147. ){
  148. const char *zSp1 = " ";
  149. const char *zSp2 = " ";
  150. if( pB==0 ){ zSp1++; }
  151. if( pC==0 ){ zSp2++; }
  152. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  153. "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
  154. jointype = JT_INNER;
  155. }else if( jointype & JT_RIGHT ){
  156. sqlite3ErrorMsg(pParse,
  157. "RIGHT and FULL OUTER JOINs are not currently supported");
  158. jointype = JT_INNER;
  159. }
  160. return jointype;
  161. }
  162. /*
  163. ** Return the index of a column in a table. Return -1 if the column
  164. ** is not contained in the table.
  165. */
  166. static int columnIndex(Table *pTab, const char *zCol){
  167. int i;
  168. for(i=0; i<pTab->nCol; i++){
  169. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  170. }
  171. return -1;
  172. }
  173. /*
  174. ** Set the value of a token to a '\000'-terminated string.
  175. */
  176. static void setToken(Token *p, const char *z){
  177. p->z = (u8*)z;
  178. p->n = z ? strlen(z) : 0;
  179. p->dyn = 0;
  180. }
  181. /*
  182. ** Set the token to the double-quoted and escaped version of the string pointed
  183. ** to by z. For example;
  184. **
  185. ** {a"bc} -> {"a""bc"}
  186. */
  187. static void setQuotedToken(Parse *pParse, Token *p, const char *z){
  188. p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z);
  189. p->dyn = 1;
  190. if( p->z ){
  191. p->n = strlen((char *)p->z);
  192. }else{
  193. pParse->db->mallocFailed = 1;
  194. }
  195. }
  196. /*
  197. ** Create an expression node for an identifier with the name of zName
  198. */
  199. Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
  200. Token dummy;
  201. setToken(&dummy, zName);
  202. return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
  203. }
  204. /*
  205. ** Add a term to the WHERE expression in *ppExpr that requires the
  206. ** zCol column to be equal in the two tables pTab1 and pTab2.
  207. */
  208. static void addWhereTerm(
  209. Parse *pParse, /* Parsing context */
  210. const char *zCol, /* Name of the column */
  211. const Table *pTab1, /* First table */
  212. const char *zAlias1, /* Alias for first table. May be NULL */
  213. const Table *pTab2, /* Second table */
  214. const char *zAlias2, /* Alias for second table. May be NULL */
  215. int iRightJoinTable, /* VDBE cursor for the right table */
  216. Expr **ppExpr /* Add the equality term to this expression */
  217. ){
  218. Expr *pE1a, *pE1b, *pE1c;
  219. Expr *pE2a, *pE2b, *pE2c;
  220. Expr *pE;
  221. pE1a = sqlite3CreateIdExpr(pParse, zCol);
  222. pE2a = sqlite3CreateIdExpr(pParse, zCol);
  223. if( zAlias1==0 ){
  224. zAlias1 = pTab1->zName;
  225. }
  226. pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
  227. if( zAlias2==0 ){
  228. zAlias2 = pTab2->zName;
  229. }
  230. pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
  231. pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
  232. pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
  233. pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
  234. if( pE ){
  235. ExprSetProperty(pE, EP_FromJoin);
  236. pE->iRightJoinTable = iRightJoinTable;
  237. }
  238. *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
  239. }
  240. /*
  241. ** Set the EP_FromJoin property on all terms of the given expression.
  242. ** And set the Expr.iRightJoinTable to iTable for every term in the
  243. ** expression.
  244. **
  245. ** The EP_FromJoin property is used on terms of an expression to tell
  246. ** the LEFT OUTER JOIN processing logic that this term is part of the
  247. ** join restriction specified in the ON or USING clause and not a part
  248. ** of the more general WHERE clause. These terms are moved over to the
  249. ** WHERE clause during join processing but we need to remember that they
  250. ** originated in the ON or USING clause.
  251. **
  252. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  253. ** expression depends on table iRightJoinTable even if that table is not
  254. ** explicitly mentioned in the expression. That information is needed
  255. ** for cases like this:
  256. **
  257. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  258. **
  259. ** The where clause needs to defer the handling of the t1.x=5
  260. ** term until after the t2 loop of the join. In that way, a
  261. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  262. ** defer the handling of t1.x=5, it will be processed immediately
  263. ** after the t1 loop and rows with t1.x!=5 will never appear in
  264. ** the output, which is incorrect.
  265. */
  266. static void setJoinExpr(Expr *p, int iTable){
  267. while( p ){
  268. ExprSetProperty(p, EP_FromJoin);
  269. p->iRightJoinTable = iTable;
  270. setJoinExpr(p->pLeft, iTable);
  271. p = p->pRight;
  272. }
  273. }
  274. /*
  275. ** This routine processes the join information for a SELECT statement.
  276. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  277. ** NATURAL joins also create extra WHERE clause terms.
  278. **
  279. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  280. ** The left most table is the first entry in Select.pSrc. The right-most
  281. ** table is the last entry. The join operator is held in the entry to
  282. ** the left. Thus entry 0 contains the join operator for the join between
  283. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  284. ** also attached to the left entry.
  285. **
  286. ** This routine returns the number of errors encountered.
  287. */
  288. static int sqliteProcessJoin(Parse *pParse, Select *p){
  289. SrcList *pSrc; /* All tables in the FROM clause */
  290. int i, j; /* Loop counters */
  291. struct SrcList_item *pLeft; /* Left table being joined */
  292. struct SrcList_item *pRight; /* Right table being joined */
  293. pSrc = p->pSrc;
  294. pLeft = &pSrc->a[0];
  295. pRight = &pLeft[1];
  296. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  297. Table *pLeftTab = pLeft->pTab;
  298. Table *pRightTab = pRight->pTab;
  299. if( pLeftTab==0 || pRightTab==0 ) continue;
  300. /* When the NATURAL keyword is present, add WHERE clause terms for
  301. ** every column that the two tables have in common.
  302. */
  303. if( pRight->jointype & JT_NATURAL ){
  304. if( pRight->pOn || pRight->pUsing ){
  305. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  306. "an ON or USING clause", 0);
  307. return 1;
  308. }
  309. for(j=0; j<pLeftTab->nCol; j++){
  310. char *zName = pLeftTab->aCol[j].zName;
  311. if( columnIndex(pRightTab, zName)>=0 ){
  312. addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
  313. pRightTab, pRight->zAlias,
  314. pRight->iCursor, &p->pWhere);
  315. }
  316. }
  317. }
  318. /* Disallow both ON and USING clauses in the same join
  319. */
  320. if( pRight->pOn && pRight->pUsing ){
  321. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  322. "clauses in the same join");
  323. return 1;
  324. }
  325. /* Add the ON clause to the end of the WHERE clause, connected by
  326. ** an AND operator.
  327. */
  328. if( pRight->pOn ){
  329. setJoinExpr(pRight->pOn, pRight->iCursor);
  330. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  331. pRight->pOn = 0;
  332. }
  333. /* Create extra terms on the WHERE clause for each column named
  334. ** in the USING clause. Example: If the two tables to be joined are
  335. ** A and B and the USING clause names X, Y, and Z, then add this
  336. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  337. ** Report an error if any column mentioned in the USING clause is
  338. ** not contained in both tables to be joined.
  339. */
  340. if( pRight->pUsing ){
  341. IdList *pList = pRight->pUsing;
  342. for(j=0; j<pList->nId; j++){
  343. char *zName = pList->a[j].zName;
  344. if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
  345. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  346. "not present in both tables", zName);
  347. return 1;
  348. }
  349. addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
  350. pRightTab, pRight->zAlias,
  351. pRight->iCursor, &p->pWhere);
  352. }
  353. }
  354. }
  355. return 0;
  356. }
  357. /*
  358. ** Insert code into "v" that will push the record on the top of the
  359. ** stack into the sorter.
  360. */
  361. static void pushOntoSorter(
  362. Parse *pParse, /* Parser context */
  363. ExprList *pOrderBy, /* The ORDER BY clause */
  364. Select *pSelect /* The whole SELECT statement */
  365. ){
  366. Vdbe *v = pParse->pVdbe;
  367. sqlite3ExprCodeExprList(pParse, pOrderBy);
  368. sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
  369. sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
  370. sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
  371. sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
  372. if( pSelect->iLimit>=0 ){
  373. int addr1, addr2;
  374. addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
  375. sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
  376. addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
  377. sqlite3VdbeJumpHere(v, addr1);
  378. sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
  379. sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0);
  380. sqlite3VdbeJumpHere(v, addr2);
  381. pSelect->iLimit = -1;
  382. }
  383. }
  384. /*
  385. ** Add code to implement the OFFSET
  386. */
  387. static void codeOffset(
  388. Vdbe *v, /* Generate code into this VM */
  389. Select *p, /* The SELECT statement being coded */
  390. int iContinue, /* Jump here to skip the current record */
  391. int nPop /* Number of times to pop stack when jumping */
  392. ){
  393. if( p->iOffset>=0 && iContinue!=0 ){
  394. int addr;
  395. sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
  396. addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
  397. if( nPop>0 ){
  398. sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
  399. }
  400. sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
  401. VdbeComment((v, "# skip OFFSET records"));
  402. sqlite3VdbeJumpHere(v, addr);
  403. }
  404. }
  405. /*
  406. ** Add code that will check to make sure the top N elements of the
  407. ** stack are distinct. iTab is a sorting index that holds previously
  408. ** seen combinations of the N values. A new entry is made in iTab
  409. ** if the current N values are new.
  410. **
  411. ** A jump to addrRepeat is made and the N+1 values are popped from the
  412. ** stack if the top N elements are not distinct.
  413. */
  414. static void codeDistinct(
  415. Vdbe *v, /* Generate code into this VM */
  416. int iTab, /* A sorting index used to test for distinctness */
  417. int addrRepeat, /* Jump to here if not distinct */
  418. int N /* The top N elements of the stack must be distinct */
  419. ){
  420. sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
  421. sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
  422. sqlite3VdbeAddOp(v, OP_Pop, N+1, 0);
  423. sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
  424. VdbeComment((v, "# skip indistinct records"));
  425. sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
  426. }
  427. /*
  428. ** Generate an error message when a SELECT is used within a subexpression
  429. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  430. ** column. We do this in a subroutine because the error occurs in multiple
  431. ** places.
  432. */
  433. static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){
  434. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  435. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  436. "a SELECT that is part of an expression");
  437. return 1;
  438. }else{
  439. return 0;
  440. }
  441. }
  442. /*
  443. ** This routine generates the code for the inside of the inner loop
  444. ** of a SELECT.
  445. **
  446. ** If srcTab and nColumn are both zero, then the pEList expressions
  447. ** are evaluated in order to get the data for this row. If nColumn>0
  448. ** then data is pulled from srcTab and pEList is used only to get the
  449. ** datatypes for each column.
  450. */
  451. static int selectInnerLoop(
  452. Parse *pParse, /* The parser context */
  453. Select *p, /* The complete select statement being coded */
  454. ExprList *pEList, /* List of values being extracted */
  455. int srcTab, /* Pull data from this table */
  456. int nColumn, /* Number of columns in the source table */
  457. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  458. int distinct, /* If >=0, make sure results are distinct */
  459. int eDest, /* How to dispose of the results */
  460. int iParm, /* An argument to the disposal method */
  461. int iContinue, /* Jump here to continue with next row */
  462. int iBreak, /* Jump here to break out of the inner loop */
  463. char *aff /* affinity string if eDest is SRT_Union */
  464. ){
  465. Vdbe *v = pParse->pVdbe;
  466. int i;
  467. int hasDistinct; /* True if the DISTINCT keyword is present */
  468. if( v==0 ) return 0;
  469. assert( pEList!=0 );
  470. /* If there was a LIMIT clause on the SELECT statement, then do the check
  471. ** to see if this row should be output.
  472. */
  473. hasDistinct = distinct>=0 && pEList->nExpr>0;
  474. if( pOrderBy==0 && !hasDistinct ){
  475. codeOffset(v, p, iContinue, 0);
  476. }
  477. /* Pull the requested columns.
  478. */
  479. if( nColumn>0 ){
  480. for(i=0; i<nColumn; i++){
  481. sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
  482. }
  483. }else{
  484. nColumn = pEList->nExpr;
  485. sqlite3ExprCodeExprList(pParse, pEList);
  486. }
  487. /* If the DISTINCT keyword was present on the SELECT statement
  488. ** and this row has been seen before, then do not make this row
  489. ** part of the result.
  490. */
  491. if( hasDistinct ){
  492. assert( pEList!=0 );
  493. assert( pEList->nExpr==nColumn );
  494. codeDistinct(v, distinct, iContinue, nColumn);
  495. if( pOrderBy==0 ){
  496. codeOffset(v, p, iContinue, nColumn);
  497. }
  498. }
  499. if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
  500. return 0;
  501. }
  502. switch( eDest ){
  503. /* In this mode, write each query result to the key of the temporary
  504. ** table iParm.
  505. */
  506. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  507. case SRT_Union: {
  508. sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  509. if( aff ){
  510. sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
  511. }
  512. sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
  513. break;
  514. }
  515. /* Construct a record from the query result, but instead of
  516. ** saving that record, use it as a key to delete elements from
  517. ** the temporary table iParm.
  518. */
  519. case SRT_Except: {
  520. int addr;
  521. addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  522. sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
  523. sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
  524. sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
  525. break;
  526. }
  527. #endif
  528. /* Store the result as data using a unique key.
  529. */
  530. case SRT_Table:
  531. case SRT_EphemTab: {
  532. sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  533. if( pOrderBy ){
  534. pushOntoSorter(pParse, pOrderBy, p);
  535. }else{
  536. sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
  537. sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
  538. sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
  539. }
  540. break;
  541. }
  542. #ifndef SQLITE_OMIT_SUBQUERY
  543. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  544. ** then there should be a single item on the stack. Write this
  545. ** item into the set table with bogus data.
  546. */
  547. case SRT_Set: {
  548. int addr1 = sqlite3VdbeCurrentAddr(v);
  549. int addr2;
  550. assert( nColumn==1 );
  551. sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
  552. sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  553. addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
  554. p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
  555. if( pOrderBy ){
  556. /* At first glance you would think we could optimize out the
  557. ** ORDER BY in this case since the order of entries in the set
  558. ** does not matter. But there might be a LIMIT clause, in which
  559. ** case the order does matter */
  560. pushOntoSorter(pParse, pOrderBy, p);
  561. }else{
  562. sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
  563. sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
  564. }
  565. sqlite3VdbeJumpHere(v, addr2);
  566. break;
  567. }
  568. /* If any row exist in the result set, record that fact and abort.
  569. */
  570. case SRT_Exists: {
  571. sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
  572. sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
  573. /* The LIMIT clause will terminate the loop for us */
  574. break;
  575. }
  576. /* If this is a scalar select that is part of an expression, then
  577. ** store the results in the appropriate memory cell and break out
  578. ** of the scan loop.
  579. */
  580. case SRT_Mem: {
  581. assert( nColumn==1 );
  582. if( pOrderBy ){
  583. pushOntoSorter(pParse, pOrderBy, p);
  584. }else{
  585. sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
  586. /* The LIMIT clause will jump out of the loop for us */
  587. }
  588. break;
  589. }
  590. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  591. /* Send the data to the callback function or to a subroutine. In the
  592. ** case of a subroutine, the subroutine itself is responsible for
  593. ** popping the data from the stack.
  594. */
  595. case SRT_Subroutine:
  596. case SRT_Callback: {
  597. if( pOrderBy ){
  598. sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  599. pushOntoSorter(pParse, pOrderBy, p);
  600. }else if( eDest==SRT_Subroutine ){
  601. sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
  602. }else{
  603. sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
  604. }
  605. break;
  606. }
  607. #if !defined(SQLITE_OMIT_TRIGGER)
  608. /* Discard the results. This is used for SELECT statements inside
  609. ** the body of a TRIGGER. The purpose of such selects is to call
  610. ** user-defined functions that have side effects. We do not care
  611. ** about the actual results of the select.
  612. */
  613. default: {
  614. assert( eDest==SRT_Discard );
  615. sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
  616. break;
  617. }
  618. #endif
  619. }
  620. /* Jump to the end of the loop if the LIMIT is reached.
  621. */
  622. if( p->iLimit>=0 && pOrderBy==0 ){
  623. sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
  624. sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
  625. }
  626. return 0;
  627. }
  628. /*
  629. ** Given an expression list, generate a KeyInfo structure that records
  630. ** the collating sequence for each expression in that expression list.
  631. **
  632. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  633. ** KeyInfo structure is appropriate for initializing a virtual index to
  634. ** implement that clause. If the ExprList is the result set of a SELECT
  635. ** then the KeyInfo structure is appropriate for initializing a virtual
  636. ** index to implement a DISTINCT test.
  637. **
  638. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  639. ** function is responsible for seeing that this structure is eventually
  640. ** freed. Add the KeyInfo structure to the P3 field of an opcode using
  641. ** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
  642. */
  643. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  644. sqlite3 *db = pParse->db;
  645. int nExpr;
  646. KeyInfo *pInfo;
  647. struct ExprList_item *pItem;
  648. int i;
  649. nExpr = pList->nExpr;
  650. pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
  651. if( pInfo ){
  652. pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
  653. pInfo->nField = nExpr;
  654. pInfo->enc = ENC(db);
  655. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  656. CollSeq *pColl;
  657. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  658. if( !pColl ){
  659. pColl = db->pDfltColl;
  660. }
  661. pInfo->aColl[i] = pColl;
  662. pInfo->aSortOrder[i] = pItem->sortOrder;
  663. }
  664. }
  665. return pInfo;
  666. }
  667. /*
  668. ** If the inner loop was generated using a non-null pOrderBy argument,
  669. ** then the results were placed in a sorter. After the loop is terminated
  670. ** we need to run the sorter and output the results. The following
  671. ** routine generates the code needed to do that.
  672. */
  673. static void generateSortTail(
  674. Parse *pParse, /* Parsing context */
  675. Select *p, /* The SELECT statement */
  676. Vdbe *v, /* Generate code into this VDBE */
  677. int nColumn, /* Number of columns of data */
  678. int eDest, /* Write the sorted results here */
  679. int iParm /* Optional parameter associated with eDest */
  680. ){
  681. int brk = sqlite3VdbeMakeLabel(v);
  682. int cont = sqlite3VdbeMakeLabel(v);
  683. int addr;
  684. int iTab;
  685. int pseudoTab = 0;
  686. ExprList *pOrderBy = p->pOrderBy;
  687. iTab = pOrderBy->iECursor;
  688. if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
  689. pseudoTab = pParse->nTab++;
  690. sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
  691. sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
  692. }
  693. addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
  694. codeOffset(v, p, cont, 0);
  695. if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
  696. sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
  697. }
  698. sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
  699. switch( eDest ){
  700. case SRT_Table:
  701. case SRT_EphemTab: {
  702. sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
  703. sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
  704. sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
  705. break;
  706. }
  707. #ifndef SQLITE_OMIT_SUBQUERY
  708. case SRT_Set: {
  709. assert( nColumn==1 );
  710. sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
  711. sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  712. sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
  713. sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
  714. sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
  715. break;
  716. }
  717. case SRT_Mem: {
  718. assert( nColumn==1 );
  719. sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
  720. /* The LIMIT clause will terminate the loop for us */
  721. break;
  722. }
  723. #endif
  724. case SRT_Callback:
  725. case SRT_Subroutine: {
  726. int i;
  727. sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
  728. for(i=0; i<nColumn; i++){
  729. sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
  730. }
  731. if( eDest==SRT_Callback ){
  732. sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
  733. }else{
  734. sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
  735. }
  736. break;
  737. }
  738. default: {
  739. /* Do nothing */
  740. break;
  741. }
  742. }
  743. /* Jump to the end of the loop when the LIMIT is reached
  744. */
  745. if( p->iLimit>=0 ){
  746. sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
  747. sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
  748. }
  749. /* The bottom of the loop
  750. */
  751. sqlite3VdbeResolveLabel(v, cont);
  752. sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
  753. sqlite3VdbeResolveLabel(v, brk);
  754. if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
  755. sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
  756. }
  757. }
  758. /*
  759. ** Return a pointer to a string containing the 'declaration type' of the
  760. ** expression pExpr. The string may be treated as static by the caller.
  761. **
  762. ** The declaration type is the exact datatype definition extracted from the
  763. ** original CREATE TABLE statement if the expression is a column. The
  764. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  765. ** is considered a column can be complex in the presence of subqueries. The
  766. ** result-set expression in all of the following SELECT statements is
  767. ** considered a column by this function.
  768. **
  769. ** SELECT col FROM tbl;
  770. ** SELECT (SELECT col FROM tbl;
  771. ** SELECT (SELECT col FROM tbl);
  772. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  773. **
  774. ** The declaration type for any expression other than a column is NULL.
  775. */
  776. static const char *columnType(
  777. NameContext *pNC,
  778. Expr *pExpr,
  779. const char **pzOriginDb,
  780. const char **pzOriginTab,
  781. const char **pzOriginCol
  782. ){
  783. char const *zType = 0;
  784. char const *zOriginDb = 0;
  785. char const *zOriginTab = 0;
  786. char const *zOriginCol = 0;
  787. int j;
  788. if( pExpr==0 || pNC->pSrcList==0 ) return 0;
  789. switch( pExpr->op ){
  790. case TK_AGG_COLUMN:
  791. case TK_COLUMN: {
  792. /* The expression is a column. Locate the table the column is being
  793. ** extracted from in NameContext.pSrcList. This table may be real
  794. ** database table or a subquery.
  795. */
  796. Table *pTab = 0; /* Table structure column is extracted from */
  797. Select *pS = 0; /* Select the column is extracted from */
  798. int iCol = pExpr->iColumn; /* Index of column in pTab */
  799. while( pNC && !pTab ){
  800. SrcList *pTabList = pNC->pSrcList;
  801. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  802. if( j<pTabList->nSrc ){
  803. pTab = pTabList->a[j].pTab;
  804. pS = pTabList->a[j].pSelect;
  805. }else{
  806. pNC = pNC->pNext;
  807. }
  808. }
  809. if( pTab==0 ){
  810. /* FIX ME:
  811. ** This can occurs if you have something like "SELECT new.x;" inside
  812. ** a trigger. In other words, if you reference the special "new"
  813. ** table in the result set of a select. We do not have a good way
  814. ** to find the actual table type, so call it "TEXT". This is really
  815. ** something of a bug, but I do not know how to fix it.
  816. **
  817. ** This code does not produce the correct answer - it just prevents
  818. ** a segfault. See ticket #1229.
  819. */
  820. zType = "TEXT";
  821. break;
  822. }
  823. assert( pTab );
  824. if( pS ){
  825. /* The "table" is actually a sub-select or a view in the FROM clause
  826. ** of the SELECT statement. Return the declaration type and origin
  827. ** data for the result-set column of the sub-select.
  828. */
  829. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  830. /* If iCol is less than zero, then the expression requests the
  831. ** rowid of the sub-select or view. This expression is legal (see
  832. ** test case misc2.2.2) - it always evaluates to NULL.
  833. */
  834. NameContext sNC;
  835. Expr *p = pS->pEList->a[iCol].pExpr;
  836. sNC.pSrcList = pS->pSrc;
  837. sNC.pNext = 0;
  838. sNC.pParse = pNC->pParse;
  839. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  840. }
  841. }else if( pTab->pSchema ){
  842. /* A real table */
  843. assert( !pS );
  844. if( iCol<0 ) iCol = pTab->iPKey;
  845. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  846. if( iCol<0 ){
  847. zType = "INTEGER";
  848. zOriginCol = "rowid";
  849. }else{
  850. zType = pTab->aCol[iCol].zType;
  851. zOriginCol = pTab->aCol[iCol].zName;
  852. }
  853. zOriginTab = pTab->zName;
  854. if( pNC->pParse ){
  855. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  856. zOriginDb = pNC->pParse->db->aDb[iDb].zName;
  857. }
  858. }
  859. break;
  860. }
  861. #ifndef SQLITE_OMIT_SUBQUERY
  862. case TK_SELECT: {
  863. /* The expression is a sub-select. Return the declaration type and
  864. ** origin info for the single column in the result set of the SELECT
  865. ** statement.
  866. */
  867. NameContext sNC;
  868. Select *pS = pExpr->pSelect;
  869. Expr *p = pS->pEList->a[0].pExpr;
  870. sNC.pSrcList = pS->pSrc;
  871. sNC.pNext = pNC;
  872. sNC.pParse = pNC->pParse;
  873. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  874. break;
  875. }
  876. #endif
  877. }
  878. if( pzOriginDb ){
  879. assert( pzOriginTab && pzOriginCol );
  880. *pzOriginDb = zOriginDb;
  881. *pzOriginTab = zOriginTab;
  882. *pzOriginCol = zOriginCol;
  883. }
  884. return zType;
  885. }
  886. /*
  887. ** Generate code that will tell the VDBE the declaration types of columns
  888. ** in the result set.
  889. */
  890. static void generateColumnTypes(
  891. Parse *pParse, /* Parser context */
  892. SrcList *pTabList, /* List of tables */
  893. ExprList *pEList /* Expressions defining the result set */
  894. ){
  895. Vdbe *v = pParse->pVdbe;
  896. int i;
  897. NameContext sNC;
  898. sNC.pSrcList = pTabList;
  899. sNC.pParse = pParse;
  900. for(i=0; i<pEList->nExpr; i++){
  901. Expr *p = pEList->a[i].pExpr;
  902. const char *zOrigDb = 0;
  903. const char *zOrigTab = 0;
  904. const char *zOrigCol = 0;
  905. const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  906. /* The vdbe must make its own copy of the column-type and other
  907. ** column specific strings, in case the schema is reset before this
  908. ** virtual machine is deleted.
  909. */
  910. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
  911. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
  912. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
  913. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
  914. }
  915. }
  916. /*
  917. ** Generate code that will tell the VDBE the names of columns
  918. ** in the result set. This information is used to provide the
  919. ** azCol[] values in the callback.
  920. */
  921. static void generateColumnNames(
  922. Parse *pParse, /* Parser context */
  923. SrcList *pTabList, /* List of tables */
  924. ExprList *pEList /* Expressions defining the result set */
  925. ){
  926. Vdbe *v = pParse->pVdbe;
  927. int i, j;
  928. sqlite3 *db = pParse->db;
  929. int fullNames, shortNames;
  930. #ifndef SQLITE_OMIT_EXPLAIN
  931. /* If this is an EXPLAIN, skip this step */
  932. if( pParse->explain ){
  933. return;
  934. }
  935. #endif
  936. assert( v!=0 );
  937. if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
  938. pParse->colNamesSet = 1;
  939. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  940. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  941. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  942. for(i=0; i<pEList->nExpr; i++){
  943. Expr *p;
  944. p = pEList->a[i].pExpr;
  945. if( p==0 ) continue;
  946. if( pEList->a[i].zName ){
  947. char *zName = pEList->a[i].zName;
  948. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
  949. continue;
  950. }
  951. if( p->op==TK_COLUMN && pTabList ){
  952. Table *pTab;
  953. char *zCol;
  954. int iCol = p->iColumn;
  955. for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
  956. assert( j<pTabList->nSrc );
  957. pTab = pTabList->a[j].pTab;
  958. if( iCol<0 ) iCol = pTab->iPKey;
  959. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  960. if( iCol<0 ){
  961. zCol = "rowid";
  962. }else{
  963. zCol = pTab->aCol[iCol].zName;
  964. }
  965. if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
  966. sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
  967. }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
  968. char *zName = 0;
  969. char *zTab;
  970. zTab = pTabList->a[j].zAlias;
  971. if( fullNames || zTab==0 ) zTab = pTab->zName;
  972. sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
  973. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
  974. }else{
  975. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
  976. }
  977. }else if( p->span.z && p->span.z[0] ){
  978. sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
  979. /* sqlite3VdbeCompressSpace(v, addr); */
  980. }else{
  981. char zName[30];
  982. assert( p->op!=TK_COLUMN || pTabList==0 );
  983. sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
  984. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
  985. }
  986. }
  987. generateColumnTypes(pParse, pTabList, pEList);
  988. }
  989. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  990. /*
  991. ** Name of the connection operator, used for error messages.
  992. */
  993. static const char *selectOpName(int id){
  994. char *z;
  995. switch( id ){
  996. case TK_ALL: z = "UNION ALL"; break;
  997. case TK_INTERSECT: z = "INTERSECT"; break;
  998. case TK_EXCEPT: z = "EXCEPT"; break;
  999. default: z = "UNION"; break;
  1000. }
  1001. return z;
  1002. }
  1003. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  1004. /*
  1005. ** Forward declaration
  1006. */
  1007. static int prepSelectStmt(Parse*, Select*);
  1008. /*
  1009. ** Given a SELECT statement, generate a Table structure that describes
  1010. ** the result set of that SELECT.
  1011. */
  1012. Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
  1013. Table *pTab;
  1014. int i, j;
  1015. ExprList *pEList;
  1016. Column *aCol, *pCol;
  1017. sqlite3 *db = pParse->db;
  1018. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  1019. if( prepSelectStmt(pParse, pSelect) ){
  1020. return 0;
  1021. }
  1022. if( sqlite3SelectResolve(pParse, pSelect, 0) ){
  1023. return 0;
  1024. }
  1025. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  1026. if( pTab==0 ){
  1027. return 0;
  1028. }
  1029. pTab->nRef = 1;
  1030. pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
  1031. pEList = pSelect->pEList;
  1032. pTab->nCol = pEList->nExpr;
  1033. assert( pTab->nCol>0 );
  1034. pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
  1035. for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
  1036. Expr *p, *pR;
  1037. char *zType;
  1038. char *zName;
  1039. int nName;
  1040. CollSeq *pColl;
  1041. int cnt;
  1042. NameContext sNC;
  1043. /* Get an appropriate name for the column
  1044. */
  1045. p = pEList->a[i].pExpr;
  1046. assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
  1047. if( (zName = pEList->a[i].zName)!=0 ){
  1048. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  1049. zName = sqlite3DbStrDup(db, zName);
  1050. }else if( p->op==TK_DOT
  1051. && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
  1052. /* For columns of the from A.B use B as the name */
  1053. zName = sqlite3MPrintf(db, "%T", &pR->token);
  1054. }else if( p->span.z && p->span.z[0] ){
  1055. /* Use the original text of the column expression as its name */
  1056. zName = sqlite3MPrintf(db, "%T", &p->span);
  1057. }else{
  1058. /* If all else fails, make up a name */
  1059. zName = sqlite3MPrintf(db, "column%d", i+1);
  1060. }
  1061. if( !zName || db->mallocFailed ){
  1062. db->mallocFailed = 1;
  1063. sqlite3_free(zName);
  1064. sqlite3DeleteTable(pTab);
  1065. return 0;
  1066. }
  1067. sqlite3Dequote(zName);
  1068. /* Make sure the column name is unique. If the name is not unique,
  1069. ** append a integer to the name so that it becomes unique.
  1070. */
  1071. nName = strlen(zName);
  1072. for(j=cnt=0; j<i; j++){
  1073. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  1074. zName[nName] = 0;
  1075. zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
  1076. j = -1;
  1077. if( zName==0 ) break;
  1078. }
  1079. }
  1080. pCol->zName = zName;
  1081. /* Get the typename, type affinity, and collating sequence for the
  1082. ** column.
  1083. */
  1084. memset(&sNC, 0, sizeof(sNC));
  1085. sNC.pSrcList = pSelect->pSrc;
  1086. zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
  1087. pCol->zType = zType;
  1088. pCol->affinity = sqlite3ExprAffinity(p);
  1089. pColl = sqlite3ExprCollSeq(pParse, p);
  1090. if( pColl ){
  1091. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  1092. }
  1093. }
  1094. pTab->iPKey = -1;
  1095. return pTab;
  1096. }
  1097. /*
  1098. ** Prepare a SELECT statement for processing by doing the following
  1099. ** things:
  1100. **
  1101. ** (1) Make sure VDBE cursor numbers have been assigned to every
  1102. ** element of the FROM clause.
  1103. **
  1104. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  1105. ** defines FROM clause. When views appear in the FROM clause,
  1106. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  1107. ** that implements the view. A copy is made of the view's SELECT
  1108. ** statement so that we can freely modify or delete that statement
  1109. ** without worrying about messing up the presistent representation
  1110. ** of the view.
  1111. **
  1112. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  1113. ** on joins and the ON and USING clause of joins.
  1114. **
  1115. ** (4) Scan the list of columns in the result set (pEList) looking
  1116. ** for instances of the "*" operator or the TABLE.* operator.
  1117. ** If found, expand each "*" to be every column in every table
  1118. ** and TABLE.* to be every column in TABLE.
  1119. **
  1120. ** Return 0 on success. If there are problems, leave an error message
  1121. ** in pParse and return non-zero.
  1122. */
  1123. static int prepSelectStmt(Parse *pParse, Select *p){
  1124. int i, j, k, rc;
  1125. SrcList *pTabList;
  1126. ExprList *pEList;
  1127. struct SrcList_item *pFrom;
  1128. sqlite3 *db = pParse->db;
  1129. if( p==0 || p->pSrc==0 || db->mallocFailed ){
  1130. return 1;
  1131. }
  1132. pTabList = p->pSrc;
  1133. pEList = p->pEList;
  1134. /* Make sure cursor numbers have been assigned to all entries in
  1135. ** the FROM clause of the SELECT statement.
  1136. */
  1137. sqlite3SrcListAssignCursors(pParse, p->pSrc);
  1138. /* Look up every table named in the FROM clause of the select. If
  1139. ** an entry of the FROM clause is a subquery instead of a table or view,
  1140. ** then create a transient table structure to describe the subquery.
  1141. */
  1142. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  1143. Table *pTab;
  1144. if( pFrom->pTab!=0 ){
  1145. /* This statement has already been prepared. There is no need
  1146. ** to go further. */
  1147. assert( i==0 );
  1148. return 0;
  1149. }
  1150. if( pFrom->zName==0 ){
  1151. #ifndef SQLITE_OMIT_SUBQUERY
  1152. /* A sub-query in the FROM clause of a SELECT */
  1153. assert( pFrom->pSelect!=0 );
  1154. if( pFrom->zAlias==0 ){
  1155. pFrom->zAlias =
  1156. sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
  1157. }
  1158. assert( pFrom->pTab==0 );
  1159. pFrom->pTab = pTab =
  1160. sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
  1161. if( pTab==0 ){
  1162. return 1;
  1163. }
  1164. /* The isEphem flag indicates that the Table structure has been
  1165. ** dynamically allocated and may be freed at any time. In other words,
  1166. ** pTab is not pointing to a persistent table structure that defines
  1167. ** part of the schema. */
  1168. pTab->isEphem = 1;
  1169. #endif
  1170. }else{
  1171. /* An ordinary table or view name in the FROM clause */
  1172. assert( pFrom->pTab==0 );
  1173. pFrom->pTab = pTab =
  1174. sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
  1175. if( pTab==0 ){
  1176. return 1;
  1177. }
  1178. pTab->nRef++;
  1179. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  1180. if( pTab->pSelect || IsVirtual(pTab) ){
  1181. /* We reach here if the named table is a really a view */
  1182. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  1183. return 1;
  1184. }
  1185. /* If pFrom->pSelect!=0 it means we are dealing with a
  1186. ** view within a view. The SELECT structure has already been
  1187. ** copied by the outer view so we can skip the copy step here
  1188. ** in the inner view.
  1189. */
  1190. if( pFrom->pSelect==0 ){
  1191. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
  1192. }
  1193. }
  1194. #endif
  1195. }
  1196. }
  1197. /* Process NATURAL keywords, and ON and USING clauses of joins.
  1198. */
  1199. if( sqliteProcessJoin(pParse, p) ) return 1;
  1200. /* For every "*" that occurs in the column list, insert the names of
  1201. ** all columns in all tables. And for every TABLE.* insert the names
  1202. ** of all columns in TABLE. The parser inserted a special expression
  1203. ** with the TK_ALL operator for each "*" that it found in the column list.
  1204. ** The following code just has to locate the TK_ALL expressions and expand
  1205. ** each one to the list of all columns in all tables.
  1206. **
  1207. ** The first loop just checks to see if there are any "*" operators
  1208. ** that need expanding.
  1209. */
  1210. for(k=0; k<pEList->nExpr; k++){
  1211. Expr *pE = pEList->a[k].pExpr;
  1212. if( pE->op==TK_ALL ) break;
  1213. if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
  1214. && pE->pLeft && pE->pLeft->op==TK_ID ) break;
  1215. }
  1216. rc = 0;
  1217. if( k<pEList->nExpr ){
  1218. /*
  1219. ** If we get here it means the result set contains one or more "*"
  1220. ** operators that need to be expanded. Loop through each expression
  1221. ** in the result set and expand them one by one.
  1222. */
  1223. struct ExprList_item *a = pEList->a;
  1224. ExprList *pNew = 0;
  1225. int flags = pParse->db->flags;
  1226. int longNames = (flags & SQLITE_FullColNames)!=0 &&
  1227. (flags & SQLITE_ShortColNames)==0;
  1228. for(k=0; k<pEList->nExpr; k++){
  1229. Expr *pE = a[k].pExpr;
  1230. if( pE->op!=TK_ALL &&
  1231. (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
  1232. /* This particular expression does not need to be expanded.
  1233. */
  1234. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
  1235. if( pNew ){
  1236. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  1237. }else{
  1238. rc = 1;
  1239. }
  1240. a[k].pExpr = 0;
  1241. a[k].zName = 0;
  1242. }else{
  1243. /* This expression is a "*" or a "TABLE.*" and needs to be
  1244. ** expanded. */
  1245. int tableSeen = 0; /* Set to 1 when TABLE matches */
  1246. char *zTName; /* text of name of TABLE */
  1247. if( pE->op==TK_DOT && pE->pLeft ){
  1248. zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
  1249. }else{
  1250. zTName = 0;
  1251. }
  1252. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  1253. Table *pTab = pFrom->pTab;
  1254. char *zTabName = pFrom->zAlias;
  1255. if( zTabName==0 || zTabName[0]==0 ){
  1256. zTabName = pTab->zName;
  1257. }
  1258. if( zTName && (zTabName==0 || zTabName[0]==0 ||
  1259. sqlite3StrICmp(zTName, zTabName)!=0) ){
  1260. continue;
  1261. }
  1262. tableSeen = 1;
  1263. for(j=0; j<pTab->nCol; j++){
  1264. Expr *pExpr, *pRight;
  1265. char *zName = pTab->aCol[j].zName;
  1266. /* If a column is marked as 'hidden' (currently only possible
  1267. ** for virtual tables), do not include it in the expanded
  1268. ** result-set list.
  1269. */
  1270. if( IsHiddenColumn(&pTab->aCol[j]) ){
  1271. assert(IsVirtual(pTab));
  1272. continue;
  1273. }
  1274. if( i>0 ){
  1275. struct SrcList_item *pLeft = &pTabList->a[i-1];
  1276. if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
  1277. columnIndex(pLeft->pTab, zName)>=0 ){
  1278. /* In a NATURAL join, omit the join columns from the
  1279. ** table on the right */
  1280. continue;
  1281. }
  1282. if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
  1283. /* In a join with a USING clause, omit columns in the
  1284. ** using clause from the table on the right. */
  1285. continue;
  1286. }
  1287. }
  1288. pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  1289. if( pRight==0 ) break;
  1290. setQuotedToken(pParse, &pRight->token, zName);
  1291. if( zTabName && (longNames || pTabList->nSrc>1) ){
  1292. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  1293. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  1294. if( pExpr==0 ) break;
  1295. setQuotedToken(pParse, &pLeft->token, zTabName);
  1296. setToken(&pExpr->span,
  1297. sqlite3MPrintf(db, "%s.%s", zTabName, zName));
  1298. pExpr->span.dyn = 1;
  1299. pExpr->token.z = 0;
  1300. pExpr->token.n = 0;
  1301. pExpr->token.dyn = 0;
  1302. }else{
  1303. pExpr = pRight;
  1304. pExpr->span = pExpr->token;
  1305. pExpr->span.dyn = 0;
  1306. }
  1307. if( longNames ){
  1308. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
  1309. }else{
  1310. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
  1311. }
  1312. }
  1313. }
  1314. if( !tableSeen ){
  1315. if( zTName ){
  1316. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  1317. }else{
  1318. sqlite3ErrorMsg(pParse, "no tables specified");
  1319. }
  1320. rc = 1;
  1321. }
  1322. sqlite3_free(zTName);
  1323. }
  1324. }
  1325. sqlite3ExprListDelete(pEList);
  1326. p->pEList = pNew;
  1327. }
  1328. if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
  1329. sqlite3ErrorMsg(pParse, "too many columns in result set");
  1330. rc = SQLITE_ERROR;
  1331. }
  1332. if( db->mallocFailed ){
  1333. rc = SQLITE_NOMEM;
  1334. }
  1335. return rc;
  1336. }
  1337. /*
  1338. ** pE is a pointer to an expression which is a single term in
  1339. ** ORDER BY or GROUP BY clause.
  1340. **
  1341. ** If pE evaluates to an integer constant i, then return i.
  1342. ** This is an indication to the caller that it should sort
  1343. ** by the i-th column of the result set.
  1344. **
  1345. ** If pE is a well-formed expression and the SELECT statement
  1346. ** is not compound, then return 0. This indicates to the
  1347. ** caller that it should sort by the value of the ORDER BY
  1348. ** expression.
  1349. **
  1350. ** If the SELECT is compound, then attempt to match pE against
  1351. ** result set columns in the left-most SELECT statement. Return
  1352. ** the index i of the matching column, as an indication to the
  1353. ** caller that it should sort by the i-th column. If there is
  1354. ** no match, return -1 and leave an error message in pParse.
  1355. */
  1356. static int matchOrderByTermToExprList(
  1357. Parse *pParse, /* Parsing context for error messages */
  1358. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  1359. Expr *pE, /* The specific ORDER BY term */
  1360. int idx, /* When ORDER BY term is this */
  1361. int isCompound, /* True if this is a compound SELECT */
  1362. u8 *pHasAgg /* True if expression contains aggregate functions */
  1363. ){
  1364. int i; /* Loop counter */
  1365. ExprList *pEList; /* The columns of the result set */
  1366. NameContext nc; /* Name context for resolving pE */
  1367. /* If the term is an integer constant, return the value of that
  1368. ** constant */
  1369. pEList = pSelect->pEList;
  1370. if( sqlite3ExprIsInteger(pE, &i) ){
  1371. if( i<=0 ){
  1372. /* If i is too small, make it too big. That way the calling
  1373. ** function still sees a value that is out of range, but does
  1374. ** not confuse the column number with 0 or -1 result code.
  1375. */
  1376. i = pEList->nExpr+1;
  1377. }
  1378. return i;
  1379. }
  1380. /* If the term is a simple identifier that try to match that identifier
  1381. ** against a column name in the result set.
  1382. */
  1383. if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
  1384. sqlite3 *db = pParse->db;
  1385. char *zCol = sqlite3NameFromToken(db, &pE->token);
  1386. if( zCol==0 ){
  1387. return -1;
  1388. }
  1389. for(i=0; i<pEList->nExpr; i++){
  1390. char *zAs = pEList->a[i].zName;
  1391. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  1392. sqlite3_free(zCol);
  1393. return i+1;
  1394. }
  1395. }
  1396. sqlite3_free(zCol);
  1397. }
  1398. /* Resolve all names in the ORDER BY term expression
  1399. */
  1400. memset(&nc, 0, sizeof(nc));
  1401. nc.pParse = pParse;
  1402. nc.pSrcList = pSelect->pSrc;
  1403. nc.pEList = pEList;
  1404. nc.allowAgg = 1;
  1405. nc.nErr = 0;
  1406. if( sqlite3ExprResolveNames(&nc, pE) ){
  1407. if( isCompound ){
  1408. sqlite3ErrorClear(pParse);
  1409. return 0;
  1410. }else{
  1411. return -1;
  1412. }
  1413. }
  1414. if( nc.hasAgg && pHasAgg ){
  1415. *pHasAgg = 1;
  1416. }
  1417. /* For a compound SELECT, we need to try to match the ORDER BY
  1418. ** expression against an expression in the result set
  1419. */
  1420. if( isCompound ){
  1421. for(i=0; i<pEList->nExpr; i++){
  1422. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
  1423. return i+1;
  1424. }
  1425. }
  1426. }
  1427. return 0;
  1428. }
  1429. /*
  1430. ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
  1431. ** Return the number of errors seen.
  1432. **
  1433. ** Every term of the ORDER BY or GROUP BY clause needs to be an
  1434. ** expression. If any expression is an integer constant, then
  1435. ** that expression is replaced by the corresponding
  1436. ** expression from the result set.
  1437. */
  1438. static int processOrderGroupBy(
  1439. Parse *pParse, /* Parsing context. Leave error messages here */
  1440. Select *pSelect, /* The SELECT statement containing the clause */
  1441. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  1442. int isOrder, /* 1 for ORDER BY. 0 for GROUP BY */
  1443. u8 *pHasAgg /* Set to TRUE if any term contains an aggregate */
  1444. ){
  1445. int i;
  1446. sqlite3 *db = pParse->db;
  1447. ExprList *pEList;
  1448. if( pOrderBy==0 ) return 0;
  1449. if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
  1450. const char *zType = isOrder ? "ORDER" : "GROUP";
  1451. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  1452. return 1;
  1453. }
  1454. pEList = pSelect->pEList;
  1455. if( pEList==0 ){
  1456. return 0;
  1457. }
  1458. for(i=0; i<pOrderBy->nExpr; i++){
  1459. int iCol;
  1460. Expr *pE = pOrderBy->a[i].pExpr;
  1461. iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
  1462. if( iCol<0 ){
  1463. return 1;
  1464. }
  1465. if( iCol>pEList->nExpr ){
  1466. const char *zType = isOrder ? "ORDER" : "GROUP";
  1467. sqlite3ErrorMsg(pParse,
  1468. "%r %s BY term out of range - should be "
  1469. "between 1 and %d", i+1, zType, pEList->nExpr);
  1470. return 1;
  1471. }
  1472. if( iCol>0 ){
  1473. CollSeq *pColl = pE->pColl;
  1474. int flags = pE->flags & EP_ExpCollate;
  1475. sqlite3ExprDelete(pE);
  1476. pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
  1477. pOrderBy->a[i].pExpr = pE;
  1478. if( pColl && flags ){
  1479. pE->pColl = pColl;
  1480. pE->flags |= flags;
  1481. }
  1482. }
  1483. }
  1484. return 0;
  1485. }
  1486. /*
  1487. ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
  1488. ** the number of errors seen.
  1489. **
  1490. ** The processing depends on whether the SELECT is simple or compound.
  1491. ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY
  1492. ** clause needs to be an expression. If any expression is an integer
  1493. ** constant, then that expression is replaced by the corresponding
  1494. ** expression from the result set.
  1495. **
  1496. ** For compound SELECT statements, every expression needs to be of
  1497. ** type TK_COLUMN with a iTable value as given in the 4th parameter.
  1498. ** If any expression is an integer, that becomes the column number.
  1499. ** Otherwise, match the expression against result set columns from
  1500. ** the left-most SELECT.
  1501. */
  1502. static int processCompoundOrderBy(
  1503. Parse *pParse, /* Parsing context. Leave error messages here */
  1504. Select *pSelect, /* The SELECT statement containing the ORDER BY */
  1505. int iTable /* Output table for compound SELECT statements */
  1506. ){
  1507. int i;
  1508. ExprList *pOrderBy;
  1509. ExprList *pEList;
  1510. sqlite3 *db;
  1511. int moreToDo = 1;
  1512. pOrderBy = pSelect->pOrderBy;
  1513. if( pOrderBy==0 ) return 0;
  1514. if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
  1515. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  1516. return 1;
  1517. }
  1518. db = pParse->db;
  1519. for(i=0; i<pOrderBy->nExpr; i++){
  1520. pOrderBy->a[i].done = 0;
  1521. }
  1522. while( pSelect->pPrior ){
  1523. pSelect = pSelect->pPrior;
  1524. }
  1525. while( pSelect && moreToDo ){
  1526. moreToDo = 0;
  1527. for(i=0; i<pOrderBy->nExpr; i++){
  1528. int iCol;
  1529. Expr *pE, *pDup;
  1530. if( pOrderBy->a[i].done ) continue;
  1531. pE = pOrderBy->a[i].pExpr;
  1532. pDup = sqlite3ExprDup(db, pE);
  1533. if( pDup==0 ){
  1534. return 1;
  1535. }
  1536. iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
  1537. sqlite3ExprDelete(pDup);
  1538. if( iCol<0 ){
  1539. return 1;
  1540. }
  1541. pEList = pSelect->pEList;
  1542. if( pEList==0 ){
  1543. return 1;
  1544. }
  1545. if( iCol>pEList->nExpr ){
  1546. sqlite3ErrorMsg(pParse,
  1547. "%r ORDER BY term out of range - should be "
  1548. "between 1 and %d", i+1, pEList->nExpr);
  1549. return 1;
  1550. }
  1551. if( iCol>0 ){
  1552. pE->op = TK_COLUMN;
  1553. pE->iTable = iTable;
  1554. pE->iAgg = -1;
  1555. pE->iColumn = iCol-1;
  1556. pE->pTab = 0;
  1557. pOrderBy->a[i].done = 1;
  1558. }else{
  1559. moreToDo = 1;
  1560. }
  1561. }
  1562. pSelect = pSelect->pNext;
  1563. }
  1564. for(i=0; i<pOrderBy->nExpr; i++){
  1565. if( pOrderBy->a[i].done==0 ){
  1566. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  1567. "column in the result set", i+1);
  1568. return 1;
  1569. }
  1570. }
  1571. return 0;
  1572. }
  1573. /*
  1574. ** Get a VDBE for the given parser context. Create a new one if necessary.
  1575. ** If an error occurs, return NULL and leave a message in pParse.
  1576. */
  1577. Vdbe *sqlite3GetVdbe(Parse *pParse){
  1578. Vdbe *v = pParse->pVdbe;
  1579. if( v==0 ){
  1580. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  1581. }
  1582. return v;
  1583. }
  1584. /*
  1585. ** Compute the iLimit and iOffset fields of the SELECT based on the
  1586. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  1587. ** that appear in the original SQL statement after the LIMIT and OFFSET
  1588. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  1589. ** are the integer memory register numbers for counters used to compute
  1590. ** the limit and offset. If there is no limit and/or offset, then
  1591. ** iLimit and iOffset are negative.
  1592. **
  1593. ** This routine changes the values of iLimit and iOffset only if
  1594. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  1595. ** iOffset should have been preset to appropriate default values
  1596. ** (usually but not always -1) prior to calling this routine.
  1597. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  1598. ** redefined. The UNION ALL operator uses this property to force
  1599. ** the reuse of the same limit and offset registers across multiple
  1600. ** SELECT statements.
  1601. */
  1602. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  1603. Vdbe *v = 0;
  1604. int iLimit = 0;
  1605. int iOffset;
  1606. int addr1, addr2;
  1607. /*
  1608. ** "LIMIT -1" always shows all rows. There is some
  1609. ** contraversy about what the correct behavior should be.
  1610. ** The current implementation interprets "LIMIT 0" to mean
  1611. ** no rows.
  1612. */
  1613. if( p->pLimit ){
  1614. p->iLimit = iLimit = pParse->nMem;
  1615. pParse->nMem += 2;
  1616. v = sqlite3GetVdbe(pParse);
  1617. if( v==0 ) return;
  1618. sqlite3ExprCode(pParse, p->pLimit);
  1619. sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
  1620. sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1);
  1621. VdbeComment((v, "# LIMIT counter"));
  1622. sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
  1623. sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0);
  1624. }
  1625. if( p->pOffset ){
  1626. p->iOffset = iOffset = pParse->nMem++;
  1627. v = sqlite3GetVdbe(pParse);
  1628. if( v==0 ) return;
  1629. sqlite3ExprCode(pParse, p->pOffset);
  1630. sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
  1631. sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
  1632. VdbeComment((v, "# OFFSET counter"));
  1633. addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
  1634. sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  1635. sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
  1636. sqlite3VdbeJumpHere(v, addr1);
  1637. if( p->pLimit ){
  1638. sqlite3VdbeAddOp(v, OP_Add, 0, 0);
  1639. }
  1640. }
  1641. if( p->pLimit ){
  1642. addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
  1643. sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  1644. sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
  1645. addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
  1646. sqlite3VdbeJumpHere(v, addr1);
  1647. sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
  1648. VdbeComment((v, "# LIMIT+OFFSET"));
  1649. sqlite3VdbeJumpHere(v, addr2);
  1650. }
  1651. }
  1652. /*
  1653. ** Allocate a virtual index to use for sorting.
  1654. */
  1655. static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
  1656. if( pOrderBy ){
  1657. int addr;
  1658. assert( pOrderBy->iECursor==0 );
  1659. pOrderBy->iECursor = pParse->nTab++;
  1660. addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
  1661. pOrderBy->iECursor, pOrderBy->nExpr+1);
  1662. assert( p->addrOpenEphm[2] == -1 );
  1663. p->addrOpenEphm[2] = addr;
  1664. }
  1665. }
  1666. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  1667. /*
  1668. ** Return the appropriate collating sequence for the iCol-th column of
  1669. ** the result set for the compound-select statement "p". Return NULL if
  1670. ** the column has no default collating sequence.
  1671. **
  1672. ** The collating sequence for the compound select is taken from the
  1673. ** left-most term of the select that has a collating sequence.
  1674. */
  1675. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  1676. CollSeq *pRet;
  1677. if( p->pPrior ){
  1678. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  1679. }else{
  1680. pRet = 0;
  1681. }
  1682. if( pRet==0 ){
  1683. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  1684. }
  1685. return pRet;
  1686. }
  1687. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  1688. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  1689. /*
  1690. ** This routine is called to process a query that is really the union
  1691. ** or intersection of two or more separate queries.
  1692. **
  1693. ** "p" points to the right-most of the two queries. the query on the
  1694. ** left is p->pPrior. The left query could also be a compound query
  1695. ** in which case this routine will be called recursively.
  1696. **
  1697. ** The results of the total query are to be written into a destination
  1698. ** of type eDest with parameter iParm.
  1699. **
  1700. ** Example 1: Consider a three-way compound SQL statement.
  1701. **
  1702. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  1703. **
  1704. ** This statement is parsed up as follows:
  1705. **
  1706. ** SELECT c FROM t3
  1707. ** |
  1708. ** `-----> SELECT b FROM t2
  1709. ** |
  1710. ** `------> SELECT a FROM t1
  1711. **
  1712. ** The arrows in the diagram above represent the Select.pPrior pointer.
  1713. ** So if this routine is called with p equal to the t3 query, then
  1714. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  1715. **
  1716. ** Notice that because of the way SQLite parses compound SELECTs, the
  1717. ** individual selects always group from left to right.
  1718. */
  1719. static int multiSelect(
  1720. Parse *pParse, /* Parsing context */
  1721. Select *p, /* The right-most of SELECTs to be coded */
  1722. int eDest, /* \___ Store query results as specified */
  1723. int iParm, /* / by these two parameters. */
  1724. char *aff /* If eDest is SRT_Union, the affinity string */
  1725. ){
  1726. int rc = SQLITE_OK; /* Success code from a subroutine */
  1727. Select *pPrior; /* Another SELECT immediately to our left */
  1728. Vdbe *v; /* Generate code to this VDBE */
  1729. int nCol; /* Number of columns in the result set */
  1730. ExprList *pOrderBy; /* The ORDER BY clause on p */
  1731. int aSetP2[2]; /* Set P2 value of these op to number of columns */
  1732. int nSetP2 = 0; /* Number of slots in aSetP2[] used */
  1733. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  1734. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  1735. */
  1736. if( p==0 || p->pPrior==0 ){
  1737. rc = 1;
  1738. goto multi_select_end;
  1739. }
  1740. pPrior = p->pPrior;
  1741. assert( pPrior->pRightmost!=pPrior );
  1742. assert( pPrior->pRightmost==p->pRightmost );
  1743. if( pPrior->pOrderBy ){
  1744. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  1745. selectOpName(p->op));
  1746. rc = 1;
  1747. goto multi_select_end;
  1748. }
  1749. if( pPrior->pLimit ){
  1750. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  1751. selectOpName(p->op));
  1752. rc = 1;
  1753. goto multi_select_end;
  1754. }
  1755. /* Make sure we have a valid query engine. If not, create a new one.
  1756. */
  1757. v = sqlite3GetVdbe(pParse);
  1758. if( v==0 ){
  1759. rc = 1;
  1760. goto multi_select_end;
  1761. }
  1762. /* Create the destination temporary table if necessary
  1763. */
  1764. if( eDest==SRT_EphemTab ){
  1765. assert( p->pEList );
  1766. assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
  1767. aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
  1768. eDest = SRT_Table;
  1769. }
  1770. /* Generate code for the left and right SELECT statements.
  1771. */
  1772. pOrderBy = p->pOrderBy;
  1773. switch( p->op ){
  1774. case TK_ALL: {
  1775. if( pOrderBy==0 ){
  1776. int addr = 0;
  1777. assert( !pPrior->pLimit );
  1778. pPrior->pLimit = p->pLimit;
  1779. pPrior->pOffset = p->pOffset;
  1780. rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
  1781. p->pLimit = 0;
  1782. p->pOffset = 0;
  1783. if( rc ){
  1784. goto multi_select_end;
  1785. }
  1786. p->pPrior = 0;
  1787. p->iLimit = pPrior->iLimit;
  1788. p->iOffset = pPrior->iOffset;
  1789. if( p->iLimit>=0 ){
  1790. addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
  1791. VdbeComment((v, "# Jump ahead if LIMIT reached"));
  1792. }
  1793. rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
  1794. p->pPrior = pPrior;
  1795. if( rc ){
  1796. goto multi_select_end;
  1797. }
  1798. if( addr ){
  1799. sqlite3VdbeJumpHere(v, addr);
  1800. }
  1801. break;
  1802. }
  1803. /* For UNION ALL ... ORDER BY fall through to the next case */
  1804. }
  1805. case TK_EXCEPT:
  1806. case TK_UNION: {
  1807. int unionTab; /* Cursor number of the temporary table holding result */
  1808. int op = 0; /* One of the SRT_ operations to apply to self */
  1809. int priorOp; /* The SRT_ operation to apply to prior selects */
  1810. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  1811. int addr;
  1812. priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
  1813. if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
  1814. /* We can reuse a temporary table generated by a SELECT to our
  1815. ** right.
  1816. */
  1817. unionTab = iParm;
  1818. }else{
  1819. /* We will need to create our own temporary table to hold the
  1820. ** intermediate results.
  1821. */
  1822. unionTab = pParse->nTab++;
  1823. if( processCompoundOrderBy(pParse, p, unionTab) ){
  1824. rc = 1;
  1825. goto multi_select_end;
  1826. }
  1827. addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
  1828. if( priorOp==SRT_Table ){
  1829. assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
  1830. aSetP2[nSetP2++] = addr;
  1831. }else{
  1832. assert( p->addrOpenEphm[0] == -1 );
  1833. p->addrOpenEphm[0] = addr;
  1834. p->pRightmost->usesEphm = 1;
  1835. }
  1836. createSortingIndex(pParse, p, pOrderBy);
  1837. assert( p->pEList );
  1838. }
  1839. /* Code the SELECT statements to our left
  1840. */
  1841. assert( !pPrior->pOrderBy );
  1842. rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
  1843. if( rc ){
  1844. goto multi_select_end;
  1845. }
  1846. /* Code the current SELECT statement
  1847. */
  1848. switch( p->op ){
  1849. case TK_EXCEPT: op = SRT_Except; break;
  1850. case TK_UNION: op = SRT_Union; break;
  1851. case TK_ALL: op = SRT_Table; break;
  1852. }
  1853. p->pPrior = 0;
  1854. p->pOrderBy = 0;
  1855. p->disallowOrderBy = pOrderBy!=0;
  1856. pLimit = p->pLimit;
  1857. p->pLimit = 0;
  1858. pOffset = p->pOffset;
  1859. p->pOffset = 0;
  1860. rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
  1861. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  1862. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  1863. sqlite3ExprListDelete(p->pOrderBy);
  1864. p->pPrior = pPrior;
  1865. p->pOrderBy = pOrderBy;
  1866. sqlite3ExprDelete(p->pLimit);
  1867. p->pLimit = pLimit;
  1868. p->pOffset = pOffset;
  1869. p->iLimit = -1;
  1870. p->iOffset = -1;
  1871. if( rc ){
  1872. goto multi_select_end;
  1873. }
  1874. /* Convert the data in the temporary table into whatever form
  1875. ** it is that we currently need.
  1876. */
  1877. if( eDest!=priorOp || unionTab!=iParm ){
  1878. int iCont, iBreak, iStart;
  1879. assert( p->pEList );
  1880. if( eDest==SRT_Callback ){
  1881. Select *pFirst = p;
  1882. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  1883. generateColumnNames(pParse, 0, pFirst->pEList);
  1884. }
  1885. iBreak = sqlite3VdbeMakeLabel(v);
  1886. iCont = sqlite3VdbeMakeLabel(v);
  1887. computeLimitRegisters(pParse, p, iBreak);
  1888. sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
  1889. iStart = sqlite3VdbeCurrentAddr(v);
  1890. rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  1891. pOrderBy, -1, eDest, iParm,
  1892. iCont, iBreak, 0);
  1893. if( rc ){
  1894. rc = 1;
  1895. goto multi_select_end;
  1896. }
  1897. sqlite3VdbeResolveLabel(v, iCont);
  1898. sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
  1899. sqlite3VdbeResolveLabel(v, iBreak);
  1900. sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
  1901. }
  1902. break;
  1903. }
  1904. case TK_INTERSECT: {
  1905. int tab1, tab2;
  1906. int iCont, iBreak, iStart;
  1907. Expr *pLimit, *pOffset;
  1908. int addr;
  1909. /* INTERSECT is different from the others since it requires
  1910. ** two temporary tables. Hence it has its own case. Begin
  1911. ** by allocating the tables we will need.
  1912. */
  1913. tab1 = pParse->nTab++;
  1914. tab2 = pParse->nTab++;
  1915. if( processCompoundOrderBy(pParse, p, tab1) ){
  1916. rc = 1;
  1917. goto multi_select_end;
  1918. }
  1919. createSortingIndex(pParse, p, pOrderBy);
  1920. addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
  1921. assert( p->addrOpenEphm[0] == -1 );
  1922. p->addrOpenEphm[0] = addr;
  1923. p->pRightmost->usesEphm = 1;
  1924. assert( p->pEList );
  1925. /* Code the SELECTs to our left into temporary table "tab1".
  1926. */
  1927. rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
  1928. if( rc ){
  1929. goto multi_select_end;
  1930. }
  1931. /* Code the current SELECT into temporary table "tab2"
  1932. */
  1933. addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
  1934. assert( p->addrOpenEphm[1] == -1 );
  1935. p->addrOpenEphm[1] = addr;
  1936. p->pPrior = 0;
  1937. pLimit = p->pLimit;
  1938. p->pLimit = 0;
  1939. pOffset = p->pOffset;
  1940. p->pOffset = 0;
  1941. rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
  1942. p->pPrior = pPrior;
  1943. sqlite3ExprDelete(p->pLimit);
  1944. p->pLimit = pLimit;
  1945. p->pOffset = pOffset;
  1946. if( rc ){
  1947. goto multi_select_end;
  1948. }
  1949. /* Generate code to take the intersection of the two temporary
  1950. ** tables.
  1951. */
  1952. assert( p->pEList );
  1953. if( eDest==SRT_Callback ){
  1954. Select *pFirst = p;
  1955. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  1956. generateColumnNames(pParse, 0, pFirst->pEList);
  1957. }
  1958. iBreak = sqlite3VdbeMakeLabel(v);
  1959. iCont = sqlite3VdbeMakeLabel(v);
  1960. computeLimitRegisters(pParse, p, iBreak);
  1961. sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
  1962. iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
  1963. sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
  1964. rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  1965. pOrderBy, -1, eDest, iParm,
  1966. iCont, iBreak, 0);
  1967. if( rc ){
  1968. rc = 1;
  1969. goto multi_select_end;
  1970. }
  1971. sqlite3VdbeResolveLabel(v, iCont);
  1972. sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
  1973. sqlite3VdbeResolveLabel(v, iBreak);
  1974. sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
  1975. sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
  1976. break;
  1977. }
  1978. }
  1979. /* Make sure all SELECTs in the statement have the same number of elements
  1980. ** in their result sets.
  1981. */
  1982. assert( p->pEList && pPrior->pEList );
  1983. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  1984. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  1985. " do not have the same number of result columns", selectOpName(p->op));
  1986. rc = 1;
  1987. goto multi_select_end;
  1988. }
  1989. /* Set the number of columns in temporary tables
  1990. */
  1991. nCol = p->pEList->nExpr;
  1992. while( nSetP2 ){
  1993. sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
  1994. }
  1995. /* Compute collating sequences used by either the ORDER BY clause or
  1996. ** by any temporary tables needed to implement the compound select.
  1997. ** Attach the KeyInfo structure to all temporary tables. Invoke the
  1998. ** ORDER BY processing if there is an ORDER BY clause.
  1999. **
  2000. ** This section is run by the right-most SELECT statement only.
  2001. ** SELECT statements to the left always skip this part. The right-most
  2002. ** SELECT might also skip this part if it has no ORDER BY clause and
  2003. ** no temp tables are required.
  2004. */
  2005. if( pOrderBy || p->usesEphm ){
  2006. int i; /* Loop counter */
  2007. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  2008. Select *pLoop; /* For looping through SELECT statements */
  2009. int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */
  2010. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  2011. CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */
  2012. assert( p->pRightmost==p );
  2013. nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
  2014. pKeyInfo = sqlite3DbMallocZero(pParse->db,
  2015. sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
  2016. if( !pKeyInfo ){
  2017. rc = SQLITE_NOMEM;
  2018. goto multi_select_end;
  2019. }
  2020. pKeyInfo->enc = ENC(pParse->db);
  2021. pKeyInfo->nField = nCol;
  2022. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  2023. *apColl = multiSelectCollSeq(pParse, p, i);
  2024. if( 0==*apColl ){
  2025. *apColl = pParse->db->pDfltColl;
  2026. }
  2027. }
  2028. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  2029. for(i=0; i<2; i++){
  2030. int addr = pLoop->addrOpenEphm[i];
  2031. if( addr<0 ){
  2032. /* If [0] is unused then [1] is also unused. So we can
  2033. ** always safely abort as soon as the first unused slot is found */
  2034. assert( pLoop->addrOpenEphm[1]<0 );
  2035. break;
  2036. }
  2037. sqlite3VdbeChangeP2(v, addr, nCol);
  2038. sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
  2039. pLoop->addrOpenEphm[i] = -1;
  2040. }
  2041. }
  2042. if( pOrderBy ){
  2043. struct ExprList_item *pOTerm = pOrderBy->a;
  2044. int nOrderByExpr = pOrderBy->nExpr;
  2045. int addr;
  2046. u8 *pSortOrder;
  2047. /* Reuse the same pKeyInfo for the ORDER BY as was used above for
  2048. ** the compound select statements. Except we have to change out the
  2049. ** pKeyInfo->aColl[] values. Some of the aColl[] values will be
  2050. ** reused when constructing the pKeyInfo for the ORDER BY, so make
  2051. ** a copy. Sufficient space to hold both the nCol entries for
  2052. ** the compound select and the nOrderbyExpr entries for the ORDER BY
  2053. ** was allocated above. But we need to move the compound select
  2054. ** entries out of the way before constructing the ORDER BY entries.
  2055. ** Move the compound select entries into aCopy[] where they can be
  2056. ** accessed and reused when constructing the ORDER BY entries.
  2057. ** Because nCol might be greater than or less than nOrderByExpr
  2058. ** we have to use memmove() when doing the copy.
  2059. */
  2060. aCopy = &pKeyInfo->aColl[nOrderByExpr];
  2061. pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
  2062. memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
  2063. apColl = pKeyInfo->aColl;
  2064. for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
  2065. Expr *pExpr = pOTerm->pExpr;
  2066. if( (pExpr->flags & EP_ExpCollate) ){
  2067. assert( pExpr->pColl!=0 );
  2068. *apColl = pExpr->pColl;
  2069. }else{
  2070. *apColl = aCopy[pExpr->iColumn];
  2071. }
  2072. *pSortOrder = pOTerm->sortOrder;
  2073. }
  2074. assert( p->pRightmost==p );
  2075. assert( p->addrOpenEphm[2]>=0 );
  2076. addr = p->addrOpenEphm[2];
  2077. sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
  2078. pKeyInfo->nField = nOrderByExpr;
  2079. sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  2080. pKeyInfo = 0;
  2081. generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
  2082. }
  2083. sqlite3_free(pKeyInfo);
  2084. }
  2085. multi_select_end:
  2086. return rc;
  2087. }
  2088. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  2089. #ifndef SQLITE_OMIT_VIEW
  2090. /* Forward Declarations */
  2091. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  2092. static void substSelect(sqlite3*, Select *, int, ExprList *);
  2093. /*
  2094. ** Scan through the expression pExpr. Replace every reference to
  2095. ** a column in table number iTable with a copy of the iColumn-th
  2096. ** entry in pEList. (But leave references to the ROWID column
  2097. ** unchanged.)
  2098. **
  2099. ** This routine is part of the flattening procedure. A subquery
  2100. ** whose result set is defined by pEList appears as entry in the
  2101. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  2102. ** FORM clause entry is iTable. This routine make the necessary
  2103. ** changes to pExpr so that it refers directly to the source table
  2104. ** of the subquery rather the result set of the subquery.
  2105. */
  2106. static void substExpr(
  2107. sqlite3 *db, /* Report malloc errors to this connection */
  2108. Expr *pExpr, /* Expr in which substitution occurs */
  2109. int iTable, /* Table to be substituted */
  2110. ExprList *pEList /* Substitute expressions */
  2111. ){
  2112. if( pExpr==0 ) return;
  2113. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  2114. if( pExpr->iColumn<0 ){
  2115. pExpr->op = TK_NULL;
  2116. }else{
  2117. Expr *pNew;
  2118. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  2119. assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
  2120. pNew = pEList->a[pExpr->iColumn].pExpr;
  2121. assert( pNew!=0 );
  2122. pExpr->op = pNew->op;
  2123. assert( pExpr->pLeft==0 );
  2124. pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
  2125. assert( pExpr->pRight==0 );
  2126. pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
  2127. assert( pExpr->pList==0 );
  2128. pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
  2129. pExpr->iTable = pNew->iTable;
  2130. pExpr->pTab = pNew->pTab;
  2131. pExpr->iColumn = pNew->iColumn;
  2132. pExpr->iAgg = pNew->iAgg;
  2133. sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
  2134. sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
  2135. pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
  2136. pExpr->flags = pNew->flags;
  2137. }
  2138. }else{
  2139. substExpr(db, pExpr->pLeft, iTable, pEList);
  2140. substExpr(db, pExpr->pRight, iTable, pEList);
  2141. substSelect(db, pExpr->pSelect, iTable, pEList);
  2142. substExprList(db, pExpr->pList, iTable, pEList);
  2143. }
  2144. }
  2145. static void substExprList(
  2146. sqlite3 *db, /* Report malloc errors here */
  2147. ExprList *pList, /* List to scan and in which to make substitutes */
  2148. int iTable, /* Table to be substituted */
  2149. ExprList *pEList /* Substitute values */
  2150. ){
  2151. int i;
  2152. if( pList==0 ) return;
  2153. for(i=0; i<pList->nExpr; i++){
  2154. substExpr(db, pList->a[i].pExpr, iTable, pEList);
  2155. }
  2156. }
  2157. static void substSelect(
  2158. sqlite3 *db, /* Report malloc errors here */
  2159. Select *p, /* SELECT statement in which to make substitutions */
  2160. int iTable, /* Table to be replaced */
  2161. ExprList *pEList /* Substitute values */
  2162. ){
  2163. if( !p ) return;
  2164. substExprList(db, p->pEList, iTable, pEList);
  2165. substExprList(db, p->pGroupBy, iTable, pEList);
  2166. substExprList(db, p->pOrderBy, iTable, pEList);
  2167. substExpr(db, p->pHaving, iTable, pEList);
  2168. substExpr(db, p->pWhere, iTable, pEList);
  2169. substSelect(db, p->pPrior, iTable, pEList);
  2170. }
  2171. #endif /* !defined(SQLITE_OMIT_VIEW) */
  2172. #ifndef SQLITE_OMIT_VIEW
  2173. /*
  2174. ** This routine attempts to flatten subqueries in order to speed
  2175. ** execution. It returns 1 if it makes changes and 0 if no flattening
  2176. ** occurs.
  2177. **
  2178. ** To understand the concept of flattening, consider the following
  2179. ** query:
  2180. **
  2181. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  2182. **
  2183. ** The default way of implementing this query is to execute the
  2184. ** subquery first and store the results in a temporary table, then
  2185. ** run the outer query on that temporary table. This requires two
  2186. ** passes over the data. Furthermore, because the temporary table
  2187. ** has no indices, the WHERE clause on the outer query cannot be
  2188. ** optimized.
  2189. **
  2190. ** This routine attempts to rewrite queries such as the above into
  2191. ** a single flat select, like this:
  2192. **
  2193. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  2194. **
  2195. ** The code generated for this simpification gives the same result
  2196. ** but only has to scan the data once. And because indices might
  2197. ** exist on the table t1, a complete scan of the data might be
  2198. ** avoided.
  2199. **
  2200. ** Flattening is only attempted if all of the following are true:
  2201. **
  2202. ** (1) The subquery and the outer query do not both use aggregates.
  2203. **
  2204. ** (2) The subquery is not an aggregate or the outer query is not a join.
  2205. **
  2206. ** (3) The subquery is not the right operand of a left outer join, or
  2207. ** the subquery is not itself a join. (Ticket #306)
  2208. **
  2209. ** (4) The subquery is not DISTINCT or the outer query is not a join.
  2210. **
  2211. ** (5) The subquery is not DISTINCT or the outer query does not use
  2212. ** aggregates.
  2213. **
  2214. ** (6) The subquery does not use aggregates or the outer query is not
  2215. ** DISTINCT.
  2216. **
  2217. ** (7) The subquery has a FROM clause.
  2218. **
  2219. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  2220. **
  2221. ** (9) The subquery does not use LIMIT or the outer query does not use
  2222. ** aggregates.
  2223. **
  2224. ** (10) The subquery does not use aggregates or the outer query does not
  2225. ** use LIMIT.
  2226. **
  2227. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  2228. **
  2229. ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
  2230. ** subquery has no WHERE clause. (added by ticket #350)
  2231. **
  2232. ** (13) The subquery and outer query do not both use LIMIT
  2233. **
  2234. ** (14) The subquery does not use OFFSET
  2235. **
  2236. ** (15) The outer query is not part of a compound select or the
  2237. ** subquery does not have both an ORDER BY and a LIMIT clause.
  2238. ** (See ticket #2339)
  2239. **
  2240. ** In this routine, the "p" parameter is a pointer to the outer query.
  2241. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  2242. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  2243. **
  2244. ** If flattening is not attempted, this routine is a no-op and returns 0.
  2245. ** If flattening is attempted this routine returns 1.
  2246. **
  2247. ** All of the expression analysis must occur on both the outer query and
  2248. ** the subquery before this routine runs.
  2249. */
  2250. static int flattenSubquery(
  2251. sqlite3 *db, /* Database connection */
  2252. Select *p, /* The parent or outer SELECT statement */
  2253. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  2254. int isAgg, /* True if outer SELECT uses aggregate functions */
  2255. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  2256. ){
  2257. Select *pSub; /* The inner query or "subquery" */
  2258. SrcList *pSrc; /* The FROM clause of the outer query */
  2259. SrcList *pSubSrc; /* The FROM clause of the subquery */
  2260. ExprList *pList; /* The result set of the outer query */
  2261. int iParent; /* VDBE cursor number of the pSub result set temp table */
  2262. int i; /* Loop counter */
  2263. Expr *pWhere; /* The WHERE clause */
  2264. struct SrcList_item *pSubitem; /* The subquery */
  2265. /* Check to see if flattening is permitted. Return 0 if not.
  2266. */
  2267. if( p==0 ) return 0;
  2268. pSrc = p->pSrc;
  2269. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  2270. pSubitem = &pSrc->a[iFrom];
  2271. pSub = pSubitem->pSelect;
  2272. assert( pSub!=0 );
  2273. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  2274. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  2275. pSubSrc = pSub->pSrc;
  2276. assert( pSubSrc );
  2277. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  2278. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  2279. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  2280. ** became arbitrary expressions, we were forced to add restrictions (13)
  2281. ** and (14). */
  2282. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  2283. if( pSub->pOffset ) return 0; /* Restriction (14) */
  2284. if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
  2285. return 0; /* Restriction (15) */
  2286. }
  2287. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  2288. if( (pSub->isDistinct || pSub->pLimit)
  2289. && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */
  2290. return 0;
  2291. }
  2292. if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */
  2293. if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
  2294. return 0; /* Restriction (11) */
  2295. }
  2296. /* Restriction 3: If the subquery is a join, make sure the subquery is
  2297. ** not used as the right operand of an outer join. Examples of why this
  2298. ** is not allowed:
  2299. **
  2300. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  2301. **
  2302. ** If we flatten the above, we would get
  2303. **
  2304. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  2305. **
  2306. ** which is not at all the same thing.
  2307. */
  2308. if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
  2309. return 0;
  2310. }
  2311. /* Restriction 12: If the subquery is the right operand of a left outer
  2312. ** join, make sure the subquery has no WHERE clause.
  2313. ** An examples of why this is not allowed:
  2314. **
  2315. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  2316. **
  2317. ** If we flatten the above, we would get
  2318. **
  2319. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  2320. **
  2321. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  2322. ** effectively converts the OUTER JOIN into an INNER JOIN.
  2323. */
  2324. if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
  2325. return 0;
  2326. }
  2327. /* If we reach this point, it means flattening is permitted for the
  2328. ** iFrom-th entry of the FROM clause in the outer query.
  2329. */
  2330. /* Move all of the FROM elements of the subquery into the
  2331. ** the FROM clause of the outer query. Before doing this, remember
  2332. ** the cursor number for the original outer query FROM element in
  2333. ** iParent. The iParent cursor will never be used. Subsequent code
  2334. ** will scan expressions looking for iParent references and replace
  2335. ** those references with expressions that resolve to the subquery FROM
  2336. ** elements we are now copying in.
  2337. */
  2338. iParent = pSubitem->iCursor;
  2339. {
  2340. int nSubSrc = pSubSrc->nSrc;
  2341. int jointype = pSubitem->jointype;
  2342. sqlite3DeleteTable(pSubitem->pTab);
  2343. sqlite3_free(pSubitem->zDatabase);
  2344. sqlite3_free(pSubitem->zName);
  2345. sqlite3_free(pSubitem->zAlias);
  2346. pSubitem->pTab = 0;
  2347. pSubitem->zDatabase = 0;
  2348. pSubitem->zName = 0;
  2349. pSubitem->zAlias = 0;
  2350. if( nSubSrc>1 ){
  2351. int extra = nSubSrc - 1;
  2352. for(i=1; i<nSubSrc; i++){
  2353. pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
  2354. if( pSrc==0 ){
  2355. p->pSrc = 0;
  2356. return 1;
  2357. }
  2358. }
  2359. p->pSrc = pSrc;
  2360. for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
  2361. pSrc->a[i] = pSrc->a[i-extra];
  2362. }
  2363. }
  2364. for(i=0; i<nSubSrc; i++){
  2365. pSrc->a[i+iFrom] = pSubSrc->a[i];
  2366. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  2367. }
  2368. pSrc->a[iFrom].jointype = jointype;
  2369. }
  2370. /* Now begin substituting subquery result set expressions for
  2371. ** references to the iParent in the outer query.
  2372. **
  2373. ** Example:
  2374. **
  2375. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  2376. ** \ \_____________ subquery __________/ /
  2377. ** \_____________________ outer query ______________________________/
  2378. **
  2379. ** We look at every expression in the outer query and every place we see
  2380. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  2381. */
  2382. pList = p->pEList;
  2383. for(i=0; i<pList->nExpr; i++){
  2384. Expr *pExpr;
  2385. if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
  2386. pList->a[i].zName =
  2387. sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
  2388. }
  2389. }
  2390. substExprList(db, p->pEList, iParent, pSub->pEList);
  2391. if( isAgg ){
  2392. substExprList(db, p->pGroupBy, iParent, pSub->pEList);
  2393. substExpr(db, p->pHaving, iParent, pSub->pEList);
  2394. }
  2395. if( pSub->pOrderBy ){
  2396. assert( p->pOrderBy==0 );
  2397. p->pOrderBy = pSub->pOrderBy;
  2398. pSub->pOrderBy = 0;
  2399. }else if( p->pOrderBy ){
  2400. substExprList(db, p->pOrderBy, iParent, pSub->pEList);
  2401. }
  2402. if( pSub->pWhere ){
  2403. pWhere = sqlite3ExprDup(db, pSub->pWhere);
  2404. }else{
  2405. pWhere = 0;
  2406. }
  2407. if( subqueryIsAgg ){
  2408. assert( p->pHaving==0 );
  2409. p->pHaving = p->pWhere;
  2410. p->pWhere = pWhere;
  2411. substExpr(db, p->pHaving, iParent, pSub->pEList);
  2412. p->pHaving = sqlite3ExprAnd(db, p->pHaving,
  2413. sqlite3ExprDup(db, pSub->pHaving));
  2414. assert( p->pGroupBy==0 );
  2415. p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
  2416. }else{
  2417. substExpr(db, p->pWhere, iParent, pSub->pEList);
  2418. p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
  2419. }
  2420. /* The flattened query is distinct if either the inner or the
  2421. ** outer query is distinct.
  2422. */
  2423. p->isDistinct = p->isDistinct || pSub->isDistinct;
  2424. /*
  2425. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  2426. **
  2427. ** One is tempted to try to add a and b to combine the limits. But this
  2428. ** does not work if either limit is negative.
  2429. */
  2430. if( pSub->pLimit ){
  2431. p->pLimit = pSub->pLimit;
  2432. pSub->pLimit = 0;
  2433. }
  2434. /* Finially, delete what is left of the subquery and return
  2435. ** success.
  2436. */
  2437. sqlite3SelectDelete(pSub);
  2438. return 1;
  2439. }
  2440. #endif /* SQLITE_OMIT_VIEW */
  2441. /*
  2442. ** Analyze the SELECT statement passed in as an argument to see if it
  2443. ** is a simple min() or max() query. If it is and this query can be
  2444. ** satisfied using a single seek to the beginning or end of an index,
  2445. ** then generate the code for this SELECT and return 1. If this is not a
  2446. ** simple min() or max() query, then return 0;
  2447. **
  2448. ** A simply min() or max() query looks like this:
  2449. **
  2450. ** SELECT min(a) FROM table;
  2451. ** SELECT max(a) FROM table;
  2452. **
  2453. ** The query may have only a single table in its FROM argument. There
  2454. ** can be no GROUP BY or HAVING or WHERE clauses. The result set must
  2455. ** be the min() or max() of a single column of the table. The column
  2456. ** in the min() or max() function must be indexed.
  2457. **
  2458. ** The parameters to this routine are the same as for sqlite3Select().
  2459. ** See the header comment on that routine for additional information.
  2460. */
  2461. static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
  2462. Expr *pExpr;
  2463. int iCol;
  2464. Table *pTab;
  2465. Index *pIdx;
  2466. int base;
  2467. Vdbe *v;
  2468. int seekOp;
  2469. ExprList *pEList, *pList, eList;
  2470. struct ExprList_item eListItem;
  2471. SrcList *pSrc;
  2472. int brk;
  2473. int iDb;
  2474. /* Check to see if this query is a simple min() or max() query. Return
  2475. ** zero if it is not.
  2476. */
  2477. if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
  2478. pSrc = p->pSrc;
  2479. if( pSrc->nSrc!=1 ) return 0;
  2480. pEList = p->pEList;
  2481. if( pEList->nExpr!=1 ) return 0;
  2482. pExpr = pEList->a[0].pExpr;
  2483. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  2484. pList = pExpr->pList;
  2485. if( pList==0 || pList->nExpr!=1 ) return 0;
  2486. if( pExpr->token.n!=3 ) return 0;
  2487. if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
  2488. seekOp = OP_Rewind;
  2489. }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
  2490. seekOp = OP_Last;
  2491. }else{
  2492. return 0;
  2493. }
  2494. pExpr = pList->a[0].pExpr;
  2495. if( pExpr->op!=TK_COLUMN ) return 0;
  2496. iCol = pExpr->iColumn;
  2497. pTab = pSrc->a[0].pTab;
  2498. /* This optimization cannot be used with virtual tables. */
  2499. if( IsVirtual(pTab) ) return 0;
  2500. /* If we get to here, it means the query is of the correct form.
  2501. ** Check to make sure we have an index and make pIdx point to the
  2502. ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
  2503. ** key column, no index is necessary so set pIdx to NULL. If no
  2504. ** usable index is found, return 0.
  2505. */
  2506. if( iCol<0 ){
  2507. pIdx = 0;
  2508. }else{
  2509. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
  2510. if( pColl==0 ) return 0;
  2511. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  2512. assert( pIdx->nColumn>=1 );
  2513. if( pIdx->aiColumn[0]==iCol &&
  2514. 0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
  2515. break;
  2516. }
  2517. }
  2518. if( pIdx==0 ) return 0;
  2519. }
  2520. /* Identify column types if we will be using the callback. This
  2521. ** step is skipped if the output is going to a table or a memory cell.
  2522. ** The column names have already been generated in the calling function.
  2523. */
  2524. v = sqlite3GetVdbe(pParse);
  2525. if( v==0 ) return 0;
  2526. /* If the output is destined for a temporary table, open that table.
  2527. */
  2528. if( eDest==SRT_EphemTab ){
  2529. sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
  2530. }
  2531. /* Generating code to find the min or the max. Basically all we have
  2532. ** to do is find the first or the last entry in the chosen index. If
  2533. ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
  2534. ** or last entry in the main table.
  2535. */
  2536. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  2537. assert( iDb>=0 || pTab->isEphem );
  2538. sqlite3CodeVerifySchema(pParse, iDb);
  2539. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  2540. base = pSrc->a[0].iCursor;
  2541. brk = sqlite3VdbeMakeLabel(v);
  2542. computeLimitRegisters(pParse, p, brk);
  2543. if( pSrc->a[0].pSelect==0 ){
  2544. sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
  2545. }
  2546. if( pIdx==0 ){
  2547. sqlite3VdbeAddOp(v, seekOp, base, 0);
  2548. }else{
  2549. /* Even though the cursor used to open the index here is closed
  2550. ** as soon as a single value has been read from it, allocate it
  2551. ** using (pParse->nTab++) to prevent the cursor id from being
  2552. ** reused. This is important for statements of the form
  2553. ** "INSERT INTO x SELECT max() FROM x".
  2554. */
  2555. int iIdx;
  2556. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  2557. iIdx = pParse->nTab++;
  2558. assert( pIdx->pSchema==pTab->pSchema );
  2559. sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  2560. sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
  2561. (char*)pKey, P3_KEYINFO_HANDOFF);
  2562. if( seekOp==OP_Rewind ){
  2563. sqlite3VdbeAddOp(v, OP_Null, 0, 0);
  2564. sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
  2565. seekOp = OP_MoveGt;
  2566. }
  2567. if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){
  2568. /* Ticket #2514: invert the seek operator if we are using
  2569. ** a descending index. */
  2570. if( seekOp==OP_Last ){
  2571. seekOp = OP_Rewind;
  2572. }else{
  2573. assert( seekOp==OP_MoveGt );
  2574. seekOp = OP_MoveLt;
  2575. }
  2576. }
  2577. sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
  2578. sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
  2579. sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
  2580. sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  2581. }
  2582. eList.nExpr = 1;
  2583. memset(&eListItem, 0, sizeof(eListItem));
  2584. eList.a = &eListItem;
  2585. eList.a[0].pExpr = pExpr;
  2586. selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
  2587. sqlite3VdbeResolveLabel(v, brk);
  2588. sqlite3VdbeAddOp(v, OP_Close, base, 0);
  2589. return 1;
  2590. }
  2591. /*
  2592. ** This routine resolves any names used in the result set of the
  2593. ** supplied SELECT statement. If the SELECT statement being resolved
  2594. ** is a sub-select, then pOuterNC is a pointer to the NameContext
  2595. ** of the parent SELECT.
  2596. */
  2597. int sqlite3SelectResolve(
  2598. Parse *pParse, /* The parser context */
  2599. Select *p, /* The SELECT statement being coded. */
  2600. NameContext *pOuterNC /* The outer name context. May be NULL. */
  2601. ){
  2602. ExprList *pEList; /* Result set. */
  2603. int i; /* For-loop variable used in multiple places */
  2604. NameContext sNC; /* Local name-context */
  2605. ExprList *pGroupBy; /* The group by clause */
  2606. /* If this routine has run before, return immediately. */
  2607. if( p->isResolved ){
  2608. assert( !pOuterNC );
  2609. return SQLITE_OK;
  2610. }
  2611. p->isResolved = 1;
  2612. /* If there have already been errors, do nothing. */
  2613. if( pParse->nErr>0 ){
  2614. return SQLITE_ERROR;
  2615. }
  2616. /* Prepare the select statement. This call will allocate all cursors
  2617. ** required to handle the tables and subqueries in the FROM clause.
  2618. */
  2619. if( prepSelectStmt(pParse, p) ){
  2620. return SQLITE_ERROR;
  2621. }
  2622. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  2623. ** are not allowed to refer to any names, so pass an empty NameContext.
  2624. */
  2625. memset(&sNC, 0, sizeof(sNC));
  2626. sNC.pParse = pParse;
  2627. if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
  2628. sqlite3ExprResolveNames(&sNC, p->pOffset) ){
  2629. return SQLITE_ERROR;
  2630. }
  2631. /* Set up the local name-context to pass to ExprResolveNames() to
  2632. ** resolve the expression-list.
  2633. */
  2634. sNC.allowAgg = 1;
  2635. sNC.pSrcList = p->pSrc;
  2636. sNC.pNext = pOuterNC;
  2637. /* Resolve names in the result set. */
  2638. pEList = p->pEList;
  2639. if( !pEList ) return SQLITE_ERROR;
  2640. for(i=0; i<pEList->nExpr; i++){
  2641. Expr *pX = pEList->a[i].pExpr;
  2642. if( sqlite3ExprResolveNames(&sNC, pX) ){
  2643. return SQLITE_ERROR;
  2644. }
  2645. }
  2646. /* If there are no aggregate functions in the result-set, and no GROUP BY
  2647. ** expression, do not allow aggregates in any of the other expressions.
  2648. */
  2649. assert( !p->isAgg );
  2650. pGroupBy = p->pGroupBy;
  2651. if( pGroupBy || sNC.hasAgg ){
  2652. p->isAgg = 1;
  2653. }else{
  2654. sNC.allowAgg = 0;
  2655. }
  2656. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  2657. */
  2658. if( p->pHaving && !pGroupBy ){
  2659. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  2660. return SQLITE_ERROR;
  2661. }
  2662. /* Add the expression list to the name-context before parsing the
  2663. ** other expressions in the SELECT statement. This is so that
  2664. ** expressions in the WHERE clause (etc.) can refer to expressions by
  2665. ** aliases in the result set.
  2666. **
  2667. ** Minor point: If this is the case, then the expression will be
  2668. ** re-evaluated for each reference to it.
  2669. */
  2670. sNC.pEList = p->pEList;
  2671. if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
  2672. sqlite3ExprResolveNames(&sNC, p->pHaving) ){
  2673. return SQLITE_ERROR;
  2674. }
  2675. if( p->pPrior==0 ){
  2676. if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
  2677. return SQLITE_ERROR;
  2678. }
  2679. }
  2680. if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
  2681. return SQLITE_ERROR;
  2682. }
  2683. if( pParse->db->mallocFailed ){
  2684. return SQLITE_NOMEM;
  2685. }
  2686. /* Make sure the GROUP BY clause does not contain aggregate functions.
  2687. */
  2688. if( pGroupBy ){
  2689. struct ExprList_item *pItem;
  2690. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  2691. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  2692. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  2693. "the GROUP BY clause");
  2694. return SQLITE_ERROR;
  2695. }
  2696. }
  2697. }
  2698. /* If this is one SELECT of a compound, be sure to resolve names
  2699. ** in the other SELECTs.
  2700. */
  2701. if( p->pPrior ){
  2702. return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
  2703. }else{
  2704. return SQLITE_OK;
  2705. }
  2706. }
  2707. /*
  2708. ** Reset the aggregate accumulator.
  2709. **
  2710. ** The aggregate accumulator is a set of memory cells that hold
  2711. ** intermediate results while calculating an aggregate. This
  2712. ** routine simply stores NULLs in all of those memory cells.
  2713. */
  2714. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  2715. Vdbe *v = pParse->pVdbe;
  2716. int i;
  2717. struct AggInfo_func *pFunc;
  2718. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  2719. return;
  2720. }
  2721. for(i=0; i<pAggInfo->nColumn; i++){
  2722. sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
  2723. }
  2724. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  2725. sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
  2726. if( pFunc->iDistinct>=0 ){
  2727. Expr *pE = pFunc->pExpr;
  2728. if( pE->pList==0 || pE->pList->nExpr!=1 ){
  2729. sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
  2730. "by an expression");
  2731. pFunc->iDistinct = -1;
  2732. }else{
  2733. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
  2734. sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0,
  2735. (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  2736. }
  2737. }
  2738. }
  2739. }
  2740. /*
  2741. ** Invoke the OP_AggFinalize opcode for every aggregate function
  2742. ** in the AggInfo structure.
  2743. */
  2744. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  2745. Vdbe *v = pParse->pVdbe;
  2746. int i;
  2747. struct AggInfo_func *pF;
  2748. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  2749. ExprList *pList = pF->pExpr->pList;
  2750. sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
  2751. (void*)pF->pFunc, P3_FUNCDEF);
  2752. }
  2753. }
  2754. /*
  2755. ** Update the accumulator memory cells for an aggregate based on
  2756. ** the current cursor position.
  2757. */
  2758. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  2759. Vdbe *v = pParse->pVdbe;
  2760. int i;
  2761. struct AggInfo_func *pF;
  2762. struct AggInfo_col *pC;
  2763. pAggInfo->directMode = 1;
  2764. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  2765. int nArg;
  2766. int addrNext = 0;
  2767. ExprList *pList = pF->pExpr->pList;
  2768. if( pList ){
  2769. nArg = pList->nExpr;
  2770. sqlite3ExprCodeExprList(pParse, pList);
  2771. }else{
  2772. nArg = 0;
  2773. }
  2774. if( pF->iDistinct>=0 ){
  2775. addrNext = sqlite3VdbeMakeLabel(v);
  2776. assert( nArg==1 );
  2777. codeDistinct(v, pF->iDistinct, addrNext, 1);
  2778. }
  2779. if( pF->pFunc->needCollSeq ){
  2780. CollSeq *pColl = 0;
  2781. struct ExprList_item *pItem;
  2782. int j;
  2783. assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */
  2784. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  2785. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  2786. }
  2787. if( !pColl ){
  2788. pColl = pParse->db->pDfltColl;
  2789. }
  2790. sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
  2791. }
  2792. sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
  2793. if( addrNext ){
  2794. sqlite3VdbeResolveLabel(v, addrNext);
  2795. }
  2796. }
  2797. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  2798. sqlite3ExprCode(pParse, pC->pExpr);
  2799. sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
  2800. }
  2801. pAggInfo->directMode = 0;
  2802. }
  2803. /*
  2804. ** Generate code for the given SELECT statement.
  2805. **
  2806. ** The results are distributed in various ways depending on the
  2807. ** value of eDest and iParm.
  2808. **
  2809. ** eDest Value Result
  2810. ** ------------ -------------------------------------------
  2811. ** SRT_Callback Invoke the callback for each row of the result.
  2812. **
  2813. ** SRT_Mem Store first result in memory cell iParm
  2814. **
  2815. ** SRT_Set Store results as keys of table iParm.
  2816. **
  2817. ** SRT_Union Store results as a key in a temporary table iParm
  2818. **
  2819. ** SRT_Except Remove results from the temporary table iParm.
  2820. **
  2821. ** SRT_Table Store results in temporary table iParm
  2822. **
  2823. ** The table above is incomplete. Additional eDist value have be added
  2824. ** since this comment was written. See the selectInnerLoop() function for
  2825. ** a complete listing of the allowed values of eDest and their meanings.
  2826. **
  2827. ** This routine returns the number of errors. If any errors are
  2828. ** encountered, then an appropriate error message is left in
  2829. ** pParse->zErrMsg.
  2830. **
  2831. ** This routine does NOT free the Select structure passed in. The
  2832. ** calling function needs to do that.
  2833. **
  2834. ** The pParent, parentTab, and *pParentAgg fields are filled in if this
  2835. ** SELECT is a subquery. This routine may try to combine this SELECT
  2836. ** with its parent to form a single flat query. In so doing, it might
  2837. ** change the parent query from a non-aggregate to an aggregate query.
  2838. ** For that reason, the pParentAgg flag is passed as a pointer, so it
  2839. ** can be changed.
  2840. **
  2841. ** Example 1: The meaning of the pParent parameter.
  2842. **
  2843. ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
  2844. ** \ \_______ subquery _______/ /
  2845. ** \ /
  2846. ** \____________________ outer query ___________________/
  2847. **
  2848. ** This routine is called for the outer query first. For that call,
  2849. ** pParent will be NULL. During the processing of the outer query, this
  2850. ** routine is called recursively to handle the subquery. For the recursive
  2851. ** call, pParent will point to the outer query. Because the subquery is
  2852. ** the second element in a three-way join, the parentTab parameter will
  2853. ** be 1 (the 2nd value of a 0-indexed array.)
  2854. */
  2855. int sqlite3Select(
  2856. Parse *pParse, /* The parser context */
  2857. Select *p, /* The SELECT statement being coded. */
  2858. int eDest, /* How to dispose of the results */
  2859. int iParm, /* A parameter used by the eDest disposal method */
  2860. Select *pParent, /* Another SELECT for which this is a sub-query */
  2861. int parentTab, /* Index in pParent->pSrc of this query */
  2862. int *pParentAgg, /* True if pParent uses aggregate functions */
  2863. char *aff /* If eDest is SRT_Union, the affinity string */
  2864. ){
  2865. int i, j; /* Loop counters */
  2866. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  2867. Vdbe *v; /* The virtual machine under construction */
  2868. int isAgg; /* True for select lists like "count(*)" */
  2869. ExprList *pEList; /* List of columns to extract. */
  2870. SrcList *pTabList; /* List of tables to select from */
  2871. Expr *pWhere; /* The WHERE clause. May be NULL */
  2872. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  2873. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  2874. Expr *pHaving; /* The HAVING clause. May be NULL */
  2875. int isDistinct; /* True if the DISTINCT keyword is present */
  2876. int distinct; /* Table to use for the distinct set */
  2877. int rc = 1; /* Value to return from this function */
  2878. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  2879. AggInfo sAggInfo; /* Information used by aggregate queries */
  2880. int iEnd; /* Address of the end of the query */
  2881. sqlite3 *db; /* The database connection */
  2882. db = pParse->db;
  2883. if( p==0 || db->mallocFailed || pParse->nErr ){
  2884. return 1;
  2885. }
  2886. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  2887. memset(&sAggInfo, 0, sizeof(sAggInfo));
  2888. pOrderBy = p->pOrderBy;
  2889. if( IgnorableOrderby(eDest) ){
  2890. p->pOrderBy = 0;
  2891. }
  2892. if( sqlite3SelectResolve(pParse, p, 0) ){
  2893. goto select_end;
  2894. }
  2895. p->pOrderBy = pOrderBy;
  2896. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  2897. /* If there is are a sequence of queries, do the earlier ones first.
  2898. */
  2899. if( p->pPrior ){
  2900. if( p->pRightmost==0 ){
  2901. Select *pLoop, *pRight = 0;
  2902. int cnt = 0;
  2903. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  2904. pLoop->pRightmost = p;
  2905. pLoop->pNext = pRight;
  2906. pRight = pLoop;
  2907. }
  2908. if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
  2909. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  2910. return 1;
  2911. }
  2912. }
  2913. return multiSelect(pParse, p, eDest, iParm, aff);
  2914. }
  2915. #endif
  2916. /* Make local copies of the parameters for this query.
  2917. */
  2918. pTabList = p->pSrc;
  2919. pWhere = p->pWhere;
  2920. pGroupBy = p->pGroupBy;
  2921. pHaving = p->pHaving;
  2922. isAgg = p->isAgg;
  2923. isDistinct = p->isDistinct;
  2924. pEList = p->pEList;
  2925. if( pEList==0 ) goto select_end;
  2926. /*
  2927. ** Do not even attempt to generate any code if we have already seen
  2928. ** errors before this routine starts.
  2929. */
  2930. if( pParse->nErr>0 ) goto select_end;
  2931. /* If writing to memory or generating a set
  2932. ** only a single column may be output.
  2933. */
  2934. #ifndef SQLITE_OMIT_SUBQUERY
  2935. if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
  2936. goto select_end;
  2937. }
  2938. #endif
  2939. /* ORDER BY is ignored for some destinations.
  2940. */
  2941. if( IgnorableOrderby(eDest) ){
  2942. pOrderBy = 0;
  2943. }
  2944. /* Begin generating code.
  2945. */
  2946. v = sqlite3GetVdbe(pParse);
  2947. if( v==0 ) goto select_end;
  2948. /* Generate code for all sub-queries in the FROM clause
  2949. */
  2950. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  2951. for(i=0; i<pTabList->nSrc; i++){
  2952. const char *zSavedAuthContext = 0;
  2953. int needRestoreContext;
  2954. struct SrcList_item *pItem = &pTabList->a[i];
  2955. if( pItem->pSelect==0 || pItem->isPopulated ) continue;
  2956. if( pItem->zName!=0 ){
  2957. zSavedAuthContext = pParse->zAuthContext;
  2958. pParse->zAuthContext = pItem->zName;
  2959. needRestoreContext = 1;
  2960. }else{
  2961. needRestoreContext = 0;
  2962. }
  2963. #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
  2964. /* Increment Parse.nHeight by the height of the largest expression
  2965. ** tree refered to by this, the parent select. The child select
  2966. ** may contain expression trees of at most
  2967. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  2968. ** more conservative than necessary, but much easier than enforcing
  2969. ** an exact limit.
  2970. */
  2971. pParse->nHeight += sqlite3SelectExprHeight(p);
  2972. #endif
  2973. sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab,
  2974. pItem->iCursor, p, i, &isAgg, 0);
  2975. if( db->mallocFailed ){
  2976. goto select_end;
  2977. }
  2978. #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
  2979. pParse->nHeight -= sqlite3SelectExprHeight(p);
  2980. #endif
  2981. if( needRestoreContext ){
  2982. pParse->zAuthContext = zSavedAuthContext;
  2983. }
  2984. pTabList = p->pSrc;
  2985. pWhere = p->pWhere;
  2986. if( !IgnorableOrderby(eDest) ){
  2987. pOrderBy = p->pOrderBy;
  2988. }
  2989. pGroupBy = p->pGroupBy;
  2990. pHaving = p->pHaving;
  2991. isDistinct = p->isDistinct;
  2992. }
  2993. #endif
  2994. /* Check for the special case of a min() or max() function by itself
  2995. ** in the result set.
  2996. */
  2997. if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
  2998. rc = 0;
  2999. goto select_end;
  3000. }
  3001. /* Check to see if this is a subquery that can be "flattened" into its parent.
  3002. ** If flattening is a possiblity, do so and return immediately.
  3003. */
  3004. #ifndef SQLITE_OMIT_VIEW
  3005. if( pParent && pParentAgg &&
  3006. flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
  3007. if( isAgg ) *pParentAgg = 1;
  3008. goto select_end;
  3009. }
  3010. #endif
  3011. /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
  3012. ** GROUP BY may use an index, DISTINCT never does.
  3013. */
  3014. if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
  3015. p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
  3016. pGroupBy = p->pGroupBy;
  3017. p->isDistinct = 0;
  3018. isDistinct = 0;
  3019. }
  3020. /* If there is an ORDER BY clause, then this sorting
  3021. ** index might end up being unused if the data can be
  3022. ** extracted in pre-sorted order. If that is the case, then the
  3023. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  3024. ** we figure out that the sorting index is not needed. The addrSortIndex
  3025. ** variable is used to facilitate that change.
  3026. */
  3027. if( pOrderBy ){
  3028. KeyInfo *pKeyInfo;
  3029. if( pParse->nErr ){
  3030. goto select_end;
  3031. }
  3032. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  3033. pOrderBy->iECursor = pParse->nTab++;
  3034. p->addrOpenEphm[2] = addrSortIndex =
  3035. sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  3036. }else{
  3037. addrSortIndex = -1;
  3038. }
  3039. /* If the output is destined for a temporary table, open that table.
  3040. */
  3041. if( eDest==SRT_EphemTab ){
  3042. sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
  3043. }
  3044. /* Set the limiter.
  3045. */
  3046. iEnd = sqlite3VdbeMakeLabel(v);
  3047. computeLimitRegisters(pParse, p, iEnd);
  3048. /* Open a virtual index to use for the distinct set.
  3049. */
  3050. if( isDistinct ){
  3051. KeyInfo *pKeyInfo;
  3052. assert( isAgg || pGroupBy );
  3053. distinct = pParse->nTab++;
  3054. pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
  3055. sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0,
  3056. (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  3057. }else{
  3058. distinct = -1;
  3059. }
  3060. /* Aggregate and non-aggregate queries are handled differently */
  3061. if( !isAgg && pGroupBy==0 ){
  3062. /* This case is for non-aggregate queries
  3063. ** Begin the database scan
  3064. */
  3065. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
  3066. if( pWInfo==0 ) goto select_end;
  3067. /* If sorting index that was created by a prior OP_OpenEphemeral
  3068. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  3069. ** into an OP_Noop.
  3070. */
  3071. if( addrSortIndex>=0 && pOrderBy==0 ){
  3072. sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
  3073. p->addrOpenEphm[2] = -1;
  3074. }
  3075. /* Use the standard inner loop
  3076. */
  3077. assert(!isDistinct);
  3078. if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, eDest,
  3079. iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
  3080. goto select_end;
  3081. }
  3082. /* End the database scan loop.
  3083. */
  3084. sqlite3WhereEnd(pWInfo);
  3085. }else{
  3086. /* This is the processing for aggregate queries */
  3087. NameContext sNC; /* Name context for processing aggregate information */
  3088. int iAMem; /* First Mem address for storing current GROUP BY */
  3089. int iBMem; /* First Mem address for previous GROUP BY */
  3090. int iUseFlag; /* Mem address holding flag indicating that at least
  3091. ** one row of the input to the aggregator has been
  3092. ** processed */
  3093. int iAbortFlag; /* Mem address which causes query abort if positive */
  3094. int groupBySort; /* Rows come from source in GROUP BY order */
  3095. /* The following variables hold addresses or labels for parts of the
  3096. ** virtual machine program we are putting together */
  3097. int addrOutputRow; /* Start of subroutine that outputs a result row */
  3098. int addrSetAbort; /* Set the abort flag and return */
  3099. int addrInitializeLoop; /* Start of code that initializes the input loop */
  3100. int addrTopOfLoop; /* Top of the input loop */
  3101. int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
  3102. int addrProcessRow; /* Code to process a single input row */
  3103. int addrEnd; /* End of all processing */
  3104. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  3105. int addrReset; /* Subroutine for resetting the accumulator */
  3106. addrEnd = sqlite3VdbeMakeLabel(v);
  3107. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  3108. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  3109. ** SELECT statement.
  3110. */
  3111. memset(&sNC, 0, sizeof(sNC));
  3112. sNC.pParse = pParse;
  3113. sNC.pSrcList = pTabList;
  3114. sNC.pAggInfo = &sAggInfo;
  3115. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  3116. sAggInfo.pGroupBy = pGroupBy;
  3117. if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
  3118. goto select_end;
  3119. }
  3120. if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
  3121. goto select_end;
  3122. }
  3123. if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
  3124. goto select_end;
  3125. }
  3126. sAggInfo.nAccumulator = sAggInfo.nColumn;
  3127. for(i=0; i<sAggInfo.nFunc; i++){
  3128. if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
  3129. goto select_end;
  3130. }
  3131. }
  3132. if( db->mallocFailed ) goto select_end;
  3133. /* Processing for aggregates with GROUP BY is very different and
  3134. ** much more complex than aggregates without a GROUP BY.
  3135. */
  3136. if( pGroupBy ){
  3137. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  3138. /* Create labels that we will be needing
  3139. */
  3140. addrInitializeLoop = sqlite3VdbeMakeLabel(v);
  3141. addrGroupByChange = sqlite3VdbeMakeLabel(v);
  3142. addrProcessRow = sqlite3VdbeMakeLabel(v);
  3143. /* If there is a GROUP BY clause we might need a sorting index to
  3144. ** implement it. Allocate that sorting index now. If it turns out
  3145. ** that we do not need it after all, the OpenEphemeral instruction
  3146. ** will be converted into a Noop.
  3147. */
  3148. sAggInfo.sortingIdx = pParse->nTab++;
  3149. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  3150. addrSortingIdx =
  3151. sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
  3152. sAggInfo.nSortingColumn,
  3153. (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  3154. /* Initialize memory locations used by GROUP BY aggregate processing
  3155. */
  3156. iUseFlag = pParse->nMem++;
  3157. iAbortFlag = pParse->nMem++;
  3158. iAMem = pParse->nMem;
  3159. pParse->nMem += pGroupBy->nExpr;
  3160. iBMem = pParse->nMem;
  3161. pParse->nMem += pGroupBy->nExpr;
  3162. sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
  3163. VdbeComment((v, "# clear abort flag"));
  3164. sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
  3165. VdbeComment((v, "# indicate accumulator empty"));
  3166. sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
  3167. /* Generate a subroutine that outputs a single row of the result
  3168. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  3169. ** is less than or equal to zero, the subroutine is a no-op. If
  3170. ** the processing calls for the query to abort, this subroutine
  3171. ** increments the iAbortFlag memory location before returning in
  3172. ** order to signal the caller to abort.
  3173. */
  3174. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  3175. sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
  3176. VdbeComment((v, "# set abort flag"));
  3177. sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  3178. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  3179. sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
  3180. VdbeComment((v, "# Groupby result generator entry point"));
  3181. sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  3182. finalizeAggFunctions(pParse, &sAggInfo);
  3183. if( pHaving ){
  3184. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
  3185. }
  3186. rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  3187. distinct, eDest, iParm,
  3188. addrOutputRow+1, addrSetAbort, aff);
  3189. if( rc ){
  3190. goto select_end;
  3191. }
  3192. sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  3193. VdbeComment((v, "# end groupby result generator"));
  3194. /* Generate a subroutine that will reset the group-by accumulator
  3195. */
  3196. addrReset = sqlite3VdbeCurrentAddr(v);
  3197. resetAccumulator(pParse, &sAggInfo);
  3198. sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  3199. /* Begin a loop that will extract all source rows in GROUP BY order.
  3200. ** This might involve two separate loops with an OP_Sort in between, or
  3201. ** it might be a single loop that uses an index to extract information
  3202. ** in the right order to begin with.
  3203. */
  3204. sqlite3VdbeResolveLabel(v, addrInitializeLoop);
  3205. sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
  3206. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
  3207. if( pWInfo==0 ) goto select_end;
  3208. if( pGroupBy==0 ){
  3209. /* The optimizer is able to deliver rows in group by order so
  3210. ** we do not have to sort. The OP_OpenEphemeral table will be
  3211. ** cancelled later because we still need to use the pKeyInfo
  3212. */
  3213. pGroupBy = p->pGroupBy;
  3214. groupBySort = 0;
  3215. }else{
  3216. /* Rows are coming out in undetermined order. We have to push
  3217. ** each row into a sorting index, terminate the first loop,
  3218. ** then loop over the sorting index in order to get the output
  3219. ** in sorted order
  3220. */
  3221. groupBySort = 1;
  3222. sqlite3ExprCodeExprList(pParse, pGroupBy);
  3223. sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
  3224. j = pGroupBy->nExpr+1;
  3225. for(i=0; i<sAggInfo.nColumn; i++){
  3226. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  3227. if( pCol->iSorterColumn<j ) continue;
  3228. sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
  3229. j++;
  3230. }
  3231. sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
  3232. sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
  3233. sqlite3WhereEnd(pWInfo);
  3234. sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
  3235. VdbeComment((v, "# GROUP BY sort"));
  3236. sAggInfo.useSortingIdx = 1;
  3237. }
  3238. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  3239. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  3240. ** Then compare the current GROUP BY terms against the GROUP BY terms
  3241. ** from the previous row currently stored in a0, a1, a2...
  3242. */
  3243. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  3244. for(j=0; j<pGroupBy->nExpr; j++){
  3245. if( groupBySort ){
  3246. sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
  3247. }else{
  3248. sAggInfo.directMode = 1;
  3249. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
  3250. }
  3251. sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
  3252. }
  3253. for(j=pGroupBy->nExpr-1; j>=0; j--){
  3254. if( j<pGroupBy->nExpr-1 ){
  3255. sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
  3256. }
  3257. sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
  3258. if( j==0 ){
  3259. sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
  3260. }else{
  3261. sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
  3262. }
  3263. sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
  3264. }
  3265. /* Generate code that runs whenever the GROUP BY changes.
  3266. ** Change in the GROUP BY are detected by the previous code
  3267. ** block. If there were no changes, this block is skipped.
  3268. **
  3269. ** This code copies current group by terms in b0,b1,b2,...
  3270. ** over to a0,a1,a2. It then calls the output subroutine
  3271. ** and resets the aggregate accumulator registers in preparation
  3272. ** for the next GROUP BY batch.
  3273. */
  3274. sqlite3VdbeResolveLabel(v, addrGroupByChange);
  3275. for(j=0; j<pGroupBy->nExpr; j++){
  3276. sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
  3277. }
  3278. sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
  3279. VdbeComment((v, "# output one row"));
  3280. sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
  3281. VdbeComment((v, "# check abort flag"));
  3282. sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
  3283. VdbeComment((v, "# reset accumulator"));
  3284. /* Update the aggregate accumulators based on the content of
  3285. ** the current row
  3286. */
  3287. sqlite3VdbeResolveLabel(v, addrProcessRow);
  3288. updateAccumulator(pParse, &sAggInfo);
  3289. sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
  3290. VdbeComment((v, "# indicate data in accumulator"));
  3291. /* End of the loop
  3292. */
  3293. if( groupBySort ){
  3294. sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
  3295. }else{
  3296. sqlite3WhereEnd(pWInfo);
  3297. sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
  3298. }
  3299. /* Output the final row of result
  3300. */
  3301. sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
  3302. VdbeComment((v, "# output final row"));
  3303. } /* endif pGroupBy */
  3304. else {
  3305. /* This case runs if the aggregate has no GROUP BY clause. The
  3306. ** processing is much simpler since there is only a single row
  3307. ** of output.
  3308. */
  3309. resetAccumulator(pParse, &sAggInfo);
  3310. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
  3311. if( pWInfo==0 ) goto select_end;
  3312. updateAccumulator(pParse, &sAggInfo);
  3313. sqlite3WhereEnd(pWInfo);
  3314. finalizeAggFunctions(pParse, &sAggInfo);
  3315. pOrderBy = 0;
  3316. if( pHaving ){
  3317. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
  3318. }
  3319. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
  3320. eDest, iParm, addrEnd, addrEnd, aff);
  3321. }
  3322. sqlite3VdbeResolveLabel(v, addrEnd);
  3323. } /* endif aggregate query */
  3324. /* If there is an ORDER BY clause, then we need to sort the results
  3325. ** and send them to the callback one by one.
  3326. */
  3327. if( pOrderBy ){
  3328. generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
  3329. }
  3330. #ifndef SQLITE_OMIT_SUBQUERY
  3331. /* If this was a subquery, we have now converted the subquery into a
  3332. ** temporary table. So set the SrcList_item.isPopulated flag to prevent
  3333. ** this subquery from being evaluated again and to force the use of
  3334. ** the temporary table.
  3335. */
  3336. if( pParent ){
  3337. assert( pParent->pSrc->nSrc>parentTab );
  3338. assert( pParent->pSrc->a[parentTab].pSelect==p );
  3339. pParent->pSrc->a[parentTab].isPopulated = 1;
  3340. }
  3341. #endif
  3342. /* Jump here to skip this query
  3343. */
  3344. sqlite3VdbeResolveLabel(v, iEnd);
  3345. /* The SELECT was successfully coded. Set the return code to 0
  3346. ** to indicate no errors.
  3347. */
  3348. rc = 0;
  3349. /* Control jumps to here if an error is encountered above, or upon
  3350. ** successful coding of the SELECT.
  3351. */
  3352. select_end:
  3353. /* Identify column names if we will be using them in a callback. This
  3354. ** step is skipped if the output is going to some other destination.
  3355. */
  3356. if( rc==SQLITE_OK && eDest==SRT_Callback ){
  3357. generateColumnNames(pParse, pTabList, pEList);
  3358. }
  3359. sqlite3_free(sAggInfo.aCol);
  3360. sqlite3_free(sAggInfo.aFunc);
  3361. return rc;
  3362. }
  3363. #if defined(SQLITE_DEBUG)
  3364. /*
  3365. *******************************************************************************
  3366. ** The following code is used for testing and debugging only. The code
  3367. ** that follows does not appear in normal builds.
  3368. **
  3369. ** These routines are used to print out the content of all or part of a
  3370. ** parse structures such as Select or Expr. Such printouts are useful
  3371. ** for helping to understand what is happening inside the code generator
  3372. ** during the execution of complex SELECT statements.
  3373. **
  3374. ** These routine are not called anywhere from within the normal
  3375. ** code base. Then are intended to be called from within the debugger
  3376. ** or from temporary "printf" statements inserted for debugging.
  3377. */
  3378. void sqlite3PrintExpr(Expr *p){
  3379. if( p->token.z && p->token.n>0 ){
  3380. sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
  3381. }else{
  3382. sqlite3DebugPrintf("(%d", p->op);
  3383. }
  3384. if( p->pLeft ){
  3385. sqlite3DebugPrintf(" ");
  3386. sqlite3PrintExpr(p->pLeft);
  3387. }
  3388. if( p->pRight ){
  3389. sqlite3DebugPrintf(" ");
  3390. sqlite3PrintExpr(p->pRight);
  3391. }
  3392. sqlite3DebugPrintf(")");
  3393. }
  3394. void sqlite3PrintExprList(ExprList *pList){
  3395. int i;
  3396. for(i=0; i<pList->nExpr; i++){
  3397. sqlite3PrintExpr(pList->a[i].pExpr);
  3398. if( i<pList->nExpr-1 ){
  3399. sqlite3DebugPrintf(", ");
  3400. }
  3401. }
  3402. }
  3403. void sqlite3PrintSelect(Select *p, int indent){
  3404. sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  3405. sqlite3PrintExprList(p->pEList);
  3406. sqlite3DebugPrintf("\n");
  3407. if( p->pSrc ){
  3408. char *zPrefix;
  3409. int i;
  3410. zPrefix = "FROM";
  3411. for(i=0; i<p->pSrc->nSrc; i++){
  3412. struct SrcList_item *pItem = &p->pSrc->a[i];
  3413. sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
  3414. zPrefix = "";
  3415. if( pItem->pSelect ){
  3416. sqlite3DebugPrintf("(\n");
  3417. sqlite3PrintSelect(pItem->pSelect, indent+10);
  3418. sqlite3DebugPrintf("%*s)", indent+8, "");
  3419. }else if( pItem->zName ){
  3420. sqlite3DebugPrintf("%s", pItem->zName);
  3421. }
  3422. if( pItem->pTab ){
  3423. sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
  3424. }
  3425. if( pItem->zAlias ){
  3426. sqlite3DebugPrintf(" AS %s", pItem->zAlias);
  3427. }
  3428. if( i<p->pSrc->nSrc-1 ){
  3429. sqlite3DebugPrintf(",");
  3430. }
  3431. sqlite3DebugPrintf("\n");
  3432. }
  3433. }
  3434. if( p->pWhere ){
  3435. sqlite3DebugPrintf("%*s WHERE ", indent, "");
  3436. sqlite3PrintExpr(p->pWhere);
  3437. sqlite3DebugPrintf("\n");
  3438. }
  3439. if( p->pGroupBy ){
  3440. sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
  3441. sqlite3PrintExprList(p->pGroupBy);
  3442. sqlite3DebugPrintf("\n");
  3443. }
  3444. if( p->pHaving ){
  3445. sqlite3DebugPrintf("%*s HAVING ", indent, "");
  3446. sqlite3PrintExpr(p->pHaving);
  3447. sqlite3DebugPrintf("\n");
  3448. }
  3449. if( p->pOrderBy ){
  3450. sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
  3451. sqlite3PrintExprList(p->pOrderBy);
  3452. sqlite3DebugPrintf("\n");
  3453. }
  3454. }
  3455. /* End of the structure debug printing code
  3456. *****************************************************************************/
  3457. #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */