1cce7d176Sdrh /* 2b19a2bc6Sdrh ** 2001 September 15 3cce7d176Sdrh ** 4b19a2bc6Sdrh ** The author disclaims copyright to this source code. In place of 5b19a2bc6Sdrh ** a legal notice, here is a blessing: 6cce7d176Sdrh ** 7b19a2bc6Sdrh ** May you do good and not evil. 8b19a2bc6Sdrh ** May you find forgiveness for yourself and forgive others. 9b19a2bc6Sdrh ** May you share freely, never taking more than you give. 10cce7d176Sdrh ** 11cce7d176Sdrh ************************************************************************* 12cce7d176Sdrh ** This file contains C code routines that are called by the parser 13b19a2bc6Sdrh ** to handle SELECT statements in SQLite. 14cce7d176Sdrh ** 15*cfa063b3Sdrh ** $Id: select.c,v 1.362 2007/11/21 15:24:01 drh Exp $ 16cce7d176Sdrh */ 17cce7d176Sdrh #include "sqliteInt.h" 18cce7d176Sdrh 19315555caSdrh 20cce7d176Sdrh /* 21eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate 22eda639e1Sdrh ** the select structure itself. 23eda639e1Sdrh */ 24f0113000Sdanielk1977 static void clearSelect(Select *p){ 25eda639e1Sdrh sqlite3ExprListDelete(p->pEList); 26eda639e1Sdrh sqlite3SrcListDelete(p->pSrc); 27eda639e1Sdrh sqlite3ExprDelete(p->pWhere); 28eda639e1Sdrh sqlite3ExprListDelete(p->pGroupBy); 29eda639e1Sdrh sqlite3ExprDelete(p->pHaving); 30eda639e1Sdrh sqlite3ExprListDelete(p->pOrderBy); 31eda639e1Sdrh sqlite3SelectDelete(p->pPrior); 32eda639e1Sdrh sqlite3ExprDelete(p->pLimit); 33eda639e1Sdrh sqlite3ExprDelete(p->pOffset); 34eda639e1Sdrh } 35eda639e1Sdrh 36eda639e1Sdrh 37eda639e1Sdrh /* 389bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 399bb61fe7Sdrh ** structure. 40cce7d176Sdrh */ 414adee20fSdanielk1977 Select *sqlite3SelectNew( 4217435752Sdrh Parse *pParse, /* Parsing context */ 43daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 44ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 45daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 46daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 47daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 48daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 499bbca4c1Sdrh int isDistinct, /* true if the DISTINCT keyword is present */ 50a2dc3b1aSdanielk1977 Expr *pLimit, /* LIMIT value. NULL means not used */ 51a2dc3b1aSdanielk1977 Expr *pOffset /* OFFSET value. NULL means no offset */ 529bb61fe7Sdrh ){ 539bb61fe7Sdrh Select *pNew; 54eda639e1Sdrh Select standin; 5517435752Sdrh sqlite3 *db = pParse->db; 5617435752Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 57a2dc3b1aSdanielk1977 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */ 58daffd0e5Sdrh if( pNew==0 ){ 59eda639e1Sdrh pNew = &standin; 60eda639e1Sdrh memset(pNew, 0, sizeof(*pNew)); 61eda639e1Sdrh } 62b733d037Sdrh if( pEList==0 ){ 63a1644fd8Sdanielk1977 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0); 64b733d037Sdrh } 659bb61fe7Sdrh pNew->pEList = pEList; 669bb61fe7Sdrh pNew->pSrc = pSrc; 679bb61fe7Sdrh pNew->pWhere = pWhere; 689bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 699bb61fe7Sdrh pNew->pHaving = pHaving; 709bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 719bb61fe7Sdrh pNew->isDistinct = isDistinct; 7282c3d636Sdrh pNew->op = TK_SELECT; 738103b7d2Sdrh assert( pOffset==0 || pLimit!=0 ); 74a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 75a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 767b58daeaSdrh pNew->iLimit = -1; 777b58daeaSdrh pNew->iOffset = -1; 78b9bb7c18Sdrh pNew->addrOpenEphm[0] = -1; 79b9bb7c18Sdrh pNew->addrOpenEphm[1] = -1; 80b9bb7c18Sdrh pNew->addrOpenEphm[2] = -1; 81eda639e1Sdrh if( pNew==&standin) { 82eda639e1Sdrh clearSelect(pNew); 83eda639e1Sdrh pNew = 0; 84daffd0e5Sdrh } 859bb61fe7Sdrh return pNew; 869bb61fe7Sdrh } 879bb61fe7Sdrh 889bb61fe7Sdrh /* 89eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 90eda639e1Sdrh */ 91eda639e1Sdrh void sqlite3SelectDelete(Select *p){ 92eda639e1Sdrh if( p ){ 93eda639e1Sdrh clearSelect(p); 9417435752Sdrh sqlite3_free(p); 95eda639e1Sdrh } 96eda639e1Sdrh } 97eda639e1Sdrh 98eda639e1Sdrh /* 9901f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 10001f3f253Sdrh ** type of join. Return an integer constant that expresses that type 10101f3f253Sdrh ** in terms of the following bit values: 10201f3f253Sdrh ** 10301f3f253Sdrh ** JT_INNER 1043dec223cSdrh ** JT_CROSS 10501f3f253Sdrh ** JT_OUTER 10601f3f253Sdrh ** JT_NATURAL 10701f3f253Sdrh ** JT_LEFT 10801f3f253Sdrh ** JT_RIGHT 10901f3f253Sdrh ** 11001f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 11101f3f253Sdrh ** 11201f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 11301f3f253Sdrh ** a join type, but put an error in the pParse structure. 11401f3f253Sdrh */ 1154adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 11601f3f253Sdrh int jointype = 0; 11701f3f253Sdrh Token *apAll[3]; 11801f3f253Sdrh Token *p; 1195719628aSdrh static const struct { 120c182d163Sdrh const char zKeyword[8]; 121290c1948Sdrh u8 nChar; 122290c1948Sdrh u8 code; 12301f3f253Sdrh } keywords[] = { 12401f3f253Sdrh { "natural", 7, JT_NATURAL }, 125195e6967Sdrh { "left", 4, JT_LEFT|JT_OUTER }, 126195e6967Sdrh { "right", 5, JT_RIGHT|JT_OUTER }, 127195e6967Sdrh { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 12801f3f253Sdrh { "outer", 5, JT_OUTER }, 12901f3f253Sdrh { "inner", 5, JT_INNER }, 1303dec223cSdrh { "cross", 5, JT_INNER|JT_CROSS }, 13101f3f253Sdrh }; 13201f3f253Sdrh int i, j; 13301f3f253Sdrh apAll[0] = pA; 13401f3f253Sdrh apAll[1] = pB; 13501f3f253Sdrh apAll[2] = pC; 136195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 13701f3f253Sdrh p = apAll[i]; 13801f3f253Sdrh for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){ 13901f3f253Sdrh if( p->n==keywords[j].nChar 1402646da7eSdrh && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){ 14101f3f253Sdrh jointype |= keywords[j].code; 14201f3f253Sdrh break; 14301f3f253Sdrh } 14401f3f253Sdrh } 14501f3f253Sdrh if( j>=sizeof(keywords)/sizeof(keywords[0]) ){ 14601f3f253Sdrh jointype |= JT_ERROR; 14701f3f253Sdrh break; 14801f3f253Sdrh } 14901f3f253Sdrh } 150ad2d8307Sdrh if( 151ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 152195e6967Sdrh (jointype & JT_ERROR)!=0 153ad2d8307Sdrh ){ 154ae29ffbeSdrh const char *zSp1 = " "; 155ae29ffbeSdrh const char *zSp2 = " "; 156ae29ffbeSdrh if( pB==0 ){ zSp1++; } 157ae29ffbeSdrh if( pC==0 ){ zSp2++; } 158ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 159ae29ffbeSdrh "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); 16001f3f253Sdrh jointype = JT_INNER; 161195e6967Sdrh }else if( jointype & JT_RIGHT ){ 1624adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 163da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 164195e6967Sdrh jointype = JT_INNER; 16501f3f253Sdrh } 16601f3f253Sdrh return jointype; 16701f3f253Sdrh } 16801f3f253Sdrh 16901f3f253Sdrh /* 170ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 171ad2d8307Sdrh ** is not contained in the table. 172ad2d8307Sdrh */ 173ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 174ad2d8307Sdrh int i; 175ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1764adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 177ad2d8307Sdrh } 178ad2d8307Sdrh return -1; 179ad2d8307Sdrh } 180ad2d8307Sdrh 181ad2d8307Sdrh /* 18291bb0eedSdrh ** Set the value of a token to a '\000'-terminated string. 18391bb0eedSdrh */ 18491bb0eedSdrh static void setToken(Token *p, const char *z){ 1852646da7eSdrh p->z = (u8*)z; 186261919ccSdanielk1977 p->n = z ? strlen(z) : 0; 18791bb0eedSdrh p->dyn = 0; 18891bb0eedSdrh } 18991bb0eedSdrh 190c182d163Sdrh /* 191f3b863edSdanielk1977 ** Set the token to the double-quoted and escaped version of the string pointed 192f3b863edSdanielk1977 ** to by z. For example; 193f3b863edSdanielk1977 ** 194f3b863edSdanielk1977 ** {a"bc} -> {"a""bc"} 195f3b863edSdanielk1977 */ 1961e536953Sdanielk1977 static void setQuotedToken(Parse *pParse, Token *p, const char *z){ 1971e536953Sdanielk1977 p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z); 198f3b863edSdanielk1977 p->dyn = 1; 199f3b863edSdanielk1977 if( p->z ){ 200f3b863edSdanielk1977 p->n = strlen((char *)p->z); 2011e536953Sdanielk1977 }else{ 2021e536953Sdanielk1977 pParse->db->mallocFailed = 1; 203f3b863edSdanielk1977 } 204f3b863edSdanielk1977 } 205f3b863edSdanielk1977 206f3b863edSdanielk1977 /* 207c182d163Sdrh ** Create an expression node for an identifier with the name of zName 208c182d163Sdrh */ 20917435752Sdrh Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){ 210c182d163Sdrh Token dummy; 211c182d163Sdrh setToken(&dummy, zName); 21217435752Sdrh return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy); 213c182d163Sdrh } 214c182d163Sdrh 21591bb0eedSdrh 21691bb0eedSdrh /* 217ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the 218ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2. 219ad2d8307Sdrh */ 220ad2d8307Sdrh static void addWhereTerm( 22117435752Sdrh Parse *pParse, /* Parsing context */ 222ad2d8307Sdrh const char *zCol, /* Name of the column */ 223ad2d8307Sdrh const Table *pTab1, /* First table */ 224030530deSdrh const char *zAlias1, /* Alias for first table. May be NULL */ 225ad2d8307Sdrh const Table *pTab2, /* Second table */ 226030530deSdrh const char *zAlias2, /* Alias for second table. May be NULL */ 22722d6a53aSdrh int iRightJoinTable, /* VDBE cursor for the right table */ 228ad2d8307Sdrh Expr **ppExpr /* Add the equality term to this expression */ 229ad2d8307Sdrh ){ 230ad2d8307Sdrh Expr *pE1a, *pE1b, *pE1c; 231ad2d8307Sdrh Expr *pE2a, *pE2b, *pE2c; 232ad2d8307Sdrh Expr *pE; 233ad2d8307Sdrh 23417435752Sdrh pE1a = sqlite3CreateIdExpr(pParse, zCol); 23517435752Sdrh pE2a = sqlite3CreateIdExpr(pParse, zCol); 236030530deSdrh if( zAlias1==0 ){ 237030530deSdrh zAlias1 = pTab1->zName; 238030530deSdrh } 23917435752Sdrh pE1b = sqlite3CreateIdExpr(pParse, zAlias1); 240030530deSdrh if( zAlias2==0 ){ 241030530deSdrh zAlias2 = pTab2->zName; 242030530deSdrh } 24317435752Sdrh pE2b = sqlite3CreateIdExpr(pParse, zAlias2); 24417435752Sdrh pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0); 24517435752Sdrh pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0); 2461e536953Sdanielk1977 pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0); 247206f3d96Sdrh if( pE ){ 2481f16230bSdrh ExprSetProperty(pE, EP_FromJoin); 24922d6a53aSdrh pE->iRightJoinTable = iRightJoinTable; 250206f3d96Sdrh } 25117435752Sdrh pE = sqlite3ExprAnd(pParse->db,*ppExpr, pE); 252206f3d96Sdrh if( pE ){ 253206f3d96Sdrh *ppExpr = pE; 254206f3d96Sdrh } 255ad2d8307Sdrh } 256ad2d8307Sdrh 257ad2d8307Sdrh /* 2581f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 25922d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 26022d6a53aSdrh ** expression. 2611cc093c2Sdrh ** 262e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 2631cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 2641f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 2651f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 2661f16230bSdrh ** WHERE clause during join processing but we need to remember that they 2671f16230bSdrh ** originated in the ON or USING clause. 26822d6a53aSdrh ** 26922d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 27022d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 27122d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 27222d6a53aSdrh ** for cases like this: 27322d6a53aSdrh ** 27422d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 27522d6a53aSdrh ** 27622d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 27722d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 27822d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 27922d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 28022d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 28122d6a53aSdrh ** the output, which is incorrect. 2821cc093c2Sdrh */ 28322d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 2841cc093c2Sdrh while( p ){ 2851f16230bSdrh ExprSetProperty(p, EP_FromJoin); 28622d6a53aSdrh p->iRightJoinTable = iTable; 28722d6a53aSdrh setJoinExpr(p->pLeft, iTable); 2881cc093c2Sdrh p = p->pRight; 2891cc093c2Sdrh } 2901cc093c2Sdrh } 2911cc093c2Sdrh 2921cc093c2Sdrh /* 293ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 294ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 295ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 296ad2d8307Sdrh ** 29791bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 29891bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 29991bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 30091bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 30191bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 30291bb0eedSdrh ** also attached to the left entry. 30391bb0eedSdrh ** 304ad2d8307Sdrh ** This routine returns the number of errors encountered. 305ad2d8307Sdrh */ 306ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 30791bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 30891bb0eedSdrh int i, j; /* Loop counters */ 30991bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 31091bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 311ad2d8307Sdrh 31291bb0eedSdrh pSrc = p->pSrc; 31391bb0eedSdrh pLeft = &pSrc->a[0]; 31491bb0eedSdrh pRight = &pLeft[1]; 31591bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 31691bb0eedSdrh Table *pLeftTab = pLeft->pTab; 31791bb0eedSdrh Table *pRightTab = pRight->pTab; 31891bb0eedSdrh 31991bb0eedSdrh if( pLeftTab==0 || pRightTab==0 ) continue; 320ad2d8307Sdrh 321ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 322ad2d8307Sdrh ** every column that the two tables have in common. 323ad2d8307Sdrh */ 32461dfc31dSdrh if( pRight->jointype & JT_NATURAL ){ 32561dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 3264adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 327ad2d8307Sdrh "an ON or USING clause", 0); 328ad2d8307Sdrh return 1; 329ad2d8307Sdrh } 33091bb0eedSdrh for(j=0; j<pLeftTab->nCol; j++){ 33191bb0eedSdrh char *zName = pLeftTab->aCol[j].zName; 33291bb0eedSdrh if( columnIndex(pRightTab, zName)>=0 ){ 3331e536953Sdanielk1977 addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 33422d6a53aSdrh pRightTab, pRight->zAlias, 33522d6a53aSdrh pRight->iCursor, &p->pWhere); 33622d6a53aSdrh 337ad2d8307Sdrh } 338ad2d8307Sdrh } 339ad2d8307Sdrh } 340ad2d8307Sdrh 341ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 342ad2d8307Sdrh */ 34361dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 3444adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 345da93d238Sdrh "clauses in the same join"); 346ad2d8307Sdrh return 1; 347ad2d8307Sdrh } 348ad2d8307Sdrh 349ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 35091bb0eedSdrh ** an AND operator. 351ad2d8307Sdrh */ 35261dfc31dSdrh if( pRight->pOn ){ 35361dfc31dSdrh setJoinExpr(pRight->pOn, pRight->iCursor); 35417435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 35561dfc31dSdrh pRight->pOn = 0; 356ad2d8307Sdrh } 357ad2d8307Sdrh 358ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 359ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 360ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 361ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 362ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 363ad2d8307Sdrh ** not contained in both tables to be joined. 364ad2d8307Sdrh */ 36561dfc31dSdrh if( pRight->pUsing ){ 36661dfc31dSdrh IdList *pList = pRight->pUsing; 367ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 36891bb0eedSdrh char *zName = pList->a[j].zName; 36991bb0eedSdrh if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){ 3704adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 37191bb0eedSdrh "not present in both tables", zName); 372ad2d8307Sdrh return 1; 373ad2d8307Sdrh } 3741e536953Sdanielk1977 addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 37522d6a53aSdrh pRightTab, pRight->zAlias, 37622d6a53aSdrh pRight->iCursor, &p->pWhere); 377ad2d8307Sdrh } 378ad2d8307Sdrh } 379ad2d8307Sdrh } 380ad2d8307Sdrh return 0; 381ad2d8307Sdrh } 382ad2d8307Sdrh 383ad2d8307Sdrh /* 384c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 385c926afbcSdrh ** stack into the sorter. 386c926afbcSdrh */ 387d59ba6ceSdrh static void pushOntoSorter( 388d59ba6ceSdrh Parse *pParse, /* Parser context */ 389d59ba6ceSdrh ExprList *pOrderBy, /* The ORDER BY clause */ 390d59ba6ceSdrh Select *pSelect /* The whole SELECT statement */ 391d59ba6ceSdrh ){ 392d59ba6ceSdrh Vdbe *v = pParse->pVdbe; 393c182d163Sdrh sqlite3ExprCodeExprList(pParse, pOrderBy); 3949d2985c7Sdrh sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0); 3954db38a70Sdrh sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0); 3964db38a70Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0); 3979d2985c7Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0); 398d59ba6ceSdrh if( pSelect->iLimit>=0 ){ 39915007a99Sdrh int addr1, addr2; 40015007a99Sdrh addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0); 40115007a99Sdrh sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1); 40215007a99Sdrh addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 403d59ba6ceSdrh sqlite3VdbeJumpHere(v, addr1); 404d59ba6ceSdrh sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0); 405d59ba6ceSdrh sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0); 40615007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 407d59ba6ceSdrh pSelect->iLimit = -1; 408d59ba6ceSdrh } 409c926afbcSdrh } 410c926afbcSdrh 411c926afbcSdrh /* 412ec7429aeSdrh ** Add code to implement the OFFSET 413ea48eb2eSdrh */ 414ec7429aeSdrh static void codeOffset( 415bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 416ea48eb2eSdrh Select *p, /* The SELECT statement being coded */ 417ea48eb2eSdrh int iContinue, /* Jump here to skip the current record */ 418ea48eb2eSdrh int nPop /* Number of times to pop stack when jumping */ 419ea48eb2eSdrh ){ 42013449892Sdrh if( p->iOffset>=0 && iContinue!=0 ){ 42115007a99Sdrh int addr; 42215007a99Sdrh sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset); 4233a129247Sdrh addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0); 424ea48eb2eSdrh if( nPop>0 ){ 425ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_Pop, nPop, 0); 426ea48eb2eSdrh } 427ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); 428ad6d9460Sdrh VdbeComment((v, "# skip OFFSET records")); 42915007a99Sdrh sqlite3VdbeJumpHere(v, addr); 430ea48eb2eSdrh } 431ea48eb2eSdrh } 432ea48eb2eSdrh 433ea48eb2eSdrh /* 434c99130fdSdrh ** Add code that will check to make sure the top N elements of the 435c99130fdSdrh ** stack are distinct. iTab is a sorting index that holds previously 436c99130fdSdrh ** seen combinations of the N values. A new entry is made in iTab 437c99130fdSdrh ** if the current N values are new. 438c99130fdSdrh ** 439f8875400Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 440c99130fdSdrh ** stack if the top N elements are not distinct. 441c99130fdSdrh */ 442c99130fdSdrh static void codeDistinct( 443c99130fdSdrh Vdbe *v, /* Generate code into this VM */ 444c99130fdSdrh int iTab, /* A sorting index used to test for distinctness */ 445c99130fdSdrh int addrRepeat, /* Jump to here if not distinct */ 446f8875400Sdrh int N /* The top N elements of the stack must be distinct */ 447c99130fdSdrh ){ 448c99130fdSdrh sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0); 449c99130fdSdrh sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3); 450f8875400Sdrh sqlite3VdbeAddOp(v, OP_Pop, N+1, 0); 451c99130fdSdrh sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat); 452c99130fdSdrh VdbeComment((v, "# skip indistinct records")); 453c99130fdSdrh sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0); 454c99130fdSdrh } 455c99130fdSdrh 456e305f43fSdrh /* 457e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression 458e305f43fSdrh ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 459e305f43fSdrh ** column. We do this in a subroutine because the error occurs in multiple 460e305f43fSdrh ** places. 461e305f43fSdrh */ 462e305f43fSdrh static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){ 463e305f43fSdrh if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 464e305f43fSdrh sqlite3ErrorMsg(pParse, "only a single result allowed for " 465e305f43fSdrh "a SELECT that is part of an expression"); 466e305f43fSdrh return 1; 467e305f43fSdrh }else{ 468e305f43fSdrh return 0; 469e305f43fSdrh } 470e305f43fSdrh } 471c99130fdSdrh 472c99130fdSdrh /* 4732282792aSdrh ** This routine generates the code for the inside of the inner loop 4742282792aSdrh ** of a SELECT. 47582c3d636Sdrh ** 47638640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 47738640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 47838640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 47938640e15Sdrh ** datatypes for each column. 4802282792aSdrh */ 4812282792aSdrh static int selectInnerLoop( 4822282792aSdrh Parse *pParse, /* The parser context */ 483df199a25Sdrh Select *p, /* The complete select statement being coded */ 4842282792aSdrh ExprList *pEList, /* List of values being extracted */ 48582c3d636Sdrh int srcTab, /* Pull data from this table */ 486967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 4872282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 4882282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 4892282792aSdrh int eDest, /* How to dispose of the results */ 4902282792aSdrh int iParm, /* An argument to the disposal method */ 4912282792aSdrh int iContinue, /* Jump here to continue with next row */ 49284ac9d02Sdanielk1977 int iBreak, /* Jump here to break out of the inner loop */ 49384ac9d02Sdanielk1977 char *aff /* affinity string if eDest is SRT_Union */ 4942282792aSdrh ){ 4952282792aSdrh Vdbe *v = pParse->pVdbe; 4962282792aSdrh int i; 497ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 49838640e15Sdrh 499daffd0e5Sdrh if( v==0 ) return 0; 50038640e15Sdrh assert( pEList!=0 ); 5012282792aSdrh 502df199a25Sdrh /* If there was a LIMIT clause on the SELECT statement, then do the check 503df199a25Sdrh ** to see if this row should be output. 504df199a25Sdrh */ 505eda639e1Sdrh hasDistinct = distinct>=0 && pEList->nExpr>0; 506ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 507ec7429aeSdrh codeOffset(v, p, iContinue, 0); 508df199a25Sdrh } 509df199a25Sdrh 510967e8b73Sdrh /* Pull the requested columns. 5112282792aSdrh */ 51238640e15Sdrh if( nColumn>0 ){ 513967e8b73Sdrh for(i=0; i<nColumn; i++){ 5144adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Column, srcTab, i); 51582c3d636Sdrh } 51638640e15Sdrh }else{ 51738640e15Sdrh nColumn = pEList->nExpr; 518c182d163Sdrh sqlite3ExprCodeExprList(pParse, pEList); 51982c3d636Sdrh } 5202282792aSdrh 521daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 522daffd0e5Sdrh ** and this row has been seen before, then do not make this row 523daffd0e5Sdrh ** part of the result. 5242282792aSdrh */ 525ea48eb2eSdrh if( hasDistinct ){ 526f8875400Sdrh assert( pEList!=0 ); 527f8875400Sdrh assert( pEList->nExpr==nColumn ); 528f8875400Sdrh codeDistinct(v, distinct, iContinue, nColumn); 529ea48eb2eSdrh if( pOrderBy==0 ){ 530ec7429aeSdrh codeOffset(v, p, iContinue, nColumn); 531ea48eb2eSdrh } 5322282792aSdrh } 53382c3d636Sdrh 534e305f43fSdrh if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ 535e305f43fSdrh return 0; 536e305f43fSdrh } 537e305f43fSdrh 538c926afbcSdrh switch( eDest ){ 53982c3d636Sdrh /* In this mode, write each query result to the key of the temporary 54082c3d636Sdrh ** table iParm. 5412282792aSdrh */ 54213449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 543c926afbcSdrh case SRT_Union: { 544f8875400Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 54513449892Sdrh if( aff ){ 54684ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 54713449892Sdrh } 548f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0); 549c926afbcSdrh break; 550c926afbcSdrh } 55182c3d636Sdrh 55282c3d636Sdrh /* Construct a record from the query result, but instead of 55382c3d636Sdrh ** saving that record, use it as a key to delete elements from 55482c3d636Sdrh ** the temporary table iParm. 55582c3d636Sdrh */ 556c926afbcSdrh case SRT_Except: { 5570bd1f4eaSdrh int addr; 558f8875400Sdrh addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 55984ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 5604adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3); 5614adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0); 562c926afbcSdrh break; 563c926afbcSdrh } 5645338a5f7Sdanielk1977 #endif 5655338a5f7Sdanielk1977 5665338a5f7Sdanielk1977 /* Store the result as data using a unique key. 5675338a5f7Sdanielk1977 */ 5685338a5f7Sdanielk1977 case SRT_Table: 569b9bb7c18Sdrh case SRT_EphemTab: { 5705338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 5715338a5f7Sdanielk1977 if( pOrderBy ){ 572d59ba6ceSdrh pushOntoSorter(pParse, pOrderBy, p); 5735338a5f7Sdanielk1977 }else{ 574f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); 5755338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 576e4d90813Sdrh sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); 5775338a5f7Sdanielk1977 } 5785338a5f7Sdanielk1977 break; 5795338a5f7Sdanielk1977 } 5802282792aSdrh 58193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 5822282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 5832282792aSdrh ** then there should be a single item on the stack. Write this 5842282792aSdrh ** item into the set table with bogus data. 5852282792aSdrh */ 586c926afbcSdrh case SRT_Set: { 5874adee20fSdanielk1977 int addr1 = sqlite3VdbeCurrentAddr(v); 58852b36cabSdrh int addr2; 589e014a838Sdanielk1977 590967e8b73Sdrh assert( nColumn==1 ); 5914adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3); 5924adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 5934adee20fSdanielk1977 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 5946c1426fdSdrh p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff); 595c926afbcSdrh if( pOrderBy ){ 596de941c60Sdrh /* At first glance you would think we could optimize out the 597de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 598de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 599de941c60Sdrh ** case the order does matter */ 600d59ba6ceSdrh pushOntoSorter(pParse, pOrderBy, p); 601c926afbcSdrh }else{ 6026c1426fdSdrh sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); 603f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); 604c926afbcSdrh } 605d654be80Sdrh sqlite3VdbeJumpHere(v, addr2); 606c926afbcSdrh break; 607c926afbcSdrh } 60882c3d636Sdrh 609504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 610ec7429aeSdrh */ 611ec7429aeSdrh case SRT_Exists: { 612ec7429aeSdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm); 613ec7429aeSdrh sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 614ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 615ec7429aeSdrh break; 616ec7429aeSdrh } 617ec7429aeSdrh 6182282792aSdrh /* If this is a scalar select that is part of an expression, then 6192282792aSdrh ** store the results in the appropriate memory cell and break out 6202282792aSdrh ** of the scan loop. 6212282792aSdrh */ 622c926afbcSdrh case SRT_Mem: { 623967e8b73Sdrh assert( nColumn==1 ); 624c926afbcSdrh if( pOrderBy ){ 625d59ba6ceSdrh pushOntoSorter(pParse, pOrderBy, p); 626c926afbcSdrh }else{ 6274adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 628ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 629c926afbcSdrh } 630c926afbcSdrh break; 631c926afbcSdrh } 63293758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 6332282792aSdrh 634c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 635c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 636c182d163Sdrh ** popping the data from the stack. 637f46f905aSdrh */ 638c182d163Sdrh case SRT_Subroutine: 6399d2985c7Sdrh case SRT_Callback: { 640f46f905aSdrh if( pOrderBy ){ 641ce665cf6Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 642d59ba6ceSdrh pushOntoSorter(pParse, pOrderBy, p); 643c182d163Sdrh }else if( eDest==SRT_Subroutine ){ 6444adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 645c182d163Sdrh }else{ 646c182d163Sdrh sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 647ac82fcf5Sdrh } 648142e30dfSdrh break; 649142e30dfSdrh } 650142e30dfSdrh 6516a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 652d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 653d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 654d7489c39Sdrh ** user-defined functions that have side effects. We do not care 655d7489c39Sdrh ** about the actual results of the select. 656d7489c39Sdrh */ 657c926afbcSdrh default: { 658f46f905aSdrh assert( eDest==SRT_Discard ); 6594adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 660c926afbcSdrh break; 661c926afbcSdrh } 66293758c8dSdanielk1977 #endif 663c926afbcSdrh } 664ec7429aeSdrh 665ec7429aeSdrh /* Jump to the end of the loop if the LIMIT is reached. 666ec7429aeSdrh */ 667ec7429aeSdrh if( p->iLimit>=0 && pOrderBy==0 ){ 66815007a99Sdrh sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); 669ec7429aeSdrh sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak); 670ec7429aeSdrh } 67182c3d636Sdrh return 0; 67282c3d636Sdrh } 67382c3d636Sdrh 67482c3d636Sdrh /* 675dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 676dece1a84Sdrh ** the collating sequence for each expression in that expression list. 677dece1a84Sdrh ** 6780342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 6790342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 6800342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 6810342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 6820342b1f5Sdrh ** index to implement a DISTINCT test. 6830342b1f5Sdrh ** 684dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 685dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 686dece1a84Sdrh ** freed. Add the KeyInfo structure to the P3 field of an opcode using 687dece1a84Sdrh ** P3_KEYINFO_HANDOFF is the usual way of dealing with this. 688dece1a84Sdrh */ 689dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 690dece1a84Sdrh sqlite3 *db = pParse->db; 691dece1a84Sdrh int nExpr; 692dece1a84Sdrh KeyInfo *pInfo; 693dece1a84Sdrh struct ExprList_item *pItem; 694dece1a84Sdrh int i; 695dece1a84Sdrh 696dece1a84Sdrh nExpr = pList->nExpr; 69717435752Sdrh pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 698dece1a84Sdrh if( pInfo ){ 6992646da7eSdrh pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 700dece1a84Sdrh pInfo->nField = nExpr; 70114db2665Sdanielk1977 pInfo->enc = ENC(db); 702dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 703dece1a84Sdrh CollSeq *pColl; 704dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 705dece1a84Sdrh if( !pColl ){ 706dece1a84Sdrh pColl = db->pDfltColl; 707dece1a84Sdrh } 708dece1a84Sdrh pInfo->aColl[i] = pColl; 709dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 710dece1a84Sdrh } 711dece1a84Sdrh } 712dece1a84Sdrh return pInfo; 713dece1a84Sdrh } 714dece1a84Sdrh 715dece1a84Sdrh 716dece1a84Sdrh /* 717d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 718d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 719d8bc7086Sdrh ** we need to run the sorter and output the results. The following 720d8bc7086Sdrh ** routine generates the code needed to do that. 721d8bc7086Sdrh */ 722c926afbcSdrh static void generateSortTail( 723cdd536f0Sdrh Parse *pParse, /* Parsing context */ 724c926afbcSdrh Select *p, /* The SELECT statement */ 725c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 726c926afbcSdrh int nColumn, /* Number of columns of data */ 727c926afbcSdrh int eDest, /* Write the sorted results here */ 728c926afbcSdrh int iParm /* Optional parameter associated with eDest */ 729c926afbcSdrh ){ 7300342b1f5Sdrh int brk = sqlite3VdbeMakeLabel(v); 7310342b1f5Sdrh int cont = sqlite3VdbeMakeLabel(v); 732d8bc7086Sdrh int addr; 7330342b1f5Sdrh int iTab; 73461fc595fSdrh int pseudoTab = 0; 7350342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 736ffbc3088Sdrh 7379d2985c7Sdrh iTab = pOrderBy->iECursor; 738cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 739cdd536f0Sdrh pseudoTab = pParse->nTab++; 740cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0); 741cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn); 742cdd536f0Sdrh } 7430342b1f5Sdrh addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk); 744ec7429aeSdrh codeOffset(v, p, cont, 0); 745cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 746cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_Integer, 1, 0); 747cdd536f0Sdrh } 7484db38a70Sdrh sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1); 749c926afbcSdrh switch( eDest ){ 750c926afbcSdrh case SRT_Table: 751b9bb7c18Sdrh case SRT_EphemTab: { 752f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); 7534adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 754e4d90813Sdrh sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); 755c926afbcSdrh break; 756c926afbcSdrh } 75793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 758c926afbcSdrh case SRT_Set: { 759c926afbcSdrh assert( nColumn==1 ); 7604adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); 7614adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 7624adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); 7636c1426fdSdrh sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); 764f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); 765c926afbcSdrh break; 766c926afbcSdrh } 767c926afbcSdrh case SRT_Mem: { 768c926afbcSdrh assert( nColumn==1 ); 7694adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 770ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 771c926afbcSdrh break; 772c926afbcSdrh } 77393758c8dSdanielk1977 #endif 774ce665cf6Sdrh case SRT_Callback: 775ac82fcf5Sdrh case SRT_Subroutine: { 776ac82fcf5Sdrh int i; 777cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0); 778ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 779cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i); 780ac82fcf5Sdrh } 781ce665cf6Sdrh if( eDest==SRT_Callback ){ 782ce665cf6Sdrh sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 783ce665cf6Sdrh }else{ 7844adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 785ce665cf6Sdrh } 786ac82fcf5Sdrh break; 787ac82fcf5Sdrh } 788c926afbcSdrh default: { 789f46f905aSdrh /* Do nothing */ 790c926afbcSdrh break; 791c926afbcSdrh } 792c926afbcSdrh } 793ec7429aeSdrh 794ec7429aeSdrh /* Jump to the end of the loop when the LIMIT is reached 795ec7429aeSdrh */ 796ec7429aeSdrh if( p->iLimit>=0 ){ 79715007a99Sdrh sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); 798ec7429aeSdrh sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk); 799ec7429aeSdrh } 800ec7429aeSdrh 801ec7429aeSdrh /* The bottom of the loop 802ec7429aeSdrh */ 8030342b1f5Sdrh sqlite3VdbeResolveLabel(v, cont); 8040342b1f5Sdrh sqlite3VdbeAddOp(v, OP_Next, iTab, addr); 8050342b1f5Sdrh sqlite3VdbeResolveLabel(v, brk); 806cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 807cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0); 808cdd536f0Sdrh } 809cdd536f0Sdrh 810d8bc7086Sdrh } 811d8bc7086Sdrh 812d8bc7086Sdrh /* 813517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 814517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 815e78e8284Sdrh ** 816955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 817955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 818955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 819955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 820955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 821955de52cSdanielk1977 ** considered a column by this function. 822e78e8284Sdrh ** 823955de52cSdanielk1977 ** SELECT col FROM tbl; 824955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 825955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 826955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 827955de52cSdanielk1977 ** 828955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 829fcb78a49Sdrh */ 830955de52cSdanielk1977 static const char *columnType( 831955de52cSdanielk1977 NameContext *pNC, 832955de52cSdanielk1977 Expr *pExpr, 833955de52cSdanielk1977 const char **pzOriginDb, 834955de52cSdanielk1977 const char **pzOriginTab, 835955de52cSdanielk1977 const char **pzOriginCol 836955de52cSdanielk1977 ){ 837955de52cSdanielk1977 char const *zType = 0; 838955de52cSdanielk1977 char const *zOriginDb = 0; 839955de52cSdanielk1977 char const *zOriginTab = 0; 840955de52cSdanielk1977 char const *zOriginCol = 0; 841517eb646Sdanielk1977 int j; 842b3bce662Sdanielk1977 if( pExpr==0 || pNC->pSrcList==0 ) return 0; 8435338a5f7Sdanielk1977 84400e279d9Sdanielk1977 switch( pExpr->op ){ 84530bcf5dbSdrh case TK_AGG_COLUMN: 84600e279d9Sdanielk1977 case TK_COLUMN: { 847955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 848955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 849955de52cSdanielk1977 ** database table or a subquery. 850955de52cSdanielk1977 */ 851955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 852955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 853955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 854b3bce662Sdanielk1977 while( pNC && !pTab ){ 855b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 856b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 857b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 8586a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 859955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 860b3bce662Sdanielk1977 }else{ 861b3bce662Sdanielk1977 pNC = pNC->pNext; 862b3bce662Sdanielk1977 } 863b3bce662Sdanielk1977 } 864955de52cSdanielk1977 8657e62779aSdrh if( pTab==0 ){ 8667e62779aSdrh /* FIX ME: 8677e62779aSdrh ** This can occurs if you have something like "SELECT new.x;" inside 8687e62779aSdrh ** a trigger. In other words, if you reference the special "new" 8697e62779aSdrh ** table in the result set of a select. We do not have a good way 8707e62779aSdrh ** to find the actual table type, so call it "TEXT". This is really 8717e62779aSdrh ** something of a bug, but I do not know how to fix it. 8727e62779aSdrh ** 8737e62779aSdrh ** This code does not produce the correct answer - it just prevents 8747e62779aSdrh ** a segfault. See ticket #1229. 8757e62779aSdrh */ 8767e62779aSdrh zType = "TEXT"; 8777e62779aSdrh break; 8787e62779aSdrh } 879955de52cSdanielk1977 880b3bce662Sdanielk1977 assert( pTab ); 881955de52cSdanielk1977 if( pS ){ 882955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 883955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 884955de52cSdanielk1977 ** data for the result-set column of the sub-select. 885955de52cSdanielk1977 */ 886955de52cSdanielk1977 if( iCol>=0 && iCol<pS->pEList->nExpr ){ 887955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 888955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 889955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 890955de52cSdanielk1977 */ 891955de52cSdanielk1977 NameContext sNC; 892955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 893955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 894955de52cSdanielk1977 sNC.pNext = 0; 895955de52cSdanielk1977 sNC.pParse = pNC->pParse; 896955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 897955de52cSdanielk1977 } 8984b2688abSdanielk1977 }else if( pTab->pSchema ){ 899955de52cSdanielk1977 /* A real table */ 900955de52cSdanielk1977 assert( !pS ); 901fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 902fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 903fcb78a49Sdrh if( iCol<0 ){ 904fcb78a49Sdrh zType = "INTEGER"; 905955de52cSdanielk1977 zOriginCol = "rowid"; 906fcb78a49Sdrh }else{ 907fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 908955de52cSdanielk1977 zOriginCol = pTab->aCol[iCol].zName; 909955de52cSdanielk1977 } 910955de52cSdanielk1977 zOriginTab = pTab->zName; 911955de52cSdanielk1977 if( pNC->pParse ){ 912955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 913955de52cSdanielk1977 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 914955de52cSdanielk1977 } 915fcb78a49Sdrh } 91600e279d9Sdanielk1977 break; 917736c22b8Sdrh } 91893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 91900e279d9Sdanielk1977 case TK_SELECT: { 920955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 921955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 922955de52cSdanielk1977 ** statement. 923955de52cSdanielk1977 */ 924b3bce662Sdanielk1977 NameContext sNC; 92500e279d9Sdanielk1977 Select *pS = pExpr->pSelect; 926955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 927955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 928b3bce662Sdanielk1977 sNC.pNext = pNC; 929955de52cSdanielk1977 sNC.pParse = pNC->pParse; 930955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 93100e279d9Sdanielk1977 break; 932fcb78a49Sdrh } 93393758c8dSdanielk1977 #endif 93400e279d9Sdanielk1977 } 93500e279d9Sdanielk1977 936955de52cSdanielk1977 if( pzOriginDb ){ 937955de52cSdanielk1977 assert( pzOriginTab && pzOriginCol ); 938955de52cSdanielk1977 *pzOriginDb = zOriginDb; 939955de52cSdanielk1977 *pzOriginTab = zOriginTab; 940955de52cSdanielk1977 *pzOriginCol = zOriginCol; 941955de52cSdanielk1977 } 942517eb646Sdanielk1977 return zType; 943517eb646Sdanielk1977 } 944517eb646Sdanielk1977 945517eb646Sdanielk1977 /* 946517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 947517eb646Sdanielk1977 ** in the result set. 948517eb646Sdanielk1977 */ 949517eb646Sdanielk1977 static void generateColumnTypes( 950517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 951517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 952517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 953517eb646Sdanielk1977 ){ 954517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 955517eb646Sdanielk1977 int i; 956b3bce662Sdanielk1977 NameContext sNC; 957b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 958955de52cSdanielk1977 sNC.pParse = pParse; 959517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 960517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 961955de52cSdanielk1977 const char *zOrigDb = 0; 962955de52cSdanielk1977 const char *zOrigTab = 0; 963955de52cSdanielk1977 const char *zOrigCol = 0; 964955de52cSdanielk1977 const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 965955de52cSdanielk1977 9664b1ae99dSdanielk1977 /* The vdbe must make it's own copy of the column-type and other 9674b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 9684b1ae99dSdanielk1977 ** virtual machine is deleted. 969fbcd585fSdanielk1977 */ 9704b1ae99dSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT); 9714b1ae99dSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT); 9724b1ae99dSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT); 9734b1ae99dSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT); 974fcb78a49Sdrh } 975fcb78a49Sdrh } 976fcb78a49Sdrh 977fcb78a49Sdrh /* 978fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 979fcb78a49Sdrh ** in the result set. This information is used to provide the 980fcabd464Sdrh ** azCol[] values in the callback. 98182c3d636Sdrh */ 982832508b7Sdrh static void generateColumnNames( 983832508b7Sdrh Parse *pParse, /* Parser context */ 984ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 985832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 986832508b7Sdrh ){ 987d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 9886a3ea0e6Sdrh int i, j; 9899bb575fdSdrh sqlite3 *db = pParse->db; 990fcabd464Sdrh int fullNames, shortNames; 991fcabd464Sdrh 992fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 9933cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 9943cf86063Sdanielk1977 if( pParse->explain ){ 99561de0d1bSdanielk1977 return; 9963cf86063Sdanielk1977 } 9975338a5f7Sdanielk1977 #endif 9983cf86063Sdanielk1977 999d6502758Sdrh assert( v!=0 ); 100017435752Sdrh if( pParse->colNamesSet || v==0 || db->mallocFailed ) return; 1001d8bc7086Sdrh pParse->colNamesSet = 1; 1002fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1003fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 100422322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 100582c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 100682c3d636Sdrh Expr *p; 10075a38705eSdrh p = pEList->a[i].pExpr; 10085a38705eSdrh if( p==0 ) continue; 100982c3d636Sdrh if( pEList->a[i].zName ){ 101082c3d636Sdrh char *zName = pEList->a[i].zName; 1011955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName)); 101282c3d636Sdrh continue; 101382c3d636Sdrh } 1014fa173a76Sdrh if( p->op==TK_COLUMN && pTabList ){ 10156a3ea0e6Sdrh Table *pTab; 101697665873Sdrh char *zCol; 10178aff1015Sdrh int iCol = p->iColumn; 10186a3ea0e6Sdrh for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 10196a3ea0e6Sdrh assert( j<pTabList->nSrc ); 10206a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 10218aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 102297665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1023b1363206Sdrh if( iCol<0 ){ 102447a6db2bSdrh zCol = "rowid"; 1025b1363206Sdrh }else{ 1026b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1027b1363206Sdrh } 1028fcabd464Sdrh if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ 1029955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 1030fcabd464Sdrh }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ 103182c3d636Sdrh char *zName = 0; 103282c3d636Sdrh char *zTab; 103382c3d636Sdrh 10346a3ea0e6Sdrh zTab = pTabList->a[j].zAlias; 1035fcabd464Sdrh if( fullNames || zTab==0 ) zTab = pTab->zName; 1036f93339deSdrh sqlite3SetString(&zName, zTab, ".", zCol, (char*)0); 1037955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC); 103882c3d636Sdrh }else{ 1039955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol)); 104082c3d636Sdrh } 10416977fea8Sdrh }else if( p->span.z && p->span.z[0] ){ 1042955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 10433cf86063Sdanielk1977 /* sqlite3VdbeCompressSpace(v, addr); */ 10441bee3d7bSdrh }else{ 10451bee3d7bSdrh char zName[30]; 10461bee3d7bSdrh assert( p->op!=TK_COLUMN || pTabList==0 ); 10475bb3eb9bSdrh sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1); 1048955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0); 104982c3d636Sdrh } 105082c3d636Sdrh } 105176d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 10525080aaa7Sdrh } 105382c3d636Sdrh 105493758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 105582c3d636Sdrh /* 1056d8bc7086Sdrh ** Name of the connection operator, used for error messages. 1057d8bc7086Sdrh */ 1058d8bc7086Sdrh static const char *selectOpName(int id){ 1059d8bc7086Sdrh char *z; 1060d8bc7086Sdrh switch( id ){ 1061d8bc7086Sdrh case TK_ALL: z = "UNION ALL"; break; 1062d8bc7086Sdrh case TK_INTERSECT: z = "INTERSECT"; break; 1063d8bc7086Sdrh case TK_EXCEPT: z = "EXCEPT"; break; 1064d8bc7086Sdrh default: z = "UNION"; break; 1065d8bc7086Sdrh } 1066d8bc7086Sdrh return z; 1067d8bc7086Sdrh } 106893758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1069d8bc7086Sdrh 1070d8bc7086Sdrh /* 1071315555caSdrh ** Forward declaration 1072315555caSdrh */ 10739b3187e1Sdrh static int prepSelectStmt(Parse*, Select*); 1074315555caSdrh 1075315555caSdrh /* 107622f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes 107722f70c32Sdrh ** the result set of that SELECT. 107822f70c32Sdrh */ 10794adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 108022f70c32Sdrh Table *pTab; 1081b733d037Sdrh int i, j; 108222f70c32Sdrh ExprList *pEList; 1083290c1948Sdrh Column *aCol, *pCol; 108417435752Sdrh sqlite3 *db = pParse->db; 108522f70c32Sdrh 108692378253Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 10879b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 108822f70c32Sdrh return 0; 108922f70c32Sdrh } 1090142bdf40Sdanielk1977 if( sqlite3SelectResolve(pParse, pSelect, 0) ){ 1091142bdf40Sdanielk1977 return 0; 1092142bdf40Sdanielk1977 } 109317435752Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 109422f70c32Sdrh if( pTab==0 ){ 109522f70c32Sdrh return 0; 109622f70c32Sdrh } 1097ed8a3bb1Sdrh pTab->nRef = 1; 109817435752Sdrh pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0; 109922f70c32Sdrh pEList = pSelect->pEList; 110022f70c32Sdrh pTab->nCol = pEList->nExpr; 1101417be79cSdrh assert( pTab->nCol>0 ); 110217435752Sdrh pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol); 1103290c1948Sdrh for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){ 110479d5f63fSdrh Expr *p, *pR; 1105517eb646Sdanielk1977 char *zType; 110691bb0eedSdrh char *zName; 11072564ef97Sdrh int nName; 1108b3bf556eSdanielk1977 CollSeq *pColl; 110979d5f63fSdrh int cnt; 1110b3bce662Sdanielk1977 NameContext sNC; 111179d5f63fSdrh 111279d5f63fSdrh /* Get an appropriate name for the column 111379d5f63fSdrh */ 111479d5f63fSdrh p = pEList->a[i].pExpr; 1115290c1948Sdrh assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 ); 111691bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 111779d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 111817435752Sdrh zName = sqlite3DbStrDup(db, zName); 1119517eb646Sdanielk1977 }else if( p->op==TK_DOT 1120b733d037Sdrh && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ 112179d5f63fSdrh /* For columns of the from A.B use B as the name */ 112217435752Sdrh zName = sqlite3MPrintf(db, "%T", &pR->token); 1123b733d037Sdrh }else if( p->span.z && p->span.z[0] ){ 112479d5f63fSdrh /* Use the original text of the column expression as its name */ 112517435752Sdrh zName = sqlite3MPrintf(db, "%T", &p->span); 112622f70c32Sdrh }else{ 112779d5f63fSdrh /* If all else fails, make up a name */ 112817435752Sdrh zName = sqlite3MPrintf(db, "column%d", i+1); 112922f70c32Sdrh } 11307751940dSdanielk1977 if( !zName || db->mallocFailed ){ 11317751940dSdanielk1977 db->mallocFailed = 1; 113217435752Sdrh sqlite3_free(zName); 1133a04a34ffSdanielk1977 sqlite3DeleteTable(pTab); 1134dd5b2fa5Sdrh return 0; 1135dd5b2fa5Sdrh } 11367751940dSdanielk1977 sqlite3Dequote(zName); 113779d5f63fSdrh 113879d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 113979d5f63fSdrh ** append a integer to the name so that it becomes unique. 114079d5f63fSdrh */ 11412564ef97Sdrh nName = strlen(zName); 114279d5f63fSdrh for(j=cnt=0; j<i; j++){ 114379d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 11442564ef97Sdrh zName[nName] = 0; 11451e536953Sdanielk1977 zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt); 114679d5f63fSdrh j = -1; 1147dd5b2fa5Sdrh if( zName==0 ) break; 114879d5f63fSdrh } 114979d5f63fSdrh } 115091bb0eedSdrh pCol->zName = zName; 1151e014a838Sdanielk1977 115279d5f63fSdrh /* Get the typename, type affinity, and collating sequence for the 115379d5f63fSdrh ** column. 115479d5f63fSdrh */ 1155c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1156b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 115717435752Sdrh zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); 1158290c1948Sdrh pCol->zType = zType; 1159c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1160b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1161b3bf556eSdanielk1977 if( pColl ){ 116217435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 11630202b29eSdanielk1977 } 116422f70c32Sdrh } 116522f70c32Sdrh pTab->iPKey = -1; 116622f70c32Sdrh return pTab; 116722f70c32Sdrh } 116822f70c32Sdrh 116922f70c32Sdrh /* 11709b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following 11719b3187e1Sdrh ** things: 1172d8bc7086Sdrh ** 11739b3187e1Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 11749b3187e1Sdrh ** element of the FROM clause. 11759b3187e1Sdrh ** 11769b3187e1Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 11779b3187e1Sdrh ** defines FROM clause. When views appear in the FROM clause, 117863eb5f29Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 117963eb5f29Sdrh ** that implements the view. A copy is made of the view's SELECT 118063eb5f29Sdrh ** statement so that we can freely modify or delete that statement 118163eb5f29Sdrh ** without worrying about messing up the presistent representation 118263eb5f29Sdrh ** of the view. 1183d8bc7086Sdrh ** 11849b3187e1Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 1185ad2d8307Sdrh ** on joins and the ON and USING clause of joins. 1186ad2d8307Sdrh ** 11879b3187e1Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 118854473229Sdrh ** for instances of the "*" operator or the TABLE.* operator. 118954473229Sdrh ** If found, expand each "*" to be every column in every table 119054473229Sdrh ** and TABLE.* to be every column in TABLE. 1191d8bc7086Sdrh ** 1192d8bc7086Sdrh ** Return 0 on success. If there are problems, leave an error message 1193d8bc7086Sdrh ** in pParse and return non-zero. 1194d8bc7086Sdrh */ 11959b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){ 119654473229Sdrh int i, j, k, rc; 1197ad3cab52Sdrh SrcList *pTabList; 1198daffd0e5Sdrh ExprList *pEList; 1199290c1948Sdrh struct SrcList_item *pFrom; 120017435752Sdrh sqlite3 *db = pParse->db; 1201daffd0e5Sdrh 120217435752Sdrh if( p==0 || p->pSrc==0 || db->mallocFailed ){ 12036f7adc8aSdrh return 1; 12046f7adc8aSdrh } 1205daffd0e5Sdrh pTabList = p->pSrc; 1206daffd0e5Sdrh pEList = p->pEList; 1207d8bc7086Sdrh 12089b3187e1Sdrh /* Make sure cursor numbers have been assigned to all entries in 12099b3187e1Sdrh ** the FROM clause of the SELECT statement. 12109b3187e1Sdrh */ 12119b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, p->pSrc); 12129b3187e1Sdrh 12139b3187e1Sdrh /* Look up every table named in the FROM clause of the select. If 12149b3187e1Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 12159b3187e1Sdrh ** then create a transient table structure to describe the subquery. 1216d8bc7086Sdrh */ 1217290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1218f0113000Sdanielk1977 Table *pTab; 12199b3187e1Sdrh if( pFrom->pTab!=0 ){ 12209b3187e1Sdrh /* This statement has already been prepared. There is no need 12219b3187e1Sdrh ** to go further. */ 12229b3187e1Sdrh assert( i==0 ); 1223d8bc7086Sdrh return 0; 1224d8bc7086Sdrh } 1225290c1948Sdrh if( pFrom->zName==0 ){ 122693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 122722f70c32Sdrh /* A sub-query in the FROM clause of a SELECT */ 1228290c1948Sdrh assert( pFrom->pSelect!=0 ); 1229290c1948Sdrh if( pFrom->zAlias==0 ){ 123091bb0eedSdrh pFrom->zAlias = 12311e536953Sdanielk1977 sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect); 1232ad2d8307Sdrh } 1233ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1234290c1948Sdrh pFrom->pTab = pTab = 1235290c1948Sdrh sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect); 123622f70c32Sdrh if( pTab==0 ){ 1237daffd0e5Sdrh return 1; 1238daffd0e5Sdrh } 1239b9bb7c18Sdrh /* The isEphem flag indicates that the Table structure has been 12405cf590c1Sdrh ** dynamically allocated and may be freed at any time. In other words, 12415cf590c1Sdrh ** pTab is not pointing to a persistent table structure that defines 12425cf590c1Sdrh ** part of the schema. */ 1243b9bb7c18Sdrh pTab->isEphem = 1; 124493758c8dSdanielk1977 #endif 124522f70c32Sdrh }else{ 1246a76b5dfcSdrh /* An ordinary table or view name in the FROM clause */ 1247ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1248290c1948Sdrh pFrom->pTab = pTab = 1249290c1948Sdrh sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase); 1250a76b5dfcSdrh if( pTab==0 ){ 1251d8bc7086Sdrh return 1; 1252d8bc7086Sdrh } 1253ed8a3bb1Sdrh pTab->nRef++; 125493626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 125593626f48Sdanielk1977 if( pTab->pSelect || IsVirtual(pTab) ){ 125663eb5f29Sdrh /* We reach here if the named table is a really a view */ 12574adee20fSdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 1258417be79cSdrh return 1; 1259417be79cSdrh } 1260290c1948Sdrh /* If pFrom->pSelect!=0 it means we are dealing with a 126163eb5f29Sdrh ** view within a view. The SELECT structure has already been 126263eb5f29Sdrh ** copied by the outer view so we can skip the copy step here 126363eb5f29Sdrh ** in the inner view. 126463eb5f29Sdrh */ 1265290c1948Sdrh if( pFrom->pSelect==0 ){ 126617435752Sdrh pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect); 1267a76b5dfcSdrh } 1268d8bc7086Sdrh } 126993758c8dSdanielk1977 #endif 127022f70c32Sdrh } 127163eb5f29Sdrh } 1272d8bc7086Sdrh 1273ad2d8307Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 1274ad2d8307Sdrh */ 1275ad2d8307Sdrh if( sqliteProcessJoin(pParse, p) ) return 1; 1276ad2d8307Sdrh 12777c917d19Sdrh /* For every "*" that occurs in the column list, insert the names of 127854473229Sdrh ** all columns in all tables. And for every TABLE.* insert the names 127954473229Sdrh ** of all columns in TABLE. The parser inserted a special expression 12807c917d19Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 12817c917d19Sdrh ** The following code just has to locate the TK_ALL expressions and expand 12827c917d19Sdrh ** each one to the list of all columns in all tables. 128354473229Sdrh ** 128454473229Sdrh ** The first loop just checks to see if there are any "*" operators 128554473229Sdrh ** that need expanding. 1286d8bc7086Sdrh */ 12877c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 128854473229Sdrh Expr *pE = pEList->a[k].pExpr; 128954473229Sdrh if( pE->op==TK_ALL ) break; 129054473229Sdrh if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 129154473229Sdrh && pE->pLeft && pE->pLeft->op==TK_ID ) break; 12927c917d19Sdrh } 129354473229Sdrh rc = 0; 12947c917d19Sdrh if( k<pEList->nExpr ){ 129554473229Sdrh /* 129654473229Sdrh ** If we get here it means the result set contains one or more "*" 129754473229Sdrh ** operators that need to be expanded. Loop through each expression 129854473229Sdrh ** in the result set and expand them one by one. 129954473229Sdrh */ 13007c917d19Sdrh struct ExprList_item *a = pEList->a; 13017c917d19Sdrh ExprList *pNew = 0; 1302d70dc52dSdrh int flags = pParse->db->flags; 1303d70dc52dSdrh int longNames = (flags & SQLITE_FullColNames)!=0 && 1304d70dc52dSdrh (flags & SQLITE_ShortColNames)==0; 1305d70dc52dSdrh 13067c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 130754473229Sdrh Expr *pE = a[k].pExpr; 130854473229Sdrh if( pE->op!=TK_ALL && 130954473229Sdrh (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 131054473229Sdrh /* This particular expression does not need to be expanded. 131154473229Sdrh */ 131217435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0); 1313261919ccSdanielk1977 if( pNew ){ 13147c917d19Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 1315261919ccSdanielk1977 }else{ 1316261919ccSdanielk1977 rc = 1; 1317261919ccSdanielk1977 } 13187c917d19Sdrh a[k].pExpr = 0; 13197c917d19Sdrh a[k].zName = 0; 13207c917d19Sdrh }else{ 132154473229Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 132254473229Sdrh ** expanded. */ 132354473229Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 1324cf55b7aeSdrh char *zTName; /* text of name of TABLE */ 132554473229Sdrh if( pE->op==TK_DOT && pE->pLeft ){ 132617435752Sdrh zTName = sqlite3NameFromToken(db, &pE->pLeft->token); 132754473229Sdrh }else{ 1328cf55b7aeSdrh zTName = 0; 132954473229Sdrh } 1330290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1331290c1948Sdrh Table *pTab = pFrom->pTab; 1332290c1948Sdrh char *zTabName = pFrom->zAlias; 133354473229Sdrh if( zTabName==0 || zTabName[0]==0 ){ 133454473229Sdrh zTabName = pTab->zName; 133554473229Sdrh } 1336cf55b7aeSdrh if( zTName && (zTabName==0 || zTabName[0]==0 || 1337cf55b7aeSdrh sqlite3StrICmp(zTName, zTabName)!=0) ){ 133854473229Sdrh continue; 133954473229Sdrh } 134054473229Sdrh tableSeen = 1; 1341d8bc7086Sdrh for(j=0; j<pTab->nCol; j++){ 1342f0113000Sdanielk1977 Expr *pExpr, *pRight; 1343ad2d8307Sdrh char *zName = pTab->aCol[j].zName; 1344ad2d8307Sdrh 1345034ca14fSdanielk1977 /* If a column is marked as 'hidden' (currently only possible 1346034ca14fSdanielk1977 ** for virtual tables), do not include it in the expanded 1347034ca14fSdanielk1977 ** result-set list. 1348034ca14fSdanielk1977 */ 1349034ca14fSdanielk1977 if( IsHiddenColumn(&pTab->aCol[j]) ){ 1350034ca14fSdanielk1977 assert(IsVirtual(pTab)); 1351034ca14fSdanielk1977 continue; 1352034ca14fSdanielk1977 } 1353034ca14fSdanielk1977 135491bb0eedSdrh if( i>0 ){ 135591bb0eedSdrh struct SrcList_item *pLeft = &pTabList->a[i-1]; 135661dfc31dSdrh if( (pLeft[1].jointype & JT_NATURAL)!=0 && 135791bb0eedSdrh columnIndex(pLeft->pTab, zName)>=0 ){ 1358ad2d8307Sdrh /* In a NATURAL join, omit the join columns from the 1359ad2d8307Sdrh ** table on the right */ 1360ad2d8307Sdrh continue; 1361ad2d8307Sdrh } 136261dfc31dSdrh if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){ 1363ad2d8307Sdrh /* In a join with a USING clause, omit columns in the 1364ad2d8307Sdrh ** using clause from the table on the right. */ 1365ad2d8307Sdrh continue; 1366ad2d8307Sdrh } 136791bb0eedSdrh } 1368a1644fd8Sdanielk1977 pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); 136922f70c32Sdrh if( pRight==0 ) break; 13701e536953Sdanielk1977 setQuotedToken(pParse, &pRight->token, zName); 1371d70dc52dSdrh if( zTabName && (longNames || pTabList->nSrc>1) ){ 1372a1644fd8Sdanielk1977 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); 1373a1644fd8Sdanielk1977 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 137422f70c32Sdrh if( pExpr==0 ) break; 13751e536953Sdanielk1977 setQuotedToken(pParse, &pLeft->token, zTabName); 13761e536953Sdanielk1977 setToken(&pExpr->span, 13771e536953Sdanielk1977 sqlite3MPrintf(db, "%s.%s", zTabName, zName)); 13786977fea8Sdrh pExpr->span.dyn = 1; 13796977fea8Sdrh pExpr->token.z = 0; 13806977fea8Sdrh pExpr->token.n = 0; 13816977fea8Sdrh pExpr->token.dyn = 0; 138222f70c32Sdrh }else{ 138322f70c32Sdrh pExpr = pRight; 13846977fea8Sdrh pExpr->span = pExpr->token; 1385f3b863edSdanielk1977 pExpr->span.dyn = 0; 138622f70c32Sdrh } 1387d70dc52dSdrh if( longNames ){ 138817435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span); 1389d70dc52dSdrh }else{ 139017435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token); 1391d8bc7086Sdrh } 1392d8bc7086Sdrh } 1393d70dc52dSdrh } 139454473229Sdrh if( !tableSeen ){ 1395cf55b7aeSdrh if( zTName ){ 1396cf55b7aeSdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 1397f5db2d3eSdrh }else{ 13984adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no tables specified"); 1399f5db2d3eSdrh } 140054473229Sdrh rc = 1; 140154473229Sdrh } 140217435752Sdrh sqlite3_free(zTName); 14037c917d19Sdrh } 14047c917d19Sdrh } 14054adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 14067c917d19Sdrh p->pEList = pNew; 1407d8bc7086Sdrh } 1408e5c941b8Sdrh if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){ 1409e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 1410e5c941b8Sdrh rc = SQLITE_ERROR; 1411e5c941b8Sdrh } 141217435752Sdrh if( db->mallocFailed ){ 1413f3b863edSdanielk1977 rc = SQLITE_NOMEM; 1414f3b863edSdanielk1977 } 141554473229Sdrh return rc; 1416d8bc7086Sdrh } 1417d8bc7086Sdrh 141893758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1419ff78bd2fSdrh /* 1420d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with 1421d8bc7086Sdrh ** columns in a result. For each ORDER BY expression, the opcode of 1422967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of 1423d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable 1424d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter. 1425d8bc7086Sdrh ** 1426d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first. A match 1427d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT. 1428d8bc7086Sdrh ** 1429d8bc7086Sdrh ** Any entry that does not match is flagged as an error. The number 1430d8bc7086Sdrh ** of errors is returned. 1431d8bc7086Sdrh */ 1432d8bc7086Sdrh static int matchOrderbyToColumn( 1433d8bc7086Sdrh Parse *pParse, /* A place to leave error messages */ 1434d8bc7086Sdrh Select *pSelect, /* Match to result columns of this SELECT */ 1435d8bc7086Sdrh ExprList *pOrderBy, /* The ORDER BY values to match against columns */ 1436e4de1febSdrh int iTable, /* Insert this value in iTable */ 1437d8bc7086Sdrh int mustComplete /* If TRUE all ORDER BYs must match */ 1438d8bc7086Sdrh ){ 1439d8bc7086Sdrh int nErr = 0; 1440d8bc7086Sdrh int i, j; 1441d8bc7086Sdrh ExprList *pEList; 144217435752Sdrh sqlite3 *db = pParse->db; 1443d8bc7086Sdrh 1444daffd0e5Sdrh if( pSelect==0 || pOrderBy==0 ) return 1; 1445d8bc7086Sdrh if( mustComplete ){ 1446d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } 1447d8bc7086Sdrh } 14489b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 1449d8bc7086Sdrh return 1; 1450d8bc7086Sdrh } 1451d8bc7086Sdrh if( pSelect->pPrior ){ 145292cd52f5Sdrh if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ 145392cd52f5Sdrh return 1; 145492cd52f5Sdrh } 1455d8bc7086Sdrh } 1456d8bc7086Sdrh pEList = pSelect->pEList; 1457d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 145894ccde58Sdrh struct ExprList_item *pItem; 1459d8bc7086Sdrh Expr *pE = pOrderBy->a[i].pExpr; 1460e4de1febSdrh int iCol = -1; 146194ccde58Sdrh char *zLabel; 146294ccde58Sdrh 1463d8bc7086Sdrh if( pOrderBy->a[i].done ) continue; 14644adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 1465e4de1febSdrh if( iCol<=0 || iCol>pEList->nExpr ){ 14664adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1467da93d238Sdrh "ORDER BY position %d should be between 1 and %d", 1468e4de1febSdrh iCol, pEList->nExpr); 1469e4de1febSdrh nErr++; 1470e4de1febSdrh break; 1471e4de1febSdrh } 1472fcb78a49Sdrh if( !mustComplete ) continue; 1473e4de1febSdrh iCol--; 1474e4de1febSdrh } 147517435752Sdrh if( iCol<0 && (zLabel = sqlite3NameFromToken(db, &pE->token))!=0 ){ 147694ccde58Sdrh for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){ 147794ccde58Sdrh char *zName; 14785ea2df91Sdrh int isMatch; 147994ccde58Sdrh if( pItem->zName ){ 148017435752Sdrh zName = sqlite3DbStrDup(db, pItem->zName); 148194ccde58Sdrh }else{ 148217435752Sdrh zName = sqlite3NameFromToken(db, &pItem->pExpr->token); 148394ccde58Sdrh } 14845ea2df91Sdrh isMatch = zName && sqlite3StrICmp(zName, zLabel)==0; 148517435752Sdrh sqlite3_free(zName); 14865ea2df91Sdrh if( isMatch ){ 1487e4de1febSdrh iCol = j; 148894ccde58Sdrh break; 148994ccde58Sdrh } 1490d8bc7086Sdrh } 149117435752Sdrh sqlite3_free(zLabel); 1492d8bc7086Sdrh } 1493e4de1febSdrh if( iCol>=0 ){ 1494967e8b73Sdrh pE->op = TK_COLUMN; 1495e4de1febSdrh pE->iColumn = iCol; 1496d8bc7086Sdrh pE->iTable = iTable; 1497a58fdfb1Sdanielk1977 pE->iAgg = -1; 1498d8bc7086Sdrh pOrderBy->a[i].done = 1; 149994ccde58Sdrh }else if( mustComplete ){ 15004adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1501da93d238Sdrh "ORDER BY term number %d does not match any result column", i+1); 1502d8bc7086Sdrh nErr++; 1503d8bc7086Sdrh break; 1504d8bc7086Sdrh } 1505d8bc7086Sdrh } 1506d8bc7086Sdrh return nErr; 1507d8bc7086Sdrh } 150893758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */ 1509d8bc7086Sdrh 1510d8bc7086Sdrh /* 1511d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1512d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1513d8bc7086Sdrh */ 15144adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1515d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1516d8bc7086Sdrh if( v==0 ){ 15174adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1518d8bc7086Sdrh } 1519d8bc7086Sdrh return v; 1520d8bc7086Sdrh } 1521d8bc7086Sdrh 152215007a99Sdrh 1523d8bc7086Sdrh /* 15247b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1525ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 15267b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1527a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1528a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1529a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1530a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 15317b58daeaSdrh ** 1532d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1533ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 15347b58daeaSdrh ** iOffset should have been preset to appropriate default values 15357b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1536ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 15377b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 15387b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 15397b58daeaSdrh ** SELECT statements. 15407b58daeaSdrh */ 1541ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 154202afc861Sdrh Vdbe *v = 0; 154302afc861Sdrh int iLimit = 0; 154415007a99Sdrh int iOffset; 154515007a99Sdrh int addr1, addr2; 154615007a99Sdrh 15477b58daeaSdrh /* 15487b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 15497b58daeaSdrh ** contraversy about what the correct behavior should be. 15507b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 15517b58daeaSdrh ** no rows. 15527b58daeaSdrh */ 1553a2dc3b1aSdanielk1977 if( p->pLimit ){ 155415007a99Sdrh p->iLimit = iLimit = pParse->nMem; 1555d59ba6ceSdrh pParse->nMem += 2; 155615007a99Sdrh v = sqlite3GetVdbe(pParse); 15577b58daeaSdrh if( v==0 ) return; 1558a2dc3b1aSdanielk1977 sqlite3ExprCode(pParse, p->pLimit); 1559a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 15601e4eaeb5Sdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1); 1561ad6d9460Sdrh VdbeComment((v, "# LIMIT counter")); 156215007a99Sdrh sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak); 15631e4eaeb5Sdanielk1977 sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0); 15647b58daeaSdrh } 1565a2dc3b1aSdanielk1977 if( p->pOffset ){ 156615007a99Sdrh p->iOffset = iOffset = pParse->nMem++; 156715007a99Sdrh v = sqlite3GetVdbe(pParse); 15687b58daeaSdrh if( v==0 ) return; 1569a2dc3b1aSdanielk1977 sqlite3ExprCode(pParse, p->pOffset); 1570a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 157115007a99Sdrh sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0); 1572ad6d9460Sdrh VdbeComment((v, "# OFFSET counter")); 157315007a99Sdrh addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0); 157415007a99Sdrh sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 157515007a99Sdrh sqlite3VdbeAddOp(v, OP_Integer, 0, 0); 157615007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 1577d59ba6ceSdrh if( p->pLimit ){ 1578d59ba6ceSdrh sqlite3VdbeAddOp(v, OP_Add, 0, 0); 1579d59ba6ceSdrh } 15807b58daeaSdrh } 1581d59ba6ceSdrh if( p->pLimit ){ 158215007a99Sdrh addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0); 158315007a99Sdrh sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 158415007a99Sdrh sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1); 158515007a99Sdrh addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 158615007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 158715007a99Sdrh sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1); 1588d59ba6ceSdrh VdbeComment((v, "# LIMIT+OFFSET")); 158915007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 1590d59ba6ceSdrh } 15917b58daeaSdrh } 15927b58daeaSdrh 15937b58daeaSdrh /* 15940342b1f5Sdrh ** Allocate a virtual index to use for sorting. 1595d3d39e93Sdrh */ 15964db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){ 15970342b1f5Sdrh if( pOrderBy ){ 1598dc1bdc4fSdanielk1977 int addr; 15999d2985c7Sdrh assert( pOrderBy->iECursor==0 ); 16009d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 1601b9bb7c18Sdrh addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral, 16029d2985c7Sdrh pOrderBy->iECursor, pOrderBy->nExpr+1); 1603b9bb7c18Sdrh assert( p->addrOpenEphm[2] == -1 ); 1604b9bb7c18Sdrh p->addrOpenEphm[2] = addr; 1605736c22b8Sdrh } 1606dc1bdc4fSdanielk1977 } 1607dc1bdc4fSdanielk1977 1608b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1609fbc4ee7bSdrh /* 1610fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1611fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1612fbc4ee7bSdrh ** the column has no default collating sequence. 1613fbc4ee7bSdrh ** 1614fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1615fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1616fbc4ee7bSdrh */ 1617dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1618fbc4ee7bSdrh CollSeq *pRet; 1619dc1bdc4fSdanielk1977 if( p->pPrior ){ 1620dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1621fbc4ee7bSdrh }else{ 1622fbc4ee7bSdrh pRet = 0; 1623dc1bdc4fSdanielk1977 } 1624fbc4ee7bSdrh if( pRet==0 ){ 1625dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1626dc1bdc4fSdanielk1977 } 1627dc1bdc4fSdanielk1977 return pRet; 1628d3d39e93Sdrh } 1629b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1630d3d39e93Sdrh 1631b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1632d3d39e93Sdrh /* 163382c3d636Sdrh ** This routine is called to process a query that is really the union 163482c3d636Sdrh ** or intersection of two or more separate queries. 1635c926afbcSdrh ** 1636e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1637e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1638e78e8284Sdrh ** in which case this routine will be called recursively. 1639e78e8284Sdrh ** 1640e78e8284Sdrh ** The results of the total query are to be written into a destination 1641e78e8284Sdrh ** of type eDest with parameter iParm. 1642e78e8284Sdrh ** 1643e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1644e78e8284Sdrh ** 1645e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1646e78e8284Sdrh ** 1647e78e8284Sdrh ** This statement is parsed up as follows: 1648e78e8284Sdrh ** 1649e78e8284Sdrh ** SELECT c FROM t3 1650e78e8284Sdrh ** | 1651e78e8284Sdrh ** `-----> SELECT b FROM t2 1652e78e8284Sdrh ** | 16534b11c6d3Sjplyon ** `------> SELECT a FROM t1 1654e78e8284Sdrh ** 1655e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1656e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1657e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1658e78e8284Sdrh ** 1659e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1660e78e8284Sdrh ** individual selects always group from left to right. 166182c3d636Sdrh */ 166284ac9d02Sdanielk1977 static int multiSelect( 1663fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1664fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1665fbc4ee7bSdrh int eDest, /* \___ Store query results as specified */ 1666fbc4ee7bSdrh int iParm, /* / by these two parameters. */ 166784ac9d02Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 166884ac9d02Sdanielk1977 ){ 166984ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 167010e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 167110e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 16728cdbf836Sdrh int nCol; /* Number of columns in the result set */ 16730342b1f5Sdrh ExprList *pOrderBy; /* The ORDER BY clause on p */ 16740342b1f5Sdrh int aSetP2[2]; /* Set P2 value of these op to number of columns */ 16750342b1f5Sdrh int nSetP2 = 0; /* Number of slots in aSetP2[] used */ 167682c3d636Sdrh 16777b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1678fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 167982c3d636Sdrh */ 168084ac9d02Sdanielk1977 if( p==0 || p->pPrior==0 ){ 168184ac9d02Sdanielk1977 rc = 1; 168284ac9d02Sdanielk1977 goto multi_select_end; 168384ac9d02Sdanielk1977 } 1684d8bc7086Sdrh pPrior = p->pPrior; 16850342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 16860342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1687d8bc7086Sdrh if( pPrior->pOrderBy ){ 16884adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1689da93d238Sdrh selectOpName(p->op)); 169084ac9d02Sdanielk1977 rc = 1; 169184ac9d02Sdanielk1977 goto multi_select_end; 169282c3d636Sdrh } 1693a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 16944adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 16957b58daeaSdrh selectOpName(p->op)); 169684ac9d02Sdanielk1977 rc = 1; 169784ac9d02Sdanielk1977 goto multi_select_end; 16987b58daeaSdrh } 169982c3d636Sdrh 1700d8bc7086Sdrh /* Make sure we have a valid query engine. If not, create a new one. 1701d8bc7086Sdrh */ 17024adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 170384ac9d02Sdanielk1977 if( v==0 ){ 170484ac9d02Sdanielk1977 rc = 1; 170584ac9d02Sdanielk1977 goto multi_select_end; 170684ac9d02Sdanielk1977 } 1707d8bc7086Sdrh 17081cc3d75fSdrh /* Create the destination temporary table if necessary 17091cc3d75fSdrh */ 1710b9bb7c18Sdrh if( eDest==SRT_EphemTab ){ 1711b4964b72Sdanielk1977 assert( p->pEList ); 17120342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 1713b9bb7c18Sdrh aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0); 17141cc3d75fSdrh eDest = SRT_Table; 17151cc3d75fSdrh } 17161cc3d75fSdrh 1717f46f905aSdrh /* Generate code for the left and right SELECT statements. 1718d8bc7086Sdrh */ 17190342b1f5Sdrh pOrderBy = p->pOrderBy; 172082c3d636Sdrh switch( p->op ){ 1721f46f905aSdrh case TK_ALL: { 17220342b1f5Sdrh if( pOrderBy==0 ){ 1723ec7429aeSdrh int addr = 0; 1724a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1725a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1726a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 1727b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff); 1728ad68cb6bSdanielk1977 p->pLimit = 0; 1729ad68cb6bSdanielk1977 p->pOffset = 0; 173084ac9d02Sdanielk1977 if( rc ){ 173184ac9d02Sdanielk1977 goto multi_select_end; 173284ac9d02Sdanielk1977 } 1733f46f905aSdrh p->pPrior = 0; 17347b58daeaSdrh p->iLimit = pPrior->iLimit; 17357b58daeaSdrh p->iOffset = pPrior->iOffset; 1736ec7429aeSdrh if( p->iLimit>=0 ){ 1737ec7429aeSdrh addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0); 1738ec7429aeSdrh VdbeComment((v, "# Jump ahead if LIMIT reached")); 1739ec7429aeSdrh } 1740b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff); 1741f46f905aSdrh p->pPrior = pPrior; 174284ac9d02Sdanielk1977 if( rc ){ 174384ac9d02Sdanielk1977 goto multi_select_end; 174484ac9d02Sdanielk1977 } 1745ec7429aeSdrh if( addr ){ 1746ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1747ec7429aeSdrh } 1748f46f905aSdrh break; 1749f46f905aSdrh } 1750f46f905aSdrh /* For UNION ALL ... ORDER BY fall through to the next case */ 1751f46f905aSdrh } 175282c3d636Sdrh case TK_EXCEPT: 175382c3d636Sdrh case TK_UNION: { 1754d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1755742f947bSdanielk1977 int op = 0; /* One of the SRT_ operations to apply to self */ 1756d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1757a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1758dc1bdc4fSdanielk1977 int addr; 175982c3d636Sdrh 1760d8bc7086Sdrh priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 17610342b1f5Sdrh if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ 1762d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1763c926afbcSdrh ** right. 1764d8bc7086Sdrh */ 176582c3d636Sdrh unionTab = iParm; 176682c3d636Sdrh }else{ 1767d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1768d8bc7086Sdrh ** intermediate results. 1769d8bc7086Sdrh */ 177082c3d636Sdrh unionTab = pParse->nTab++; 17710342b1f5Sdrh if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){ 177284ac9d02Sdanielk1977 rc = 1; 177384ac9d02Sdanielk1977 goto multi_select_end; 1774d8bc7086Sdrh } 1775b9bb7c18Sdrh addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0); 17760342b1f5Sdrh if( priorOp==SRT_Table ){ 17770342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 17780342b1f5Sdrh aSetP2[nSetP2++] = addr; 17790342b1f5Sdrh }else{ 1780b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1781b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 1782b9bb7c18Sdrh p->pRightmost->usesEphm = 1; 1783dc1bdc4fSdanielk1977 } 17840342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 178584ac9d02Sdanielk1977 assert( p->pEList ); 1786d8bc7086Sdrh } 1787d8bc7086Sdrh 1788d8bc7086Sdrh /* Code the SELECT statements to our left 1789d8bc7086Sdrh */ 1790b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 1791b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); 179284ac9d02Sdanielk1977 if( rc ){ 179384ac9d02Sdanielk1977 goto multi_select_end; 179484ac9d02Sdanielk1977 } 1795d8bc7086Sdrh 1796d8bc7086Sdrh /* Code the current SELECT statement 1797d8bc7086Sdrh */ 1798d8bc7086Sdrh switch( p->op ){ 1799d8bc7086Sdrh case TK_EXCEPT: op = SRT_Except; break; 1800d8bc7086Sdrh case TK_UNION: op = SRT_Union; break; 1801d8bc7086Sdrh case TK_ALL: op = SRT_Table; break; 1802d8bc7086Sdrh } 180382c3d636Sdrh p->pPrior = 0; 1804c926afbcSdrh p->pOrderBy = 0; 18054b14b4d7Sdrh p->disallowOrderBy = pOrderBy!=0; 1806a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1807a2dc3b1aSdanielk1977 p->pLimit = 0; 1808a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1809a2dc3b1aSdanielk1977 p->pOffset = 0; 1810b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff); 18115bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 18125bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 18135bd1bf2eSdrh sqlite3ExprListDelete(p->pOrderBy); 181482c3d636Sdrh p->pPrior = pPrior; 1815c926afbcSdrh p->pOrderBy = pOrderBy; 1816a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 1817a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1818a2dc3b1aSdanielk1977 p->pOffset = pOffset; 1819be5fd490Sdrh p->iLimit = -1; 1820be5fd490Sdrh p->iOffset = -1; 182184ac9d02Sdanielk1977 if( rc ){ 182284ac9d02Sdanielk1977 goto multi_select_end; 182384ac9d02Sdanielk1977 } 182484ac9d02Sdanielk1977 1825d8bc7086Sdrh 1826d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1827d8bc7086Sdrh ** it is that we currently need. 1828d8bc7086Sdrh */ 1829c926afbcSdrh if( eDest!=priorOp || unionTab!=iParm ){ 18306b56344dSdrh int iCont, iBreak, iStart; 183182c3d636Sdrh assert( p->pEList ); 183241202ccaSdrh if( eDest==SRT_Callback ){ 183392378253Sdrh Select *pFirst = p; 183492378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 183592378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 183641202ccaSdrh } 18374adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 18384adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1839ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 18404adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); 18414adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 184238640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 18430342b1f5Sdrh pOrderBy, -1, eDest, iParm, 184484ac9d02Sdanielk1977 iCont, iBreak, 0); 184584ac9d02Sdanielk1977 if( rc ){ 184684ac9d02Sdanielk1977 rc = 1; 184784ac9d02Sdanielk1977 goto multi_select_end; 184884ac9d02Sdanielk1977 } 18494adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 18504adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); 18514adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 18524adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); 185382c3d636Sdrh } 185482c3d636Sdrh break; 185582c3d636Sdrh } 185682c3d636Sdrh case TK_INTERSECT: { 185782c3d636Sdrh int tab1, tab2; 18586b56344dSdrh int iCont, iBreak, iStart; 1859a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 1860dc1bdc4fSdanielk1977 int addr; 186182c3d636Sdrh 1862d8bc7086Sdrh /* INTERSECT is different from the others since it requires 18636206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1864d8bc7086Sdrh ** by allocating the tables we will need. 1865d8bc7086Sdrh */ 186682c3d636Sdrh tab1 = pParse->nTab++; 186782c3d636Sdrh tab2 = pParse->nTab++; 18680342b1f5Sdrh if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){ 186984ac9d02Sdanielk1977 rc = 1; 187084ac9d02Sdanielk1977 goto multi_select_end; 1871d8bc7086Sdrh } 18720342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 1873dc1bdc4fSdanielk1977 1874b9bb7c18Sdrh addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0); 1875b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1876b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 1877b9bb7c18Sdrh p->pRightmost->usesEphm = 1; 187884ac9d02Sdanielk1977 assert( p->pEList ); 1879d8bc7086Sdrh 1880d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1881d8bc7086Sdrh */ 1882b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); 188384ac9d02Sdanielk1977 if( rc ){ 188484ac9d02Sdanielk1977 goto multi_select_end; 188584ac9d02Sdanielk1977 } 1886d8bc7086Sdrh 1887d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1888d8bc7086Sdrh */ 1889b9bb7c18Sdrh addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0); 1890b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 1891b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 189282c3d636Sdrh p->pPrior = 0; 1893a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1894a2dc3b1aSdanielk1977 p->pLimit = 0; 1895a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1896a2dc3b1aSdanielk1977 p->pOffset = 0; 1897b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); 189882c3d636Sdrh p->pPrior = pPrior; 1899a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 1900a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1901a2dc3b1aSdanielk1977 p->pOffset = pOffset; 190284ac9d02Sdanielk1977 if( rc ){ 190384ac9d02Sdanielk1977 goto multi_select_end; 190484ac9d02Sdanielk1977 } 1905d8bc7086Sdrh 1906d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1907d8bc7086Sdrh ** tables. 1908d8bc7086Sdrh */ 190982c3d636Sdrh assert( p->pEList ); 191041202ccaSdrh if( eDest==SRT_Callback ){ 191192378253Sdrh Select *pFirst = p; 191292378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 191392378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 191441202ccaSdrh } 19154adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 19164adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1917ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 19184adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak); 19194a9f241cSdrh iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0); 19204adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont); 192138640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 19220342b1f5Sdrh pOrderBy, -1, eDest, iParm, 192384ac9d02Sdanielk1977 iCont, iBreak, 0); 192484ac9d02Sdanielk1977 if( rc ){ 192584ac9d02Sdanielk1977 rc = 1; 192684ac9d02Sdanielk1977 goto multi_select_end; 192784ac9d02Sdanielk1977 } 19284adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 19294adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); 19304adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 19314adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab2, 0); 19324adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab1, 0); 193382c3d636Sdrh break; 193482c3d636Sdrh } 193582c3d636Sdrh } 19368cdbf836Sdrh 19378cdbf836Sdrh /* Make sure all SELECTs in the statement have the same number of elements 19388cdbf836Sdrh ** in their result sets. 19398cdbf836Sdrh */ 194082c3d636Sdrh assert( p->pEList && pPrior->pEList ); 194182c3d636Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 19424adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1943da93d238Sdrh " do not have the same number of result columns", selectOpName(p->op)); 194484ac9d02Sdanielk1977 rc = 1; 194584ac9d02Sdanielk1977 goto multi_select_end; 19462282792aSdrh } 194784ac9d02Sdanielk1977 19488cdbf836Sdrh /* Set the number of columns in temporary tables 19498cdbf836Sdrh */ 19508cdbf836Sdrh nCol = p->pEList->nExpr; 19510342b1f5Sdrh while( nSetP2 ){ 19520342b1f5Sdrh sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol); 19538cdbf836Sdrh } 19548cdbf836Sdrh 1955fbc4ee7bSdrh /* Compute collating sequences used by either the ORDER BY clause or 1956fbc4ee7bSdrh ** by any temporary tables needed to implement the compound select. 1957fbc4ee7bSdrh ** Attach the KeyInfo structure to all temporary tables. Invoke the 1958fbc4ee7bSdrh ** ORDER BY processing if there is an ORDER BY clause. 19598cdbf836Sdrh ** 19608cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 19618cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 19628cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 19638cdbf836Sdrh ** no temp tables are required. 1964fbc4ee7bSdrh */ 1965b9bb7c18Sdrh if( pOrderBy || p->usesEphm ){ 1966fbc4ee7bSdrh int i; /* Loop counter */ 1967fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 19680342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 19691e31e0b2Sdrh int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */ 1970f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 1971f68d7d17Sdrh CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */ 1972fbc4ee7bSdrh 19730342b1f5Sdrh assert( p->pRightmost==p ); 19741e31e0b2Sdrh nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0); 197517435752Sdrh pKeyInfo = sqlite3DbMallocZero(pParse->db, 197617435752Sdrh sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1)); 1977dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1978dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1979dc1bdc4fSdanielk1977 goto multi_select_end; 1980dc1bdc4fSdanielk1977 } 1981dc1bdc4fSdanielk1977 198214db2665Sdanielk1977 pKeyInfo->enc = ENC(pParse->db); 1983dc1bdc4fSdanielk1977 pKeyInfo->nField = nCol; 1984dc1bdc4fSdanielk1977 19850342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 19860342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 19870342b1f5Sdrh if( 0==*apColl ){ 19880342b1f5Sdrh *apColl = pParse->db->pDfltColl; 1989dc1bdc4fSdanielk1977 } 1990dc1bdc4fSdanielk1977 } 1991dc1bdc4fSdanielk1977 19920342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 19930342b1f5Sdrh for(i=0; i<2; i++){ 1994b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 19950342b1f5Sdrh if( addr<0 ){ 19960342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 19970342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 1998b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 19990342b1f5Sdrh break; 20000342b1f5Sdrh } 20010342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 20020342b1f5Sdrh sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO); 20030ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 20040342b1f5Sdrh } 2005dc1bdc4fSdanielk1977 } 2006dc1bdc4fSdanielk1977 20070342b1f5Sdrh if( pOrderBy ){ 20080342b1f5Sdrh struct ExprList_item *pOTerm = pOrderBy->a; 20094efc083fSdrh int nOrderByExpr = pOrderBy->nExpr; 20100342b1f5Sdrh int addr; 20114db38a70Sdrh u8 *pSortOrder; 20120342b1f5Sdrh 2013f68d7d17Sdrh /* Reuse the same pKeyInfo for the ORDER BY as was used above for 2014f68d7d17Sdrh ** the compound select statements. Except we have to change out the 2015f68d7d17Sdrh ** pKeyInfo->aColl[] values. Some of the aColl[] values will be 2016f68d7d17Sdrh ** reused when constructing the pKeyInfo for the ORDER BY, so make 2017f68d7d17Sdrh ** a copy. Sufficient space to hold both the nCol entries for 2018f68d7d17Sdrh ** the compound select and the nOrderbyExpr entries for the ORDER BY 2019f68d7d17Sdrh ** was allocated above. But we need to move the compound select 2020f68d7d17Sdrh ** entries out of the way before constructing the ORDER BY entries. 2021f68d7d17Sdrh ** Move the compound select entries into aCopy[] where they can be 2022f68d7d17Sdrh ** accessed and reused when constructing the ORDER BY entries. 2023f68d7d17Sdrh ** Because nCol might be greater than or less than nOrderByExpr 2024f68d7d17Sdrh ** we have to use memmove() when doing the copy. 2025f68d7d17Sdrh */ 20261e31e0b2Sdrh aCopy = &pKeyInfo->aColl[nOrderByExpr]; 20274efc083fSdrh pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol]; 2028f68d7d17Sdrh memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*)); 2029f68d7d17Sdrh 20300342b1f5Sdrh apColl = pKeyInfo->aColl; 20314efc083fSdrh for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){ 20320342b1f5Sdrh Expr *pExpr = pOTerm->pExpr; 20338b4c40d8Sdrh if( (pExpr->flags & EP_ExpCollate) ){ 20348b4c40d8Sdrh assert( pExpr->pColl!=0 ); 20358b4c40d8Sdrh *apColl = pExpr->pColl; 203684ac9d02Sdanielk1977 }else{ 20370342b1f5Sdrh *apColl = aCopy[pExpr->iColumn]; 203884ac9d02Sdanielk1977 } 20394db38a70Sdrh *pSortOrder = pOTerm->sortOrder; 204084ac9d02Sdanielk1977 } 20410342b1f5Sdrh assert( p->pRightmost==p ); 2042b9bb7c18Sdrh assert( p->addrOpenEphm[2]>=0 ); 2043b9bb7c18Sdrh addr = p->addrOpenEphm[2]; 2044a670b226Sdanielk1977 sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2); 20454efc083fSdrh pKeyInfo->nField = nOrderByExpr; 20464db38a70Sdrh sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 20474db38a70Sdrh pKeyInfo = 0; 2048cdd536f0Sdrh generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm); 2049dc1bdc4fSdanielk1977 } 2050dc1bdc4fSdanielk1977 205117435752Sdrh sqlite3_free(pKeyInfo); 2052dc1bdc4fSdanielk1977 } 2053dc1bdc4fSdanielk1977 2054dc1bdc4fSdanielk1977 multi_select_end: 205584ac9d02Sdanielk1977 return rc; 20562282792aSdrh } 2057b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 20582282792aSdrh 2059b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 206017435752Sdrh /* Forward Declarations */ 206117435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*); 206217435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *); 206317435752Sdrh 20642282792aSdrh /* 2065832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 20666a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 206784e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 20686a3ea0e6Sdrh ** unchanged.) 2069832508b7Sdrh ** 2070832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 2071832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 2072832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 2073832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 2074832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 2075832508b7Sdrh ** of the subquery rather the result set of the subquery. 2076832508b7Sdrh */ 207717435752Sdrh static void substExpr( 207817435752Sdrh sqlite3 *db, /* Report malloc errors to this connection */ 207917435752Sdrh Expr *pExpr, /* Expr in which substitution occurs */ 208017435752Sdrh int iTable, /* Table to be substituted */ 208117435752Sdrh ExprList *pEList /* Substitute expressions */ 208217435752Sdrh ){ 2083832508b7Sdrh if( pExpr==0 ) return; 208450350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 208550350a15Sdrh if( pExpr->iColumn<0 ){ 208650350a15Sdrh pExpr->op = TK_NULL; 208750350a15Sdrh }else{ 2088832508b7Sdrh Expr *pNew; 208984e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 2090832508b7Sdrh assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 2091832508b7Sdrh pNew = pEList->a[pExpr->iColumn].pExpr; 2092832508b7Sdrh assert( pNew!=0 ); 2093832508b7Sdrh pExpr->op = pNew->op; 2094d94a6698Sdrh assert( pExpr->pLeft==0 ); 209517435752Sdrh pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft); 2096d94a6698Sdrh assert( pExpr->pRight==0 ); 209717435752Sdrh pExpr->pRight = sqlite3ExprDup(db, pNew->pRight); 2098d94a6698Sdrh assert( pExpr->pList==0 ); 209917435752Sdrh pExpr->pList = sqlite3ExprListDup(db, pNew->pList); 2100832508b7Sdrh pExpr->iTable = pNew->iTable; 2101fbbe005aSdanielk1977 pExpr->pTab = pNew->pTab; 2102832508b7Sdrh pExpr->iColumn = pNew->iColumn; 2103832508b7Sdrh pExpr->iAgg = pNew->iAgg; 210417435752Sdrh sqlite3TokenCopy(db, &pExpr->token, &pNew->token); 210517435752Sdrh sqlite3TokenCopy(db, &pExpr->span, &pNew->span); 210617435752Sdrh pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect); 2107a1cb183dSdanielk1977 pExpr->flags = pNew->flags; 210850350a15Sdrh } 2109832508b7Sdrh }else{ 211017435752Sdrh substExpr(db, pExpr->pLeft, iTable, pEList); 211117435752Sdrh substExpr(db, pExpr->pRight, iTable, pEList); 211217435752Sdrh substSelect(db, pExpr->pSelect, iTable, pEList); 211317435752Sdrh substExprList(db, pExpr->pList, iTable, pEList); 2114832508b7Sdrh } 2115832508b7Sdrh } 211617435752Sdrh static void substExprList( 211717435752Sdrh sqlite3 *db, /* Report malloc errors here */ 211817435752Sdrh ExprList *pList, /* List to scan and in which to make substitutes */ 211917435752Sdrh int iTable, /* Table to be substituted */ 212017435752Sdrh ExprList *pEList /* Substitute values */ 212117435752Sdrh ){ 2122832508b7Sdrh int i; 2123832508b7Sdrh if( pList==0 ) return; 2124832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 212517435752Sdrh substExpr(db, pList->a[i].pExpr, iTable, pEList); 2126832508b7Sdrh } 2127832508b7Sdrh } 212817435752Sdrh static void substSelect( 212917435752Sdrh sqlite3 *db, /* Report malloc errors here */ 213017435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 213117435752Sdrh int iTable, /* Table to be replaced */ 213217435752Sdrh ExprList *pEList /* Substitute values */ 213317435752Sdrh ){ 2134b3bce662Sdanielk1977 if( !p ) return; 213517435752Sdrh substExprList(db, p->pEList, iTable, pEList); 213617435752Sdrh substExprList(db, p->pGroupBy, iTable, pEList); 213717435752Sdrh substExprList(db, p->pOrderBy, iTable, pEList); 213817435752Sdrh substExpr(db, p->pHaving, iTable, pEList); 213917435752Sdrh substExpr(db, p->pWhere, iTable, pEList); 214017435752Sdrh substSelect(db, p->pPrior, iTable, pEList); 2141b3bce662Sdanielk1977 } 2142b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */ 2143832508b7Sdrh 2144b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 2145832508b7Sdrh /* 21461350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 21471350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 21481350b030Sdrh ** occurs. 21491350b030Sdrh ** 21501350b030Sdrh ** To understand the concept of flattening, consider the following 21511350b030Sdrh ** query: 21521350b030Sdrh ** 21531350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 21541350b030Sdrh ** 21551350b030Sdrh ** The default way of implementing this query is to execute the 21561350b030Sdrh ** subquery first and store the results in a temporary table, then 21571350b030Sdrh ** run the outer query on that temporary table. This requires two 21581350b030Sdrh ** passes over the data. Furthermore, because the temporary table 21591350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 2160832508b7Sdrh ** optimized. 21611350b030Sdrh ** 2162832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 21631350b030Sdrh ** a single flat select, like this: 21641350b030Sdrh ** 21651350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 21661350b030Sdrh ** 21671350b030Sdrh ** The code generated for this simpification gives the same result 2168832508b7Sdrh ** but only has to scan the data once. And because indices might 2169832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 2170832508b7Sdrh ** avoided. 21711350b030Sdrh ** 2172832508b7Sdrh ** Flattening is only attempted if all of the following are true: 21731350b030Sdrh ** 2174832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 21751350b030Sdrh ** 2176832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 2177832508b7Sdrh ** 21788af4d3acSdrh ** (3) The subquery is not the right operand of a left outer join, or 21798af4d3acSdrh ** the subquery is not itself a join. (Ticket #306) 2180832508b7Sdrh ** 2181832508b7Sdrh ** (4) The subquery is not DISTINCT or the outer query is not a join. 2182832508b7Sdrh ** 2183832508b7Sdrh ** (5) The subquery is not DISTINCT or the outer query does not use 2184832508b7Sdrh ** aggregates. 2185832508b7Sdrh ** 2186832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 2187832508b7Sdrh ** DISTINCT. 2188832508b7Sdrh ** 218908192d5fSdrh ** (7) The subquery has a FROM clause. 219008192d5fSdrh ** 2191df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 2192df199a25Sdrh ** 2193df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 2194df199a25Sdrh ** aggregates. 2195df199a25Sdrh ** 2196df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 2197df199a25Sdrh ** use LIMIT. 2198df199a25Sdrh ** 2199174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 2200174b6195Sdrh ** 22013fc673e6Sdrh ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 22023fc673e6Sdrh ** subquery has no WHERE clause. (added by ticket #350) 22033fc673e6Sdrh ** 2204ac83963aSdrh ** (13) The subquery and outer query do not both use LIMIT 2205ac83963aSdrh ** 2206ac83963aSdrh ** (14) The subquery does not use OFFSET 2207ac83963aSdrh ** 2208ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 2209ad91c6cdSdrh ** subquery does not have both an ORDER BY and a LIMIT clause. 2210ad91c6cdSdrh ** (See ticket #2339) 2211ad91c6cdSdrh ** 2212832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 2213832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2214832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2215832508b7Sdrh ** 2216665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 2217832508b7Sdrh ** If flattening is attempted this routine returns 1. 2218832508b7Sdrh ** 2219832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 2220832508b7Sdrh ** the subquery before this routine runs. 22211350b030Sdrh */ 22228c74a8caSdrh static int flattenSubquery( 222317435752Sdrh sqlite3 *db, /* Database connection */ 22248c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 22258c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 22268c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 22278c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 22288c74a8caSdrh ){ 22290bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2230ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2231ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 22320bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 22336a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 223491bb0eedSdrh int i; /* Loop counter */ 223591bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 223691bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 22371350b030Sdrh 2238832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2239832508b7Sdrh */ 2240832508b7Sdrh if( p==0 ) return 0; 2241832508b7Sdrh pSrc = p->pSrc; 2242ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 224391bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 224491bb0eedSdrh pSub = pSubitem->pSelect; 2245832508b7Sdrh assert( pSub!=0 ); 2246ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2247ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2248832508b7Sdrh pSubSrc = pSub->pSrc; 2249832508b7Sdrh assert( pSubSrc ); 2250ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2251ac83963aSdrh ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2252ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 2253ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 2254ac83963aSdrh ** and (14). */ 2255ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2256ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 2257ad91c6cdSdrh if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){ 2258ad91c6cdSdrh return 0; /* Restriction (15) */ 2259ad91c6cdSdrh } 2260ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 2261ac83963aSdrh if( (pSub->isDistinct || pSub->pLimit) 2262ac83963aSdrh && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */ 2263df199a25Sdrh return 0; 2264df199a25Sdrh } 2265ac83963aSdrh if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */ 2266ac83963aSdrh if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){ 2267ac83963aSdrh return 0; /* Restriction (11) */ 2268ac83963aSdrh } 2269832508b7Sdrh 22708af4d3acSdrh /* Restriction 3: If the subquery is a join, make sure the subquery is 22718af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 22728af4d3acSdrh ** is not allowed: 22738af4d3acSdrh ** 22748af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 22758af4d3acSdrh ** 22768af4d3acSdrh ** If we flatten the above, we would get 22778af4d3acSdrh ** 22788af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 22798af4d3acSdrh ** 22808af4d3acSdrh ** which is not at all the same thing. 22818af4d3acSdrh */ 228261dfc31dSdrh if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){ 22838af4d3acSdrh return 0; 22848af4d3acSdrh } 22858af4d3acSdrh 22863fc673e6Sdrh /* Restriction 12: If the subquery is the right operand of a left outer 22873fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 22883fc673e6Sdrh ** An examples of why this is not allowed: 22893fc673e6Sdrh ** 22903fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 22913fc673e6Sdrh ** 22923fc673e6Sdrh ** If we flatten the above, we would get 22933fc673e6Sdrh ** 22943fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 22953fc673e6Sdrh ** 22963fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 22973fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 22983fc673e6Sdrh */ 229961dfc31dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){ 23003fc673e6Sdrh return 0; 23013fc673e6Sdrh } 23023fc673e6Sdrh 23030bb28106Sdrh /* If we reach this point, it means flattening is permitted for the 230463eb5f29Sdrh ** iFrom-th entry of the FROM clause in the outer query. 2305832508b7Sdrh */ 2306c31c2eb8Sdrh 2307c31c2eb8Sdrh /* Move all of the FROM elements of the subquery into the 2308c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2309c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2310c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2311c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2312c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2313c31c2eb8Sdrh ** elements we are now copying in. 2314c31c2eb8Sdrh */ 231591bb0eedSdrh iParent = pSubitem->iCursor; 2316c31c2eb8Sdrh { 2317c31c2eb8Sdrh int nSubSrc = pSubSrc->nSrc; 231891bb0eedSdrh int jointype = pSubitem->jointype; 2319c31c2eb8Sdrh 2320a04a34ffSdanielk1977 sqlite3DeleteTable(pSubitem->pTab); 232117435752Sdrh sqlite3_free(pSubitem->zDatabase); 232217435752Sdrh sqlite3_free(pSubitem->zName); 232317435752Sdrh sqlite3_free(pSubitem->zAlias); 2324*cfa063b3Sdrh pSubitem->pTab = 0; 2325*cfa063b3Sdrh pSubitem->zDatabase = 0; 2326*cfa063b3Sdrh pSubitem->zName = 0; 2327*cfa063b3Sdrh pSubitem->zAlias = 0; 2328c31c2eb8Sdrh if( nSubSrc>1 ){ 2329c31c2eb8Sdrh int extra = nSubSrc - 1; 2330c31c2eb8Sdrh for(i=1; i<nSubSrc; i++){ 233117435752Sdrh pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0); 2332*cfa063b3Sdrh if( pSrc==0 ){ 2333*cfa063b3Sdrh p->pSrc = 0; 2334*cfa063b3Sdrh return 1; 2335*cfa063b3Sdrh } 2336c31c2eb8Sdrh } 2337c31c2eb8Sdrh p->pSrc = pSrc; 2338c31c2eb8Sdrh for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 2339c31c2eb8Sdrh pSrc->a[i] = pSrc->a[i-extra]; 2340c31c2eb8Sdrh } 2341c31c2eb8Sdrh } 2342c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2343c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2344c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2345c31c2eb8Sdrh } 234661dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 2347c31c2eb8Sdrh } 2348c31c2eb8Sdrh 2349c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2350c31c2eb8Sdrh ** references to the iParent in the outer query. 2351c31c2eb8Sdrh ** 2352c31c2eb8Sdrh ** Example: 2353c31c2eb8Sdrh ** 2354c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2355c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 2356c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 2357c31c2eb8Sdrh ** 2358c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 2359c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2360c31c2eb8Sdrh */ 2361832508b7Sdrh pList = p->pEList; 2362832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 23636977fea8Sdrh Expr *pExpr; 23646977fea8Sdrh if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 236517435752Sdrh pList->a[i].zName = 236617435752Sdrh sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n); 2367832508b7Sdrh } 2368832508b7Sdrh } 23691e536953Sdanielk1977 substExprList(db, p->pEList, iParent, pSub->pEList); 23701b2e0329Sdrh if( isAgg ){ 23711e536953Sdanielk1977 substExprList(db, p->pGroupBy, iParent, pSub->pEList); 23721e536953Sdanielk1977 substExpr(db, p->pHaving, iParent, pSub->pEList); 23731b2e0329Sdrh } 2374174b6195Sdrh if( pSub->pOrderBy ){ 2375174b6195Sdrh assert( p->pOrderBy==0 ); 2376174b6195Sdrh p->pOrderBy = pSub->pOrderBy; 2377174b6195Sdrh pSub->pOrderBy = 0; 2378174b6195Sdrh }else if( p->pOrderBy ){ 23791e536953Sdanielk1977 substExprList(db, p->pOrderBy, iParent, pSub->pEList); 2380174b6195Sdrh } 2381832508b7Sdrh if( pSub->pWhere ){ 238217435752Sdrh pWhere = sqlite3ExprDup(db, pSub->pWhere); 2383832508b7Sdrh }else{ 2384832508b7Sdrh pWhere = 0; 2385832508b7Sdrh } 2386832508b7Sdrh if( subqueryIsAgg ){ 2387832508b7Sdrh assert( p->pHaving==0 ); 23881b2e0329Sdrh p->pHaving = p->pWhere; 23891b2e0329Sdrh p->pWhere = pWhere; 23901e536953Sdanielk1977 substExpr(db, p->pHaving, iParent, pSub->pEList); 239117435752Sdrh p->pHaving = sqlite3ExprAnd(db, p->pHaving, 239217435752Sdrh sqlite3ExprDup(db, pSub->pHaving)); 23931b2e0329Sdrh assert( p->pGroupBy==0 ); 239417435752Sdrh p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy); 2395832508b7Sdrh }else{ 23961e536953Sdanielk1977 substExpr(db, p->pWhere, iParent, pSub->pEList); 239717435752Sdrh p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere); 2398832508b7Sdrh } 2399c31c2eb8Sdrh 2400c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 2401c31c2eb8Sdrh ** outer query is distinct. 2402c31c2eb8Sdrh */ 2403832508b7Sdrh p->isDistinct = p->isDistinct || pSub->isDistinct; 24048c74a8caSdrh 2405a58fdfb1Sdanielk1977 /* 2406a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 2407ac83963aSdrh ** 2408ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 2409ac83963aSdrh ** does not work if either limit is negative. 2410a58fdfb1Sdanielk1977 */ 2411a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 2412a2dc3b1aSdanielk1977 p->pLimit = pSub->pLimit; 2413a2dc3b1aSdanielk1977 pSub->pLimit = 0; 2414df199a25Sdrh } 24158c74a8caSdrh 2416c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 2417c31c2eb8Sdrh ** success. 2418c31c2eb8Sdrh */ 24194adee20fSdanielk1977 sqlite3SelectDelete(pSub); 2420832508b7Sdrh return 1; 24211350b030Sdrh } 2422b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 24231350b030Sdrh 24241350b030Sdrh /* 24259562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it 24269562b551Sdrh ** is a simple min() or max() query. If it is and this query can be 24279562b551Sdrh ** satisfied using a single seek to the beginning or end of an index, 2428e78e8284Sdrh ** then generate the code for this SELECT and return 1. If this is not a 24299562b551Sdrh ** simple min() or max() query, then return 0; 24309562b551Sdrh ** 24319562b551Sdrh ** A simply min() or max() query looks like this: 24329562b551Sdrh ** 24339562b551Sdrh ** SELECT min(a) FROM table; 24349562b551Sdrh ** SELECT max(a) FROM table; 24359562b551Sdrh ** 24369562b551Sdrh ** The query may have only a single table in its FROM argument. There 24379562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses. The result set must 24389562b551Sdrh ** be the min() or max() of a single column of the table. The column 24399562b551Sdrh ** in the min() or max() function must be indexed. 24409562b551Sdrh ** 24414adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select(). 24429562b551Sdrh ** See the header comment on that routine for additional information. 24439562b551Sdrh */ 24449562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ 24459562b551Sdrh Expr *pExpr; 24469562b551Sdrh int iCol; 24479562b551Sdrh Table *pTab; 24489562b551Sdrh Index *pIdx; 24499562b551Sdrh int base; 24509562b551Sdrh Vdbe *v; 24519562b551Sdrh int seekOp; 24526e17529eSdrh ExprList *pEList, *pList, eList; 24539562b551Sdrh struct ExprList_item eListItem; 24546e17529eSdrh SrcList *pSrc; 2455ec7429aeSdrh int brk; 2456da184236Sdanielk1977 int iDb; 24576e17529eSdrh 24589562b551Sdrh /* Check to see if this query is a simple min() or max() query. Return 24599562b551Sdrh ** zero if it is not. 24609562b551Sdrh */ 24619562b551Sdrh if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; 24626e17529eSdrh pSrc = p->pSrc; 24636e17529eSdrh if( pSrc->nSrc!=1 ) return 0; 24646e17529eSdrh pEList = p->pEList; 24656e17529eSdrh if( pEList->nExpr!=1 ) return 0; 24666e17529eSdrh pExpr = pEList->a[0].pExpr; 24679562b551Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 24686e17529eSdrh pList = pExpr->pList; 24696e17529eSdrh if( pList==0 || pList->nExpr!=1 ) return 0; 24706977fea8Sdrh if( pExpr->token.n!=3 ) return 0; 24712646da7eSdrh if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ 24720bce8354Sdrh seekOp = OP_Rewind; 24732646da7eSdrh }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ 24740bce8354Sdrh seekOp = OP_Last; 24750bce8354Sdrh }else{ 24760bce8354Sdrh return 0; 24770bce8354Sdrh } 24786e17529eSdrh pExpr = pList->a[0].pExpr; 24799562b551Sdrh if( pExpr->op!=TK_COLUMN ) return 0; 24809562b551Sdrh iCol = pExpr->iColumn; 24816e17529eSdrh pTab = pSrc->a[0].pTab; 24829562b551Sdrh 2483a41c7497Sdanielk1977 /* This optimization cannot be used with virtual tables. */ 2484a41c7497Sdanielk1977 if( IsVirtual(pTab) ) return 0; 2485c00da105Sdanielk1977 24869562b551Sdrh /* If we get to here, it means the query is of the correct form. 248717f71934Sdrh ** Check to make sure we have an index and make pIdx point to the 248817f71934Sdrh ** appropriate index. If the min() or max() is on an INTEGER PRIMARY 248917f71934Sdrh ** key column, no index is necessary so set pIdx to NULL. If no 249017f71934Sdrh ** usable index is found, return 0. 24919562b551Sdrh */ 24929562b551Sdrh if( iCol<0 ){ 24939562b551Sdrh pIdx = 0; 24949562b551Sdrh }else{ 2495dc1bdc4fSdanielk1977 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr); 2496206f3d96Sdrh if( pColl==0 ) return 0; 24979562b551Sdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 24989562b551Sdrh assert( pIdx->nColumn>=1 ); 2499b3bf556eSdanielk1977 if( pIdx->aiColumn[0]==iCol && 2500b3bf556eSdanielk1977 0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){ 2501b3bf556eSdanielk1977 break; 2502b3bf556eSdanielk1977 } 25039562b551Sdrh } 25049562b551Sdrh if( pIdx==0 ) return 0; 25059562b551Sdrh } 25069562b551Sdrh 2507e5f50722Sdrh /* Identify column types if we will be using the callback. This 25089562b551Sdrh ** step is skipped if the output is going to a table or a memory cell. 2509e5f50722Sdrh ** The column names have already been generated in the calling function. 25109562b551Sdrh */ 25114adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 25129562b551Sdrh if( v==0 ) return 0; 25139562b551Sdrh 25140c37e630Sdrh /* If the output is destined for a temporary table, open that table. 25150c37e630Sdrh */ 2516b9bb7c18Sdrh if( eDest==SRT_EphemTab ){ 2517b9bb7c18Sdrh sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1); 25180c37e630Sdrh } 25190c37e630Sdrh 252017f71934Sdrh /* Generating code to find the min or the max. Basically all we have 252117f71934Sdrh ** to do is find the first or the last entry in the chosen index. If 252217f71934Sdrh ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first 252317f71934Sdrh ** or last entry in the main table. 25249562b551Sdrh */ 2525da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 2526b9bb7c18Sdrh assert( iDb>=0 || pTab->isEphem ); 2527da184236Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 2528c00da105Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 25296e17529eSdrh base = pSrc->a[0].iCursor; 2530ec7429aeSdrh brk = sqlite3VdbeMakeLabel(v); 2531ec7429aeSdrh computeLimitRegisters(pParse, p, brk); 25326e17529eSdrh if( pSrc->a[0].pSelect==0 ){ 2533c00da105Sdanielk1977 sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead); 25346e17529eSdrh } 25359562b551Sdrh if( pIdx==0 ){ 25364adee20fSdanielk1977 sqlite3VdbeAddOp(v, seekOp, base, 0); 25379562b551Sdrh }else{ 25383719d7f9Sdanielk1977 /* Even though the cursor used to open the index here is closed 25393719d7f9Sdanielk1977 ** as soon as a single value has been read from it, allocate it 25403719d7f9Sdanielk1977 ** using (pParse->nTab++) to prevent the cursor id from being 25413719d7f9Sdanielk1977 ** reused. This is important for statements of the form 25423719d7f9Sdanielk1977 ** "INSERT INTO x SELECT max() FROM x". 25433719d7f9Sdanielk1977 */ 25443719d7f9Sdanielk1977 int iIdx; 2545b3bf556eSdanielk1977 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); 25463719d7f9Sdanielk1977 iIdx = pParse->nTab++; 2547da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 2548da184236Sdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); 25493719d7f9Sdanielk1977 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, 2550b3bf556eSdanielk1977 (char*)pKey, P3_KEYINFO_HANDOFF); 25519eb516c0Sdrh if( seekOp==OP_Rewind ){ 2552f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_Null, 0, 0); 25531af3fdb4Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0); 25541af3fdb4Sdrh seekOp = OP_MoveGt; 25559eb516c0Sdrh } 2556309be024Sdrh if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){ 2557309be024Sdrh /* Ticket #2514: invert the seek operator if we are using 2558309be024Sdrh ** a descending index. */ 2559309be024Sdrh if( seekOp==OP_Last ){ 2560309be024Sdrh seekOp = OP_Rewind; 2561309be024Sdrh }else{ 2562309be024Sdrh assert( seekOp==OP_MoveGt ); 2563309be024Sdrh seekOp = OP_MoveLt; 2564309be024Sdrh } 2565309be024Sdrh } 25663719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, seekOp, iIdx, 0); 2567f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0); 25683719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); 25697cf6e4deSdrh sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 25709562b551Sdrh } 25715cf8e8c7Sdrh eList.nExpr = 1; 25725cf8e8c7Sdrh memset(&eListItem, 0, sizeof(eListItem)); 25735cf8e8c7Sdrh eList.a = &eListItem; 25745cf8e8c7Sdrh eList.a[0].pExpr = pExpr; 2575ec7429aeSdrh selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0); 2576ec7429aeSdrh sqlite3VdbeResolveLabel(v, brk); 25774adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, base, 0); 25786e17529eSdrh 25799562b551Sdrh return 1; 25809562b551Sdrh } 25819562b551Sdrh 25829562b551Sdrh /* 2583290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return 2584290c1948Sdrh ** the number of errors seen. 2585290c1948Sdrh ** 2586290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions. If any expression 2587290c1948Sdrh ** is an integer constant, then that expression is replaced by the 2588290c1948Sdrh ** corresponding entry in the result set. 2589290c1948Sdrh */ 2590290c1948Sdrh static int processOrderGroupBy( 2591b3bce662Sdanielk1977 NameContext *pNC, /* Name context of the SELECT statement. */ 2592290c1948Sdrh ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 2593290c1948Sdrh const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 2594290c1948Sdrh ){ 2595290c1948Sdrh int i; 2596b3bce662Sdanielk1977 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */ 2597b3bce662Sdanielk1977 Parse *pParse = pNC->pParse; /* The result set of the SELECT */ 2598b3bce662Sdanielk1977 assert( pEList ); 2599b3bce662Sdanielk1977 2600290c1948Sdrh if( pOrderBy==0 ) return 0; 2601e5c941b8Sdrh if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ 2602e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 2603e5c941b8Sdrh return 1; 2604e5c941b8Sdrh } 2605290c1948Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 2606290c1948Sdrh int iCol; 2607290c1948Sdrh Expr *pE = pOrderBy->a[i].pExpr; 2608b3bce662Sdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 2609b3bce662Sdanielk1977 if( iCol>0 && iCol<=pEList->nExpr ){ 26108b4c40d8Sdrh CollSeq *pColl = pE->pColl; 26118b4c40d8Sdrh int flags = pE->flags & EP_ExpCollate; 2612290c1948Sdrh sqlite3ExprDelete(pE); 261317435752Sdrh pE = sqlite3ExprDup(pParse->db, pEList->a[iCol-1].pExpr); 261417435752Sdrh pOrderBy->a[i].pExpr = pE; 26158b4c40d8Sdrh if( pColl && flags ){ 26168b4c40d8Sdrh pE->pColl = pColl; 26178b4c40d8Sdrh pE->flags |= flags; 26188b4c40d8Sdrh } 2619b3bce662Sdanielk1977 }else{ 2620290c1948Sdrh sqlite3ErrorMsg(pParse, 2621290c1948Sdrh "%s BY column number %d out of range - should be " 2622290c1948Sdrh "between 1 and %d", zType, iCol, pEList->nExpr); 2623290c1948Sdrh return 1; 2624290c1948Sdrh } 2625290c1948Sdrh } 2626b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(pNC, pE) ){ 2627b3bce662Sdanielk1977 return 1; 2628b3bce662Sdanielk1977 } 2629290c1948Sdrh } 2630290c1948Sdrh return 0; 2631290c1948Sdrh } 2632290c1948Sdrh 2633290c1948Sdrh /* 2634b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the 2635b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved 2636b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext 2637b3bce662Sdanielk1977 ** of the parent SELECT. 2638b3bce662Sdanielk1977 */ 2639b3bce662Sdanielk1977 int sqlite3SelectResolve( 2640b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 2641b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 2642b3bce662Sdanielk1977 NameContext *pOuterNC /* The outer name context. May be NULL. */ 2643b3bce662Sdanielk1977 ){ 2644b3bce662Sdanielk1977 ExprList *pEList; /* Result set. */ 2645b3bce662Sdanielk1977 int i; /* For-loop variable used in multiple places */ 2646b3bce662Sdanielk1977 NameContext sNC; /* Local name-context */ 264713449892Sdrh ExprList *pGroupBy; /* The group by clause */ 2648b3bce662Sdanielk1977 2649b3bce662Sdanielk1977 /* If this routine has run before, return immediately. */ 2650b3bce662Sdanielk1977 if( p->isResolved ){ 2651b3bce662Sdanielk1977 assert( !pOuterNC ); 2652b3bce662Sdanielk1977 return SQLITE_OK; 2653b3bce662Sdanielk1977 } 2654b3bce662Sdanielk1977 p->isResolved = 1; 2655b3bce662Sdanielk1977 2656b3bce662Sdanielk1977 /* If there have already been errors, do nothing. */ 2657b3bce662Sdanielk1977 if( pParse->nErr>0 ){ 2658b3bce662Sdanielk1977 return SQLITE_ERROR; 2659b3bce662Sdanielk1977 } 2660b3bce662Sdanielk1977 2661b3bce662Sdanielk1977 /* Prepare the select statement. This call will allocate all cursors 2662b3bce662Sdanielk1977 ** required to handle the tables and subqueries in the FROM clause. 2663b3bce662Sdanielk1977 */ 2664b3bce662Sdanielk1977 if( prepSelectStmt(pParse, p) ){ 2665b3bce662Sdanielk1977 return SQLITE_ERROR; 2666b3bce662Sdanielk1977 } 2667b3bce662Sdanielk1977 2668a2dc3b1aSdanielk1977 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 2669a2dc3b1aSdanielk1977 ** are not allowed to refer to any names, so pass an empty NameContext. 2670a2dc3b1aSdanielk1977 */ 2671ffe07b2dSdrh memset(&sNC, 0, sizeof(sNC)); 2672b3bce662Sdanielk1977 sNC.pParse = pParse; 2673a2dc3b1aSdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pLimit) || 2674a2dc3b1aSdanielk1977 sqlite3ExprResolveNames(&sNC, p->pOffset) ){ 2675a2dc3b1aSdanielk1977 return SQLITE_ERROR; 2676a2dc3b1aSdanielk1977 } 2677a2dc3b1aSdanielk1977 2678a2dc3b1aSdanielk1977 /* Set up the local name-context to pass to ExprResolveNames() to 2679a2dc3b1aSdanielk1977 ** resolve the expression-list. 2680a2dc3b1aSdanielk1977 */ 2681a2dc3b1aSdanielk1977 sNC.allowAgg = 1; 2682a2dc3b1aSdanielk1977 sNC.pSrcList = p->pSrc; 2683a2dc3b1aSdanielk1977 sNC.pNext = pOuterNC; 2684b3bce662Sdanielk1977 2685b3bce662Sdanielk1977 /* Resolve names in the result set. */ 2686b3bce662Sdanielk1977 pEList = p->pEList; 2687b3bce662Sdanielk1977 if( !pEList ) return SQLITE_ERROR; 2688b3bce662Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 2689b3bce662Sdanielk1977 Expr *pX = pEList->a[i].pExpr; 2690b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pX) ){ 2691b3bce662Sdanielk1977 return SQLITE_ERROR; 2692b3bce662Sdanielk1977 } 2693b3bce662Sdanielk1977 } 2694b3bce662Sdanielk1977 2695b3bce662Sdanielk1977 /* If there are no aggregate functions in the result-set, and no GROUP BY 2696b3bce662Sdanielk1977 ** expression, do not allow aggregates in any of the other expressions. 2697b3bce662Sdanielk1977 */ 2698b3bce662Sdanielk1977 assert( !p->isAgg ); 269913449892Sdrh pGroupBy = p->pGroupBy; 270013449892Sdrh if( pGroupBy || sNC.hasAgg ){ 2701b3bce662Sdanielk1977 p->isAgg = 1; 2702b3bce662Sdanielk1977 }else{ 2703b3bce662Sdanielk1977 sNC.allowAgg = 0; 2704b3bce662Sdanielk1977 } 2705b3bce662Sdanielk1977 2706b3bce662Sdanielk1977 /* If a HAVING clause is present, then there must be a GROUP BY clause. 2707b3bce662Sdanielk1977 */ 270813449892Sdrh if( p->pHaving && !pGroupBy ){ 2709b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2710b3bce662Sdanielk1977 return SQLITE_ERROR; 2711b3bce662Sdanielk1977 } 2712b3bce662Sdanielk1977 2713b3bce662Sdanielk1977 /* Add the expression list to the name-context before parsing the 2714b3bce662Sdanielk1977 ** other expressions in the SELECT statement. This is so that 2715b3bce662Sdanielk1977 ** expressions in the WHERE clause (etc.) can refer to expressions by 2716b3bce662Sdanielk1977 ** aliases in the result set. 2717b3bce662Sdanielk1977 ** 2718b3bce662Sdanielk1977 ** Minor point: If this is the case, then the expression will be 2719b3bce662Sdanielk1977 ** re-evaluated for each reference to it. 2720b3bce662Sdanielk1977 */ 2721b3bce662Sdanielk1977 sNC.pEList = p->pEList; 2722b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pWhere) || 2723994c80afSdrh sqlite3ExprResolveNames(&sNC, p->pHaving) ){ 2724b3bce662Sdanielk1977 return SQLITE_ERROR; 2725b3bce662Sdanielk1977 } 2726994c80afSdrh if( p->pPrior==0 ){ 2727994c80afSdrh if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") || 2728994c80afSdrh processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){ 2729994c80afSdrh return SQLITE_ERROR; 2730994c80afSdrh } 2731994c80afSdrh } 2732b3bce662Sdanielk1977 27331e536953Sdanielk1977 if( pParse->db->mallocFailed ){ 27349afe689eSdanielk1977 return SQLITE_NOMEM; 27359afe689eSdanielk1977 } 27369afe689eSdanielk1977 273713449892Sdrh /* Make sure the GROUP BY clause does not contain aggregate functions. 273813449892Sdrh */ 273913449892Sdrh if( pGroupBy ){ 274013449892Sdrh struct ExprList_item *pItem; 274113449892Sdrh 274213449892Sdrh for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 274313449892Sdrh if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 274413449892Sdrh sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 274513449892Sdrh "the GROUP BY clause"); 274613449892Sdrh return SQLITE_ERROR; 274713449892Sdrh } 274813449892Sdrh } 274913449892Sdrh } 275013449892Sdrh 2751f6bbe022Sdrh /* If this is one SELECT of a compound, be sure to resolve names 2752f6bbe022Sdrh ** in the other SELECTs. 2753f6bbe022Sdrh */ 2754f6bbe022Sdrh if( p->pPrior ){ 2755f6bbe022Sdrh return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC); 2756f6bbe022Sdrh }else{ 2757b3bce662Sdanielk1977 return SQLITE_OK; 2758b3bce662Sdanielk1977 } 2759f6bbe022Sdrh } 2760b3bce662Sdanielk1977 2761b3bce662Sdanielk1977 /* 276213449892Sdrh ** Reset the aggregate accumulator. 276313449892Sdrh ** 276413449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 276513449892Sdrh ** intermediate results while calculating an aggregate. This 276613449892Sdrh ** routine simply stores NULLs in all of those memory cells. 2767b3bce662Sdanielk1977 */ 276813449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 276913449892Sdrh Vdbe *v = pParse->pVdbe; 277013449892Sdrh int i; 2771c99130fdSdrh struct AggInfo_func *pFunc; 277213449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 277313449892Sdrh return; 277413449892Sdrh } 277513449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 2776d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0); 277713449892Sdrh } 2778c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 2779d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0); 2780c99130fdSdrh if( pFunc->iDistinct>=0 ){ 2781c99130fdSdrh Expr *pE = pFunc->pExpr; 2782c99130fdSdrh if( pE->pList==0 || pE->pList->nExpr!=1 ){ 2783c99130fdSdrh sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " 2784c99130fdSdrh "by an expression"); 2785c99130fdSdrh pFunc->iDistinct = -1; 2786c99130fdSdrh }else{ 2787c99130fdSdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); 2788b9bb7c18Sdrh sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 2789c99130fdSdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 2790c99130fdSdrh } 2791c99130fdSdrh } 279213449892Sdrh } 2793b3bce662Sdanielk1977 } 2794b3bce662Sdanielk1977 2795b3bce662Sdanielk1977 /* 279613449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 279713449892Sdrh ** in the AggInfo structure. 2798b3bce662Sdanielk1977 */ 279913449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 280013449892Sdrh Vdbe *v = pParse->pVdbe; 280113449892Sdrh int i; 280213449892Sdrh struct AggInfo_func *pF; 280313449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 2804a10a34b8Sdrh ExprList *pList = pF->pExpr->pList; 2805a10a34b8Sdrh sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 2806a10a34b8Sdrh (void*)pF->pFunc, P3_FUNCDEF); 2807b3bce662Sdanielk1977 } 280813449892Sdrh } 280913449892Sdrh 281013449892Sdrh /* 281113449892Sdrh ** Update the accumulator memory cells for an aggregate based on 281213449892Sdrh ** the current cursor position. 281313449892Sdrh */ 281413449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 281513449892Sdrh Vdbe *v = pParse->pVdbe; 281613449892Sdrh int i; 281713449892Sdrh struct AggInfo_func *pF; 281813449892Sdrh struct AggInfo_col *pC; 281913449892Sdrh 282013449892Sdrh pAggInfo->directMode = 1; 282113449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 282213449892Sdrh int nArg; 2823c99130fdSdrh int addrNext = 0; 282413449892Sdrh ExprList *pList = pF->pExpr->pList; 282513449892Sdrh if( pList ){ 282613449892Sdrh nArg = pList->nExpr; 282713449892Sdrh sqlite3ExprCodeExprList(pParse, pList); 282813449892Sdrh }else{ 282913449892Sdrh nArg = 0; 283013449892Sdrh } 2831c99130fdSdrh if( pF->iDistinct>=0 ){ 2832c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 2833c99130fdSdrh assert( nArg==1 ); 2834f8875400Sdrh codeDistinct(v, pF->iDistinct, addrNext, 1); 2835c99130fdSdrh } 283613449892Sdrh if( pF->pFunc->needCollSeq ){ 283713449892Sdrh CollSeq *pColl = 0; 283813449892Sdrh struct ExprList_item *pItem; 283913449892Sdrh int j; 284043617e9aSdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */ 284143617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 284213449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 284313449892Sdrh } 284413449892Sdrh if( !pColl ){ 284513449892Sdrh pColl = pParse->db->pDfltColl; 284613449892Sdrh } 284713449892Sdrh sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); 284813449892Sdrh } 284913449892Sdrh sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF); 2850c99130fdSdrh if( addrNext ){ 2851c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 2852c99130fdSdrh } 285313449892Sdrh } 285413449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 28555774b806Sdrh sqlite3ExprCode(pParse, pC->pExpr); 285613449892Sdrh sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1); 285713449892Sdrh } 285813449892Sdrh pAggInfo->directMode = 0; 285913449892Sdrh } 286013449892Sdrh 2861b3bce662Sdanielk1977 2862b3bce662Sdanielk1977 /* 28639bb61fe7Sdrh ** Generate code for the given SELECT statement. 28649bb61fe7Sdrh ** 2865fef5208cSdrh ** The results are distributed in various ways depending on the 2866fef5208cSdrh ** value of eDest and iParm. 2867fef5208cSdrh ** 2868fef5208cSdrh ** eDest Value Result 2869fef5208cSdrh ** ------------ ------------------------------------------- 2870fef5208cSdrh ** SRT_Callback Invoke the callback for each row of the result. 2871fef5208cSdrh ** 2872fef5208cSdrh ** SRT_Mem Store first result in memory cell iParm 2873fef5208cSdrh ** 2874e014a838Sdanielk1977 ** SRT_Set Store results as keys of table iParm. 2875fef5208cSdrh ** 287682c3d636Sdrh ** SRT_Union Store results as a key in a temporary table iParm 287782c3d636Sdrh ** 28784b11c6d3Sjplyon ** SRT_Except Remove results from the temporary table iParm. 2879c4a3c779Sdrh ** 2880c4a3c779Sdrh ** SRT_Table Store results in temporary table iParm 28819bb61fe7Sdrh ** 2882e78e8284Sdrh ** The table above is incomplete. Additional eDist value have be added 2883e78e8284Sdrh ** since this comment was written. See the selectInnerLoop() function for 2884e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings. 2885e78e8284Sdrh ** 28869bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 28879bb61fe7Sdrh ** encountered, then an appropriate error message is left in 28889bb61fe7Sdrh ** pParse->zErrMsg. 28899bb61fe7Sdrh ** 28909bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 28919bb61fe7Sdrh ** calling function needs to do that. 28921b2e0329Sdrh ** 28931b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this 28941b2e0329Sdrh ** SELECT is a subquery. This routine may try to combine this SELECT 28951b2e0329Sdrh ** with its parent to form a single flat query. In so doing, it might 28961b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query. 28971b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it 28981b2e0329Sdrh ** can be changed. 2899e78e8284Sdrh ** 2900e78e8284Sdrh ** Example 1: The meaning of the pParent parameter. 2901e78e8284Sdrh ** 2902e78e8284Sdrh ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2903e78e8284Sdrh ** \ \_______ subquery _______/ / 2904e78e8284Sdrh ** \ / 2905e78e8284Sdrh ** \____________________ outer query ___________________/ 2906e78e8284Sdrh ** 2907e78e8284Sdrh ** This routine is called for the outer query first. For that call, 2908e78e8284Sdrh ** pParent will be NULL. During the processing of the outer query, this 2909e78e8284Sdrh ** routine is called recursively to handle the subquery. For the recursive 2910e78e8284Sdrh ** call, pParent will point to the outer query. Because the subquery is 2911e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will 2912e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.) 29139bb61fe7Sdrh */ 29144adee20fSdanielk1977 int sqlite3Select( 2915cce7d176Sdrh Parse *pParse, /* The parser context */ 29169bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 2917e78e8284Sdrh int eDest, /* How to dispose of the results */ 2918e78e8284Sdrh int iParm, /* A parameter used by the eDest disposal method */ 2919832508b7Sdrh Select *pParent, /* Another SELECT for which this is a sub-query */ 2920832508b7Sdrh int parentTab, /* Index in pParent->pSrc of this query */ 292184ac9d02Sdanielk1977 int *pParentAgg, /* True if pParent uses aggregate functions */ 2922b3bce662Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 2923cce7d176Sdrh ){ 292413449892Sdrh int i, j; /* Loop counters */ 292513449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 292613449892Sdrh Vdbe *v; /* The virtual machine under construction */ 2927b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 2928a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 2929ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 29309bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 29319bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 29322282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 29332282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 293419a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 293519a775c2Sdrh int distinct; /* Table to use for the distinct set */ 29361d83f052Sdrh int rc = 1; /* Value to return from this function */ 2937b9bb7c18Sdrh int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 293813449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 2939ec7429aeSdrh int iEnd; /* Address of the end of the query */ 294017435752Sdrh sqlite3 *db; /* The database connection */ 29419bb61fe7Sdrh 294217435752Sdrh db = pParse->db; 294317435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 29446f7adc8aSdrh return 1; 29456f7adc8aSdrh } 29464adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 294713449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 2948daffd0e5Sdrh 2949b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 295082c3d636Sdrh /* If there is are a sequence of queries, do the earlier ones first. 295182c3d636Sdrh */ 295282c3d636Sdrh if( p->pPrior ){ 29530342b1f5Sdrh if( p->pRightmost==0 ){ 29540342b1f5Sdrh Select *pLoop; 29550325d873Sdrh int cnt = 0; 29560325d873Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 29570342b1f5Sdrh pLoop->pRightmost = p; 29580342b1f5Sdrh } 29590325d873Sdrh if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){ 29600325d873Sdrh sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 29610325d873Sdrh return 1; 29620325d873Sdrh } 29630342b1f5Sdrh } 296484ac9d02Sdanielk1977 return multiSelect(pParse, p, eDest, iParm, aff); 296582c3d636Sdrh } 2966b7f9164eSdrh #endif 296782c3d636Sdrh 2968b3bce662Sdanielk1977 pOrderBy = p->pOrderBy; 296913449892Sdrh if( IgnorableOrderby(eDest) ){ 2970b3bce662Sdanielk1977 p->pOrderBy = 0; 2971b3bce662Sdanielk1977 } 2972b3bce662Sdanielk1977 if( sqlite3SelectResolve(pParse, p, 0) ){ 2973b3bce662Sdanielk1977 goto select_end; 2974b3bce662Sdanielk1977 } 2975b3bce662Sdanielk1977 p->pOrderBy = pOrderBy; 2976b3bce662Sdanielk1977 297782c3d636Sdrh /* Make local copies of the parameters for this query. 297882c3d636Sdrh */ 29799bb61fe7Sdrh pTabList = p->pSrc; 29809bb61fe7Sdrh pWhere = p->pWhere; 29812282792aSdrh pGroupBy = p->pGroupBy; 29822282792aSdrh pHaving = p->pHaving; 2983b3bce662Sdanielk1977 isAgg = p->isAgg; 298419a775c2Sdrh isDistinct = p->isDistinct; 2985b3bce662Sdanielk1977 pEList = p->pEList; 2986b3bce662Sdanielk1977 if( pEList==0 ) goto select_end; 29879bb61fe7Sdrh 29889bb61fe7Sdrh /* 29899bb61fe7Sdrh ** Do not even attempt to generate any code if we have already seen 29909bb61fe7Sdrh ** errors before this routine starts. 29919bb61fe7Sdrh */ 29921d83f052Sdrh if( pParse->nErr>0 ) goto select_end; 2993cce7d176Sdrh 29942282792aSdrh /* If writing to memory or generating a set 29952282792aSdrh ** only a single column may be output. 299619a775c2Sdrh */ 299793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 2998e305f43fSdrh if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ 29991d83f052Sdrh goto select_end; 300019a775c2Sdrh } 300193758c8dSdanielk1977 #endif 300219a775c2Sdrh 3003c926afbcSdrh /* ORDER BY is ignored for some destinations. 30042282792aSdrh */ 300513449892Sdrh if( IgnorableOrderby(eDest) ){ 3006acd4c695Sdrh pOrderBy = 0; 30072282792aSdrh } 30082282792aSdrh 3009d820cb1bSdrh /* Begin generating code. 3010d820cb1bSdrh */ 30114adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 3012d820cb1bSdrh if( v==0 ) goto select_end; 3013d820cb1bSdrh 3014d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 3015d820cb1bSdrh */ 301651522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3017ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 3018742f947bSdanielk1977 const char *zSavedAuthContext = 0; 3019c31c2eb8Sdrh int needRestoreContext; 302013449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 3021c31c2eb8Sdrh 30221787ccabSdanielk1977 if( pItem->pSelect==0 || pItem->isPopulated ) continue; 302313449892Sdrh if( pItem->zName!=0 ){ 30245cf590c1Sdrh zSavedAuthContext = pParse->zAuthContext; 302513449892Sdrh pParse->zAuthContext = pItem->zName; 3026c31c2eb8Sdrh needRestoreContext = 1; 3027c31c2eb8Sdrh }else{ 3028c31c2eb8Sdrh needRestoreContext = 0; 30295cf590c1Sdrh } 3030e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 3031fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 3032fc976065Sdanielk1977 ** tree refered to by this, the parent select. The child select 3033fc976065Sdanielk1977 ** may contain expression trees of at most 3034fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 3035fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 3036fc976065Sdanielk1977 ** an exact limit. 3037fc976065Sdanielk1977 */ 3038fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 3039fc976065Sdanielk1977 #endif 3040b9bb7c18Sdrh sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab, 304113449892Sdrh pItem->iCursor, p, i, &isAgg, 0); 3042*cfa063b3Sdrh if( db->mallocFailed ){ 3043*cfa063b3Sdrh goto select_end; 3044*cfa063b3Sdrh } 3045e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 3046fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 3047fc976065Sdanielk1977 #endif 3048c31c2eb8Sdrh if( needRestoreContext ){ 30495cf590c1Sdrh pParse->zAuthContext = zSavedAuthContext; 30505cf590c1Sdrh } 3051832508b7Sdrh pTabList = p->pSrc; 3052832508b7Sdrh pWhere = p->pWhere; 305313449892Sdrh if( !IgnorableOrderby(eDest) ){ 3054832508b7Sdrh pOrderBy = p->pOrderBy; 3055acd4c695Sdrh } 3056832508b7Sdrh pGroupBy = p->pGroupBy; 3057832508b7Sdrh pHaving = p->pHaving; 3058832508b7Sdrh isDistinct = p->isDistinct; 30591b2e0329Sdrh } 306051522cd3Sdrh #endif 30611b2e0329Sdrh 30626e17529eSdrh /* Check for the special case of a min() or max() function by itself 30636e17529eSdrh ** in the result set. 30646e17529eSdrh */ 30656e17529eSdrh if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ 30666e17529eSdrh rc = 0; 30676e17529eSdrh goto select_end; 30686e17529eSdrh } 30696e17529eSdrh 30701b2e0329Sdrh /* Check to see if this is a subquery that can be "flattened" into its parent. 30711b2e0329Sdrh ** If flattening is a possiblity, do so and return immediately. 30721b2e0329Sdrh */ 3073b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 30741b2e0329Sdrh if( pParent && pParentAgg && 307517435752Sdrh flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){ 30761b2e0329Sdrh if( isAgg ) *pParentAgg = 1; 3077b3bce662Sdanielk1977 goto select_end; 30781b2e0329Sdrh } 3079b7f9164eSdrh #endif 3080832508b7Sdrh 30810318d441Sdanielk1977 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT. 30820318d441Sdanielk1977 ** GROUP BY may use an index, DISTINCT never does. 30833c4809a2Sdanielk1977 */ 30843c4809a2Sdanielk1977 if( p->isDistinct && !p->isAgg && !p->pGroupBy ){ 30853c4809a2Sdanielk1977 p->pGroupBy = sqlite3ExprListDup(db, p->pEList); 30863c4809a2Sdanielk1977 pGroupBy = p->pGroupBy; 30873c4809a2Sdanielk1977 p->isDistinct = 0; 30883c4809a2Sdanielk1977 isDistinct = 0; 30893c4809a2Sdanielk1977 } 30903c4809a2Sdanielk1977 30918b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 30928b4c40d8Sdrh ** index might end up being unused if the data can be 30939d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 3094b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 30959d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 30969d2985c7Sdrh ** variable is used to facilitate that change. 30977cedc8d4Sdanielk1977 */ 30987cedc8d4Sdanielk1977 if( pOrderBy ){ 30990342b1f5Sdrh KeyInfo *pKeyInfo; 31007cedc8d4Sdanielk1977 if( pParse->nErr ){ 31017cedc8d4Sdanielk1977 goto select_end; 31027cedc8d4Sdanielk1977 } 31030342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 31049d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 3105b9bb7c18Sdrh p->addrOpenEphm[2] = addrSortIndex = 31061e31e0b2Sdrh sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 31079d2985c7Sdrh }else{ 31089d2985c7Sdrh addrSortIndex = -1; 31097cedc8d4Sdanielk1977 } 31107cedc8d4Sdanielk1977 31112d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 31122d0794e3Sdrh */ 3113b9bb7c18Sdrh if( eDest==SRT_EphemTab ){ 3114b9bb7c18Sdrh sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr); 31152d0794e3Sdrh } 31162d0794e3Sdrh 3117f42bacc2Sdrh /* Set the limiter. 3118f42bacc2Sdrh */ 3119f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 3120f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 3121f42bacc2Sdrh 3122dece1a84Sdrh /* Open a virtual index to use for the distinct set. 3123cce7d176Sdrh */ 312419a775c2Sdrh if( isDistinct ){ 31250342b1f5Sdrh KeyInfo *pKeyInfo; 31263c4809a2Sdanielk1977 assert( isAgg || pGroupBy ); 3127832508b7Sdrh distinct = pParse->nTab++; 31280342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 3129b9bb7c18Sdrh sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0, 31300342b1f5Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 3131832508b7Sdrh }else{ 3132832508b7Sdrh distinct = -1; 3133efb7251dSdrh } 3134832508b7Sdrh 313513449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 313613449892Sdrh if( !isAgg && pGroupBy==0 ){ 313713449892Sdrh /* This case is for non-aggregate queries 313813449892Sdrh ** Begin the database scan 3139832508b7Sdrh */ 314013449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy); 31411d83f052Sdrh if( pWInfo==0 ) goto select_end; 3142cce7d176Sdrh 3143b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 3144b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 31459d2985c7Sdrh ** into an OP_Noop. 31469d2985c7Sdrh */ 31479d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 3148f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortIndex, 1); 3149b9bb7c18Sdrh p->addrOpenEphm[2] = -1; 31509d2985c7Sdrh } 31519d2985c7Sdrh 315213449892Sdrh /* Use the standard inner loop 3153cce7d176Sdrh */ 31543c4809a2Sdanielk1977 assert(!isDistinct); 31553c4809a2Sdanielk1977 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, eDest, 315684ac9d02Sdanielk1977 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ 31571d83f052Sdrh goto select_end; 3158cce7d176Sdrh } 31592282792aSdrh 3160cce7d176Sdrh /* End the database scan loop. 3161cce7d176Sdrh */ 31624adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 316313449892Sdrh }else{ 316413449892Sdrh /* This is the processing for aggregate queries */ 316513449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 316613449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 316713449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 316813449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 316913449892Sdrh ** one row of the input to the aggregator has been 317013449892Sdrh ** processed */ 317113449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 317213449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 3173cce7d176Sdrh 317413449892Sdrh 317513449892Sdrh /* The following variables hold addresses or labels for parts of the 317613449892Sdrh ** virtual machine program we are putting together */ 317713449892Sdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 317813449892Sdrh int addrSetAbort; /* Set the abort flag and return */ 317913449892Sdrh int addrInitializeLoop; /* Start of code that initializes the input loop */ 318013449892Sdrh int addrTopOfLoop; /* Top of the input loop */ 318113449892Sdrh int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ 318213449892Sdrh int addrProcessRow; /* Code to process a single input row */ 318313449892Sdrh int addrEnd; /* End of all processing */ 3184b9bb7c18Sdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 3185e313382eSdrh int addrReset; /* Subroutine for resetting the accumulator */ 318613449892Sdrh 318713449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 318813449892Sdrh 318913449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 319013449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 319113449892Sdrh ** SELECT statement. 31922282792aSdrh */ 319313449892Sdrh memset(&sNC, 0, sizeof(sNC)); 319413449892Sdrh sNC.pParse = pParse; 319513449892Sdrh sNC.pSrcList = pTabList; 319613449892Sdrh sNC.pAggInfo = &sAggInfo; 319713449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 31989d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 319913449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){ 32001d83f052Sdrh goto select_end; 32012282792aSdrh } 320213449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){ 320313449892Sdrh goto select_end; 32042282792aSdrh } 320513449892Sdrh if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){ 320613449892Sdrh goto select_end; 320713449892Sdrh } 320813449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 320913449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 321013449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){ 321113449892Sdrh goto select_end; 321213449892Sdrh } 321313449892Sdrh } 321417435752Sdrh if( db->mallocFailed ) goto select_end; 321513449892Sdrh 321613449892Sdrh /* Processing for aggregates with GROUP BY is very different and 32173c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 321813449892Sdrh */ 321913449892Sdrh if( pGroupBy ){ 322013449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 322113449892Sdrh 322213449892Sdrh /* Create labels that we will be needing 322313449892Sdrh */ 322413449892Sdrh 322513449892Sdrh addrInitializeLoop = sqlite3VdbeMakeLabel(v); 322613449892Sdrh addrGroupByChange = sqlite3VdbeMakeLabel(v); 322713449892Sdrh addrProcessRow = sqlite3VdbeMakeLabel(v); 322813449892Sdrh 322913449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 323013449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 3231b9bb7c18Sdrh ** that we do not need it after all, the OpenEphemeral instruction 323213449892Sdrh ** will be converted into a Noop. 323313449892Sdrh */ 323413449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 323513449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 323613449892Sdrh addrSortingIdx = 3237b9bb7c18Sdrh sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx, 323813449892Sdrh sAggInfo.nSortingColumn, 323913449892Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 324013449892Sdrh 324113449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 324213449892Sdrh */ 324313449892Sdrh iUseFlag = pParse->nMem++; 324413449892Sdrh iAbortFlag = pParse->nMem++; 324513449892Sdrh iAMem = pParse->nMem; 324613449892Sdrh pParse->nMem += pGroupBy->nExpr; 324713449892Sdrh iBMem = pParse->nMem; 324813449892Sdrh pParse->nMem += pGroupBy->nExpr; 3249d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag); 3250de29e3e9Sdrh VdbeComment((v, "# clear abort flag")); 3251d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag); 3252de29e3e9Sdrh VdbeComment((v, "# indicate accumulator empty")); 325313449892Sdrh sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop); 325413449892Sdrh 325513449892Sdrh /* Generate a subroutine that outputs a single row of the result 325613449892Sdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 325713449892Sdrh ** is less than or equal to zero, the subroutine is a no-op. If 325813449892Sdrh ** the processing calls for the query to abort, this subroutine 325913449892Sdrh ** increments the iAbortFlag memory location before returning in 326013449892Sdrh ** order to signal the caller to abort. 326113449892Sdrh */ 326213449892Sdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 3263de29e3e9Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag); 3264de29e3e9Sdrh VdbeComment((v, "# set abort flag")); 326513449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 326613449892Sdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 326713449892Sdrh sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2); 3268de29e3e9Sdrh VdbeComment((v, "# Groupby result generator entry point")); 326913449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 327013449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 327113449892Sdrh if( pHaving ){ 327213449892Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1); 327313449892Sdrh } 327413449892Sdrh rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 327513449892Sdrh distinct, eDest, iParm, 327613449892Sdrh addrOutputRow+1, addrSetAbort, aff); 327713449892Sdrh if( rc ){ 327813449892Sdrh goto select_end; 327913449892Sdrh } 328013449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 3281de29e3e9Sdrh VdbeComment((v, "# end groupby result generator")); 328213449892Sdrh 3283e313382eSdrh /* Generate a subroutine that will reset the group-by accumulator 3284e313382eSdrh */ 3285e313382eSdrh addrReset = sqlite3VdbeCurrentAddr(v); 3286e313382eSdrh resetAccumulator(pParse, &sAggInfo); 3287e313382eSdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 3288e313382eSdrh 328913449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 329013449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 329113449892Sdrh ** it might be a single loop that uses an index to extract information 329213449892Sdrh ** in the right order to begin with. 329313449892Sdrh */ 329413449892Sdrh sqlite3VdbeResolveLabel(v, addrInitializeLoop); 3295e313382eSdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); 329613449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy); 32975360ad34Sdrh if( pWInfo==0 ) goto select_end; 329813449892Sdrh if( pGroupBy==0 ){ 329913449892Sdrh /* The optimizer is able to deliver rows in group by order so 3300b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 330113449892Sdrh ** cancelled later because we still need to use the pKeyInfo 330213449892Sdrh */ 330313449892Sdrh pGroupBy = p->pGroupBy; 330413449892Sdrh groupBySort = 0; 330513449892Sdrh }else{ 330613449892Sdrh /* Rows are coming out in undetermined order. We have to push 330713449892Sdrh ** each row into a sorting index, terminate the first loop, 330813449892Sdrh ** then loop over the sorting index in order to get the output 330913449892Sdrh ** in sorted order 331013449892Sdrh */ 331113449892Sdrh groupBySort = 1; 331213449892Sdrh sqlite3ExprCodeExprList(pParse, pGroupBy); 331313449892Sdrh sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0); 331413449892Sdrh j = pGroupBy->nExpr+1; 331513449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 331613449892Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 331713449892Sdrh if( pCol->iSorterColumn<j ) continue; 3318945498f3Sdrh sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable); 331913449892Sdrh j++; 332013449892Sdrh } 332113449892Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0); 332213449892Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0); 332313449892Sdrh sqlite3WhereEnd(pWInfo); 332497571957Sdrh sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); 3325de29e3e9Sdrh VdbeComment((v, "# GROUP BY sort")); 332613449892Sdrh sAggInfo.useSortingIdx = 1; 332713449892Sdrh } 332813449892Sdrh 332913449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 333013449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 333113449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 333213449892Sdrh ** from the previous row currently stored in a0, a1, a2... 333313449892Sdrh */ 333413449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 333513449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 333613449892Sdrh if( groupBySort ){ 333713449892Sdrh sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j); 333813449892Sdrh }else{ 333913449892Sdrh sAggInfo.directMode = 1; 334013449892Sdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr); 334113449892Sdrh } 334213449892Sdrh sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1); 334313449892Sdrh } 334413449892Sdrh for(j=pGroupBy->nExpr-1; j>=0; j--){ 334513449892Sdrh if( j<pGroupBy->nExpr-1 ){ 334613449892Sdrh sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0); 334713449892Sdrh } 334813449892Sdrh sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0); 334913449892Sdrh if( j==0 ){ 3350e313382eSdrh sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow); 335113449892Sdrh }else{ 33524f686238Sdrh sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange); 335313449892Sdrh } 335413449892Sdrh sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ); 335513449892Sdrh } 335613449892Sdrh 335713449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 335813449892Sdrh ** Change in the GROUP BY are detected by the previous code 335913449892Sdrh ** block. If there were no changes, this block is skipped. 336013449892Sdrh ** 336113449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 336213449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 336313449892Sdrh ** and resets the aggregate accumulator registers in preparation 336413449892Sdrh ** for the next GROUP BY batch. 336513449892Sdrh */ 336613449892Sdrh sqlite3VdbeResolveLabel(v, addrGroupByChange); 336713449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 3368d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j); 336913449892Sdrh } 337013449892Sdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); 3371de29e3e9Sdrh VdbeComment((v, "# output one row")); 337213449892Sdrh sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd); 3373de29e3e9Sdrh VdbeComment((v, "# check abort flag")); 3374e313382eSdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); 3375de29e3e9Sdrh VdbeComment((v, "# reset accumulator")); 337613449892Sdrh 337713449892Sdrh /* Update the aggregate accumulators based on the content of 337813449892Sdrh ** the current row 337913449892Sdrh */ 338013449892Sdrh sqlite3VdbeResolveLabel(v, addrProcessRow); 338113449892Sdrh updateAccumulator(pParse, &sAggInfo); 3382de29e3e9Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag); 3383de29e3e9Sdrh VdbeComment((v, "# indicate data in accumulator")); 338413449892Sdrh 338513449892Sdrh /* End of the loop 338613449892Sdrh */ 338713449892Sdrh if( groupBySort ){ 338813449892Sdrh sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); 338913449892Sdrh }else{ 339013449892Sdrh sqlite3WhereEnd(pWInfo); 3391f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); 339213449892Sdrh } 339313449892Sdrh 339413449892Sdrh /* Output the final row of result 339513449892Sdrh */ 339613449892Sdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); 3397de29e3e9Sdrh VdbeComment((v, "# output final row")); 339813449892Sdrh 339913449892Sdrh } /* endif pGroupBy */ 340013449892Sdrh else { 340113449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 340213449892Sdrh ** processing is much simpler since there is only a single row 340313449892Sdrh ** of output. 340413449892Sdrh */ 340513449892Sdrh resetAccumulator(pParse, &sAggInfo); 340613449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); 34075360ad34Sdrh if( pWInfo==0 ) goto select_end; 340813449892Sdrh updateAccumulator(pParse, &sAggInfo); 340913449892Sdrh sqlite3WhereEnd(pWInfo); 341013449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 341113449892Sdrh pOrderBy = 0; 34125774b806Sdrh if( pHaving ){ 34135774b806Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1); 34145774b806Sdrh } 341513449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 341613449892Sdrh eDest, iParm, addrEnd, addrEnd, aff); 341713449892Sdrh } 341813449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 341913449892Sdrh 342013449892Sdrh } /* endif aggregate query */ 34212282792aSdrh 3422cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 3423cce7d176Sdrh ** and send them to the callback one by one. 3424cce7d176Sdrh */ 3425cce7d176Sdrh if( pOrderBy ){ 3426cdd536f0Sdrh generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm); 3427cce7d176Sdrh } 34286a535340Sdrh 342993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 3430f620b4e2Sdrh /* If this was a subquery, we have now converted the subquery into a 34311787ccabSdanielk1977 ** temporary table. So set the SrcList_item.isPopulated flag to prevent 34321787ccabSdanielk1977 ** this subquery from being evaluated again and to force the use of 34331787ccabSdanielk1977 ** the temporary table. 3434f620b4e2Sdrh */ 3435f620b4e2Sdrh if( pParent ){ 3436f620b4e2Sdrh assert( pParent->pSrc->nSrc>parentTab ); 3437f620b4e2Sdrh assert( pParent->pSrc->a[parentTab].pSelect==p ); 34381787ccabSdanielk1977 pParent->pSrc->a[parentTab].isPopulated = 1; 3439f620b4e2Sdrh } 344093758c8dSdanielk1977 #endif 3441f620b4e2Sdrh 3442ec7429aeSdrh /* Jump here to skip this query 3443ec7429aeSdrh */ 3444ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 3445ec7429aeSdrh 34461d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 34471d83f052Sdrh ** to indicate no errors. 34481d83f052Sdrh */ 34491d83f052Sdrh rc = 0; 34501d83f052Sdrh 34511d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 34521d83f052Sdrh ** successful coding of the SELECT. 34531d83f052Sdrh */ 34541d83f052Sdrh select_end: 3455955de52cSdanielk1977 3456955de52cSdanielk1977 /* Identify column names if we will be using them in a callback. This 3457955de52cSdanielk1977 ** step is skipped if the output is going to some other destination. 3458955de52cSdanielk1977 */ 3459955de52cSdanielk1977 if( rc==SQLITE_OK && eDest==SRT_Callback ){ 3460955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 3461955de52cSdanielk1977 } 3462955de52cSdanielk1977 346317435752Sdrh sqlite3_free(sAggInfo.aCol); 346417435752Sdrh sqlite3_free(sAggInfo.aFunc); 34651d83f052Sdrh return rc; 3466cce7d176Sdrh } 3467485f0039Sdrh 346877a2a5e7Sdrh #if defined(SQLITE_DEBUG) 3469485f0039Sdrh /* 3470485f0039Sdrh ******************************************************************************* 3471485f0039Sdrh ** The following code is used for testing and debugging only. The code 3472485f0039Sdrh ** that follows does not appear in normal builds. 3473485f0039Sdrh ** 3474485f0039Sdrh ** These routines are used to print out the content of all or part of a 3475485f0039Sdrh ** parse structures such as Select or Expr. Such printouts are useful 3476485f0039Sdrh ** for helping to understand what is happening inside the code generator 3477485f0039Sdrh ** during the execution of complex SELECT statements. 3478485f0039Sdrh ** 3479485f0039Sdrh ** These routine are not called anywhere from within the normal 3480485f0039Sdrh ** code base. Then are intended to be called from within the debugger 3481485f0039Sdrh ** or from temporary "printf" statements inserted for debugging. 3482485f0039Sdrh */ 3483485f0039Sdrh void sqlite3PrintExpr(Expr *p){ 3484485f0039Sdrh if( p->token.z && p->token.n>0 ){ 3485485f0039Sdrh sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z); 3486485f0039Sdrh }else{ 3487485f0039Sdrh sqlite3DebugPrintf("(%d", p->op); 3488485f0039Sdrh } 3489485f0039Sdrh if( p->pLeft ){ 3490485f0039Sdrh sqlite3DebugPrintf(" "); 3491485f0039Sdrh sqlite3PrintExpr(p->pLeft); 3492485f0039Sdrh } 3493485f0039Sdrh if( p->pRight ){ 3494485f0039Sdrh sqlite3DebugPrintf(" "); 3495485f0039Sdrh sqlite3PrintExpr(p->pRight); 3496485f0039Sdrh } 3497485f0039Sdrh sqlite3DebugPrintf(")"); 3498485f0039Sdrh } 3499485f0039Sdrh void sqlite3PrintExprList(ExprList *pList){ 3500485f0039Sdrh int i; 3501485f0039Sdrh for(i=0; i<pList->nExpr; i++){ 3502485f0039Sdrh sqlite3PrintExpr(pList->a[i].pExpr); 3503485f0039Sdrh if( i<pList->nExpr-1 ){ 3504485f0039Sdrh sqlite3DebugPrintf(", "); 3505485f0039Sdrh } 3506485f0039Sdrh } 3507485f0039Sdrh } 3508485f0039Sdrh void sqlite3PrintSelect(Select *p, int indent){ 3509485f0039Sdrh sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p); 3510485f0039Sdrh sqlite3PrintExprList(p->pEList); 3511485f0039Sdrh sqlite3DebugPrintf("\n"); 3512485f0039Sdrh if( p->pSrc ){ 3513485f0039Sdrh char *zPrefix; 3514485f0039Sdrh int i; 3515485f0039Sdrh zPrefix = "FROM"; 3516485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 3517485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 3518485f0039Sdrh sqlite3DebugPrintf("%*s ", indent+6, zPrefix); 3519485f0039Sdrh zPrefix = ""; 3520485f0039Sdrh if( pItem->pSelect ){ 3521485f0039Sdrh sqlite3DebugPrintf("(\n"); 3522485f0039Sdrh sqlite3PrintSelect(pItem->pSelect, indent+10); 3523485f0039Sdrh sqlite3DebugPrintf("%*s)", indent+8, ""); 3524485f0039Sdrh }else if( pItem->zName ){ 3525485f0039Sdrh sqlite3DebugPrintf("%s", pItem->zName); 3526485f0039Sdrh } 3527485f0039Sdrh if( pItem->pTab ){ 3528485f0039Sdrh sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName); 3529485f0039Sdrh } 3530485f0039Sdrh if( pItem->zAlias ){ 3531485f0039Sdrh sqlite3DebugPrintf(" AS %s", pItem->zAlias); 3532485f0039Sdrh } 3533485f0039Sdrh if( i<p->pSrc->nSrc-1 ){ 3534485f0039Sdrh sqlite3DebugPrintf(","); 3535485f0039Sdrh } 3536485f0039Sdrh sqlite3DebugPrintf("\n"); 3537485f0039Sdrh } 3538485f0039Sdrh } 3539485f0039Sdrh if( p->pWhere ){ 3540485f0039Sdrh sqlite3DebugPrintf("%*s WHERE ", indent, ""); 3541485f0039Sdrh sqlite3PrintExpr(p->pWhere); 3542485f0039Sdrh sqlite3DebugPrintf("\n"); 3543485f0039Sdrh } 3544485f0039Sdrh if( p->pGroupBy ){ 3545485f0039Sdrh sqlite3DebugPrintf("%*s GROUP BY ", indent, ""); 3546485f0039Sdrh sqlite3PrintExprList(p->pGroupBy); 3547485f0039Sdrh sqlite3DebugPrintf("\n"); 3548485f0039Sdrh } 3549485f0039Sdrh if( p->pHaving ){ 3550485f0039Sdrh sqlite3DebugPrintf("%*s HAVING ", indent, ""); 3551485f0039Sdrh sqlite3PrintExpr(p->pHaving); 3552485f0039Sdrh sqlite3DebugPrintf("\n"); 3553485f0039Sdrh } 3554485f0039Sdrh if( p->pOrderBy ){ 3555485f0039Sdrh sqlite3DebugPrintf("%*s ORDER BY ", indent, ""); 3556485f0039Sdrh sqlite3PrintExprList(p->pOrderBy); 3557485f0039Sdrh sqlite3DebugPrintf("\n"); 3558485f0039Sdrh } 3559485f0039Sdrh } 3560485f0039Sdrh /* End of the structure debug printing code 3561485f0039Sdrh *****************************************************************************/ 3562485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ 3563