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*15cdbebeSdanielk1977 ** $Id: select.c,v 1.408 2008/01/23 15:44:51 danielk1977 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 361013c932Sdrh /* 371013c932Sdrh ** Initialize a SelectDest structure. 381013c932Sdrh */ 391013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 401013c932Sdrh pDest->eDest = eDest; 411013c932Sdrh pDest->iParm = iParm; 421013c932Sdrh pDest->affinity = 0; 431013c932Sdrh pDest->iMem = 0; 441013c932Sdrh } 451013c932Sdrh 46eda639e1Sdrh 47eda639e1Sdrh /* 489bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 499bb61fe7Sdrh ** structure. 50cce7d176Sdrh */ 514adee20fSdanielk1977 Select *sqlite3SelectNew( 5217435752Sdrh Parse *pParse, /* Parsing context */ 53daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 54ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 55daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 56daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 57daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 58daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 599bbca4c1Sdrh int isDistinct, /* true if the DISTINCT keyword is present */ 60a2dc3b1aSdanielk1977 Expr *pLimit, /* LIMIT value. NULL means not used */ 61a2dc3b1aSdanielk1977 Expr *pOffset /* OFFSET value. NULL means no offset */ 629bb61fe7Sdrh ){ 639bb61fe7Sdrh Select *pNew; 64eda639e1Sdrh Select standin; 6517435752Sdrh sqlite3 *db = pParse->db; 6617435752Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 67a2dc3b1aSdanielk1977 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */ 68daffd0e5Sdrh if( pNew==0 ){ 69eda639e1Sdrh pNew = &standin; 70eda639e1Sdrh memset(pNew, 0, sizeof(*pNew)); 71eda639e1Sdrh } 72b733d037Sdrh if( pEList==0 ){ 73a1644fd8Sdanielk1977 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0); 74b733d037Sdrh } 759bb61fe7Sdrh pNew->pEList = pEList; 769bb61fe7Sdrh pNew->pSrc = pSrc; 779bb61fe7Sdrh pNew->pWhere = pWhere; 789bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 799bb61fe7Sdrh pNew->pHaving = pHaving; 809bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 819bb61fe7Sdrh pNew->isDistinct = isDistinct; 8282c3d636Sdrh pNew->op = TK_SELECT; 838103b7d2Sdrh assert( pOffset==0 || pLimit!=0 ); 84a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 85a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 867b58daeaSdrh pNew->iLimit = -1; 877b58daeaSdrh pNew->iOffset = -1; 88b9bb7c18Sdrh pNew->addrOpenEphm[0] = -1; 89b9bb7c18Sdrh pNew->addrOpenEphm[1] = -1; 90b9bb7c18Sdrh pNew->addrOpenEphm[2] = -1; 91eda639e1Sdrh if( pNew==&standin) { 92eda639e1Sdrh clearSelect(pNew); 93eda639e1Sdrh pNew = 0; 94daffd0e5Sdrh } 959bb61fe7Sdrh return pNew; 969bb61fe7Sdrh } 979bb61fe7Sdrh 989bb61fe7Sdrh /* 99eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 100eda639e1Sdrh */ 101eda639e1Sdrh void sqlite3SelectDelete(Select *p){ 102eda639e1Sdrh if( p ){ 103eda639e1Sdrh clearSelect(p); 10417435752Sdrh sqlite3_free(p); 105eda639e1Sdrh } 106eda639e1Sdrh } 107eda639e1Sdrh 108eda639e1Sdrh /* 10901f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 11001f3f253Sdrh ** type of join. Return an integer constant that expresses that type 11101f3f253Sdrh ** in terms of the following bit values: 11201f3f253Sdrh ** 11301f3f253Sdrh ** JT_INNER 1143dec223cSdrh ** JT_CROSS 11501f3f253Sdrh ** JT_OUTER 11601f3f253Sdrh ** JT_NATURAL 11701f3f253Sdrh ** JT_LEFT 11801f3f253Sdrh ** JT_RIGHT 11901f3f253Sdrh ** 12001f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 12101f3f253Sdrh ** 12201f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 12301f3f253Sdrh ** a join type, but put an error in the pParse structure. 12401f3f253Sdrh */ 1254adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 12601f3f253Sdrh int jointype = 0; 12701f3f253Sdrh Token *apAll[3]; 12801f3f253Sdrh Token *p; 1295719628aSdrh static const struct { 130c182d163Sdrh const char zKeyword[8]; 131290c1948Sdrh u8 nChar; 132290c1948Sdrh u8 code; 13301f3f253Sdrh } keywords[] = { 13401f3f253Sdrh { "natural", 7, JT_NATURAL }, 135195e6967Sdrh { "left", 4, JT_LEFT|JT_OUTER }, 136195e6967Sdrh { "right", 5, JT_RIGHT|JT_OUTER }, 137195e6967Sdrh { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 13801f3f253Sdrh { "outer", 5, JT_OUTER }, 13901f3f253Sdrh { "inner", 5, JT_INNER }, 1403dec223cSdrh { "cross", 5, JT_INNER|JT_CROSS }, 14101f3f253Sdrh }; 14201f3f253Sdrh int i, j; 14301f3f253Sdrh apAll[0] = pA; 14401f3f253Sdrh apAll[1] = pB; 14501f3f253Sdrh apAll[2] = pC; 146195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 14701f3f253Sdrh p = apAll[i]; 14801f3f253Sdrh for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){ 14901f3f253Sdrh if( p->n==keywords[j].nChar 1502646da7eSdrh && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){ 15101f3f253Sdrh jointype |= keywords[j].code; 15201f3f253Sdrh break; 15301f3f253Sdrh } 15401f3f253Sdrh } 15501f3f253Sdrh if( j>=sizeof(keywords)/sizeof(keywords[0]) ){ 15601f3f253Sdrh jointype |= JT_ERROR; 15701f3f253Sdrh break; 15801f3f253Sdrh } 15901f3f253Sdrh } 160ad2d8307Sdrh if( 161ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 162195e6967Sdrh (jointype & JT_ERROR)!=0 163ad2d8307Sdrh ){ 164ae29ffbeSdrh const char *zSp1 = " "; 165ae29ffbeSdrh const char *zSp2 = " "; 166ae29ffbeSdrh if( pB==0 ){ zSp1++; } 167ae29ffbeSdrh if( pC==0 ){ zSp2++; } 168ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 169ae29ffbeSdrh "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); 17001f3f253Sdrh jointype = JT_INNER; 171195e6967Sdrh }else if( jointype & JT_RIGHT ){ 1724adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 173da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 174195e6967Sdrh jointype = JT_INNER; 17501f3f253Sdrh } 17601f3f253Sdrh return jointype; 17701f3f253Sdrh } 17801f3f253Sdrh 17901f3f253Sdrh /* 180ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 181ad2d8307Sdrh ** is not contained in the table. 182ad2d8307Sdrh */ 183ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 184ad2d8307Sdrh int i; 185ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1864adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 187ad2d8307Sdrh } 188ad2d8307Sdrh return -1; 189ad2d8307Sdrh } 190ad2d8307Sdrh 191ad2d8307Sdrh /* 19291bb0eedSdrh ** Set the value of a token to a '\000'-terminated string. 19391bb0eedSdrh */ 19491bb0eedSdrh static void setToken(Token *p, const char *z){ 1952646da7eSdrh p->z = (u8*)z; 196261919ccSdanielk1977 p->n = z ? strlen(z) : 0; 19791bb0eedSdrh p->dyn = 0; 19891bb0eedSdrh } 19991bb0eedSdrh 200c182d163Sdrh /* 201f3b863edSdanielk1977 ** Set the token to the double-quoted and escaped version of the string pointed 202f3b863edSdanielk1977 ** to by z. For example; 203f3b863edSdanielk1977 ** 204f3b863edSdanielk1977 ** {a"bc} -> {"a""bc"} 205f3b863edSdanielk1977 */ 2061e536953Sdanielk1977 static void setQuotedToken(Parse *pParse, Token *p, const char *z){ 2071e536953Sdanielk1977 p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z); 208f3b863edSdanielk1977 p->dyn = 1; 209f3b863edSdanielk1977 if( p->z ){ 210f3b863edSdanielk1977 p->n = strlen((char *)p->z); 2111e536953Sdanielk1977 }else{ 2121e536953Sdanielk1977 pParse->db->mallocFailed = 1; 213f3b863edSdanielk1977 } 214f3b863edSdanielk1977 } 215f3b863edSdanielk1977 216f3b863edSdanielk1977 /* 217c182d163Sdrh ** Create an expression node for an identifier with the name of zName 218c182d163Sdrh */ 21917435752Sdrh Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){ 220c182d163Sdrh Token dummy; 221c182d163Sdrh setToken(&dummy, zName); 22217435752Sdrh return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy); 223c182d163Sdrh } 224c182d163Sdrh 22591bb0eedSdrh 22691bb0eedSdrh /* 227ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the 228ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2. 229ad2d8307Sdrh */ 230ad2d8307Sdrh static void addWhereTerm( 23117435752Sdrh Parse *pParse, /* Parsing context */ 232ad2d8307Sdrh const char *zCol, /* Name of the column */ 233ad2d8307Sdrh const Table *pTab1, /* First table */ 234030530deSdrh const char *zAlias1, /* Alias for first table. May be NULL */ 235ad2d8307Sdrh const Table *pTab2, /* Second table */ 236030530deSdrh const char *zAlias2, /* Alias for second table. May be NULL */ 23722d6a53aSdrh int iRightJoinTable, /* VDBE cursor for the right table */ 238ad2d8307Sdrh Expr **ppExpr /* Add the equality term to this expression */ 239ad2d8307Sdrh ){ 240ad2d8307Sdrh Expr *pE1a, *pE1b, *pE1c; 241ad2d8307Sdrh Expr *pE2a, *pE2b, *pE2c; 242ad2d8307Sdrh Expr *pE; 243ad2d8307Sdrh 24417435752Sdrh pE1a = sqlite3CreateIdExpr(pParse, zCol); 24517435752Sdrh pE2a = sqlite3CreateIdExpr(pParse, zCol); 246030530deSdrh if( zAlias1==0 ){ 247030530deSdrh zAlias1 = pTab1->zName; 248030530deSdrh } 24917435752Sdrh pE1b = sqlite3CreateIdExpr(pParse, zAlias1); 250030530deSdrh if( zAlias2==0 ){ 251030530deSdrh zAlias2 = pTab2->zName; 252030530deSdrh } 25317435752Sdrh pE2b = sqlite3CreateIdExpr(pParse, zAlias2); 25417435752Sdrh pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0); 25517435752Sdrh pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0); 2561e536953Sdanielk1977 pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0); 257206f3d96Sdrh if( pE ){ 2581f16230bSdrh ExprSetProperty(pE, EP_FromJoin); 25922d6a53aSdrh pE->iRightJoinTable = iRightJoinTable; 260206f3d96Sdrh } 261f4ce8ed0Sdrh *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE); 262ad2d8307Sdrh } 263ad2d8307Sdrh 264ad2d8307Sdrh /* 2651f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 26622d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 26722d6a53aSdrh ** expression. 2681cc093c2Sdrh ** 269e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 2701cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 2711f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 2721f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 2731f16230bSdrh ** WHERE clause during join processing but we need to remember that they 2741f16230bSdrh ** originated in the ON or USING clause. 27522d6a53aSdrh ** 27622d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 27722d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 27822d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 27922d6a53aSdrh ** for cases like this: 28022d6a53aSdrh ** 28122d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 28222d6a53aSdrh ** 28322d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 28422d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 28522d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 28622d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 28722d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 28822d6a53aSdrh ** the output, which is incorrect. 2891cc093c2Sdrh */ 29022d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 2911cc093c2Sdrh while( p ){ 2921f16230bSdrh ExprSetProperty(p, EP_FromJoin); 29322d6a53aSdrh p->iRightJoinTable = iTable; 29422d6a53aSdrh setJoinExpr(p->pLeft, iTable); 2951cc093c2Sdrh p = p->pRight; 2961cc093c2Sdrh } 2971cc093c2Sdrh } 2981cc093c2Sdrh 2991cc093c2Sdrh /* 300ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 301ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 302ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 303ad2d8307Sdrh ** 30491bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 30591bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 30691bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 30791bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 30891bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 30991bb0eedSdrh ** also attached to the left entry. 31091bb0eedSdrh ** 311ad2d8307Sdrh ** This routine returns the number of errors encountered. 312ad2d8307Sdrh */ 313ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 31491bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 31591bb0eedSdrh int i, j; /* Loop counters */ 31691bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 31791bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 318ad2d8307Sdrh 31991bb0eedSdrh pSrc = p->pSrc; 32091bb0eedSdrh pLeft = &pSrc->a[0]; 32191bb0eedSdrh pRight = &pLeft[1]; 32291bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 32391bb0eedSdrh Table *pLeftTab = pLeft->pTab; 32491bb0eedSdrh Table *pRightTab = pRight->pTab; 32591bb0eedSdrh 32691bb0eedSdrh if( pLeftTab==0 || pRightTab==0 ) continue; 327ad2d8307Sdrh 328ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 329ad2d8307Sdrh ** every column that the two tables have in common. 330ad2d8307Sdrh */ 33161dfc31dSdrh if( pRight->jointype & JT_NATURAL ){ 33261dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 3334adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 334ad2d8307Sdrh "an ON or USING clause", 0); 335ad2d8307Sdrh return 1; 336ad2d8307Sdrh } 33791bb0eedSdrh for(j=0; j<pLeftTab->nCol; j++){ 33891bb0eedSdrh char *zName = pLeftTab->aCol[j].zName; 33991bb0eedSdrh if( columnIndex(pRightTab, zName)>=0 ){ 3401e536953Sdanielk1977 addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 34122d6a53aSdrh pRightTab, pRight->zAlias, 34222d6a53aSdrh pRight->iCursor, &p->pWhere); 34322d6a53aSdrh 344ad2d8307Sdrh } 345ad2d8307Sdrh } 346ad2d8307Sdrh } 347ad2d8307Sdrh 348ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 349ad2d8307Sdrh */ 35061dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 3514adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 352da93d238Sdrh "clauses in the same join"); 353ad2d8307Sdrh return 1; 354ad2d8307Sdrh } 355ad2d8307Sdrh 356ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 35791bb0eedSdrh ** an AND operator. 358ad2d8307Sdrh */ 35961dfc31dSdrh if( pRight->pOn ){ 36061dfc31dSdrh setJoinExpr(pRight->pOn, pRight->iCursor); 36117435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 36261dfc31dSdrh pRight->pOn = 0; 363ad2d8307Sdrh } 364ad2d8307Sdrh 365ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 366ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 367ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 368ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 369ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 370ad2d8307Sdrh ** not contained in both tables to be joined. 371ad2d8307Sdrh */ 37261dfc31dSdrh if( pRight->pUsing ){ 37361dfc31dSdrh IdList *pList = pRight->pUsing; 374ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 37591bb0eedSdrh char *zName = pList->a[j].zName; 37691bb0eedSdrh if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){ 3774adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 37891bb0eedSdrh "not present in both tables", zName); 379ad2d8307Sdrh return 1; 380ad2d8307Sdrh } 3811e536953Sdanielk1977 addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 38222d6a53aSdrh pRightTab, pRight->zAlias, 38322d6a53aSdrh pRight->iCursor, &p->pWhere); 384ad2d8307Sdrh } 385ad2d8307Sdrh } 386ad2d8307Sdrh } 387ad2d8307Sdrh return 0; 388ad2d8307Sdrh } 389ad2d8307Sdrh 390ad2d8307Sdrh /* 391c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 392c926afbcSdrh ** stack into the sorter. 393c926afbcSdrh */ 394d59ba6ceSdrh static void pushOntoSorter( 395d59ba6ceSdrh Parse *pParse, /* Parser context */ 396d59ba6ceSdrh ExprList *pOrderBy, /* The ORDER BY clause */ 397b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 398b7654111Sdrh int regData /* Register holding data to be sorted */ 399d59ba6ceSdrh ){ 400d59ba6ceSdrh Vdbe *v = pParse->pVdbe; 401892d3179Sdrh int nExpr = pOrderBy->nExpr; 402892d3179Sdrh int regBase = sqlite3GetTempRange(pParse, nExpr+2); 403892d3179Sdrh int regRecord = sqlite3GetTempReg(pParse); 404892d3179Sdrh sqlite3ExprCodeExprList(pParse, pOrderBy, regBase); 405892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); 406b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Move, regData, regBase+nExpr+1); 4071db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord); 408892d3179Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord); 409892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 410892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nExpr+2); 411d59ba6ceSdrh if( pSelect->iLimit>=0 ){ 41215007a99Sdrh int addr1, addr2; 413b7654111Sdrh int iLimit; 414b7654111Sdrh if( pSelect->pOffset ){ 415b7654111Sdrh iLimit = pSelect->iOffset+1; 416b7654111Sdrh }else{ 417b7654111Sdrh iLimit = pSelect->iLimit; 418b7654111Sdrh } 419b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); 420b7654111Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); 4213c84ddffSdrh addr2 = sqlite3VdbeAddOp0(v, OP_Goto); 422d59ba6ceSdrh sqlite3VdbeJumpHere(v, addr1); 4233c84ddffSdrh sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); 4243c84ddffSdrh sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); 42515007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 426d59ba6ceSdrh pSelect->iLimit = -1; 427d59ba6ceSdrh } 428c926afbcSdrh } 429c926afbcSdrh 430c926afbcSdrh /* 431ec7429aeSdrh ** Add code to implement the OFFSET 432ea48eb2eSdrh */ 433ec7429aeSdrh static void codeOffset( 434bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 435ea48eb2eSdrh Select *p, /* The SELECT statement being coded */ 436b7654111Sdrh int iContinue /* Jump here to skip the current record */ 437ea48eb2eSdrh ){ 43813449892Sdrh if( p->iOffset>=0 && iContinue!=0 ){ 43915007a99Sdrh int addr; 4408558cde1Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1); 4413c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset); 44266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); 443d4e70ebdSdrh VdbeComment((v, "skip OFFSET records")); 44415007a99Sdrh sqlite3VdbeJumpHere(v, addr); 445ea48eb2eSdrh } 446ea48eb2eSdrh } 447ea48eb2eSdrh 448ea48eb2eSdrh /* 44998757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 45098757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 451a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 452a2a49dc9Sdrh ** if the current N values are new. 453a2a49dc9Sdrh ** 454a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 455a2a49dc9Sdrh ** stack if the top N elements are not distinct. 456a2a49dc9Sdrh */ 457a2a49dc9Sdrh static void codeDistinct( 4582dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 459a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 460a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 461477df4b3Sdrh int N, /* Number of elements */ 462a2a49dc9Sdrh int iMem /* First element */ 463a2a49dc9Sdrh ){ 4642dcef11bSdrh Vdbe *v; 4652dcef11bSdrh int r1; 4662dcef11bSdrh 4672dcef11bSdrh v = pParse->pVdbe; 4682dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 4691db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 4702dcef11bSdrh sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1); 4712dcef11bSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); 4722dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 473a2a49dc9Sdrh } 474a2a49dc9Sdrh 475a2a49dc9Sdrh /* 476e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression 477e305f43fSdrh ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 478e305f43fSdrh ** column. We do this in a subroutine because the error occurs in multiple 479e305f43fSdrh ** places. 480e305f43fSdrh */ 4816c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError( 4826c8c8ce0Sdanielk1977 Parse *pParse, /* Parse context. */ 4836c8c8ce0Sdanielk1977 SelectDest *pDest, /* Destination of SELECT results */ 4846c8c8ce0Sdanielk1977 int nExpr /* Number of result columns returned by SELECT */ 4856c8c8ce0Sdanielk1977 ){ 4866c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 487e305f43fSdrh if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 488e305f43fSdrh sqlite3ErrorMsg(pParse, "only a single result allowed for " 489e305f43fSdrh "a SELECT that is part of an expression"); 490e305f43fSdrh return 1; 491e305f43fSdrh }else{ 492e305f43fSdrh return 0; 493e305f43fSdrh } 494e305f43fSdrh } 495c99130fdSdrh 496c99130fdSdrh /* 4972282792aSdrh ** This routine generates the code for the inside of the inner loop 4982282792aSdrh ** of a SELECT. 49982c3d636Sdrh ** 50038640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 50138640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 50238640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 50338640e15Sdrh ** datatypes for each column. 5042282792aSdrh */ 505d2b3e23bSdrh static void selectInnerLoop( 5062282792aSdrh Parse *pParse, /* The parser context */ 507df199a25Sdrh Select *p, /* The complete select statement being coded */ 5082282792aSdrh ExprList *pEList, /* List of values being extracted */ 50982c3d636Sdrh int srcTab, /* Pull data from this table */ 510967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 5112282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 5122282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 5136c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 5142282792aSdrh int iContinue, /* Jump here to continue with next row */ 51584ac9d02Sdanielk1977 int iBreak, /* Jump here to break out of the inner loop */ 51684ac9d02Sdanielk1977 char *aff /* affinity string if eDest is SRT_Union */ 5172282792aSdrh ){ 5182282792aSdrh Vdbe *v = pParse->pVdbe; 519d847eaadSdrh int i; 520ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 521d847eaadSdrh int regResult; /* Start of memory holding result set */ 522d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 523d847eaadSdrh int iParm = pDest->iParm; /* First argument to disposal method */ 524d847eaadSdrh int nResultCol; /* Number of result columns */ 525d847eaadSdrh int nToFree; /* Number of result columns to release */ 52638640e15Sdrh 527d2b3e23bSdrh if( v==0 ) return; 52838640e15Sdrh assert( pEList!=0 ); 5292282792aSdrh 530df199a25Sdrh /* If there was a LIMIT clause on the SELECT statement, then do the check 531df199a25Sdrh ** to see if this row should be output. 532df199a25Sdrh */ 533eda639e1Sdrh hasDistinct = distinct>=0 && pEList->nExpr>0; 534ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 535b7654111Sdrh codeOffset(v, p, iContinue); 536df199a25Sdrh } 537df199a25Sdrh 538967e8b73Sdrh /* Pull the requested columns. 5392282792aSdrh */ 54038640e15Sdrh if( nColumn>0 ){ 541d847eaadSdrh nResultCol = nColumn; 542a2a49dc9Sdrh }else{ 543d847eaadSdrh nResultCol = pEList->nExpr; 544a2a49dc9Sdrh } 5451013c932Sdrh if( pDest->iMem>0 ){ 546d847eaadSdrh regResult = pDest->iMem; 547d847eaadSdrh nToFree = 0; 5481013c932Sdrh }else{ 549d847eaadSdrh pDest->iMem = regResult = sqlite3GetTempRange(pParse, nResultCol); 550d847eaadSdrh nToFree = nResultCol; 5511013c932Sdrh } 552a2a49dc9Sdrh if( nColumn>0 ){ 553967e8b73Sdrh for(i=0; i<nColumn; i++){ 554d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 55582c3d636Sdrh } 5569ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 5579ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 5589ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 5599ed1dfa8Sdanielk1977 */ 560d847eaadSdrh for(i=0; i<nResultCol; i++){ 561d847eaadSdrh sqlite3ExprCode(pParse, pEList->a[i].pExpr, regResult+i); 56282c3d636Sdrh } 563a2a49dc9Sdrh } 564d847eaadSdrh nColumn = nResultCol; 5652282792aSdrh 566daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 567daffd0e5Sdrh ** and this row has been seen before, then do not make this row 568daffd0e5Sdrh ** part of the result. 5692282792aSdrh */ 570ea48eb2eSdrh if( hasDistinct ){ 571f8875400Sdrh assert( pEList!=0 ); 572f8875400Sdrh assert( pEList->nExpr==nColumn ); 573d847eaadSdrh codeDistinct(pParse, distinct, iContinue, nColumn, regResult); 574ea48eb2eSdrh if( pOrderBy==0 ){ 575b7654111Sdrh codeOffset(v, p, iContinue); 576ea48eb2eSdrh } 5772282792aSdrh } 57882c3d636Sdrh 5796c8c8ce0Sdanielk1977 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 580d2b3e23bSdrh return; 581e305f43fSdrh } 582e305f43fSdrh 583c926afbcSdrh switch( eDest ){ 58482c3d636Sdrh /* In this mode, write each query result to the key of the temporary 58582c3d636Sdrh ** table iParm. 5862282792aSdrh */ 58713449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 588c926afbcSdrh case SRT_Union: { 5899cbf3425Sdrh int r1; 5909cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 591d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 59213449892Sdrh if( aff ){ 59366a5167bSdrh sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC); 59413449892Sdrh } 5959cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 5969cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 597c926afbcSdrh break; 598c926afbcSdrh } 59982c3d636Sdrh 60082c3d636Sdrh /* Construct a record from the query result, but instead of 60182c3d636Sdrh ** saving that record, use it as a key to delete elements from 60282c3d636Sdrh ** the temporary table iParm. 60382c3d636Sdrh */ 604c926afbcSdrh case SRT_Except: { 605a05a722fSdrh int r1; 6069cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 607a05a722fSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 60866a5167bSdrh sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC); 609a05a722fSdrh sqlite3VdbeAddOp2(v, OP_IdxDelete, iParm, r1); 6109cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 611c926afbcSdrh break; 612c926afbcSdrh } 6135338a5f7Sdanielk1977 #endif 6145338a5f7Sdanielk1977 6155338a5f7Sdanielk1977 /* Store the result as data using a unique key. 6165338a5f7Sdanielk1977 */ 6175338a5f7Sdanielk1977 case SRT_Table: 618b9bb7c18Sdrh case SRT_EphemTab: { 619b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 620d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6215338a5f7Sdanielk1977 if( pOrderBy ){ 622b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 6235338a5f7Sdanielk1977 }else{ 624b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 625b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 626b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 627b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 628b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 6295338a5f7Sdanielk1977 } 630b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 6315338a5f7Sdanielk1977 break; 6325338a5f7Sdanielk1977 } 6332282792aSdrh 63493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 6352282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 6362282792aSdrh ** then there should be a single item on the stack. Write this 6372282792aSdrh ** item into the set table with bogus data. 6382282792aSdrh */ 639c926afbcSdrh case SRT_Set: { 64052b36cabSdrh int addr2; 641e014a838Sdanielk1977 642967e8b73Sdrh assert( nColumn==1 ); 643d847eaadSdrh addr2 = sqlite3VdbeAddOp1(v, OP_IsNull, regResult); 6446c8c8ce0Sdanielk1977 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity); 645c926afbcSdrh if( pOrderBy ){ 646de941c60Sdrh /* At first glance you would think we could optimize out the 647de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 648de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 649de941c60Sdrh ** case the order does matter */ 650d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 651c926afbcSdrh }else{ 652b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 653d847eaadSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1); 654b7654111Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 655b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 656c926afbcSdrh } 657d654be80Sdrh sqlite3VdbeJumpHere(v, addr2); 658c926afbcSdrh break; 659c926afbcSdrh } 66082c3d636Sdrh 661504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 662ec7429aeSdrh */ 663ec7429aeSdrh case SRT_Exists: { 6644c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 665ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 666ec7429aeSdrh break; 667ec7429aeSdrh } 668ec7429aeSdrh 6692282792aSdrh /* If this is a scalar select that is part of an expression, then 6702282792aSdrh ** store the results in the appropriate memory cell and break out 6712282792aSdrh ** of the scan loop. 6722282792aSdrh */ 673c926afbcSdrh case SRT_Mem: { 674967e8b73Sdrh assert( nColumn==1 ); 675c926afbcSdrh if( pOrderBy ){ 676d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 677c926afbcSdrh }else{ 678d847eaadSdrh sqlite3VdbeAddOp2(v, OP_Move, regResult, iParm); 679ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 680c926afbcSdrh } 681c926afbcSdrh break; 682c926afbcSdrh } 68393758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 6842282792aSdrh 685c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 686c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 687c182d163Sdrh ** popping the data from the stack. 688f46f905aSdrh */ 689c182d163Sdrh case SRT_Subroutine: 6909d2985c7Sdrh case SRT_Callback: { 691f46f905aSdrh if( pOrderBy ){ 692b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 693d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 694b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 695b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 696c182d163Sdrh }else if( eDest==SRT_Subroutine ){ 697d847eaadSdrh nToFree = 0; /* Preserve registers. Subroutine will need them. */ 69866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm); 699c182d163Sdrh }else{ 700d847eaadSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); 701ac82fcf5Sdrh } 702142e30dfSdrh break; 703142e30dfSdrh } 704142e30dfSdrh 7056a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 706d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 707d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 708d7489c39Sdrh ** user-defined functions that have side effects. We do not care 709d7489c39Sdrh ** about the actual results of the select. 710d7489c39Sdrh */ 711c926afbcSdrh default: { 712f46f905aSdrh assert( eDest==SRT_Discard ); 713c926afbcSdrh break; 714c926afbcSdrh } 71593758c8dSdanielk1977 #endif 716c926afbcSdrh } 717ec7429aeSdrh 718ec7429aeSdrh /* Jump to the end of the loop if the LIMIT is reached. 719ec7429aeSdrh */ 720ec7429aeSdrh if( p->iLimit>=0 && pOrderBy==0 ){ 7218558cde1Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); 7223c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak); 723ec7429aeSdrh } 724d847eaadSdrh sqlite3ReleaseTempRange(pParse, regResult, nToFree); 72582c3d636Sdrh } 72682c3d636Sdrh 72782c3d636Sdrh /* 728dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 729dece1a84Sdrh ** the collating sequence for each expression in that expression list. 730dece1a84Sdrh ** 7310342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 7320342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 7330342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 7340342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 7350342b1f5Sdrh ** index to implement a DISTINCT test. 7360342b1f5Sdrh ** 737dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 738dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 73966a5167bSdrh ** freed. Add the KeyInfo structure to the P4 field of an opcode using 74066a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. 741dece1a84Sdrh */ 742dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 743dece1a84Sdrh sqlite3 *db = pParse->db; 744dece1a84Sdrh int nExpr; 745dece1a84Sdrh KeyInfo *pInfo; 746dece1a84Sdrh struct ExprList_item *pItem; 747dece1a84Sdrh int i; 748dece1a84Sdrh 749dece1a84Sdrh nExpr = pList->nExpr; 75017435752Sdrh pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 751dece1a84Sdrh if( pInfo ){ 7522646da7eSdrh pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 753dece1a84Sdrh pInfo->nField = nExpr; 75414db2665Sdanielk1977 pInfo->enc = ENC(db); 755dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 756dece1a84Sdrh CollSeq *pColl; 757dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 758dece1a84Sdrh if( !pColl ){ 759dece1a84Sdrh pColl = db->pDfltColl; 760dece1a84Sdrh } 761dece1a84Sdrh pInfo->aColl[i] = pColl; 762dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 763dece1a84Sdrh } 764dece1a84Sdrh } 765dece1a84Sdrh return pInfo; 766dece1a84Sdrh } 767dece1a84Sdrh 768dece1a84Sdrh 769dece1a84Sdrh /* 770d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 771d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 772d8bc7086Sdrh ** we need to run the sorter and output the results. The following 773d8bc7086Sdrh ** routine generates the code needed to do that. 774d8bc7086Sdrh */ 775c926afbcSdrh static void generateSortTail( 776cdd536f0Sdrh Parse *pParse, /* Parsing context */ 777c926afbcSdrh Select *p, /* The SELECT statement */ 778c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 779c926afbcSdrh int nColumn, /* Number of columns of data */ 7806c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 781c926afbcSdrh ){ 7820342b1f5Sdrh int brk = sqlite3VdbeMakeLabel(v); 7830342b1f5Sdrh int cont = sqlite3VdbeMakeLabel(v); 784d8bc7086Sdrh int addr; 7850342b1f5Sdrh int iTab; 78661fc595fSdrh int pseudoTab = 0; 7870342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 788ffbc3088Sdrh 7896c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 7906c8c8ce0Sdanielk1977 int iParm = pDest->iParm; 7916c8c8ce0Sdanielk1977 7922d401ab8Sdrh int regRow; 7932d401ab8Sdrh int regRowid; 7942d401ab8Sdrh 7959d2985c7Sdrh iTab = pOrderBy->iECursor; 796cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 797cdd536f0Sdrh pseudoTab = pParse->nTab++; 79866a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, 0); 79966a5167bSdrh sqlite3VdbeAddOp2(v, OP_SetNumColumns, pseudoTab, nColumn); 800cdd536f0Sdrh } 80166a5167bSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk); 802b7654111Sdrh codeOffset(v, p, cont); 8032d401ab8Sdrh regRow = sqlite3GetTempReg(pParse); 8042d401ab8Sdrh regRowid = sqlite3GetTempReg(pParse); 8052d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow); 806c926afbcSdrh switch( eDest ){ 807c926afbcSdrh case SRT_Table: 808b9bb7c18Sdrh case SRT_EphemTab: { 8092d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 8102d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 8112d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 812c926afbcSdrh break; 813c926afbcSdrh } 81493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 815c926afbcSdrh case SRT_Set: { 8162d401ab8Sdrh int j1; 817c926afbcSdrh assert( nColumn==1 ); 8182d401ab8Sdrh j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regRow); 8191db639ceSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRow, &p->affinity, 1); 8202d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRow); 8216a288a33Sdrh sqlite3VdbeJumpHere(v, j1); 822c926afbcSdrh break; 823c926afbcSdrh } 824c926afbcSdrh case SRT_Mem: { 825c926afbcSdrh assert( nColumn==1 ); 8262d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_Move, regRow, iParm); 827ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 828c926afbcSdrh break; 829c926afbcSdrh } 83093758c8dSdanielk1977 #endif 831ce665cf6Sdrh case SRT_Callback: 832ac82fcf5Sdrh case SRT_Subroutine: { 833ac82fcf5Sdrh int i; 8342d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid); 8352d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid); 836ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 8371013c932Sdrh sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i); 838ac82fcf5Sdrh } 839ce665cf6Sdrh if( eDest==SRT_Callback ){ 8401013c932Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn); 841ce665cf6Sdrh }else{ 84266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm); 843ce665cf6Sdrh } 844ac82fcf5Sdrh break; 845ac82fcf5Sdrh } 846c926afbcSdrh default: { 847f46f905aSdrh /* Do nothing */ 848c926afbcSdrh break; 849c926afbcSdrh } 850c926afbcSdrh } 8512d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 8522d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 853ec7429aeSdrh 854ec7429aeSdrh /* Jump to the end of the loop when the LIMIT is reached 855ec7429aeSdrh */ 856ec7429aeSdrh if( p->iLimit>=0 ){ 8578558cde1Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); 8583c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, brk); 859ec7429aeSdrh } 860ec7429aeSdrh 861ec7429aeSdrh /* The bottom of the loop 862ec7429aeSdrh */ 8630342b1f5Sdrh sqlite3VdbeResolveLabel(v, cont); 86466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); 8650342b1f5Sdrh sqlite3VdbeResolveLabel(v, brk); 866cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 86766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); 868cdd536f0Sdrh } 869cdd536f0Sdrh 870d8bc7086Sdrh } 871d8bc7086Sdrh 872d8bc7086Sdrh /* 873517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 874517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 875e78e8284Sdrh ** 876955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 877955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 878955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 879955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 880955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 881955de52cSdanielk1977 ** considered a column by this function. 882e78e8284Sdrh ** 883955de52cSdanielk1977 ** SELECT col FROM tbl; 884955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 885955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 886955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 887955de52cSdanielk1977 ** 888955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 889fcb78a49Sdrh */ 890955de52cSdanielk1977 static const char *columnType( 891955de52cSdanielk1977 NameContext *pNC, 892955de52cSdanielk1977 Expr *pExpr, 893955de52cSdanielk1977 const char **pzOriginDb, 894955de52cSdanielk1977 const char **pzOriginTab, 895955de52cSdanielk1977 const char **pzOriginCol 896955de52cSdanielk1977 ){ 897955de52cSdanielk1977 char const *zType = 0; 898955de52cSdanielk1977 char const *zOriginDb = 0; 899955de52cSdanielk1977 char const *zOriginTab = 0; 900955de52cSdanielk1977 char const *zOriginCol = 0; 901517eb646Sdanielk1977 int j; 902b3bce662Sdanielk1977 if( pExpr==0 || pNC->pSrcList==0 ) return 0; 9035338a5f7Sdanielk1977 90400e279d9Sdanielk1977 switch( pExpr->op ){ 90530bcf5dbSdrh case TK_AGG_COLUMN: 90600e279d9Sdanielk1977 case TK_COLUMN: { 907955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 908955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 909955de52cSdanielk1977 ** database table or a subquery. 910955de52cSdanielk1977 */ 911955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 912955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 913955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 914b3bce662Sdanielk1977 while( pNC && !pTab ){ 915b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 916b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 917b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 9186a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 919955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 920b3bce662Sdanielk1977 }else{ 921b3bce662Sdanielk1977 pNC = pNC->pNext; 922b3bce662Sdanielk1977 } 923b3bce662Sdanielk1977 } 924955de52cSdanielk1977 9257e62779aSdrh if( pTab==0 ){ 9267e62779aSdrh /* FIX ME: 9277e62779aSdrh ** This can occurs if you have something like "SELECT new.x;" inside 9287e62779aSdrh ** a trigger. In other words, if you reference the special "new" 9297e62779aSdrh ** table in the result set of a select. We do not have a good way 9307e62779aSdrh ** to find the actual table type, so call it "TEXT". This is really 9317e62779aSdrh ** something of a bug, but I do not know how to fix it. 9327e62779aSdrh ** 9337e62779aSdrh ** This code does not produce the correct answer - it just prevents 9347e62779aSdrh ** a segfault. See ticket #1229. 9357e62779aSdrh */ 9367e62779aSdrh zType = "TEXT"; 9377e62779aSdrh break; 9387e62779aSdrh } 939955de52cSdanielk1977 940b3bce662Sdanielk1977 assert( pTab ); 941955de52cSdanielk1977 if( pS ){ 942955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 943955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 944955de52cSdanielk1977 ** data for the result-set column of the sub-select. 945955de52cSdanielk1977 */ 946955de52cSdanielk1977 if( iCol>=0 && iCol<pS->pEList->nExpr ){ 947955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 948955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 949955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 950955de52cSdanielk1977 */ 951955de52cSdanielk1977 NameContext sNC; 952955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 953955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 954955de52cSdanielk1977 sNC.pNext = 0; 955955de52cSdanielk1977 sNC.pParse = pNC->pParse; 956955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 957955de52cSdanielk1977 } 9584b2688abSdanielk1977 }else if( pTab->pSchema ){ 959955de52cSdanielk1977 /* A real table */ 960955de52cSdanielk1977 assert( !pS ); 961fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 962fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 963fcb78a49Sdrh if( iCol<0 ){ 964fcb78a49Sdrh zType = "INTEGER"; 965955de52cSdanielk1977 zOriginCol = "rowid"; 966fcb78a49Sdrh }else{ 967fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 968955de52cSdanielk1977 zOriginCol = pTab->aCol[iCol].zName; 969955de52cSdanielk1977 } 970955de52cSdanielk1977 zOriginTab = pTab->zName; 971955de52cSdanielk1977 if( pNC->pParse ){ 972955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 973955de52cSdanielk1977 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 974955de52cSdanielk1977 } 975fcb78a49Sdrh } 97600e279d9Sdanielk1977 break; 977736c22b8Sdrh } 97893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 97900e279d9Sdanielk1977 case TK_SELECT: { 980955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 981955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 982955de52cSdanielk1977 ** statement. 983955de52cSdanielk1977 */ 984b3bce662Sdanielk1977 NameContext sNC; 98500e279d9Sdanielk1977 Select *pS = pExpr->pSelect; 986955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 987955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 988b3bce662Sdanielk1977 sNC.pNext = pNC; 989955de52cSdanielk1977 sNC.pParse = pNC->pParse; 990955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 99100e279d9Sdanielk1977 break; 992fcb78a49Sdrh } 99393758c8dSdanielk1977 #endif 99400e279d9Sdanielk1977 } 99500e279d9Sdanielk1977 996955de52cSdanielk1977 if( pzOriginDb ){ 997955de52cSdanielk1977 assert( pzOriginTab && pzOriginCol ); 998955de52cSdanielk1977 *pzOriginDb = zOriginDb; 999955de52cSdanielk1977 *pzOriginTab = zOriginTab; 1000955de52cSdanielk1977 *pzOriginCol = zOriginCol; 1001955de52cSdanielk1977 } 1002517eb646Sdanielk1977 return zType; 1003517eb646Sdanielk1977 } 1004517eb646Sdanielk1977 1005517eb646Sdanielk1977 /* 1006517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1007517eb646Sdanielk1977 ** in the result set. 1008517eb646Sdanielk1977 */ 1009517eb646Sdanielk1977 static void generateColumnTypes( 1010517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1011517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1012517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1013517eb646Sdanielk1977 ){ 1014517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1015517eb646Sdanielk1977 int i; 1016b3bce662Sdanielk1977 NameContext sNC; 1017b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1018955de52cSdanielk1977 sNC.pParse = pParse; 1019517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1020517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 1021955de52cSdanielk1977 const char *zOrigDb = 0; 1022955de52cSdanielk1977 const char *zOrigTab = 0; 1023955de52cSdanielk1977 const char *zOrigCol = 0; 1024955de52cSdanielk1977 const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1025955de52cSdanielk1977 102685b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 10274b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 10284b1ae99dSdanielk1977 ** virtual machine is deleted. 1029fbcd585fSdanielk1977 */ 103066a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT); 103166a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT); 103266a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT); 103366a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT); 1034fcb78a49Sdrh } 1035fcb78a49Sdrh } 1036fcb78a49Sdrh 1037fcb78a49Sdrh /* 1038fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1039fcb78a49Sdrh ** in the result set. This information is used to provide the 1040fcabd464Sdrh ** azCol[] values in the callback. 104182c3d636Sdrh */ 1042832508b7Sdrh static void generateColumnNames( 1043832508b7Sdrh Parse *pParse, /* Parser context */ 1044ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1045832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1046832508b7Sdrh ){ 1047d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 10486a3ea0e6Sdrh int i, j; 10499bb575fdSdrh sqlite3 *db = pParse->db; 1050fcabd464Sdrh int fullNames, shortNames; 1051fcabd464Sdrh 1052fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 10533cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 10543cf86063Sdanielk1977 if( pParse->explain ){ 105561de0d1bSdanielk1977 return; 10563cf86063Sdanielk1977 } 10575338a5f7Sdanielk1977 #endif 10583cf86063Sdanielk1977 1059d6502758Sdrh assert( v!=0 ); 106017435752Sdrh if( pParse->colNamesSet || v==0 || db->mallocFailed ) return; 1061d8bc7086Sdrh pParse->colNamesSet = 1; 1062fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1063fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 106422322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 106582c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 106682c3d636Sdrh Expr *p; 10675a38705eSdrh p = pEList->a[i].pExpr; 10685a38705eSdrh if( p==0 ) continue; 106982c3d636Sdrh if( pEList->a[i].zName ){ 107082c3d636Sdrh char *zName = pEList->a[i].zName; 1071955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName)); 107282c3d636Sdrh continue; 107382c3d636Sdrh } 1074fa173a76Sdrh if( p->op==TK_COLUMN && pTabList ){ 10756a3ea0e6Sdrh Table *pTab; 107697665873Sdrh char *zCol; 10778aff1015Sdrh int iCol = p->iColumn; 10786a3ea0e6Sdrh for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 10796a3ea0e6Sdrh assert( j<pTabList->nSrc ); 10806a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 10818aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 108297665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1083b1363206Sdrh if( iCol<0 ){ 108447a6db2bSdrh zCol = "rowid"; 1085b1363206Sdrh }else{ 1086b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1087b1363206Sdrh } 1088fcabd464Sdrh if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ 1089955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 1090fcabd464Sdrh }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ 109182c3d636Sdrh char *zName = 0; 109282c3d636Sdrh char *zTab; 109382c3d636Sdrh 10946a3ea0e6Sdrh zTab = pTabList->a[j].zAlias; 1095fcabd464Sdrh if( fullNames || zTab==0 ) zTab = pTab->zName; 1096f93339deSdrh sqlite3SetString(&zName, zTab, ".", zCol, (char*)0); 109766a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC); 109882c3d636Sdrh }else{ 1099955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol)); 110082c3d636Sdrh } 11016977fea8Sdrh }else if( p->span.z && p->span.z[0] ){ 1102955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 11033cf86063Sdanielk1977 /* sqlite3VdbeCompressSpace(v, addr); */ 11041bee3d7bSdrh }else{ 11051bee3d7bSdrh char zName[30]; 11061bee3d7bSdrh assert( p->op!=TK_COLUMN || pTabList==0 ); 11075bb3eb9bSdrh sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1); 1108955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0); 110982c3d636Sdrh } 111082c3d636Sdrh } 111176d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 11125080aaa7Sdrh } 111382c3d636Sdrh 111493758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 111582c3d636Sdrh /* 1116d8bc7086Sdrh ** Name of the connection operator, used for error messages. 1117d8bc7086Sdrh */ 1118d8bc7086Sdrh static const char *selectOpName(int id){ 1119d8bc7086Sdrh char *z; 1120d8bc7086Sdrh switch( id ){ 1121d8bc7086Sdrh case TK_ALL: z = "UNION ALL"; break; 1122d8bc7086Sdrh case TK_INTERSECT: z = "INTERSECT"; break; 1123d8bc7086Sdrh case TK_EXCEPT: z = "EXCEPT"; break; 1124d8bc7086Sdrh default: z = "UNION"; break; 1125d8bc7086Sdrh } 1126d8bc7086Sdrh return z; 1127d8bc7086Sdrh } 112893758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1129d8bc7086Sdrh 1130d8bc7086Sdrh /* 1131315555caSdrh ** Forward declaration 1132315555caSdrh */ 11339b3187e1Sdrh static int prepSelectStmt(Parse*, Select*); 1134315555caSdrh 1135315555caSdrh /* 113622f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes 113722f70c32Sdrh ** the result set of that SELECT. 113822f70c32Sdrh */ 11394adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 114022f70c32Sdrh Table *pTab; 1141b733d037Sdrh int i, j; 114222f70c32Sdrh ExprList *pEList; 1143290c1948Sdrh Column *aCol, *pCol; 114417435752Sdrh sqlite3 *db = pParse->db; 114522f70c32Sdrh 114692378253Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 11479b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 114822f70c32Sdrh return 0; 114922f70c32Sdrh } 1150142bdf40Sdanielk1977 if( sqlite3SelectResolve(pParse, pSelect, 0) ){ 1151142bdf40Sdanielk1977 return 0; 1152142bdf40Sdanielk1977 } 115317435752Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 115422f70c32Sdrh if( pTab==0 ){ 115522f70c32Sdrh return 0; 115622f70c32Sdrh } 1157ed8a3bb1Sdrh pTab->nRef = 1; 115817435752Sdrh pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0; 115922f70c32Sdrh pEList = pSelect->pEList; 116022f70c32Sdrh pTab->nCol = pEList->nExpr; 1161417be79cSdrh assert( pTab->nCol>0 ); 116217435752Sdrh pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol); 1163290c1948Sdrh for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){ 116479d5f63fSdrh Expr *p, *pR; 1165517eb646Sdanielk1977 char *zType; 116691bb0eedSdrh char *zName; 11672564ef97Sdrh int nName; 1168b3bf556eSdanielk1977 CollSeq *pColl; 116979d5f63fSdrh int cnt; 1170b3bce662Sdanielk1977 NameContext sNC; 117179d5f63fSdrh 117279d5f63fSdrh /* Get an appropriate name for the column 117379d5f63fSdrh */ 117479d5f63fSdrh p = pEList->a[i].pExpr; 1175290c1948Sdrh assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 ); 117691bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 117779d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 117817435752Sdrh zName = sqlite3DbStrDup(db, zName); 1179517eb646Sdanielk1977 }else if( p->op==TK_DOT 1180b733d037Sdrh && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ 118179d5f63fSdrh /* For columns of the from A.B use B as the name */ 118217435752Sdrh zName = sqlite3MPrintf(db, "%T", &pR->token); 1183b733d037Sdrh }else if( p->span.z && p->span.z[0] ){ 118479d5f63fSdrh /* Use the original text of the column expression as its name */ 118517435752Sdrh zName = sqlite3MPrintf(db, "%T", &p->span); 118622f70c32Sdrh }else{ 118779d5f63fSdrh /* If all else fails, make up a name */ 118817435752Sdrh zName = sqlite3MPrintf(db, "column%d", i+1); 118922f70c32Sdrh } 11907751940dSdanielk1977 if( !zName || db->mallocFailed ){ 11917751940dSdanielk1977 db->mallocFailed = 1; 119217435752Sdrh sqlite3_free(zName); 1193a04a34ffSdanielk1977 sqlite3DeleteTable(pTab); 1194dd5b2fa5Sdrh return 0; 1195dd5b2fa5Sdrh } 11967751940dSdanielk1977 sqlite3Dequote(zName); 119779d5f63fSdrh 119879d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 119979d5f63fSdrh ** append a integer to the name so that it becomes unique. 120079d5f63fSdrh */ 12012564ef97Sdrh nName = strlen(zName); 120279d5f63fSdrh for(j=cnt=0; j<i; j++){ 120379d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 12042564ef97Sdrh zName[nName] = 0; 12051e536953Sdanielk1977 zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt); 120679d5f63fSdrh j = -1; 1207dd5b2fa5Sdrh if( zName==0 ) break; 120879d5f63fSdrh } 120979d5f63fSdrh } 121091bb0eedSdrh pCol->zName = zName; 1211e014a838Sdanielk1977 121279d5f63fSdrh /* Get the typename, type affinity, and collating sequence for the 121379d5f63fSdrh ** column. 121479d5f63fSdrh */ 1215c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1216b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 121717435752Sdrh zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); 1218290c1948Sdrh pCol->zType = zType; 1219c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1220b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1221b3bf556eSdanielk1977 if( pColl ){ 122217435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 12230202b29eSdanielk1977 } 122422f70c32Sdrh } 122522f70c32Sdrh pTab->iPKey = -1; 122622f70c32Sdrh return pTab; 122722f70c32Sdrh } 122822f70c32Sdrh 122922f70c32Sdrh /* 12309b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following 12319b3187e1Sdrh ** things: 1232d8bc7086Sdrh ** 12339b3187e1Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 12349b3187e1Sdrh ** element of the FROM clause. 12359b3187e1Sdrh ** 12369b3187e1Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 12379b3187e1Sdrh ** defines FROM clause. When views appear in the FROM clause, 123863eb5f29Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 123963eb5f29Sdrh ** that implements the view. A copy is made of the view's SELECT 124063eb5f29Sdrh ** statement so that we can freely modify or delete that statement 124163eb5f29Sdrh ** without worrying about messing up the presistent representation 124263eb5f29Sdrh ** of the view. 1243d8bc7086Sdrh ** 12449b3187e1Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 1245ad2d8307Sdrh ** on joins and the ON and USING clause of joins. 1246ad2d8307Sdrh ** 12479b3187e1Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 124854473229Sdrh ** for instances of the "*" operator or the TABLE.* operator. 124954473229Sdrh ** If found, expand each "*" to be every column in every table 125054473229Sdrh ** and TABLE.* to be every column in TABLE. 1251d8bc7086Sdrh ** 1252d8bc7086Sdrh ** Return 0 on success. If there are problems, leave an error message 1253d8bc7086Sdrh ** in pParse and return non-zero. 1254d8bc7086Sdrh */ 12559b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){ 125654473229Sdrh int i, j, k, rc; 1257ad3cab52Sdrh SrcList *pTabList; 1258daffd0e5Sdrh ExprList *pEList; 1259290c1948Sdrh struct SrcList_item *pFrom; 126017435752Sdrh sqlite3 *db = pParse->db; 1261daffd0e5Sdrh 126217435752Sdrh if( p==0 || p->pSrc==0 || db->mallocFailed ){ 12636f7adc8aSdrh return 1; 12646f7adc8aSdrh } 1265daffd0e5Sdrh pTabList = p->pSrc; 1266daffd0e5Sdrh pEList = p->pEList; 1267d8bc7086Sdrh 12689b3187e1Sdrh /* Make sure cursor numbers have been assigned to all entries in 12699b3187e1Sdrh ** the FROM clause of the SELECT statement. 12709b3187e1Sdrh */ 12719b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, p->pSrc); 12729b3187e1Sdrh 12739b3187e1Sdrh /* Look up every table named in the FROM clause of the select. If 12749b3187e1Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 12759b3187e1Sdrh ** then create a transient table structure to describe the subquery. 1276d8bc7086Sdrh */ 1277290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1278f0113000Sdanielk1977 Table *pTab; 12799b3187e1Sdrh if( pFrom->pTab!=0 ){ 12809b3187e1Sdrh /* This statement has already been prepared. There is no need 12819b3187e1Sdrh ** to go further. */ 12829b3187e1Sdrh assert( i==0 ); 1283d8bc7086Sdrh return 0; 1284d8bc7086Sdrh } 1285290c1948Sdrh if( pFrom->zName==0 ){ 128693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 128722f70c32Sdrh /* A sub-query in the FROM clause of a SELECT */ 1288290c1948Sdrh assert( pFrom->pSelect!=0 ); 1289290c1948Sdrh if( pFrom->zAlias==0 ){ 129091bb0eedSdrh pFrom->zAlias = 12911e536953Sdanielk1977 sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect); 1292ad2d8307Sdrh } 1293ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1294290c1948Sdrh pFrom->pTab = pTab = 1295290c1948Sdrh sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect); 129622f70c32Sdrh if( pTab==0 ){ 1297daffd0e5Sdrh return 1; 1298daffd0e5Sdrh } 1299b9bb7c18Sdrh /* The isEphem flag indicates that the Table structure has been 13005cf590c1Sdrh ** dynamically allocated and may be freed at any time. In other words, 13015cf590c1Sdrh ** pTab is not pointing to a persistent table structure that defines 13025cf590c1Sdrh ** part of the schema. */ 1303b9bb7c18Sdrh pTab->isEphem = 1; 130493758c8dSdanielk1977 #endif 130522f70c32Sdrh }else{ 1306a76b5dfcSdrh /* An ordinary table or view name in the FROM clause */ 1307ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1308290c1948Sdrh pFrom->pTab = pTab = 1309290c1948Sdrh sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase); 1310a76b5dfcSdrh if( pTab==0 ){ 1311d8bc7086Sdrh return 1; 1312d8bc7086Sdrh } 1313ed8a3bb1Sdrh pTab->nRef++; 131493626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 131593626f48Sdanielk1977 if( pTab->pSelect || IsVirtual(pTab) ){ 131663eb5f29Sdrh /* We reach here if the named table is a really a view */ 13174adee20fSdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 1318417be79cSdrh return 1; 1319417be79cSdrh } 1320290c1948Sdrh /* If pFrom->pSelect!=0 it means we are dealing with a 132163eb5f29Sdrh ** view within a view. The SELECT structure has already been 132263eb5f29Sdrh ** copied by the outer view so we can skip the copy step here 132363eb5f29Sdrh ** in the inner view. 132463eb5f29Sdrh */ 1325290c1948Sdrh if( pFrom->pSelect==0 ){ 132617435752Sdrh pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect); 1327a76b5dfcSdrh } 1328d8bc7086Sdrh } 132993758c8dSdanielk1977 #endif 133022f70c32Sdrh } 133163eb5f29Sdrh } 1332d8bc7086Sdrh 1333ad2d8307Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 1334ad2d8307Sdrh */ 1335ad2d8307Sdrh if( sqliteProcessJoin(pParse, p) ) return 1; 1336ad2d8307Sdrh 13377c917d19Sdrh /* For every "*" that occurs in the column list, insert the names of 133854473229Sdrh ** all columns in all tables. And for every TABLE.* insert the names 133954473229Sdrh ** of all columns in TABLE. The parser inserted a special expression 13407c917d19Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 13417c917d19Sdrh ** The following code just has to locate the TK_ALL expressions and expand 13427c917d19Sdrh ** each one to the list of all columns in all tables. 134354473229Sdrh ** 134454473229Sdrh ** The first loop just checks to see if there are any "*" operators 134554473229Sdrh ** that need expanding. 1346d8bc7086Sdrh */ 13477c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 134854473229Sdrh Expr *pE = pEList->a[k].pExpr; 134954473229Sdrh if( pE->op==TK_ALL ) break; 135054473229Sdrh if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 135154473229Sdrh && pE->pLeft && pE->pLeft->op==TK_ID ) break; 13527c917d19Sdrh } 135354473229Sdrh rc = 0; 13547c917d19Sdrh if( k<pEList->nExpr ){ 135554473229Sdrh /* 135654473229Sdrh ** If we get here it means the result set contains one or more "*" 135754473229Sdrh ** operators that need to be expanded. Loop through each expression 135854473229Sdrh ** in the result set and expand them one by one. 135954473229Sdrh */ 13607c917d19Sdrh struct ExprList_item *a = pEList->a; 13617c917d19Sdrh ExprList *pNew = 0; 1362d70dc52dSdrh int flags = pParse->db->flags; 1363d70dc52dSdrh int longNames = (flags & SQLITE_FullColNames)!=0 && 1364d70dc52dSdrh (flags & SQLITE_ShortColNames)==0; 1365d70dc52dSdrh 13667c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 136754473229Sdrh Expr *pE = a[k].pExpr; 136854473229Sdrh if( pE->op!=TK_ALL && 136954473229Sdrh (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 137054473229Sdrh /* This particular expression does not need to be expanded. 137154473229Sdrh */ 137217435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0); 1373261919ccSdanielk1977 if( pNew ){ 13747c917d19Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 1375261919ccSdanielk1977 }else{ 1376261919ccSdanielk1977 rc = 1; 1377261919ccSdanielk1977 } 13787c917d19Sdrh a[k].pExpr = 0; 13797c917d19Sdrh a[k].zName = 0; 13807c917d19Sdrh }else{ 138154473229Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 138254473229Sdrh ** expanded. */ 138354473229Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 1384cf55b7aeSdrh char *zTName; /* text of name of TABLE */ 138554473229Sdrh if( pE->op==TK_DOT && pE->pLeft ){ 138617435752Sdrh zTName = sqlite3NameFromToken(db, &pE->pLeft->token); 138754473229Sdrh }else{ 1388cf55b7aeSdrh zTName = 0; 138954473229Sdrh } 1390290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1391290c1948Sdrh Table *pTab = pFrom->pTab; 1392290c1948Sdrh char *zTabName = pFrom->zAlias; 139354473229Sdrh if( zTabName==0 || zTabName[0]==0 ){ 139454473229Sdrh zTabName = pTab->zName; 139554473229Sdrh } 1396cf55b7aeSdrh if( zTName && (zTabName==0 || zTabName[0]==0 || 1397cf55b7aeSdrh sqlite3StrICmp(zTName, zTabName)!=0) ){ 139854473229Sdrh continue; 139954473229Sdrh } 140054473229Sdrh tableSeen = 1; 1401d8bc7086Sdrh for(j=0; j<pTab->nCol; j++){ 1402f0113000Sdanielk1977 Expr *pExpr, *pRight; 1403ad2d8307Sdrh char *zName = pTab->aCol[j].zName; 1404ad2d8307Sdrh 1405034ca14fSdanielk1977 /* If a column is marked as 'hidden' (currently only possible 1406034ca14fSdanielk1977 ** for virtual tables), do not include it in the expanded 1407034ca14fSdanielk1977 ** result-set list. 1408034ca14fSdanielk1977 */ 1409034ca14fSdanielk1977 if( IsHiddenColumn(&pTab->aCol[j]) ){ 1410034ca14fSdanielk1977 assert(IsVirtual(pTab)); 1411034ca14fSdanielk1977 continue; 1412034ca14fSdanielk1977 } 1413034ca14fSdanielk1977 141491bb0eedSdrh if( i>0 ){ 141591bb0eedSdrh struct SrcList_item *pLeft = &pTabList->a[i-1]; 141661dfc31dSdrh if( (pLeft[1].jointype & JT_NATURAL)!=0 && 141791bb0eedSdrh columnIndex(pLeft->pTab, zName)>=0 ){ 1418ad2d8307Sdrh /* In a NATURAL join, omit the join columns from the 1419ad2d8307Sdrh ** table on the right */ 1420ad2d8307Sdrh continue; 1421ad2d8307Sdrh } 142261dfc31dSdrh if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){ 1423ad2d8307Sdrh /* In a join with a USING clause, omit columns in the 1424ad2d8307Sdrh ** using clause from the table on the right. */ 1425ad2d8307Sdrh continue; 1426ad2d8307Sdrh } 142791bb0eedSdrh } 1428a1644fd8Sdanielk1977 pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); 142922f70c32Sdrh if( pRight==0 ) break; 14301e536953Sdanielk1977 setQuotedToken(pParse, &pRight->token, zName); 1431d70dc52dSdrh if( zTabName && (longNames || pTabList->nSrc>1) ){ 1432a1644fd8Sdanielk1977 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); 1433a1644fd8Sdanielk1977 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 143422f70c32Sdrh if( pExpr==0 ) break; 14351e536953Sdanielk1977 setQuotedToken(pParse, &pLeft->token, zTabName); 14361e536953Sdanielk1977 setToken(&pExpr->span, 14371e536953Sdanielk1977 sqlite3MPrintf(db, "%s.%s", zTabName, zName)); 14386977fea8Sdrh pExpr->span.dyn = 1; 14396977fea8Sdrh pExpr->token.z = 0; 14406977fea8Sdrh pExpr->token.n = 0; 14416977fea8Sdrh pExpr->token.dyn = 0; 144222f70c32Sdrh }else{ 144322f70c32Sdrh pExpr = pRight; 14446977fea8Sdrh pExpr->span = pExpr->token; 1445f3b863edSdanielk1977 pExpr->span.dyn = 0; 144622f70c32Sdrh } 1447d70dc52dSdrh if( longNames ){ 144817435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span); 1449d70dc52dSdrh }else{ 145017435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token); 1451d8bc7086Sdrh } 1452d8bc7086Sdrh } 1453d70dc52dSdrh } 145454473229Sdrh if( !tableSeen ){ 1455cf55b7aeSdrh if( zTName ){ 1456cf55b7aeSdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 1457f5db2d3eSdrh }else{ 14584adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no tables specified"); 1459f5db2d3eSdrh } 146054473229Sdrh rc = 1; 146154473229Sdrh } 146217435752Sdrh sqlite3_free(zTName); 14637c917d19Sdrh } 14647c917d19Sdrh } 14654adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 14667c917d19Sdrh p->pEList = pNew; 1467d8bc7086Sdrh } 1468e5c941b8Sdrh if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){ 1469e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 1470e5c941b8Sdrh rc = SQLITE_ERROR; 1471e5c941b8Sdrh } 147217435752Sdrh if( db->mallocFailed ){ 1473f3b863edSdanielk1977 rc = SQLITE_NOMEM; 1474f3b863edSdanielk1977 } 147554473229Sdrh return rc; 1476d8bc7086Sdrh } 1477d8bc7086Sdrh 1478ff78bd2fSdrh /* 14799a99334dSdrh ** pE is a pointer to an expression which is a single term in 14809a99334dSdrh ** ORDER BY or GROUP BY clause. 1481d8bc7086Sdrh ** 14829a99334dSdrh ** If pE evaluates to an integer constant i, then return i. 14839a99334dSdrh ** This is an indication to the caller that it should sort 14849a99334dSdrh ** by the i-th column of the result set. 14859a99334dSdrh ** 14869a99334dSdrh ** If pE is a well-formed expression and the SELECT statement 14879a99334dSdrh ** is not compound, then return 0. This indicates to the 14889a99334dSdrh ** caller that it should sort by the value of the ORDER BY 14899a99334dSdrh ** expression. 14909a99334dSdrh ** 14919a99334dSdrh ** If the SELECT is compound, then attempt to match pE against 14929a99334dSdrh ** result set columns in the left-most SELECT statement. Return 14939a99334dSdrh ** the index i of the matching column, as an indication to the 14949a99334dSdrh ** caller that it should sort by the i-th column. If there is 14959a99334dSdrh ** no match, return -1 and leave an error message in pParse. 1496d8bc7086Sdrh */ 14979a99334dSdrh static int matchOrderByTermToExprList( 14989a99334dSdrh Parse *pParse, /* Parsing context for error messages */ 14999a99334dSdrh Select *pSelect, /* The SELECT statement with the ORDER BY clause */ 15009a99334dSdrh Expr *pE, /* The specific ORDER BY term */ 15019a99334dSdrh int idx, /* When ORDER BY term is this */ 15029a99334dSdrh int isCompound, /* True if this is a compound SELECT */ 15039a99334dSdrh u8 *pHasAgg /* True if expression contains aggregate functions */ 1504d8bc7086Sdrh ){ 15059a99334dSdrh int i; /* Loop counter */ 15069a99334dSdrh ExprList *pEList; /* The columns of the result set */ 15079a99334dSdrh NameContext nc; /* Name context for resolving pE */ 15089a99334dSdrh 15099a99334dSdrh 15109a99334dSdrh /* If the term is an integer constant, return the value of that 15119a99334dSdrh ** constant */ 15129a99334dSdrh pEList = pSelect->pEList; 15139a99334dSdrh if( sqlite3ExprIsInteger(pE, &i) ){ 15149a99334dSdrh if( i<=0 ){ 15159a99334dSdrh /* If i is too small, make it too big. That way the calling 15169a99334dSdrh ** function still sees a value that is out of range, but does 15179a99334dSdrh ** not confuse the column number with 0 or -1 result code. 15189a99334dSdrh */ 15199a99334dSdrh i = pEList->nExpr+1; 15209a99334dSdrh } 15219a99334dSdrh return i; 15229a99334dSdrh } 15239a99334dSdrh 15249a99334dSdrh /* If the term is a simple identifier that try to match that identifier 15259a99334dSdrh ** against a column name in the result set. 15269a99334dSdrh */ 15279a99334dSdrh if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){ 152817435752Sdrh sqlite3 *db = pParse->db; 15299a99334dSdrh char *zCol = sqlite3NameFromToken(db, &pE->token); 1530ef0bea92Sdrh if( zCol==0 ){ 15319a99334dSdrh return -1; 15329a99334dSdrh } 15339a99334dSdrh for(i=0; i<pEList->nExpr; i++){ 15349a99334dSdrh char *zAs = pEList->a[i].zName; 15359a99334dSdrh if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 15369a99334dSdrh sqlite3_free(zCol); 15379a99334dSdrh return i+1; 15389a99334dSdrh } 15399a99334dSdrh } 15409a99334dSdrh sqlite3_free(zCol); 15414c774314Sdrh } 154270517ab9Sdanielk1977 15439a99334dSdrh /* Resolve all names in the ORDER BY term expression 15449a99334dSdrh */ 154570517ab9Sdanielk1977 memset(&nc, 0, sizeof(nc)); 154670517ab9Sdanielk1977 nc.pParse = pParse; 15479a99334dSdrh nc.pSrcList = pSelect->pSrc; 154870517ab9Sdanielk1977 nc.pEList = pEList; 154970517ab9Sdanielk1977 nc.allowAgg = 1; 15504c774314Sdrh nc.nErr = 0; 15519a99334dSdrh if( sqlite3ExprResolveNames(&nc, pE) ){ 15521e281291Sdrh if( isCompound ){ 15531e281291Sdrh sqlite3ErrorClear(pParse); 15541e281291Sdrh return 0; 15551e281291Sdrh }else{ 15569a99334dSdrh return -1; 15579a99334dSdrh } 15581e281291Sdrh } 15599a99334dSdrh if( nc.hasAgg && pHasAgg ){ 15609a99334dSdrh *pHasAgg = 1; 15619a99334dSdrh } 15629a99334dSdrh 15639a99334dSdrh /* For a compound SELECT, we need to try to match the ORDER BY 15649a99334dSdrh ** expression against an expression in the result set 15659a99334dSdrh */ 15669a99334dSdrh if( isCompound ){ 15679a99334dSdrh for(i=0; i<pEList->nExpr; i++){ 15689a99334dSdrh if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){ 15699a99334dSdrh return i+1; 15709a99334dSdrh } 15719a99334dSdrh } 15724c774314Sdrh } 15731e281291Sdrh return 0; 157470517ab9Sdanielk1977 } 157570517ab9Sdanielk1977 15769a99334dSdrh 15779a99334dSdrh /* 15789a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement. 15799a99334dSdrh ** Return the number of errors seen. 15809a99334dSdrh ** 15819a99334dSdrh ** Every term of the ORDER BY or GROUP BY clause needs to be an 15829a99334dSdrh ** expression. If any expression is an integer constant, then 15839a99334dSdrh ** that expression is replaced by the corresponding 15849a99334dSdrh ** expression from the result set. 15859a99334dSdrh */ 15869a99334dSdrh static int processOrderGroupBy( 15879a99334dSdrh Parse *pParse, /* Parsing context. Leave error messages here */ 15889a99334dSdrh Select *pSelect, /* The SELECT statement containing the clause */ 15899a99334dSdrh ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 15909a99334dSdrh int isOrder, /* 1 for ORDER BY. 0 for GROUP BY */ 15919a99334dSdrh u8 *pHasAgg /* Set to TRUE if any term contains an aggregate */ 15929a99334dSdrh ){ 15939a99334dSdrh int i; 15949a99334dSdrh sqlite3 *db = pParse->db; 15959a99334dSdrh ExprList *pEList; 15969a99334dSdrh 1597*15cdbebeSdanielk1977 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; 15989a99334dSdrh if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ 15999a99334dSdrh const char *zType = isOrder ? "ORDER" : "GROUP"; 16009a99334dSdrh sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 16019a99334dSdrh return 1; 16029a99334dSdrh } 16039a99334dSdrh pEList = pSelect->pEList; 16049a99334dSdrh if( pEList==0 ){ 16059a99334dSdrh return 0; 16069a99334dSdrh } 16079a99334dSdrh for(i=0; i<pOrderBy->nExpr; i++){ 16089a99334dSdrh int iCol; 16099a99334dSdrh Expr *pE = pOrderBy->a[i].pExpr; 16109a99334dSdrh iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg); 161170517ab9Sdanielk1977 if( iCol<0 ){ 16129a99334dSdrh return 1; 16139a99334dSdrh } 16149a99334dSdrh if( iCol>pEList->nExpr ){ 16159a99334dSdrh const char *zType = isOrder ? "ORDER" : "GROUP"; 161670517ab9Sdanielk1977 sqlite3ErrorMsg(pParse, 16179a99334dSdrh "%r %s BY term out of range - should be " 16189a99334dSdrh "between 1 and %d", i+1, zType, pEList->nExpr); 16199a99334dSdrh return 1; 16209a99334dSdrh } 16219a99334dSdrh if( iCol>0 ){ 16229a99334dSdrh CollSeq *pColl = pE->pColl; 16239a99334dSdrh int flags = pE->flags & EP_ExpCollate; 16249a99334dSdrh sqlite3ExprDelete(pE); 16259a99334dSdrh pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr); 16269a99334dSdrh pOrderBy->a[i].pExpr = pE; 1627*15cdbebeSdanielk1977 if( pE && pColl && flags ){ 16289a99334dSdrh pE->pColl = pColl; 16299a99334dSdrh pE->flags |= flags; 16309a99334dSdrh } 16319a99334dSdrh } 16329a99334dSdrh } 16339a99334dSdrh return 0; 16349a99334dSdrh } 16359a99334dSdrh 16369a99334dSdrh /* 16379a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return 16389a99334dSdrh ** the number of errors seen. 16399a99334dSdrh ** 16409a99334dSdrh ** The processing depends on whether the SELECT is simple or compound. 16419a99334dSdrh ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY 16429a99334dSdrh ** clause needs to be an expression. If any expression is an integer 16439a99334dSdrh ** constant, then that expression is replaced by the corresponding 16449a99334dSdrh ** expression from the result set. 16459a99334dSdrh ** 16469a99334dSdrh ** For compound SELECT statements, every expression needs to be of 16479a99334dSdrh ** type TK_COLUMN with a iTable value as given in the 4th parameter. 16489a99334dSdrh ** If any expression is an integer, that becomes the column number. 16499a99334dSdrh ** Otherwise, match the expression against result set columns from 16509a99334dSdrh ** the left-most SELECT. 16519a99334dSdrh */ 16529a99334dSdrh static int processCompoundOrderBy( 16539a99334dSdrh Parse *pParse, /* Parsing context. Leave error messages here */ 16549a99334dSdrh Select *pSelect, /* The SELECT statement containing the ORDER BY */ 16559a99334dSdrh int iTable /* Output table for compound SELECT statements */ 16569a99334dSdrh ){ 16579a99334dSdrh int i; 16589a99334dSdrh ExprList *pOrderBy; 16599a99334dSdrh ExprList *pEList; 16601e281291Sdrh sqlite3 *db; 16611e281291Sdrh int moreToDo = 1; 16629a99334dSdrh 16639a99334dSdrh pOrderBy = pSelect->pOrderBy; 16649a99334dSdrh if( pOrderBy==0 ) return 0; 16659a99334dSdrh if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ 16669a99334dSdrh sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); 16679a99334dSdrh return 1; 16689a99334dSdrh } 16691e281291Sdrh db = pParse->db; 16701e281291Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 16711e281291Sdrh pOrderBy->a[i].done = 0; 16721e281291Sdrh } 16739a99334dSdrh while( pSelect->pPrior ){ 16749a99334dSdrh pSelect = pSelect->pPrior; 16759a99334dSdrh } 16761e281291Sdrh while( pSelect && moreToDo ){ 16771e281291Sdrh moreToDo = 0; 16789a99334dSdrh for(i=0; i<pOrderBy->nExpr; i++){ 16799a99334dSdrh int iCol; 16808f0ecaaeSdrh Expr *pE, *pDup; 16811e281291Sdrh if( pOrderBy->a[i].done ) continue; 16821e281291Sdrh pE = pOrderBy->a[i].pExpr; 16838f0ecaaeSdrh pDup = sqlite3ExprDup(db, pE); 16841e281291Sdrh if( pDup==0 ){ 16851e281291Sdrh return 1; 16861e281291Sdrh } 16871e281291Sdrh iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0); 16881e281291Sdrh sqlite3ExprDelete(pDup); 16899a99334dSdrh if( iCol<0 ){ 16909a99334dSdrh return 1; 16919a99334dSdrh } 16921e281291Sdrh pEList = pSelect->pEList; 16931e281291Sdrh if( pEList==0 ){ 16941e281291Sdrh return 1; 16951e281291Sdrh } 16969a99334dSdrh if( iCol>pEList->nExpr ){ 16979a99334dSdrh sqlite3ErrorMsg(pParse, 16989a99334dSdrh "%r ORDER BY term out of range - should be " 16999a99334dSdrh "between 1 and %d", i+1, pEList->nExpr); 17009a99334dSdrh return 1; 17019a99334dSdrh } 17021e281291Sdrh if( iCol>0 ){ 1703967e8b73Sdrh pE->op = TK_COLUMN; 1704d8bc7086Sdrh pE->iTable = iTable; 1705a58fdfb1Sdanielk1977 pE->iAgg = -1; 17069a99334dSdrh pE->iColumn = iCol-1; 17079a99334dSdrh pE->pTab = 0; 17081e281291Sdrh pOrderBy->a[i].done = 1; 17091e281291Sdrh }else{ 17101e281291Sdrh moreToDo = 1; 17111e281291Sdrh } 17121e281291Sdrh } 17131e281291Sdrh pSelect = pSelect->pNext; 17141e281291Sdrh } 17151e281291Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 17161e281291Sdrh if( pOrderBy->a[i].done==0 ){ 17171e281291Sdrh sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " 17181e281291Sdrh "column in the result set", i+1); 17191e281291Sdrh return 1; 17201e281291Sdrh } 172170517ab9Sdanielk1977 } 17229a99334dSdrh return 0; 1723d8bc7086Sdrh } 1724d8bc7086Sdrh 1725d8bc7086Sdrh /* 1726d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1727d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1728d8bc7086Sdrh */ 17294adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1730d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1731d8bc7086Sdrh if( v==0 ){ 17324adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1733949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE 1734949f9cd5Sdrh if( v ){ 1735949f9cd5Sdrh sqlite3VdbeAddOp0(v, OP_Trace); 1736949f9cd5Sdrh } 1737949f9cd5Sdrh #endif 1738d8bc7086Sdrh } 1739d8bc7086Sdrh return v; 1740d8bc7086Sdrh } 1741d8bc7086Sdrh 174215007a99Sdrh 1743d8bc7086Sdrh /* 17447b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1745ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 17467b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1747a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1748a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1749a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1750a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 17517b58daeaSdrh ** 1752d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1753ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 17547b58daeaSdrh ** iOffset should have been preset to appropriate default values 17557b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1756ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 17577b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 17587b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 17597b58daeaSdrh ** SELECT statements. 17607b58daeaSdrh */ 1761ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 176202afc861Sdrh Vdbe *v = 0; 176302afc861Sdrh int iLimit = 0; 176415007a99Sdrh int iOffset; 1765b7654111Sdrh int addr1; 176615007a99Sdrh 17677b58daeaSdrh /* 17687b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 17697b58daeaSdrh ** contraversy about what the correct behavior should be. 17707b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 17717b58daeaSdrh ** no rows. 17727b58daeaSdrh */ 1773a2dc3b1aSdanielk1977 if( p->pLimit ){ 17740a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 177515007a99Sdrh v = sqlite3GetVdbe(pParse); 17767b58daeaSdrh if( v==0 ) return; 1777b7654111Sdrh sqlite3ExprCode(pParse, p->pLimit, iLimit); 1778b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); 1779d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 17803c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); 17817b58daeaSdrh } 1782a2dc3b1aSdanielk1977 if( p->pOffset ){ 17830a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 1784b7654111Sdrh if( p->pLimit ){ 1785b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 1786b7654111Sdrh } 178715007a99Sdrh v = sqlite3GetVdbe(pParse); 17887b58daeaSdrh if( v==0 ) return; 1789b7654111Sdrh sqlite3ExprCode(pParse, p->pOffset, iOffset); 1790b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); 1791d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 17923c84ddffSdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); 1793b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); 179415007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 1795d59ba6ceSdrh if( p->pLimit ){ 1796b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1797d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 1798b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); 1799b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); 1800b7654111Sdrh sqlite3VdbeJumpHere(v, addr1); 1801b7654111Sdrh } 1802d59ba6ceSdrh } 18037b58daeaSdrh } 18047b58daeaSdrh 18057b58daeaSdrh /* 18060342b1f5Sdrh ** Allocate a virtual index to use for sorting. 1807d3d39e93Sdrh */ 18084db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){ 18090342b1f5Sdrh if( pOrderBy ){ 1810dc1bdc4fSdanielk1977 int addr; 18119d2985c7Sdrh assert( pOrderBy->iECursor==0 ); 18129d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 181366a5167bSdrh addr = sqlite3VdbeAddOp2(pParse->pVdbe, OP_OpenEphemeral, 18149d2985c7Sdrh pOrderBy->iECursor, pOrderBy->nExpr+1); 1815b9bb7c18Sdrh assert( p->addrOpenEphm[2] == -1 ); 1816b9bb7c18Sdrh p->addrOpenEphm[2] = addr; 1817736c22b8Sdrh } 1818dc1bdc4fSdanielk1977 } 1819dc1bdc4fSdanielk1977 1820b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1821fbc4ee7bSdrh /* 1822fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1823fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1824fbc4ee7bSdrh ** the column has no default collating sequence. 1825fbc4ee7bSdrh ** 1826fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1827fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1828fbc4ee7bSdrh */ 1829dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1830fbc4ee7bSdrh CollSeq *pRet; 1831dc1bdc4fSdanielk1977 if( p->pPrior ){ 1832dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1833fbc4ee7bSdrh }else{ 1834fbc4ee7bSdrh pRet = 0; 1835dc1bdc4fSdanielk1977 } 1836fbc4ee7bSdrh if( pRet==0 ){ 1837dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1838dc1bdc4fSdanielk1977 } 1839dc1bdc4fSdanielk1977 return pRet; 1840d3d39e93Sdrh } 1841b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1842d3d39e93Sdrh 1843b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1844d3d39e93Sdrh /* 184582c3d636Sdrh ** This routine is called to process a query that is really the union 184682c3d636Sdrh ** or intersection of two or more separate queries. 1847c926afbcSdrh ** 1848e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1849e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1850e78e8284Sdrh ** in which case this routine will be called recursively. 1851e78e8284Sdrh ** 1852e78e8284Sdrh ** The results of the total query are to be written into a destination 1853e78e8284Sdrh ** of type eDest with parameter iParm. 1854e78e8284Sdrh ** 1855e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1856e78e8284Sdrh ** 1857e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1858e78e8284Sdrh ** 1859e78e8284Sdrh ** This statement is parsed up as follows: 1860e78e8284Sdrh ** 1861e78e8284Sdrh ** SELECT c FROM t3 1862e78e8284Sdrh ** | 1863e78e8284Sdrh ** `-----> SELECT b FROM t2 1864e78e8284Sdrh ** | 18654b11c6d3Sjplyon ** `------> SELECT a FROM t1 1866e78e8284Sdrh ** 1867e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1868e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1869e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1870e78e8284Sdrh ** 1871e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1872e78e8284Sdrh ** individual selects always group from left to right. 187382c3d636Sdrh */ 187484ac9d02Sdanielk1977 static int multiSelect( 1875fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1876fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 18776c8c8ce0Sdanielk1977 SelectDest *pDest, /* What to do with query results */ 187884ac9d02Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 187984ac9d02Sdanielk1977 ){ 188084ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 188110e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 188210e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 18838cdbf836Sdrh int nCol; /* Number of columns in the result set */ 18840342b1f5Sdrh ExprList *pOrderBy; /* The ORDER BY clause on p */ 18850342b1f5Sdrh int aSetP2[2]; /* Set P2 value of these op to number of columns */ 18860342b1f5Sdrh int nSetP2 = 0; /* Number of slots in aSetP2[] used */ 18871013c932Sdrh SelectDest dest; /* Alternative data destination */ 188882c3d636Sdrh 18891013c932Sdrh dest = *pDest; 18906c8c8ce0Sdanielk1977 18917b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1892fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 189382c3d636Sdrh */ 189484ac9d02Sdanielk1977 if( p==0 || p->pPrior==0 ){ 189584ac9d02Sdanielk1977 rc = 1; 189684ac9d02Sdanielk1977 goto multi_select_end; 189784ac9d02Sdanielk1977 } 1898d8bc7086Sdrh pPrior = p->pPrior; 18990342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 19000342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1901d8bc7086Sdrh if( pPrior->pOrderBy ){ 19024adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1903da93d238Sdrh selectOpName(p->op)); 190484ac9d02Sdanielk1977 rc = 1; 190584ac9d02Sdanielk1977 goto multi_select_end; 190682c3d636Sdrh } 1907a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 19084adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 19097b58daeaSdrh selectOpName(p->op)); 191084ac9d02Sdanielk1977 rc = 1; 191184ac9d02Sdanielk1977 goto multi_select_end; 19127b58daeaSdrh } 191382c3d636Sdrh 1914d8bc7086Sdrh /* Make sure we have a valid query engine. If not, create a new one. 1915d8bc7086Sdrh */ 19164adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 191784ac9d02Sdanielk1977 if( v==0 ){ 191884ac9d02Sdanielk1977 rc = 1; 191984ac9d02Sdanielk1977 goto multi_select_end; 192084ac9d02Sdanielk1977 } 1921d8bc7086Sdrh 19221cc3d75fSdrh /* Create the destination temporary table if necessary 19231cc3d75fSdrh */ 19246c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 1925b4964b72Sdanielk1977 assert( p->pEList ); 19260342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 192766a5167bSdrh aSetP2[nSetP2++] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, 0); 19286c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 19291cc3d75fSdrh } 19301cc3d75fSdrh 1931f46f905aSdrh /* Generate code for the left and right SELECT statements. 1932d8bc7086Sdrh */ 19330342b1f5Sdrh pOrderBy = p->pOrderBy; 193482c3d636Sdrh switch( p->op ){ 1935f46f905aSdrh case TK_ALL: { 19360342b1f5Sdrh if( pOrderBy==0 ){ 1937ec7429aeSdrh int addr = 0; 1938a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1939a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1940a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 19416c8c8ce0Sdanielk1977 rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0, aff); 1942ad68cb6bSdanielk1977 p->pLimit = 0; 1943ad68cb6bSdanielk1977 p->pOffset = 0; 194484ac9d02Sdanielk1977 if( rc ){ 194584ac9d02Sdanielk1977 goto multi_select_end; 194684ac9d02Sdanielk1977 } 1947f46f905aSdrh p->pPrior = 0; 19487b58daeaSdrh p->iLimit = pPrior->iLimit; 19497b58daeaSdrh p->iOffset = pPrior->iOffset; 1950ec7429aeSdrh if( p->iLimit>=0 ){ 19513c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); 1952d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 1953ec7429aeSdrh } 19546c8c8ce0Sdanielk1977 rc = sqlite3Select(pParse, p, &dest, 0, 0, 0, aff); 1955f46f905aSdrh p->pPrior = pPrior; 195684ac9d02Sdanielk1977 if( rc ){ 195784ac9d02Sdanielk1977 goto multi_select_end; 195884ac9d02Sdanielk1977 } 1959ec7429aeSdrh if( addr ){ 1960ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1961ec7429aeSdrh } 1962f46f905aSdrh break; 1963f46f905aSdrh } 1964f46f905aSdrh /* For UNION ALL ... ORDER BY fall through to the next case */ 1965f46f905aSdrh } 196682c3d636Sdrh case TK_EXCEPT: 196782c3d636Sdrh case TK_UNION: { 1968d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1969742f947bSdanielk1977 int op = 0; /* One of the SRT_ operations to apply to self */ 1970d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1971a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1972dc1bdc4fSdanielk1977 int addr; 19736c8c8ce0Sdanielk1977 SelectDest uniondest; 197482c3d636Sdrh 1975d8bc7086Sdrh priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 19766c8c8ce0Sdanielk1977 if( dest.eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ 1977d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1978c926afbcSdrh ** right. 1979d8bc7086Sdrh */ 19806c8c8ce0Sdanielk1977 unionTab = dest.iParm; 198182c3d636Sdrh }else{ 1982d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1983d8bc7086Sdrh ** intermediate results. 1984d8bc7086Sdrh */ 198582c3d636Sdrh unionTab = pParse->nTab++; 19869a99334dSdrh if( processCompoundOrderBy(pParse, p, unionTab) ){ 198784ac9d02Sdanielk1977 rc = 1; 198884ac9d02Sdanielk1977 goto multi_select_end; 1989d8bc7086Sdrh } 199066a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 19910342b1f5Sdrh if( priorOp==SRT_Table ){ 19920342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 19930342b1f5Sdrh aSetP2[nSetP2++] = addr; 19940342b1f5Sdrh }else{ 1995b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1996b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 1997b9bb7c18Sdrh p->pRightmost->usesEphm = 1; 1998dc1bdc4fSdanielk1977 } 19990342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 200084ac9d02Sdanielk1977 assert( p->pEList ); 2001d8bc7086Sdrh } 2002d8bc7086Sdrh 2003d8bc7086Sdrh /* Code the SELECT statements to our left 2004d8bc7086Sdrh */ 2005b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 20061013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 20076c8c8ce0Sdanielk1977 rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0, aff); 200884ac9d02Sdanielk1977 if( rc ){ 200984ac9d02Sdanielk1977 goto multi_select_end; 201084ac9d02Sdanielk1977 } 2011d8bc7086Sdrh 2012d8bc7086Sdrh /* Code the current SELECT statement 2013d8bc7086Sdrh */ 2014d8bc7086Sdrh switch( p->op ){ 2015d8bc7086Sdrh case TK_EXCEPT: op = SRT_Except; break; 2016d8bc7086Sdrh case TK_UNION: op = SRT_Union; break; 2017d8bc7086Sdrh case TK_ALL: op = SRT_Table; break; 2018d8bc7086Sdrh } 201982c3d636Sdrh p->pPrior = 0; 2020c926afbcSdrh p->pOrderBy = 0; 20214b14b4d7Sdrh p->disallowOrderBy = pOrderBy!=0; 2022a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2023a2dc3b1aSdanielk1977 p->pLimit = 0; 2024a2dc3b1aSdanielk1977 pOffset = p->pOffset; 2025a2dc3b1aSdanielk1977 p->pOffset = 0; 20266c8c8ce0Sdanielk1977 uniondest.eDest = op; 20276c8c8ce0Sdanielk1977 rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0, aff); 20285bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 20295bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 20305bd1bf2eSdrh sqlite3ExprListDelete(p->pOrderBy); 203182c3d636Sdrh p->pPrior = pPrior; 2032c926afbcSdrh p->pOrderBy = pOrderBy; 2033a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 2034a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2035a2dc3b1aSdanielk1977 p->pOffset = pOffset; 2036be5fd490Sdrh p->iLimit = -1; 2037be5fd490Sdrh p->iOffset = -1; 203884ac9d02Sdanielk1977 if( rc ){ 203984ac9d02Sdanielk1977 goto multi_select_end; 204084ac9d02Sdanielk1977 } 204184ac9d02Sdanielk1977 2042d8bc7086Sdrh 2043d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2044d8bc7086Sdrh ** it is that we currently need. 2045d8bc7086Sdrh */ 20466c8c8ce0Sdanielk1977 if( dest.eDest!=priorOp || unionTab!=dest.iParm ){ 20476b56344dSdrh int iCont, iBreak, iStart; 204882c3d636Sdrh assert( p->pEList ); 20496c8c8ce0Sdanielk1977 if( dest.eDest==SRT_Callback ){ 205092378253Sdrh Select *pFirst = p; 205192378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 205292378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 205341202ccaSdrh } 20544adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 20554adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2056ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 205766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); 20584adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 2059d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 20606c8c8ce0Sdanielk1977 pOrderBy, -1, &dest, iCont, iBreak, 0); 20614adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 206266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); 20634adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 206466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 206582c3d636Sdrh } 206682c3d636Sdrh break; 206782c3d636Sdrh } 206882c3d636Sdrh case TK_INTERSECT: { 206982c3d636Sdrh int tab1, tab2; 20706b56344dSdrh int iCont, iBreak, iStart; 2071a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 2072dc1bdc4fSdanielk1977 int addr; 20731013c932Sdrh SelectDest intersectdest; 20749cbf3425Sdrh int r1; 207582c3d636Sdrh 2076d8bc7086Sdrh /* INTERSECT is different from the others since it requires 20776206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2078d8bc7086Sdrh ** by allocating the tables we will need. 2079d8bc7086Sdrh */ 208082c3d636Sdrh tab1 = pParse->nTab++; 208182c3d636Sdrh tab2 = pParse->nTab++; 20829a99334dSdrh if( processCompoundOrderBy(pParse, p, tab1) ){ 208384ac9d02Sdanielk1977 rc = 1; 208484ac9d02Sdanielk1977 goto multi_select_end; 2085d8bc7086Sdrh } 20860342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 2087dc1bdc4fSdanielk1977 208866a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2089b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2090b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2091b9bb7c18Sdrh p->pRightmost->usesEphm = 1; 209284ac9d02Sdanielk1977 assert( p->pEList ); 2093d8bc7086Sdrh 2094d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2095d8bc7086Sdrh */ 20961013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 20976c8c8ce0Sdanielk1977 rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0, aff); 209884ac9d02Sdanielk1977 if( rc ){ 209984ac9d02Sdanielk1977 goto multi_select_end; 210084ac9d02Sdanielk1977 } 2101d8bc7086Sdrh 2102d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2103d8bc7086Sdrh */ 210466a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2105b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2106b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 210782c3d636Sdrh p->pPrior = 0; 2108a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2109a2dc3b1aSdanielk1977 p->pLimit = 0; 2110a2dc3b1aSdanielk1977 pOffset = p->pOffset; 2111a2dc3b1aSdanielk1977 p->pOffset = 0; 21126c8c8ce0Sdanielk1977 intersectdest.iParm = tab2; 21136c8c8ce0Sdanielk1977 rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0, aff); 211482c3d636Sdrh p->pPrior = pPrior; 2115a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 2116a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2117a2dc3b1aSdanielk1977 p->pOffset = pOffset; 211884ac9d02Sdanielk1977 if( rc ){ 211984ac9d02Sdanielk1977 goto multi_select_end; 212084ac9d02Sdanielk1977 } 2121d8bc7086Sdrh 2122d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 2123d8bc7086Sdrh ** tables. 2124d8bc7086Sdrh */ 212582c3d636Sdrh assert( p->pEList ); 21266c8c8ce0Sdanielk1977 if( dest.eDest==SRT_Callback ){ 212792378253Sdrh Select *pFirst = p; 212892378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 212992378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 213041202ccaSdrh } 21314adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 21324adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2133ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 213466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); 21359cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 21369cbf3425Sdrh iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 21379cbf3425Sdrh sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1); 21389cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 2139d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 21406c8c8ce0Sdanielk1977 pOrderBy, -1, &dest, iCont, iBreak, 0); 21414adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 214266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); 21434adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 214466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 214566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 214682c3d636Sdrh break; 214782c3d636Sdrh } 214882c3d636Sdrh } 21498cdbf836Sdrh 21508cdbf836Sdrh /* Make sure all SELECTs in the statement have the same number of elements 21518cdbf836Sdrh ** in their result sets. 21528cdbf836Sdrh */ 215382c3d636Sdrh assert( p->pEList && pPrior->pEList ); 215482c3d636Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 21554adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 2156da93d238Sdrh " do not have the same number of result columns", selectOpName(p->op)); 215784ac9d02Sdanielk1977 rc = 1; 215884ac9d02Sdanielk1977 goto multi_select_end; 21592282792aSdrh } 216084ac9d02Sdanielk1977 21618cdbf836Sdrh /* Set the number of columns in temporary tables 21628cdbf836Sdrh */ 21638cdbf836Sdrh nCol = p->pEList->nExpr; 21640342b1f5Sdrh while( nSetP2 ){ 21650342b1f5Sdrh sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol); 21668cdbf836Sdrh } 21678cdbf836Sdrh 2168fbc4ee7bSdrh /* Compute collating sequences used by either the ORDER BY clause or 2169fbc4ee7bSdrh ** by any temporary tables needed to implement the compound select. 2170fbc4ee7bSdrh ** Attach the KeyInfo structure to all temporary tables. Invoke the 2171fbc4ee7bSdrh ** ORDER BY processing if there is an ORDER BY clause. 21728cdbf836Sdrh ** 21738cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 21748cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 21758cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 21768cdbf836Sdrh ** no temp tables are required. 2177fbc4ee7bSdrh */ 2178b9bb7c18Sdrh if( pOrderBy || p->usesEphm ){ 2179fbc4ee7bSdrh int i; /* Loop counter */ 2180fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 21810342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 21821e31e0b2Sdrh int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */ 2183f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 2184f68d7d17Sdrh CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */ 2185fbc4ee7bSdrh 21860342b1f5Sdrh assert( p->pRightmost==p ); 21871e31e0b2Sdrh nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0); 218817435752Sdrh pKeyInfo = sqlite3DbMallocZero(pParse->db, 218917435752Sdrh sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1)); 2190dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 2191dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 2192dc1bdc4fSdanielk1977 goto multi_select_end; 2193dc1bdc4fSdanielk1977 } 2194dc1bdc4fSdanielk1977 219514db2665Sdanielk1977 pKeyInfo->enc = ENC(pParse->db); 2196dc1bdc4fSdanielk1977 pKeyInfo->nField = nCol; 2197dc1bdc4fSdanielk1977 21980342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 21990342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 22000342b1f5Sdrh if( 0==*apColl ){ 22010342b1f5Sdrh *apColl = pParse->db->pDfltColl; 2202dc1bdc4fSdanielk1977 } 2203dc1bdc4fSdanielk1977 } 2204dc1bdc4fSdanielk1977 22050342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 22060342b1f5Sdrh for(i=0; i<2; i++){ 2207b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 22080342b1f5Sdrh if( addr<0 ){ 22090342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 22100342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 2211b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 22120342b1f5Sdrh break; 22130342b1f5Sdrh } 22140342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 221566a5167bSdrh sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); 22160ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 22170342b1f5Sdrh } 2218dc1bdc4fSdanielk1977 } 2219dc1bdc4fSdanielk1977 22200342b1f5Sdrh if( pOrderBy ){ 22210342b1f5Sdrh struct ExprList_item *pOTerm = pOrderBy->a; 22224efc083fSdrh int nOrderByExpr = pOrderBy->nExpr; 22230342b1f5Sdrh int addr; 22244db38a70Sdrh u8 *pSortOrder; 22250342b1f5Sdrh 2226f68d7d17Sdrh /* Reuse the same pKeyInfo for the ORDER BY as was used above for 2227f68d7d17Sdrh ** the compound select statements. Except we have to change out the 2228f68d7d17Sdrh ** pKeyInfo->aColl[] values. Some of the aColl[] values will be 2229f68d7d17Sdrh ** reused when constructing the pKeyInfo for the ORDER BY, so make 2230f68d7d17Sdrh ** a copy. Sufficient space to hold both the nCol entries for 2231f68d7d17Sdrh ** the compound select and the nOrderbyExpr entries for the ORDER BY 2232f68d7d17Sdrh ** was allocated above. But we need to move the compound select 2233f68d7d17Sdrh ** entries out of the way before constructing the ORDER BY entries. 2234f68d7d17Sdrh ** Move the compound select entries into aCopy[] where they can be 2235f68d7d17Sdrh ** accessed and reused when constructing the ORDER BY entries. 2236f68d7d17Sdrh ** Because nCol might be greater than or less than nOrderByExpr 2237f68d7d17Sdrh ** we have to use memmove() when doing the copy. 2238f68d7d17Sdrh */ 22391e31e0b2Sdrh aCopy = &pKeyInfo->aColl[nOrderByExpr]; 22404efc083fSdrh pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol]; 2241f68d7d17Sdrh memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*)); 2242f68d7d17Sdrh 22430342b1f5Sdrh apColl = pKeyInfo->aColl; 22444efc083fSdrh for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){ 22450342b1f5Sdrh Expr *pExpr = pOTerm->pExpr; 22468b4c40d8Sdrh if( (pExpr->flags & EP_ExpCollate) ){ 22478b4c40d8Sdrh assert( pExpr->pColl!=0 ); 22488b4c40d8Sdrh *apColl = pExpr->pColl; 224984ac9d02Sdanielk1977 }else{ 22500342b1f5Sdrh *apColl = aCopy[pExpr->iColumn]; 225184ac9d02Sdanielk1977 } 22524db38a70Sdrh *pSortOrder = pOTerm->sortOrder; 225384ac9d02Sdanielk1977 } 22540342b1f5Sdrh assert( p->pRightmost==p ); 2255b9bb7c18Sdrh assert( p->addrOpenEphm[2]>=0 ); 2256b9bb7c18Sdrh addr = p->addrOpenEphm[2]; 2257a670b226Sdanielk1977 sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2); 22584efc083fSdrh pKeyInfo->nField = nOrderByExpr; 225966a5167bSdrh sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 22604db38a70Sdrh pKeyInfo = 0; 22616c8c8ce0Sdanielk1977 generateSortTail(pParse, p, v, p->pEList->nExpr, &dest); 2262dc1bdc4fSdanielk1977 } 2263dc1bdc4fSdanielk1977 226417435752Sdrh sqlite3_free(pKeyInfo); 2265dc1bdc4fSdanielk1977 } 2266dc1bdc4fSdanielk1977 2267dc1bdc4fSdanielk1977 multi_select_end: 22681013c932Sdrh pDest->iMem = dest.iMem; 226984ac9d02Sdanielk1977 return rc; 22702282792aSdrh } 2271b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 22722282792aSdrh 2273b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 227417435752Sdrh /* Forward Declarations */ 227517435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*); 227617435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *); 227717435752Sdrh 22782282792aSdrh /* 2279832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 22806a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 228184e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 22826a3ea0e6Sdrh ** unchanged.) 2283832508b7Sdrh ** 2284832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 2285832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 2286832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 2287832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 2288832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 2289832508b7Sdrh ** of the subquery rather the result set of the subquery. 2290832508b7Sdrh */ 229117435752Sdrh static void substExpr( 229217435752Sdrh sqlite3 *db, /* Report malloc errors to this connection */ 229317435752Sdrh Expr *pExpr, /* Expr in which substitution occurs */ 229417435752Sdrh int iTable, /* Table to be substituted */ 229517435752Sdrh ExprList *pEList /* Substitute expressions */ 229617435752Sdrh ){ 2297832508b7Sdrh if( pExpr==0 ) return; 229850350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 229950350a15Sdrh if( pExpr->iColumn<0 ){ 230050350a15Sdrh pExpr->op = TK_NULL; 230150350a15Sdrh }else{ 2302832508b7Sdrh Expr *pNew; 230384e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 2304832508b7Sdrh assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 2305832508b7Sdrh pNew = pEList->a[pExpr->iColumn].pExpr; 2306832508b7Sdrh assert( pNew!=0 ); 2307832508b7Sdrh pExpr->op = pNew->op; 2308d94a6698Sdrh assert( pExpr->pLeft==0 ); 230917435752Sdrh pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft); 2310d94a6698Sdrh assert( pExpr->pRight==0 ); 231117435752Sdrh pExpr->pRight = sqlite3ExprDup(db, pNew->pRight); 2312d94a6698Sdrh assert( pExpr->pList==0 ); 231317435752Sdrh pExpr->pList = sqlite3ExprListDup(db, pNew->pList); 2314832508b7Sdrh pExpr->iTable = pNew->iTable; 2315fbbe005aSdanielk1977 pExpr->pTab = pNew->pTab; 2316832508b7Sdrh pExpr->iColumn = pNew->iColumn; 2317832508b7Sdrh pExpr->iAgg = pNew->iAgg; 231817435752Sdrh sqlite3TokenCopy(db, &pExpr->token, &pNew->token); 231917435752Sdrh sqlite3TokenCopy(db, &pExpr->span, &pNew->span); 232017435752Sdrh pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect); 2321a1cb183dSdanielk1977 pExpr->flags = pNew->flags; 232250350a15Sdrh } 2323832508b7Sdrh }else{ 232417435752Sdrh substExpr(db, pExpr->pLeft, iTable, pEList); 232517435752Sdrh substExpr(db, pExpr->pRight, iTable, pEList); 232617435752Sdrh substSelect(db, pExpr->pSelect, iTable, pEList); 232717435752Sdrh substExprList(db, pExpr->pList, iTable, pEList); 2328832508b7Sdrh } 2329832508b7Sdrh } 233017435752Sdrh static void substExprList( 233117435752Sdrh sqlite3 *db, /* Report malloc errors here */ 233217435752Sdrh ExprList *pList, /* List to scan and in which to make substitutes */ 233317435752Sdrh int iTable, /* Table to be substituted */ 233417435752Sdrh ExprList *pEList /* Substitute values */ 233517435752Sdrh ){ 2336832508b7Sdrh int i; 2337832508b7Sdrh if( pList==0 ) return; 2338832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 233917435752Sdrh substExpr(db, pList->a[i].pExpr, iTable, pEList); 2340832508b7Sdrh } 2341832508b7Sdrh } 234217435752Sdrh static void substSelect( 234317435752Sdrh sqlite3 *db, /* Report malloc errors here */ 234417435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 234517435752Sdrh int iTable, /* Table to be replaced */ 234617435752Sdrh ExprList *pEList /* Substitute values */ 234717435752Sdrh ){ 2348b3bce662Sdanielk1977 if( !p ) return; 234917435752Sdrh substExprList(db, p->pEList, iTable, pEList); 235017435752Sdrh substExprList(db, p->pGroupBy, iTable, pEList); 235117435752Sdrh substExprList(db, p->pOrderBy, iTable, pEList); 235217435752Sdrh substExpr(db, p->pHaving, iTable, pEList); 235317435752Sdrh substExpr(db, p->pWhere, iTable, pEList); 235417435752Sdrh substSelect(db, p->pPrior, iTable, pEList); 2355b3bce662Sdanielk1977 } 2356b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */ 2357832508b7Sdrh 2358b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 2359832508b7Sdrh /* 23601350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 23611350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 23621350b030Sdrh ** occurs. 23631350b030Sdrh ** 23641350b030Sdrh ** To understand the concept of flattening, consider the following 23651350b030Sdrh ** query: 23661350b030Sdrh ** 23671350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 23681350b030Sdrh ** 23691350b030Sdrh ** The default way of implementing this query is to execute the 23701350b030Sdrh ** subquery first and store the results in a temporary table, then 23711350b030Sdrh ** run the outer query on that temporary table. This requires two 23721350b030Sdrh ** passes over the data. Furthermore, because the temporary table 23731350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 2374832508b7Sdrh ** optimized. 23751350b030Sdrh ** 2376832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 23771350b030Sdrh ** a single flat select, like this: 23781350b030Sdrh ** 23791350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 23801350b030Sdrh ** 23811350b030Sdrh ** The code generated for this simpification gives the same result 2382832508b7Sdrh ** but only has to scan the data once. And because indices might 2383832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 2384832508b7Sdrh ** avoided. 23851350b030Sdrh ** 2386832508b7Sdrh ** Flattening is only attempted if all of the following are true: 23871350b030Sdrh ** 2388832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 23891350b030Sdrh ** 2390832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 2391832508b7Sdrh ** 23928af4d3acSdrh ** (3) The subquery is not the right operand of a left outer join, or 23938af4d3acSdrh ** the subquery is not itself a join. (Ticket #306) 2394832508b7Sdrh ** 2395832508b7Sdrh ** (4) The subquery is not DISTINCT or the outer query is not a join. 2396832508b7Sdrh ** 2397832508b7Sdrh ** (5) The subquery is not DISTINCT or the outer query does not use 2398832508b7Sdrh ** aggregates. 2399832508b7Sdrh ** 2400832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 2401832508b7Sdrh ** DISTINCT. 2402832508b7Sdrh ** 240308192d5fSdrh ** (7) The subquery has a FROM clause. 240408192d5fSdrh ** 2405df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 2406df199a25Sdrh ** 2407df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 2408df199a25Sdrh ** aggregates. 2409df199a25Sdrh ** 2410df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 2411df199a25Sdrh ** use LIMIT. 2412df199a25Sdrh ** 2413174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 2414174b6195Sdrh ** 24153fc673e6Sdrh ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 24163fc673e6Sdrh ** subquery has no WHERE clause. (added by ticket #350) 24173fc673e6Sdrh ** 2418ac83963aSdrh ** (13) The subquery and outer query do not both use LIMIT 2419ac83963aSdrh ** 2420ac83963aSdrh ** (14) The subquery does not use OFFSET 2421ac83963aSdrh ** 2422ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 2423ad91c6cdSdrh ** subquery does not have both an ORDER BY and a LIMIT clause. 2424ad91c6cdSdrh ** (See ticket #2339) 2425ad91c6cdSdrh ** 2426832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 2427832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2428832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2429832508b7Sdrh ** 2430665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 2431832508b7Sdrh ** If flattening is attempted this routine returns 1. 2432832508b7Sdrh ** 2433832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 2434832508b7Sdrh ** the subquery before this routine runs. 24351350b030Sdrh */ 24368c74a8caSdrh static int flattenSubquery( 243717435752Sdrh sqlite3 *db, /* Database connection */ 24388c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 24398c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 24408c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 24418c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 24428c74a8caSdrh ){ 24430bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2444ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2445ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 24460bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 24476a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 244891bb0eedSdrh int i; /* Loop counter */ 244991bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 245091bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 24511350b030Sdrh 2452832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2453832508b7Sdrh */ 2454832508b7Sdrh if( p==0 ) return 0; 2455832508b7Sdrh pSrc = p->pSrc; 2456ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 245791bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 245891bb0eedSdrh pSub = pSubitem->pSelect; 2459832508b7Sdrh assert( pSub!=0 ); 2460ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2461ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2462832508b7Sdrh pSubSrc = pSub->pSrc; 2463832508b7Sdrh assert( pSubSrc ); 2464ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2465ac83963aSdrh ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2466ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 2467ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 2468ac83963aSdrh ** and (14). */ 2469ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2470ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 2471ad91c6cdSdrh if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){ 2472ad91c6cdSdrh return 0; /* Restriction (15) */ 2473ad91c6cdSdrh } 2474ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 2475ac83963aSdrh if( (pSub->isDistinct || pSub->pLimit) 2476ac83963aSdrh && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */ 2477df199a25Sdrh return 0; 2478df199a25Sdrh } 2479ac83963aSdrh if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */ 2480ac83963aSdrh if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){ 2481ac83963aSdrh return 0; /* Restriction (11) */ 2482ac83963aSdrh } 2483832508b7Sdrh 24848af4d3acSdrh /* Restriction 3: If the subquery is a join, make sure the subquery is 24858af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 24868af4d3acSdrh ** is not allowed: 24878af4d3acSdrh ** 24888af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 24898af4d3acSdrh ** 24908af4d3acSdrh ** If we flatten the above, we would get 24918af4d3acSdrh ** 24928af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 24938af4d3acSdrh ** 24948af4d3acSdrh ** which is not at all the same thing. 24958af4d3acSdrh */ 249661dfc31dSdrh if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){ 24978af4d3acSdrh return 0; 24988af4d3acSdrh } 24998af4d3acSdrh 25003fc673e6Sdrh /* Restriction 12: If the subquery is the right operand of a left outer 25013fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 25023fc673e6Sdrh ** An examples of why this is not allowed: 25033fc673e6Sdrh ** 25043fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 25053fc673e6Sdrh ** 25063fc673e6Sdrh ** If we flatten the above, we would get 25073fc673e6Sdrh ** 25083fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 25093fc673e6Sdrh ** 25103fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 25113fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 25123fc673e6Sdrh */ 251361dfc31dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){ 25143fc673e6Sdrh return 0; 25153fc673e6Sdrh } 25163fc673e6Sdrh 25170bb28106Sdrh /* If we reach this point, it means flattening is permitted for the 251863eb5f29Sdrh ** iFrom-th entry of the FROM clause in the outer query. 2519832508b7Sdrh */ 2520c31c2eb8Sdrh 2521c31c2eb8Sdrh /* Move all of the FROM elements of the subquery into the 2522c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2523c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2524c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2525c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2526c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2527c31c2eb8Sdrh ** elements we are now copying in. 2528c31c2eb8Sdrh */ 252991bb0eedSdrh iParent = pSubitem->iCursor; 2530c31c2eb8Sdrh { 2531c31c2eb8Sdrh int nSubSrc = pSubSrc->nSrc; 253291bb0eedSdrh int jointype = pSubitem->jointype; 2533c31c2eb8Sdrh 2534a04a34ffSdanielk1977 sqlite3DeleteTable(pSubitem->pTab); 253517435752Sdrh sqlite3_free(pSubitem->zDatabase); 253617435752Sdrh sqlite3_free(pSubitem->zName); 253717435752Sdrh sqlite3_free(pSubitem->zAlias); 2538cfa063b3Sdrh pSubitem->pTab = 0; 2539cfa063b3Sdrh pSubitem->zDatabase = 0; 2540cfa063b3Sdrh pSubitem->zName = 0; 2541cfa063b3Sdrh pSubitem->zAlias = 0; 2542c31c2eb8Sdrh if( nSubSrc>1 ){ 2543c31c2eb8Sdrh int extra = nSubSrc - 1; 2544c31c2eb8Sdrh for(i=1; i<nSubSrc; i++){ 254517435752Sdrh pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0); 2546cfa063b3Sdrh if( pSrc==0 ){ 2547cfa063b3Sdrh p->pSrc = 0; 2548cfa063b3Sdrh return 1; 2549cfa063b3Sdrh } 2550c31c2eb8Sdrh } 2551c31c2eb8Sdrh p->pSrc = pSrc; 2552c31c2eb8Sdrh for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 2553c31c2eb8Sdrh pSrc->a[i] = pSrc->a[i-extra]; 2554c31c2eb8Sdrh } 2555c31c2eb8Sdrh } 2556c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2557c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2558c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2559c31c2eb8Sdrh } 256061dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 2561c31c2eb8Sdrh } 2562c31c2eb8Sdrh 2563c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2564c31c2eb8Sdrh ** references to the iParent in the outer query. 2565c31c2eb8Sdrh ** 2566c31c2eb8Sdrh ** Example: 2567c31c2eb8Sdrh ** 2568c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2569c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 2570c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 2571c31c2eb8Sdrh ** 2572c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 2573c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2574c31c2eb8Sdrh */ 2575832508b7Sdrh pList = p->pEList; 2576832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 25776977fea8Sdrh Expr *pExpr; 25786977fea8Sdrh if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 257917435752Sdrh pList->a[i].zName = 258017435752Sdrh sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n); 2581832508b7Sdrh } 2582832508b7Sdrh } 25831e536953Sdanielk1977 substExprList(db, p->pEList, iParent, pSub->pEList); 25841b2e0329Sdrh if( isAgg ){ 25851e536953Sdanielk1977 substExprList(db, p->pGroupBy, iParent, pSub->pEList); 25861e536953Sdanielk1977 substExpr(db, p->pHaving, iParent, pSub->pEList); 25871b2e0329Sdrh } 2588174b6195Sdrh if( pSub->pOrderBy ){ 2589174b6195Sdrh assert( p->pOrderBy==0 ); 2590174b6195Sdrh p->pOrderBy = pSub->pOrderBy; 2591174b6195Sdrh pSub->pOrderBy = 0; 2592174b6195Sdrh }else if( p->pOrderBy ){ 25931e536953Sdanielk1977 substExprList(db, p->pOrderBy, iParent, pSub->pEList); 2594174b6195Sdrh } 2595832508b7Sdrh if( pSub->pWhere ){ 259617435752Sdrh pWhere = sqlite3ExprDup(db, pSub->pWhere); 2597832508b7Sdrh }else{ 2598832508b7Sdrh pWhere = 0; 2599832508b7Sdrh } 2600832508b7Sdrh if( subqueryIsAgg ){ 2601832508b7Sdrh assert( p->pHaving==0 ); 26021b2e0329Sdrh p->pHaving = p->pWhere; 26031b2e0329Sdrh p->pWhere = pWhere; 26041e536953Sdanielk1977 substExpr(db, p->pHaving, iParent, pSub->pEList); 260517435752Sdrh p->pHaving = sqlite3ExprAnd(db, p->pHaving, 260617435752Sdrh sqlite3ExprDup(db, pSub->pHaving)); 26071b2e0329Sdrh assert( p->pGroupBy==0 ); 260817435752Sdrh p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy); 2609832508b7Sdrh }else{ 26101e536953Sdanielk1977 substExpr(db, p->pWhere, iParent, pSub->pEList); 261117435752Sdrh p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere); 2612832508b7Sdrh } 2613c31c2eb8Sdrh 2614c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 2615c31c2eb8Sdrh ** outer query is distinct. 2616c31c2eb8Sdrh */ 2617832508b7Sdrh p->isDistinct = p->isDistinct || pSub->isDistinct; 26188c74a8caSdrh 2619a58fdfb1Sdanielk1977 /* 2620a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 2621ac83963aSdrh ** 2622ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 2623ac83963aSdrh ** does not work if either limit is negative. 2624a58fdfb1Sdanielk1977 */ 2625a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 2626a2dc3b1aSdanielk1977 p->pLimit = pSub->pLimit; 2627a2dc3b1aSdanielk1977 pSub->pLimit = 0; 2628df199a25Sdrh } 26298c74a8caSdrh 2630c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 2631c31c2eb8Sdrh ** success. 2632c31c2eb8Sdrh */ 26334adee20fSdanielk1977 sqlite3SelectDelete(pSub); 2634832508b7Sdrh return 1; 26351350b030Sdrh } 2636b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 26371350b030Sdrh 26381350b030Sdrh /* 2639a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it 2640a9d1ccb9Sdanielk1977 ** is a min() or max() query. Return ORDERBY_MIN or ORDERBY_MAX if 2641a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be 2642a9d1ccb9Sdanielk1977 ** a min()/max() query if: 2643a9d1ccb9Sdanielk1977 ** 2644738bdcfbSdanielk1977 ** 1. There is a single object in the FROM clause. 2645738bdcfbSdanielk1977 ** 2646738bdcfbSdanielk1977 ** 2. There is a single expression in the result set, and it is 2647738bdcfbSdanielk1977 ** either min(x) or max(x), where x is a column reference. 2648a9d1ccb9Sdanielk1977 */ 2649a9d1ccb9Sdanielk1977 static int minMaxQuery(Parse *pParse, Select *p){ 2650a9d1ccb9Sdanielk1977 Expr *pExpr; 2651a9d1ccb9Sdanielk1977 ExprList *pEList = p->pEList; 2652a9d1ccb9Sdanielk1977 2653a9d1ccb9Sdanielk1977 if( pEList->nExpr!=1 ) return ORDERBY_NORMAL; 2654a9d1ccb9Sdanielk1977 pExpr = pEList->a[0].pExpr; 2655a9d1ccb9Sdanielk1977 pEList = pExpr->pList; 2656a9d1ccb9Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0; 2657a9d1ccb9Sdanielk1977 if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return ORDERBY_NORMAL; 2658a9d1ccb9Sdanielk1977 if( pExpr->token.n!=3 ) return ORDERBY_NORMAL; 2659a9d1ccb9Sdanielk1977 if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ 2660a9d1ccb9Sdanielk1977 return ORDERBY_MIN; 2661a9d1ccb9Sdanielk1977 }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ 2662a9d1ccb9Sdanielk1977 return ORDERBY_MAX; 2663a9d1ccb9Sdanielk1977 } 2664a9d1ccb9Sdanielk1977 return ORDERBY_NORMAL; 2665a9d1ccb9Sdanielk1977 } 2666a9d1ccb9Sdanielk1977 2667a9d1ccb9Sdanielk1977 /* 2668b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the 2669b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved 2670b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext 2671b3bce662Sdanielk1977 ** of the parent SELECT. 2672b3bce662Sdanielk1977 */ 2673b3bce662Sdanielk1977 int sqlite3SelectResolve( 2674b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 2675b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 2676b3bce662Sdanielk1977 NameContext *pOuterNC /* The outer name context. May be NULL. */ 2677b3bce662Sdanielk1977 ){ 2678b3bce662Sdanielk1977 ExprList *pEList; /* Result set. */ 2679b3bce662Sdanielk1977 int i; /* For-loop variable used in multiple places */ 2680b3bce662Sdanielk1977 NameContext sNC; /* Local name-context */ 268113449892Sdrh ExprList *pGroupBy; /* The group by clause */ 2682b3bce662Sdanielk1977 2683b3bce662Sdanielk1977 /* If this routine has run before, return immediately. */ 2684b3bce662Sdanielk1977 if( p->isResolved ){ 2685b3bce662Sdanielk1977 assert( !pOuterNC ); 2686b3bce662Sdanielk1977 return SQLITE_OK; 2687b3bce662Sdanielk1977 } 2688b3bce662Sdanielk1977 p->isResolved = 1; 2689b3bce662Sdanielk1977 2690b3bce662Sdanielk1977 /* If there have already been errors, do nothing. */ 2691b3bce662Sdanielk1977 if( pParse->nErr>0 ){ 2692b3bce662Sdanielk1977 return SQLITE_ERROR; 2693b3bce662Sdanielk1977 } 2694b3bce662Sdanielk1977 2695b3bce662Sdanielk1977 /* Prepare the select statement. This call will allocate all cursors 2696b3bce662Sdanielk1977 ** required to handle the tables and subqueries in the FROM clause. 2697b3bce662Sdanielk1977 */ 2698b3bce662Sdanielk1977 if( prepSelectStmt(pParse, p) ){ 2699b3bce662Sdanielk1977 return SQLITE_ERROR; 2700b3bce662Sdanielk1977 } 2701b3bce662Sdanielk1977 2702a2dc3b1aSdanielk1977 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 2703a2dc3b1aSdanielk1977 ** are not allowed to refer to any names, so pass an empty NameContext. 2704a2dc3b1aSdanielk1977 */ 2705ffe07b2dSdrh memset(&sNC, 0, sizeof(sNC)); 2706b3bce662Sdanielk1977 sNC.pParse = pParse; 2707a2dc3b1aSdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pLimit) || 2708a2dc3b1aSdanielk1977 sqlite3ExprResolveNames(&sNC, p->pOffset) ){ 2709a2dc3b1aSdanielk1977 return SQLITE_ERROR; 2710a2dc3b1aSdanielk1977 } 2711a2dc3b1aSdanielk1977 2712a2dc3b1aSdanielk1977 /* Set up the local name-context to pass to ExprResolveNames() to 2713a2dc3b1aSdanielk1977 ** resolve the expression-list. 2714a2dc3b1aSdanielk1977 */ 2715a2dc3b1aSdanielk1977 sNC.allowAgg = 1; 2716a2dc3b1aSdanielk1977 sNC.pSrcList = p->pSrc; 2717a2dc3b1aSdanielk1977 sNC.pNext = pOuterNC; 2718b3bce662Sdanielk1977 2719b3bce662Sdanielk1977 /* Resolve names in the result set. */ 2720b3bce662Sdanielk1977 pEList = p->pEList; 2721b3bce662Sdanielk1977 if( !pEList ) return SQLITE_ERROR; 2722b3bce662Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 2723b3bce662Sdanielk1977 Expr *pX = pEList->a[i].pExpr; 2724b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pX) ){ 2725b3bce662Sdanielk1977 return SQLITE_ERROR; 2726b3bce662Sdanielk1977 } 2727b3bce662Sdanielk1977 } 2728b3bce662Sdanielk1977 2729b3bce662Sdanielk1977 /* If there are no aggregate functions in the result-set, and no GROUP BY 2730b3bce662Sdanielk1977 ** expression, do not allow aggregates in any of the other expressions. 2731b3bce662Sdanielk1977 */ 2732b3bce662Sdanielk1977 assert( !p->isAgg ); 273313449892Sdrh pGroupBy = p->pGroupBy; 273413449892Sdrh if( pGroupBy || sNC.hasAgg ){ 2735b3bce662Sdanielk1977 p->isAgg = 1; 2736b3bce662Sdanielk1977 }else{ 2737b3bce662Sdanielk1977 sNC.allowAgg = 0; 2738b3bce662Sdanielk1977 } 2739b3bce662Sdanielk1977 2740b3bce662Sdanielk1977 /* If a HAVING clause is present, then there must be a GROUP BY clause. 2741b3bce662Sdanielk1977 */ 274213449892Sdrh if( p->pHaving && !pGroupBy ){ 2743b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2744b3bce662Sdanielk1977 return SQLITE_ERROR; 2745b3bce662Sdanielk1977 } 2746b3bce662Sdanielk1977 2747b3bce662Sdanielk1977 /* Add the expression list to the name-context before parsing the 2748b3bce662Sdanielk1977 ** other expressions in the SELECT statement. This is so that 2749b3bce662Sdanielk1977 ** expressions in the WHERE clause (etc.) can refer to expressions by 2750b3bce662Sdanielk1977 ** aliases in the result set. 2751b3bce662Sdanielk1977 ** 2752b3bce662Sdanielk1977 ** Minor point: If this is the case, then the expression will be 2753b3bce662Sdanielk1977 ** re-evaluated for each reference to it. 2754b3bce662Sdanielk1977 */ 2755b3bce662Sdanielk1977 sNC.pEList = p->pEList; 2756b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pWhere) || 2757994c80afSdrh sqlite3ExprResolveNames(&sNC, p->pHaving) ){ 2758b3bce662Sdanielk1977 return SQLITE_ERROR; 2759b3bce662Sdanielk1977 } 27609a99334dSdrh if( p->pPrior==0 ){ 276101874bfcSdanielk1977 if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){ 2762994c80afSdrh return SQLITE_ERROR; 2763994c80afSdrh } 27649a99334dSdrh } 27659a99334dSdrh if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){ 27664c774314Sdrh return SQLITE_ERROR; 2767994c80afSdrh } 2768b3bce662Sdanielk1977 27691e536953Sdanielk1977 if( pParse->db->mallocFailed ){ 27709afe689eSdanielk1977 return SQLITE_NOMEM; 27719afe689eSdanielk1977 } 27729afe689eSdanielk1977 277313449892Sdrh /* Make sure the GROUP BY clause does not contain aggregate functions. 277413449892Sdrh */ 277513449892Sdrh if( pGroupBy ){ 277613449892Sdrh struct ExprList_item *pItem; 277713449892Sdrh 277813449892Sdrh for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 277913449892Sdrh if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 278013449892Sdrh sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 278113449892Sdrh "the GROUP BY clause"); 278213449892Sdrh return SQLITE_ERROR; 278313449892Sdrh } 278413449892Sdrh } 278513449892Sdrh } 278613449892Sdrh 2787f6bbe022Sdrh /* If this is one SELECT of a compound, be sure to resolve names 2788f6bbe022Sdrh ** in the other SELECTs. 2789f6bbe022Sdrh */ 2790f6bbe022Sdrh if( p->pPrior ){ 2791f6bbe022Sdrh return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC); 2792f6bbe022Sdrh }else{ 2793b3bce662Sdanielk1977 return SQLITE_OK; 2794b3bce662Sdanielk1977 } 2795f6bbe022Sdrh } 2796b3bce662Sdanielk1977 2797b3bce662Sdanielk1977 /* 279813449892Sdrh ** Reset the aggregate accumulator. 279913449892Sdrh ** 280013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 280113449892Sdrh ** intermediate results while calculating an aggregate. This 280213449892Sdrh ** routine simply stores NULLs in all of those memory cells. 2803b3bce662Sdanielk1977 */ 280413449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 280513449892Sdrh Vdbe *v = pParse->pVdbe; 280613449892Sdrh int i; 2807c99130fdSdrh struct AggInfo_func *pFunc; 280813449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 280913449892Sdrh return; 281013449892Sdrh } 281113449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 28124c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); 281313449892Sdrh } 2814c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 28154c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); 2816c99130fdSdrh if( pFunc->iDistinct>=0 ){ 2817c99130fdSdrh Expr *pE = pFunc->pExpr; 2818c99130fdSdrh if( pE->pList==0 || pE->pList->nExpr!=1 ){ 2819c99130fdSdrh sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " 2820c99130fdSdrh "by an expression"); 2821c99130fdSdrh pFunc->iDistinct = -1; 2822c99130fdSdrh }else{ 2823c99130fdSdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); 282466a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 282566a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 2826c99130fdSdrh } 2827c99130fdSdrh } 282813449892Sdrh } 2829b3bce662Sdanielk1977 } 2830b3bce662Sdanielk1977 2831b3bce662Sdanielk1977 /* 283213449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 283313449892Sdrh ** in the AggInfo structure. 2834b3bce662Sdanielk1977 */ 283513449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 283613449892Sdrh Vdbe *v = pParse->pVdbe; 283713449892Sdrh int i; 283813449892Sdrh struct AggInfo_func *pF; 283913449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 2840a10a34b8Sdrh ExprList *pList = pF->pExpr->pList; 284166a5167bSdrh sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 284266a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 2843b3bce662Sdanielk1977 } 284413449892Sdrh } 284513449892Sdrh 284613449892Sdrh /* 284713449892Sdrh ** Update the accumulator memory cells for an aggregate based on 284813449892Sdrh ** the current cursor position. 284913449892Sdrh */ 285013449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 285113449892Sdrh Vdbe *v = pParse->pVdbe; 285213449892Sdrh int i; 285313449892Sdrh struct AggInfo_func *pF; 285413449892Sdrh struct AggInfo_col *pC; 285513449892Sdrh 285613449892Sdrh pAggInfo->directMode = 1; 285713449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 285813449892Sdrh int nArg; 2859c99130fdSdrh int addrNext = 0; 286098757157Sdrh int regAgg; 286113449892Sdrh ExprList *pList = pF->pExpr->pList; 286213449892Sdrh if( pList ){ 286313449892Sdrh nArg = pList->nExpr; 2864892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 2865892d3179Sdrh sqlite3ExprCodeExprList(pParse, pList, regAgg); 286613449892Sdrh }else{ 286713449892Sdrh nArg = 0; 286898757157Sdrh regAgg = 0; 286913449892Sdrh } 2870c99130fdSdrh if( pF->iDistinct>=0 ){ 2871c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 2872c99130fdSdrh assert( nArg==1 ); 28732dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 2874c99130fdSdrh } 287513449892Sdrh if( pF->pFunc->needCollSeq ){ 287613449892Sdrh CollSeq *pColl = 0; 287713449892Sdrh struct ExprList_item *pItem; 287813449892Sdrh int j; 287943617e9aSdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */ 288043617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 288113449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 288213449892Sdrh } 288313449892Sdrh if( !pColl ){ 288413449892Sdrh pColl = pParse->db->pDfltColl; 288513449892Sdrh } 288666a5167bSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 288713449892Sdrh } 288898757157Sdrh sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 288966a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 289098757157Sdrh sqlite3VdbeChangeP5(v, nArg); 2891892d3179Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 2892c99130fdSdrh if( addrNext ){ 2893c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 2894c99130fdSdrh } 289513449892Sdrh } 289613449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 2897389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 289813449892Sdrh } 289913449892Sdrh pAggInfo->directMode = 0; 290013449892Sdrh } 290113449892Sdrh 29028f2c54e6Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER 29038f2c54e6Sdanielk1977 /* 29048f2c54e6Sdanielk1977 ** This function is used when a SELECT statement is used to create a 29058f2c54e6Sdanielk1977 ** temporary table for iterating through when running an INSTEAD OF 29068f2c54e6Sdanielk1977 ** UPDATE or INSTEAD OF DELETE trigger. 29078f2c54e6Sdanielk1977 ** 29088f2c54e6Sdanielk1977 ** If possible, the SELECT statement is modified so that NULL values 29098f2c54e6Sdanielk1977 ** are stored in the temporary table for all columns for which the 29108f2c54e6Sdanielk1977 ** corresponding bit in argument mask is not set. If mask takes the 29118f2c54e6Sdanielk1977 ** special value 0xffffffff, then all columns are populated. 29128f2c54e6Sdanielk1977 */ 2913d2b3e23bSdrh void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){ 29148f2c54e6Sdanielk1977 if( !p->pPrior && !p->isDistinct && mask!=0xffffffff ){ 29158f2c54e6Sdanielk1977 ExprList *pEList; 29168f2c54e6Sdanielk1977 int i; 2917d2b3e23bSdrh sqlite3SelectResolve(pParse, p, 0); 29188f2c54e6Sdanielk1977 pEList = p->pEList; 29198f2c54e6Sdanielk1977 for(i=0; i<pEList->nExpr && i<32; i++){ 29208f2c54e6Sdanielk1977 if( !(mask&((u32)1<<i)) ){ 29218f2c54e6Sdanielk1977 sqlite3ExprDelete(pEList->a[i].pExpr); 29228f2c54e6Sdanielk1977 pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0); 29238f2c54e6Sdanielk1977 } 29248f2c54e6Sdanielk1977 } 29258f2c54e6Sdanielk1977 } 29268f2c54e6Sdanielk1977 } 29278f2c54e6Sdanielk1977 #endif 2928b3bce662Sdanielk1977 2929b3bce662Sdanielk1977 /* 29309bb61fe7Sdrh ** Generate code for the given SELECT statement. 29319bb61fe7Sdrh ** 2932fef5208cSdrh ** The results are distributed in various ways depending on the 29336c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest 29346c8c8ce0Sdanielk1977 ** as follows: 2935fef5208cSdrh ** 29366c8c8ce0Sdanielk1977 ** pDest->eDest Result 2937fef5208cSdrh ** ------------ ------------------------------------------- 2938fef5208cSdrh ** SRT_Callback Invoke the callback for each row of the result. 2939fef5208cSdrh ** 29406c8c8ce0Sdanielk1977 ** SRT_Mem Store first result in memory cell pDest->iParm 2941fef5208cSdrh ** 29426c8c8ce0Sdanielk1977 ** SRT_Set Store non-null results as keys of table pDest->iParm. 29436c8c8ce0Sdanielk1977 ** Apply the affinity pDest->affinity before storing them. 2944fef5208cSdrh ** 29456c8c8ce0Sdanielk1977 ** SRT_Union Store results as a key in a temporary table pDest->iParm. 294682c3d636Sdrh ** 29476c8c8ce0Sdanielk1977 ** SRT_Except Remove results from the temporary table pDest->iParm. 2948c4a3c779Sdrh ** 29496c8c8ce0Sdanielk1977 ** SRT_Table Store results in temporary table pDest->iParm 29509bb61fe7Sdrh ** 29516c8c8ce0Sdanielk1977 ** SRT_EphemTab Create an temporary table pDest->iParm and store 29526c8c8ce0Sdanielk1977 ** the result there. The cursor is left open after 29536c8c8ce0Sdanielk1977 ** returning. 29546c8c8ce0Sdanielk1977 ** 29556c8c8ce0Sdanielk1977 ** SRT_Subroutine For each row returned, push the results onto the 29566c8c8ce0Sdanielk1977 ** vdbe stack and call the subroutine (via OP_Gosub) 29576c8c8ce0Sdanielk1977 ** at address pDest->iParm. 29586c8c8ce0Sdanielk1977 ** 29596c8c8ce0Sdanielk1977 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result 29606c8c8ce0Sdanielk1977 ** set is not empty. 29616c8c8ce0Sdanielk1977 ** 29626c8c8ce0Sdanielk1977 ** SRT_Discard Throw the results away. 29636c8c8ce0Sdanielk1977 ** 29646c8c8ce0Sdanielk1977 ** See the selectInnerLoop() function for a canonical listing of the 29656c8c8ce0Sdanielk1977 ** allowed values of eDest and their meanings. 2966e78e8284Sdrh ** 29679bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 29689bb61fe7Sdrh ** encountered, then an appropriate error message is left in 29699bb61fe7Sdrh ** pParse->zErrMsg. 29709bb61fe7Sdrh ** 29719bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 29729bb61fe7Sdrh ** calling function needs to do that. 29731b2e0329Sdrh ** 29741b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this 29751b2e0329Sdrh ** SELECT is a subquery. This routine may try to combine this SELECT 29761b2e0329Sdrh ** with its parent to form a single flat query. In so doing, it might 29771b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query. 29781b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it 29791b2e0329Sdrh ** can be changed. 2980e78e8284Sdrh ** 2981e78e8284Sdrh ** Example 1: The meaning of the pParent parameter. 2982e78e8284Sdrh ** 2983e78e8284Sdrh ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2984e78e8284Sdrh ** \ \_______ subquery _______/ / 2985e78e8284Sdrh ** \ / 2986e78e8284Sdrh ** \____________________ outer query ___________________/ 2987e78e8284Sdrh ** 2988e78e8284Sdrh ** This routine is called for the outer query first. For that call, 2989e78e8284Sdrh ** pParent will be NULL. During the processing of the outer query, this 2990e78e8284Sdrh ** routine is called recursively to handle the subquery. For the recursive 2991e78e8284Sdrh ** call, pParent will point to the outer query. Because the subquery is 2992e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will 2993e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.) 29949bb61fe7Sdrh */ 29954adee20fSdanielk1977 int sqlite3Select( 2996cce7d176Sdrh Parse *pParse, /* The parser context */ 29979bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 29986c8c8ce0Sdanielk1977 SelectDest *pDest, /* What to do with the query results */ 2999832508b7Sdrh Select *pParent, /* Another SELECT for which this is a sub-query */ 3000832508b7Sdrh int parentTab, /* Index in pParent->pSrc of this query */ 300184ac9d02Sdanielk1977 int *pParentAgg, /* True if pParent uses aggregate functions */ 3002b3bce662Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 3003cce7d176Sdrh ){ 300413449892Sdrh int i, j; /* Loop counters */ 300513449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 300613449892Sdrh Vdbe *v; /* The virtual machine under construction */ 3007b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 3008a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 3009ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 30109bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 30119bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 30122282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 30132282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 301419a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 301519a775c2Sdrh int distinct; /* Table to use for the distinct set */ 30161d83f052Sdrh int rc = 1; /* Value to return from this function */ 3017b9bb7c18Sdrh int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 301813449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 3019ec7429aeSdrh int iEnd; /* Address of the end of the query */ 302017435752Sdrh sqlite3 *db; /* The database connection */ 30219bb61fe7Sdrh 302217435752Sdrh db = pParse->db; 302317435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 30246f7adc8aSdrh return 1; 30256f7adc8aSdrh } 30264adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 302713449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 3028daffd0e5Sdrh 30299a99334dSdrh pOrderBy = p->pOrderBy; 30306c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 30319a99334dSdrh p->pOrderBy = 0; 30329ed1dfa8Sdanielk1977 30339ed1dfa8Sdanielk1977 /* In these cases the DISTINCT operator makes no difference to the 30349ed1dfa8Sdanielk1977 ** results, so remove it if it were specified. 30359ed1dfa8Sdanielk1977 */ 30369ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 30379ed1dfa8Sdanielk1977 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); 30389ed1dfa8Sdanielk1977 p->isDistinct = 0; 30399a99334dSdrh } 30409a99334dSdrh if( sqlite3SelectResolve(pParse, p, 0) ){ 30419a99334dSdrh goto select_end; 30429a99334dSdrh } 30439a99334dSdrh p->pOrderBy = pOrderBy; 30449a99334dSdrh 3045b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 304682c3d636Sdrh /* If there is are a sequence of queries, do the earlier ones first. 304782c3d636Sdrh */ 304882c3d636Sdrh if( p->pPrior ){ 30490342b1f5Sdrh if( p->pRightmost==0 ){ 30501e281291Sdrh Select *pLoop, *pRight = 0; 30510325d873Sdrh int cnt = 0; 30520325d873Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 30530342b1f5Sdrh pLoop->pRightmost = p; 30541e281291Sdrh pLoop->pNext = pRight; 30551e281291Sdrh pRight = pLoop; 30560342b1f5Sdrh } 30570325d873Sdrh if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){ 30580325d873Sdrh sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 30590325d873Sdrh return 1; 30600325d873Sdrh } 30610342b1f5Sdrh } 30626c8c8ce0Sdanielk1977 return multiSelect(pParse, p, pDest, aff); 306382c3d636Sdrh } 3064b7f9164eSdrh #endif 306582c3d636Sdrh 306682c3d636Sdrh /* Make local copies of the parameters for this query. 306782c3d636Sdrh */ 30689bb61fe7Sdrh pTabList = p->pSrc; 30699bb61fe7Sdrh pWhere = p->pWhere; 30702282792aSdrh pGroupBy = p->pGroupBy; 30712282792aSdrh pHaving = p->pHaving; 3072b3bce662Sdanielk1977 isAgg = p->isAgg; 307319a775c2Sdrh isDistinct = p->isDistinct; 3074b3bce662Sdanielk1977 pEList = p->pEList; 3075b3bce662Sdanielk1977 if( pEList==0 ) goto select_end; 30769bb61fe7Sdrh 30779bb61fe7Sdrh /* 30789bb61fe7Sdrh ** Do not even attempt to generate any code if we have already seen 30799bb61fe7Sdrh ** errors before this routine starts. 30809bb61fe7Sdrh */ 30811d83f052Sdrh if( pParse->nErr>0 ) goto select_end; 3082cce7d176Sdrh 30832282792aSdrh /* If writing to memory or generating a set 30842282792aSdrh ** only a single column may be output. 308519a775c2Sdrh */ 308693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 30876c8c8ce0Sdanielk1977 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 30881d83f052Sdrh goto select_end; 308919a775c2Sdrh } 309093758c8dSdanielk1977 #endif 309119a775c2Sdrh 3092c926afbcSdrh /* ORDER BY is ignored for some destinations. 30932282792aSdrh */ 30946c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 3095acd4c695Sdrh pOrderBy = 0; 30962282792aSdrh } 30972282792aSdrh 3098d820cb1bSdrh /* Begin generating code. 3099d820cb1bSdrh */ 31004adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 3101d820cb1bSdrh if( v==0 ) goto select_end; 3102d820cb1bSdrh 3103d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 3104d820cb1bSdrh */ 310551522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3106ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 3107742f947bSdanielk1977 const char *zSavedAuthContext = 0; 3108c31c2eb8Sdrh int needRestoreContext; 310913449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 31101013c932Sdrh SelectDest dest; 3111c31c2eb8Sdrh 31121787ccabSdanielk1977 if( pItem->pSelect==0 || pItem->isPopulated ) continue; 311313449892Sdrh if( pItem->zName!=0 ){ 31145cf590c1Sdrh zSavedAuthContext = pParse->zAuthContext; 311513449892Sdrh pParse->zAuthContext = pItem->zName; 3116c31c2eb8Sdrh needRestoreContext = 1; 3117c31c2eb8Sdrh }else{ 3118c31c2eb8Sdrh needRestoreContext = 0; 31195cf590c1Sdrh } 3120e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 3121fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 3122fc976065Sdanielk1977 ** tree refered to by this, the parent select. The child select 3123fc976065Sdanielk1977 ** may contain expression trees of at most 3124fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 3125fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 3126fc976065Sdanielk1977 ** an exact limit. 3127fc976065Sdanielk1977 */ 3128fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 3129fc976065Sdanielk1977 #endif 31301013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 31316c8c8ce0Sdanielk1977 sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0); 3132cfa063b3Sdrh if( db->mallocFailed ){ 3133cfa063b3Sdrh goto select_end; 3134cfa063b3Sdrh } 3135e6a58a4eSdanielk1977 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 3136fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 3137fc976065Sdanielk1977 #endif 3138c31c2eb8Sdrh if( needRestoreContext ){ 31395cf590c1Sdrh pParse->zAuthContext = zSavedAuthContext; 31405cf590c1Sdrh } 3141832508b7Sdrh pTabList = p->pSrc; 3142832508b7Sdrh pWhere = p->pWhere; 31436c8c8ce0Sdanielk1977 if( !IgnorableOrderby(pDest) ){ 3144832508b7Sdrh pOrderBy = p->pOrderBy; 3145acd4c695Sdrh } 3146832508b7Sdrh pGroupBy = p->pGroupBy; 3147832508b7Sdrh pHaving = p->pHaving; 3148832508b7Sdrh isDistinct = p->isDistinct; 31491b2e0329Sdrh } 315051522cd3Sdrh #endif 31511b2e0329Sdrh 31526e17529eSdrh /* Check for the special case of a min() or max() function by itself 31536e17529eSdrh ** in the result set. 31546e17529eSdrh */ 3155a9d1ccb9Sdanielk1977 #if 0 31566c8c8ce0Sdanielk1977 if( simpleMinMaxQuery(pParse, p, pDest) ){ 31576e17529eSdrh rc = 0; 31586e17529eSdrh goto select_end; 31596e17529eSdrh } 3160a9d1ccb9Sdanielk1977 #endif 31616e17529eSdrh 31621b2e0329Sdrh /* Check to see if this is a subquery that can be "flattened" into its parent. 31631b2e0329Sdrh ** If flattening is a possiblity, do so and return immediately. 31641b2e0329Sdrh */ 3165b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 31661b2e0329Sdrh if( pParent && pParentAgg && 316717435752Sdrh flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){ 31681b2e0329Sdrh if( isAgg ) *pParentAgg = 1; 3169b3bce662Sdanielk1977 goto select_end; 31701b2e0329Sdrh } 3171b7f9164eSdrh #endif 3172832508b7Sdrh 31730318d441Sdanielk1977 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT. 31740318d441Sdanielk1977 ** GROUP BY may use an index, DISTINCT never does. 31753c4809a2Sdanielk1977 */ 31763c4809a2Sdanielk1977 if( p->isDistinct && !p->isAgg && !p->pGroupBy ){ 31773c4809a2Sdanielk1977 p->pGroupBy = sqlite3ExprListDup(db, p->pEList); 31783c4809a2Sdanielk1977 pGroupBy = p->pGroupBy; 31793c4809a2Sdanielk1977 p->isDistinct = 0; 31803c4809a2Sdanielk1977 isDistinct = 0; 31813c4809a2Sdanielk1977 } 31823c4809a2Sdanielk1977 31838b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 31848b4c40d8Sdrh ** index might end up being unused if the data can be 31859d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 3186b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 31879d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 31889d2985c7Sdrh ** variable is used to facilitate that change. 31897cedc8d4Sdanielk1977 */ 31907cedc8d4Sdanielk1977 if( pOrderBy ){ 31910342b1f5Sdrh KeyInfo *pKeyInfo; 31920342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 31939d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 3194b9bb7c18Sdrh p->addrOpenEphm[2] = addrSortIndex = 319566a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 319666a5167bSdrh pOrderBy->iECursor, pOrderBy->nExpr+2, 0, 319766a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 31989d2985c7Sdrh }else{ 31999d2985c7Sdrh addrSortIndex = -1; 32007cedc8d4Sdanielk1977 } 32017cedc8d4Sdanielk1977 32022d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 32032d0794e3Sdrh */ 32046c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 320566a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr); 32062d0794e3Sdrh } 32072d0794e3Sdrh 3208f42bacc2Sdrh /* Set the limiter. 3209f42bacc2Sdrh */ 3210f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 3211f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 3212f42bacc2Sdrh 3213dece1a84Sdrh /* Open a virtual index to use for the distinct set. 3214cce7d176Sdrh */ 321519a775c2Sdrh if( isDistinct ){ 32160342b1f5Sdrh KeyInfo *pKeyInfo; 32173c4809a2Sdanielk1977 assert( isAgg || pGroupBy ); 3218832508b7Sdrh distinct = pParse->nTab++; 32190342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 322066a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0, 322166a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3222832508b7Sdrh }else{ 3223832508b7Sdrh distinct = -1; 3224efb7251dSdrh } 3225832508b7Sdrh 322613449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 322713449892Sdrh if( !isAgg && pGroupBy==0 ){ 322813449892Sdrh /* This case is for non-aggregate queries 322913449892Sdrh ** Begin the database scan 3230832508b7Sdrh */ 3231a9d1ccb9Sdanielk1977 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0); 32321d83f052Sdrh if( pWInfo==0 ) goto select_end; 3233cce7d176Sdrh 3234b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 3235b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 32369d2985c7Sdrh ** into an OP_Noop. 32379d2985c7Sdrh */ 32389d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 3239f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortIndex, 1); 3240b9bb7c18Sdrh p->addrOpenEphm[2] = -1; 32419d2985c7Sdrh } 32429d2985c7Sdrh 324313449892Sdrh /* Use the standard inner loop 3244cce7d176Sdrh */ 32453c4809a2Sdanielk1977 assert(!isDistinct); 3246d2b3e23bSdrh selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest, 3247d2b3e23bSdrh pWInfo->iContinue, pWInfo->iBreak, aff); 32482282792aSdrh 3249cce7d176Sdrh /* End the database scan loop. 3250cce7d176Sdrh */ 32514adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 325213449892Sdrh }else{ 325313449892Sdrh /* This is the processing for aggregate queries */ 325413449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 325513449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 325613449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 325713449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 325813449892Sdrh ** one row of the input to the aggregator has been 325913449892Sdrh ** processed */ 326013449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 326113449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 3262cce7d176Sdrh 326313449892Sdrh 326413449892Sdrh /* The following variables hold addresses or labels for parts of the 326513449892Sdrh ** virtual machine program we are putting together */ 326613449892Sdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 326713449892Sdrh int addrSetAbort; /* Set the abort flag and return */ 326813449892Sdrh int addrInitializeLoop; /* Start of code that initializes the input loop */ 326913449892Sdrh int addrTopOfLoop; /* Top of the input loop */ 327013449892Sdrh int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ 327113449892Sdrh int addrProcessRow; /* Code to process a single input row */ 327213449892Sdrh int addrEnd; /* End of all processing */ 3273b9bb7c18Sdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 3274e313382eSdrh int addrReset; /* Subroutine for resetting the accumulator */ 327513449892Sdrh 327613449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 327713449892Sdrh 327813449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 327913449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 328013449892Sdrh ** SELECT statement. 32812282792aSdrh */ 328213449892Sdrh memset(&sNC, 0, sizeof(sNC)); 328313449892Sdrh sNC.pParse = pParse; 328413449892Sdrh sNC.pSrcList = pTabList; 328513449892Sdrh sNC.pAggInfo = &sAggInfo; 328613449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 32879d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 3288d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 3289d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); 3290d2b3e23bSdrh if( pHaving ){ 3291d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 329213449892Sdrh } 329313449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 329413449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 3295d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList); 329613449892Sdrh } 329717435752Sdrh if( db->mallocFailed ) goto select_end; 329813449892Sdrh 329913449892Sdrh /* Processing for aggregates with GROUP BY is very different and 33003c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 330113449892Sdrh */ 330213449892Sdrh if( pGroupBy ){ 330313449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 330413449892Sdrh 330513449892Sdrh /* Create labels that we will be needing 330613449892Sdrh */ 330713449892Sdrh 330813449892Sdrh addrInitializeLoop = sqlite3VdbeMakeLabel(v); 330913449892Sdrh addrGroupByChange = sqlite3VdbeMakeLabel(v); 331013449892Sdrh addrProcessRow = sqlite3VdbeMakeLabel(v); 331113449892Sdrh 331213449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 331313449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 3314b9bb7c18Sdrh ** that we do not need it after all, the OpenEphemeral instruction 331513449892Sdrh ** will be converted into a Noop. 331613449892Sdrh */ 331713449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 331813449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 331913449892Sdrh addrSortingIdx = 332066a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sAggInfo.sortingIdx, 332166a5167bSdrh sAggInfo.nSortingColumn, 0, 332266a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 332313449892Sdrh 332413449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 332513449892Sdrh */ 33260a07c107Sdrh iUseFlag = ++pParse->nMem; 33270a07c107Sdrh iAbortFlag = ++pParse->nMem; 33280a07c107Sdrh iAMem = pParse->nMem + 1; 332913449892Sdrh pParse->nMem += pGroupBy->nExpr; 33300a07c107Sdrh iBMem = pParse->nMem + 1; 333113449892Sdrh pParse->nMem += pGroupBy->nExpr; 33324c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 3333d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 33344c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 3335d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 333666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop); 333713449892Sdrh 333813449892Sdrh /* Generate a subroutine that outputs a single row of the result 333913449892Sdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 334013449892Sdrh ** is less than or equal to zero, the subroutine is a no-op. If 334113449892Sdrh ** the processing calls for the query to abort, this subroutine 334213449892Sdrh ** increments the iAbortFlag memory location before returning in 334313449892Sdrh ** order to signal the caller to abort. 334413449892Sdrh */ 334513449892Sdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 33464c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 3347d4e70ebdSdrh VdbeComment((v, "set abort flag")); 334866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 334913449892Sdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 33503c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 3351d4e70ebdSdrh VdbeComment((v, "Groupby result generator entry point")); 335266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 335313449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 335413449892Sdrh if( pHaving ){ 335535573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 335613449892Sdrh } 3357d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 33586c8c8ce0Sdanielk1977 distinct, pDest, 335913449892Sdrh addrOutputRow+1, addrSetAbort, aff); 336066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 3361d4e70ebdSdrh VdbeComment((v, "end groupby result generator")); 336213449892Sdrh 3363e313382eSdrh /* Generate a subroutine that will reset the group-by accumulator 3364e313382eSdrh */ 3365e313382eSdrh addrReset = sqlite3VdbeCurrentAddr(v); 3366e313382eSdrh resetAccumulator(pParse, &sAggInfo); 336766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 3368e313382eSdrh 336913449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 337013449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 337113449892Sdrh ** it might be a single loop that uses an index to extract information 337213449892Sdrh ** in the right order to begin with. 337313449892Sdrh */ 337413449892Sdrh sqlite3VdbeResolveLabel(v, addrInitializeLoop); 337566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset); 3376a9d1ccb9Sdanielk1977 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0); 33775360ad34Sdrh if( pWInfo==0 ) goto select_end; 337813449892Sdrh if( pGroupBy==0 ){ 337913449892Sdrh /* The optimizer is able to deliver rows in group by order so 3380b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 338113449892Sdrh ** cancelled later because we still need to use the pKeyInfo 338213449892Sdrh */ 338313449892Sdrh pGroupBy = p->pGroupBy; 338413449892Sdrh groupBySort = 0; 338513449892Sdrh }else{ 338613449892Sdrh /* Rows are coming out in undetermined order. We have to push 338713449892Sdrh ** each row into a sorting index, terminate the first loop, 338813449892Sdrh ** then loop over the sorting index in order to get the output 338913449892Sdrh ** in sorted order 339013449892Sdrh */ 3391892d3179Sdrh int regBase; 3392892d3179Sdrh int regRecord; 3393892d3179Sdrh int nCol; 3394892d3179Sdrh int nGroupBy; 3395892d3179Sdrh 339613449892Sdrh groupBySort = 1; 3397892d3179Sdrh nGroupBy = pGroupBy->nExpr; 3398892d3179Sdrh nCol = nGroupBy + 1; 3399892d3179Sdrh j = nGroupBy+1; 340013449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 3401892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 3402892d3179Sdrh nCol++; 340313449892Sdrh j++; 340413449892Sdrh } 3405892d3179Sdrh } 3406892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 3407892d3179Sdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase); 3408892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); 3409892d3179Sdrh j = nGroupBy+1; 3410892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 3411892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 3412892d3179Sdrh if( pCol->iSorterColumn>=j ){ 3413892d3179Sdrh sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable, 3414892d3179Sdrh j + regBase); 3415892d3179Sdrh j++; 3416892d3179Sdrh } 3417892d3179Sdrh } 3418892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 34191db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 3420892d3179Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord); 3421892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 3422892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 342313449892Sdrh sqlite3WhereEnd(pWInfo); 342466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); 3425d4e70ebdSdrh VdbeComment((v, "GROUP BY sort")); 342613449892Sdrh sAggInfo.useSortingIdx = 1; 342713449892Sdrh } 342813449892Sdrh 342913449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 343013449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 343113449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 343213449892Sdrh ** from the previous row currently stored in a0, a1, a2... 343313449892Sdrh */ 343413449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 343513449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 343613449892Sdrh if( groupBySort ){ 34372dcef11bSdrh sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j); 343813449892Sdrh }else{ 343913449892Sdrh sAggInfo.directMode = 1; 34402dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 344113449892Sdrh } 344213449892Sdrh } 344313449892Sdrh for(j=pGroupBy->nExpr-1; j>=0; j--){ 344413449892Sdrh if( j==0 ){ 34452dcef11bSdrh sqlite3VdbeAddOp3(v, OP_Eq, iAMem+j, addrProcessRow, iBMem+j); 344613449892Sdrh }else{ 34472dcef11bSdrh sqlite3VdbeAddOp3(v, OP_Ne, iAMem+j, addrGroupByChange, iBMem+j); 344813449892Sdrh } 344966a5167bSdrh sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ); 345035573356Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQUAL); 345113449892Sdrh } 345213449892Sdrh 345313449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 345413449892Sdrh ** Change in the GROUP BY are detected by the previous code 345513449892Sdrh ** block. If there were no changes, this block is skipped. 345613449892Sdrh ** 345713449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 345813449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 345913449892Sdrh ** and resets the aggregate accumulator registers in preparation 346013449892Sdrh ** for the next GROUP BY batch. 346113449892Sdrh */ 346213449892Sdrh sqlite3VdbeResolveLabel(v, addrGroupByChange); 346313449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 3464b1fdb2adSdrh sqlite3VdbeAddOp2(v, OP_Move, iBMem+j, iAMem+j); 346513449892Sdrh } 346666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow); 3467d4e70ebdSdrh VdbeComment((v, "output one row")); 34683c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); 3469d4e70ebdSdrh VdbeComment((v, "check abort flag")); 347066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset); 3471d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 347213449892Sdrh 347313449892Sdrh /* Update the aggregate accumulators based on the content of 347413449892Sdrh ** the current row 347513449892Sdrh */ 347613449892Sdrh sqlite3VdbeResolveLabel(v, addrProcessRow); 347713449892Sdrh updateAccumulator(pParse, &sAggInfo); 34784c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 3479d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 348013449892Sdrh 348113449892Sdrh /* End of the loop 348213449892Sdrh */ 348313449892Sdrh if( groupBySort ){ 348466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); 348513449892Sdrh }else{ 348613449892Sdrh sqlite3WhereEnd(pWInfo); 3487f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); 348813449892Sdrh } 348913449892Sdrh 349013449892Sdrh /* Output the final row of result 349113449892Sdrh */ 349266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow); 3493d4e70ebdSdrh VdbeComment((v, "output final row")); 349413449892Sdrh 349513449892Sdrh } /* endif pGroupBy */ 349613449892Sdrh else { 3497a9d1ccb9Sdanielk1977 ExprList *pMinMax = 0; 3498dba0137eSdanielk1977 ExprList *pDel = 0; 3499a9d1ccb9Sdanielk1977 u8 flag; 3500a9d1ccb9Sdanielk1977 3501738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 3502738bdcfbSdanielk1977 ** 3503738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 3504738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 3505738bdcfbSdanielk1977 ** 3506738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 3507738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 3508738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 3509738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 3510738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 3511738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 3512738bdcfbSdanielk1977 ** value of x, the only row required). 3513738bdcfbSdanielk1977 ** 3514738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 3515738bdcfbSdanielk1977 ** modify behaviour as follows: 3516738bdcfbSdanielk1977 ** 3517738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 3518738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 3519738bdcfbSdanielk1977 ** for x. 3520738bdcfbSdanielk1977 ** 3521738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 3522738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 3523738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 3524738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 3525738bdcfbSdanielk1977 */ 3526a9d1ccb9Sdanielk1977 flag = minMaxQuery(pParse, p); 3527a9d1ccb9Sdanielk1977 if( flag ){ 35288cc74322Sdrh pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList); 35290e359b30Sdrh if( pMinMax && !db->mallocFailed ){ 3530a9d1ccb9Sdanielk1977 pMinMax->a[0].sortOrder = ((flag==ORDERBY_MIN)?0:1); 3531a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 3532a9d1ccb9Sdanielk1977 } 35331013c932Sdrh } 3534a9d1ccb9Sdanielk1977 353513449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 353613449892Sdrh ** processing is much simpler since there is only a single row 353713449892Sdrh ** of output. 353813449892Sdrh */ 353913449892Sdrh resetAccumulator(pParse, &sAggInfo); 3540a9d1ccb9Sdanielk1977 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag); 3541dba0137eSdanielk1977 if( pWInfo==0 ){ 35421013c932Sdrh sqlite3ExprListDelete(pDel); 3543dba0137eSdanielk1977 goto select_end; 3544dba0137eSdanielk1977 } 354513449892Sdrh updateAccumulator(pParse, &sAggInfo); 3546a9d1ccb9Sdanielk1977 if( !pMinMax && flag ){ 3547a9d1ccb9Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); 3548a9d1ccb9Sdanielk1977 VdbeComment((v, "%s() by index", (flag==ORDERBY_MIN?"min":"max"))); 3549a9d1ccb9Sdanielk1977 } 355013449892Sdrh sqlite3WhereEnd(pWInfo); 355113449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 355213449892Sdrh pOrderBy = 0; 35535774b806Sdrh if( pHaving ){ 355435573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 35555774b806Sdrh } 355613449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 35576c8c8ce0Sdanielk1977 pDest, addrEnd, addrEnd, aff); 3558a9d1ccb9Sdanielk1977 3559dba0137eSdanielk1977 sqlite3ExprListDelete(pDel); 356013449892Sdrh } 356113449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 356213449892Sdrh 356313449892Sdrh } /* endif aggregate query */ 35642282792aSdrh 3565cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 3566cce7d176Sdrh ** and send them to the callback one by one. 3567cce7d176Sdrh */ 3568cce7d176Sdrh if( pOrderBy ){ 35696c8c8ce0Sdanielk1977 generateSortTail(pParse, p, v, pEList->nExpr, pDest); 3570cce7d176Sdrh } 35716a535340Sdrh 357293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 3573f620b4e2Sdrh /* If this was a subquery, we have now converted the subquery into a 35741787ccabSdanielk1977 ** temporary table. So set the SrcList_item.isPopulated flag to prevent 35751787ccabSdanielk1977 ** this subquery from being evaluated again and to force the use of 35761787ccabSdanielk1977 ** the temporary table. 3577f620b4e2Sdrh */ 3578f620b4e2Sdrh if( pParent ){ 3579f620b4e2Sdrh assert( pParent->pSrc->nSrc>parentTab ); 3580f620b4e2Sdrh assert( pParent->pSrc->a[parentTab].pSelect==p ); 35811787ccabSdanielk1977 pParent->pSrc->a[parentTab].isPopulated = 1; 3582f620b4e2Sdrh } 358393758c8dSdanielk1977 #endif 3584f620b4e2Sdrh 3585ec7429aeSdrh /* Jump here to skip this query 3586ec7429aeSdrh */ 3587ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 3588ec7429aeSdrh 35891d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 35901d83f052Sdrh ** to indicate no errors. 35911d83f052Sdrh */ 35921d83f052Sdrh rc = 0; 35931d83f052Sdrh 35941d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 35951d83f052Sdrh ** successful coding of the SELECT. 35961d83f052Sdrh */ 35971d83f052Sdrh select_end: 3598955de52cSdanielk1977 3599955de52cSdanielk1977 /* Identify column names if we will be using them in a callback. This 3600955de52cSdanielk1977 ** step is skipped if the output is going to some other destination. 3601955de52cSdanielk1977 */ 36026c8c8ce0Sdanielk1977 if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){ 3603955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 3604955de52cSdanielk1977 } 3605955de52cSdanielk1977 360617435752Sdrh sqlite3_free(sAggInfo.aCol); 360717435752Sdrh sqlite3_free(sAggInfo.aFunc); 36081d83f052Sdrh return rc; 3609cce7d176Sdrh } 3610485f0039Sdrh 361177a2a5e7Sdrh #if defined(SQLITE_DEBUG) 3612485f0039Sdrh /* 3613485f0039Sdrh ******************************************************************************* 3614485f0039Sdrh ** The following code is used for testing and debugging only. The code 3615485f0039Sdrh ** that follows does not appear in normal builds. 3616485f0039Sdrh ** 3617485f0039Sdrh ** These routines are used to print out the content of all or part of a 3618485f0039Sdrh ** parse structures such as Select or Expr. Such printouts are useful 3619485f0039Sdrh ** for helping to understand what is happening inside the code generator 3620485f0039Sdrh ** during the execution of complex SELECT statements. 3621485f0039Sdrh ** 3622485f0039Sdrh ** These routine are not called anywhere from within the normal 3623485f0039Sdrh ** code base. Then are intended to be called from within the debugger 3624485f0039Sdrh ** or from temporary "printf" statements inserted for debugging. 3625485f0039Sdrh */ 3626485f0039Sdrh void sqlite3PrintExpr(Expr *p){ 3627485f0039Sdrh if( p->token.z && p->token.n>0 ){ 3628485f0039Sdrh sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z); 3629485f0039Sdrh }else{ 3630485f0039Sdrh sqlite3DebugPrintf("(%d", p->op); 3631485f0039Sdrh } 3632485f0039Sdrh if( p->pLeft ){ 3633485f0039Sdrh sqlite3DebugPrintf(" "); 3634485f0039Sdrh sqlite3PrintExpr(p->pLeft); 3635485f0039Sdrh } 3636485f0039Sdrh if( p->pRight ){ 3637485f0039Sdrh sqlite3DebugPrintf(" "); 3638485f0039Sdrh sqlite3PrintExpr(p->pRight); 3639485f0039Sdrh } 3640485f0039Sdrh sqlite3DebugPrintf(")"); 3641485f0039Sdrh } 3642485f0039Sdrh void sqlite3PrintExprList(ExprList *pList){ 3643485f0039Sdrh int i; 3644485f0039Sdrh for(i=0; i<pList->nExpr; i++){ 3645485f0039Sdrh sqlite3PrintExpr(pList->a[i].pExpr); 3646485f0039Sdrh if( i<pList->nExpr-1 ){ 3647485f0039Sdrh sqlite3DebugPrintf(", "); 3648485f0039Sdrh } 3649485f0039Sdrh } 3650485f0039Sdrh } 3651485f0039Sdrh void sqlite3PrintSelect(Select *p, int indent){ 3652485f0039Sdrh sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p); 3653485f0039Sdrh sqlite3PrintExprList(p->pEList); 3654485f0039Sdrh sqlite3DebugPrintf("\n"); 3655485f0039Sdrh if( p->pSrc ){ 3656485f0039Sdrh char *zPrefix; 3657485f0039Sdrh int i; 3658485f0039Sdrh zPrefix = "FROM"; 3659485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 3660485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 3661485f0039Sdrh sqlite3DebugPrintf("%*s ", indent+6, zPrefix); 3662485f0039Sdrh zPrefix = ""; 3663485f0039Sdrh if( pItem->pSelect ){ 3664485f0039Sdrh sqlite3DebugPrintf("(\n"); 3665485f0039Sdrh sqlite3PrintSelect(pItem->pSelect, indent+10); 3666485f0039Sdrh sqlite3DebugPrintf("%*s)", indent+8, ""); 3667485f0039Sdrh }else if( pItem->zName ){ 3668485f0039Sdrh sqlite3DebugPrintf("%s", pItem->zName); 3669485f0039Sdrh } 3670485f0039Sdrh if( pItem->pTab ){ 3671485f0039Sdrh sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName); 3672485f0039Sdrh } 3673485f0039Sdrh if( pItem->zAlias ){ 3674485f0039Sdrh sqlite3DebugPrintf(" AS %s", pItem->zAlias); 3675485f0039Sdrh } 3676485f0039Sdrh if( i<p->pSrc->nSrc-1 ){ 3677485f0039Sdrh sqlite3DebugPrintf(","); 3678485f0039Sdrh } 3679485f0039Sdrh sqlite3DebugPrintf("\n"); 3680485f0039Sdrh } 3681485f0039Sdrh } 3682485f0039Sdrh if( p->pWhere ){ 3683485f0039Sdrh sqlite3DebugPrintf("%*s WHERE ", indent, ""); 3684485f0039Sdrh sqlite3PrintExpr(p->pWhere); 3685485f0039Sdrh sqlite3DebugPrintf("\n"); 3686485f0039Sdrh } 3687485f0039Sdrh if( p->pGroupBy ){ 3688485f0039Sdrh sqlite3DebugPrintf("%*s GROUP BY ", indent, ""); 3689485f0039Sdrh sqlite3PrintExprList(p->pGroupBy); 3690485f0039Sdrh sqlite3DebugPrintf("\n"); 3691485f0039Sdrh } 3692485f0039Sdrh if( p->pHaving ){ 3693485f0039Sdrh sqlite3DebugPrintf("%*s HAVING ", indent, ""); 3694485f0039Sdrh sqlite3PrintExpr(p->pHaving); 3695485f0039Sdrh sqlite3DebugPrintf("\n"); 3696485f0039Sdrh } 3697485f0039Sdrh if( p->pOrderBy ){ 3698485f0039Sdrh sqlite3DebugPrintf("%*s ORDER BY ", indent, ""); 3699485f0039Sdrh sqlite3PrintExprList(p->pOrderBy); 3700485f0039Sdrh sqlite3DebugPrintf("\n"); 3701485f0039Sdrh } 3702485f0039Sdrh } 3703485f0039Sdrh /* End of the structure debug printing code 3704485f0039Sdrh *****************************************************************************/ 3705485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ 3706