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*bb4957f8Sdrh ** $Id: select.c,v 1.416 2008/03/20 14:03:29 drh Exp $ 16cce7d176Sdrh */ 17cce7d176Sdrh #include "sqliteInt.h" 18cce7d176Sdrh 19315555caSdrh 20cce7d176Sdrh /* 21eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate 22eda639e1Sdrh ** the select structure itself. 23eda639e1Sdrh */ 24f0113000Sdanielk1977 static void clearSelect(Select *p){ 25eda639e1Sdrh sqlite3ExprListDelete(p->pEList); 26eda639e1Sdrh sqlite3SrcListDelete(p->pSrc); 27eda639e1Sdrh sqlite3ExprDelete(p->pWhere); 28eda639e1Sdrh sqlite3ExprListDelete(p->pGroupBy); 29eda639e1Sdrh sqlite3ExprDelete(p->pHaving); 30eda639e1Sdrh sqlite3ExprListDelete(p->pOrderBy); 31eda639e1Sdrh sqlite3SelectDelete(p->pPrior); 32eda639e1Sdrh sqlite3ExprDelete(p->pLimit); 33eda639e1Sdrh sqlite3ExprDelete(p->pOffset); 34eda639e1Sdrh } 35eda639e1Sdrh 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 */ 52538640e15Sdrh 526d2b3e23bSdrh if( v==0 ) return; 52738640e15Sdrh assert( pEList!=0 ); 5282282792aSdrh 529df199a25Sdrh /* If there was a LIMIT clause on the SELECT statement, then do the check 530df199a25Sdrh ** to see if this row should be output. 531df199a25Sdrh */ 532eda639e1Sdrh hasDistinct = distinct>=0 && pEList->nExpr>0; 533ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 534b7654111Sdrh codeOffset(v, p, iContinue); 535df199a25Sdrh } 536df199a25Sdrh 537967e8b73Sdrh /* Pull the requested columns. 5382282792aSdrh */ 53938640e15Sdrh if( nColumn>0 ){ 540d847eaadSdrh nResultCol = nColumn; 541a2a49dc9Sdrh }else{ 542d847eaadSdrh nResultCol = pEList->nExpr; 543a2a49dc9Sdrh } 5441ece7325Sdrh if( pDest->iMem==0 ){ 5451ece7325Sdrh pDest->iMem = sqlite3GetTempRange(pParse, nResultCol); 5461013c932Sdrh } 5471ece7325Sdrh regResult = pDest->iMem; 548a2a49dc9Sdrh if( nColumn>0 ){ 549967e8b73Sdrh for(i=0; i<nColumn; i++){ 550d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 55182c3d636Sdrh } 5529ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 5539ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 5549ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 5559ed1dfa8Sdanielk1977 */ 556d847eaadSdrh for(i=0; i<nResultCol; i++){ 557d847eaadSdrh sqlite3ExprCode(pParse, pEList->a[i].pExpr, regResult+i); 55882c3d636Sdrh } 559a2a49dc9Sdrh } 560d847eaadSdrh nColumn = nResultCol; 5612282792aSdrh 562daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 563daffd0e5Sdrh ** and this row has been seen before, then do not make this row 564daffd0e5Sdrh ** part of the result. 5652282792aSdrh */ 566ea48eb2eSdrh if( hasDistinct ){ 567f8875400Sdrh assert( pEList!=0 ); 568f8875400Sdrh assert( pEList->nExpr==nColumn ); 569d847eaadSdrh codeDistinct(pParse, distinct, iContinue, nColumn, regResult); 570ea48eb2eSdrh if( pOrderBy==0 ){ 571b7654111Sdrh codeOffset(v, p, iContinue); 572ea48eb2eSdrh } 5732282792aSdrh } 57482c3d636Sdrh 5756c8c8ce0Sdanielk1977 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 576d2b3e23bSdrh return; 577e305f43fSdrh } 578e305f43fSdrh 579c926afbcSdrh switch( eDest ){ 58082c3d636Sdrh /* In this mode, write each query result to the key of the temporary 58182c3d636Sdrh ** table iParm. 5822282792aSdrh */ 58313449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 584c926afbcSdrh case SRT_Union: { 5859cbf3425Sdrh int r1; 5869cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 587d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 58813449892Sdrh if( aff ){ 58966a5167bSdrh sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC); 59013449892Sdrh } 5919cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 5929cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 593c926afbcSdrh break; 594c926afbcSdrh } 59582c3d636Sdrh 59682c3d636Sdrh /* Construct a record from the query result, but instead of 59782c3d636Sdrh ** saving that record, use it as a key to delete elements from 59882c3d636Sdrh ** the temporary table iParm. 59982c3d636Sdrh */ 600c926afbcSdrh case SRT_Except: { 601a05a722fSdrh int r1; 6029cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 603a05a722fSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 60466a5167bSdrh sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC); 605a05a722fSdrh sqlite3VdbeAddOp2(v, OP_IdxDelete, iParm, r1); 6069cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 607c926afbcSdrh break; 608c926afbcSdrh } 6095338a5f7Sdanielk1977 #endif 6105338a5f7Sdanielk1977 6115338a5f7Sdanielk1977 /* Store the result as data using a unique key. 6125338a5f7Sdanielk1977 */ 6135338a5f7Sdanielk1977 case SRT_Table: 614b9bb7c18Sdrh case SRT_EphemTab: { 615b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 616d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6175338a5f7Sdanielk1977 if( pOrderBy ){ 618b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 6195338a5f7Sdanielk1977 }else{ 620b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 621b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 622b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 623b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 624b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 6255338a5f7Sdanielk1977 } 626b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 6275338a5f7Sdanielk1977 break; 6285338a5f7Sdanielk1977 } 6292282792aSdrh 63093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 6312282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 6322282792aSdrh ** then there should be a single item on the stack. Write this 6332282792aSdrh ** item into the set table with bogus data. 6342282792aSdrh */ 635c926afbcSdrh case SRT_Set: { 63652b36cabSdrh int addr2; 637e014a838Sdanielk1977 638967e8b73Sdrh assert( nColumn==1 ); 639d847eaadSdrh addr2 = sqlite3VdbeAddOp1(v, OP_IsNull, regResult); 6406c8c8ce0Sdanielk1977 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity); 641c926afbcSdrh if( pOrderBy ){ 642de941c60Sdrh /* At first glance you would think we could optimize out the 643de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 644de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 645de941c60Sdrh ** case the order does matter */ 646d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 647c926afbcSdrh }else{ 648b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 649d847eaadSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1); 650b7654111Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 651b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 652c926afbcSdrh } 653d654be80Sdrh sqlite3VdbeJumpHere(v, addr2); 654c926afbcSdrh break; 655c926afbcSdrh } 65682c3d636Sdrh 657504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 658ec7429aeSdrh */ 659ec7429aeSdrh case SRT_Exists: { 6604c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 661ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 662ec7429aeSdrh break; 663ec7429aeSdrh } 664ec7429aeSdrh 6652282792aSdrh /* If this is a scalar select that is part of an expression, then 6662282792aSdrh ** store the results in the appropriate memory cell and break out 6672282792aSdrh ** of the scan loop. 6682282792aSdrh */ 669c926afbcSdrh case SRT_Mem: { 670967e8b73Sdrh assert( nColumn==1 ); 671c926afbcSdrh if( pOrderBy ){ 672d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 673c926afbcSdrh }else{ 674d847eaadSdrh sqlite3VdbeAddOp2(v, OP_Move, regResult, iParm); 675ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 676c926afbcSdrh } 677c926afbcSdrh break; 678c926afbcSdrh } 67993758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 6802282792aSdrh 681c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 682c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 683c182d163Sdrh ** popping the data from the stack. 684f46f905aSdrh */ 685c182d163Sdrh case SRT_Subroutine: 6869d2985c7Sdrh case SRT_Callback: { 687f46f905aSdrh if( pOrderBy ){ 688b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 689d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 690b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 691b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 692c182d163Sdrh }else if( eDest==SRT_Subroutine ){ 69366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm); 694c182d163Sdrh }else{ 695d847eaadSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); 696ac82fcf5Sdrh } 697142e30dfSdrh break; 698142e30dfSdrh } 699142e30dfSdrh 7006a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 701d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 702d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 703d7489c39Sdrh ** user-defined functions that have side effects. We do not care 704d7489c39Sdrh ** about the actual results of the select. 705d7489c39Sdrh */ 706c926afbcSdrh default: { 707f46f905aSdrh assert( eDest==SRT_Discard ); 708c926afbcSdrh break; 709c926afbcSdrh } 71093758c8dSdanielk1977 #endif 711c926afbcSdrh } 712ec7429aeSdrh 713ec7429aeSdrh /* Jump to the end of the loop if the LIMIT is reached. 714ec7429aeSdrh */ 715ec7429aeSdrh if( p->iLimit>=0 && pOrderBy==0 ){ 7168558cde1Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); 7173c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak); 718ec7429aeSdrh } 71982c3d636Sdrh } 72082c3d636Sdrh 72182c3d636Sdrh /* 722dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 723dece1a84Sdrh ** the collating sequence for each expression in that expression list. 724dece1a84Sdrh ** 7250342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 7260342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 7270342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 7280342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 7290342b1f5Sdrh ** index to implement a DISTINCT test. 7300342b1f5Sdrh ** 731dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 732dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 73366a5167bSdrh ** freed. Add the KeyInfo structure to the P4 field of an opcode using 73466a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. 735dece1a84Sdrh */ 736dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 737dece1a84Sdrh sqlite3 *db = pParse->db; 738dece1a84Sdrh int nExpr; 739dece1a84Sdrh KeyInfo *pInfo; 740dece1a84Sdrh struct ExprList_item *pItem; 741dece1a84Sdrh int i; 742dece1a84Sdrh 743dece1a84Sdrh nExpr = pList->nExpr; 74417435752Sdrh pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 745dece1a84Sdrh if( pInfo ){ 7462646da7eSdrh pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 747dece1a84Sdrh pInfo->nField = nExpr; 74814db2665Sdanielk1977 pInfo->enc = ENC(db); 749dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 750dece1a84Sdrh CollSeq *pColl; 751dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 752dece1a84Sdrh if( !pColl ){ 753dece1a84Sdrh pColl = db->pDfltColl; 754dece1a84Sdrh } 755dece1a84Sdrh pInfo->aColl[i] = pColl; 756dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 757dece1a84Sdrh } 758dece1a84Sdrh } 759dece1a84Sdrh return pInfo; 760dece1a84Sdrh } 761dece1a84Sdrh 762dece1a84Sdrh 763dece1a84Sdrh /* 764d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 765d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 766d8bc7086Sdrh ** we need to run the sorter and output the results. The following 767d8bc7086Sdrh ** routine generates the code needed to do that. 768d8bc7086Sdrh */ 769c926afbcSdrh static void generateSortTail( 770cdd536f0Sdrh Parse *pParse, /* Parsing context */ 771c926afbcSdrh Select *p, /* The SELECT statement */ 772c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 773c926afbcSdrh int nColumn, /* Number of columns of data */ 7746c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 775c926afbcSdrh ){ 7760342b1f5Sdrh int brk = sqlite3VdbeMakeLabel(v); 7770342b1f5Sdrh int cont = sqlite3VdbeMakeLabel(v); 778d8bc7086Sdrh int addr; 7790342b1f5Sdrh int iTab; 78061fc595fSdrh int pseudoTab = 0; 7810342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 782ffbc3088Sdrh 7836c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 7846c8c8ce0Sdanielk1977 int iParm = pDest->iParm; 7856c8c8ce0Sdanielk1977 7862d401ab8Sdrh int regRow; 7872d401ab8Sdrh int regRowid; 7882d401ab8Sdrh 7899d2985c7Sdrh iTab = pOrderBy->iECursor; 790cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 791cdd536f0Sdrh pseudoTab = pParse->nTab++; 79266a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, 0); 79366a5167bSdrh sqlite3VdbeAddOp2(v, OP_SetNumColumns, pseudoTab, nColumn); 794cdd536f0Sdrh } 79566a5167bSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk); 796b7654111Sdrh codeOffset(v, p, cont); 7972d401ab8Sdrh regRow = sqlite3GetTempReg(pParse); 7982d401ab8Sdrh regRowid = sqlite3GetTempReg(pParse); 7992d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow); 800c926afbcSdrh switch( eDest ){ 801c926afbcSdrh case SRT_Table: 802b9bb7c18Sdrh case SRT_EphemTab: { 8032d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 8042d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 8052d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 806c926afbcSdrh break; 807c926afbcSdrh } 80893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 809c926afbcSdrh case SRT_Set: { 8102d401ab8Sdrh int j1; 811c926afbcSdrh assert( nColumn==1 ); 8122d401ab8Sdrh j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regRow); 813a7a8e14bSdanielk1977 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1); 814a7a8e14bSdanielk1977 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); 8156a288a33Sdrh sqlite3VdbeJumpHere(v, j1); 816c926afbcSdrh break; 817c926afbcSdrh } 818c926afbcSdrh case SRT_Mem: { 819c926afbcSdrh assert( nColumn==1 ); 8202d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_Move, regRow, iParm); 821ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 822c926afbcSdrh break; 823c926afbcSdrh } 82493758c8dSdanielk1977 #endif 825ce665cf6Sdrh case SRT_Callback: 826ac82fcf5Sdrh case SRT_Subroutine: { 827ac82fcf5Sdrh int i; 8282d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid); 8292d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid); 830ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 8311013c932Sdrh sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i); 832ac82fcf5Sdrh } 833ce665cf6Sdrh if( eDest==SRT_Callback ){ 8341013c932Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn); 835ce665cf6Sdrh }else{ 83666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm); 837ce665cf6Sdrh } 838ac82fcf5Sdrh break; 839ac82fcf5Sdrh } 840c926afbcSdrh default: { 841f46f905aSdrh /* Do nothing */ 842c926afbcSdrh break; 843c926afbcSdrh } 844c926afbcSdrh } 8452d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 8462d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 847ec7429aeSdrh 848ec7429aeSdrh /* Jump to the end of the loop when the LIMIT is reached 849ec7429aeSdrh */ 850ec7429aeSdrh if( p->iLimit>=0 ){ 8518558cde1Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); 8523c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, brk); 853ec7429aeSdrh } 854ec7429aeSdrh 855ec7429aeSdrh /* The bottom of the loop 856ec7429aeSdrh */ 8570342b1f5Sdrh sqlite3VdbeResolveLabel(v, cont); 85866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); 8590342b1f5Sdrh sqlite3VdbeResolveLabel(v, brk); 860cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 86166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); 862cdd536f0Sdrh } 863cdd536f0Sdrh 864d8bc7086Sdrh } 865d8bc7086Sdrh 866d8bc7086Sdrh /* 867517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 868517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 869e78e8284Sdrh ** 870955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 871955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 872955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 873955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 874955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 875955de52cSdanielk1977 ** considered a column by this function. 876e78e8284Sdrh ** 877955de52cSdanielk1977 ** SELECT col FROM tbl; 878955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 879955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 880955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 881955de52cSdanielk1977 ** 882955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 883fcb78a49Sdrh */ 884955de52cSdanielk1977 static const char *columnType( 885955de52cSdanielk1977 NameContext *pNC, 886955de52cSdanielk1977 Expr *pExpr, 887955de52cSdanielk1977 const char **pzOriginDb, 888955de52cSdanielk1977 const char **pzOriginTab, 889955de52cSdanielk1977 const char **pzOriginCol 890955de52cSdanielk1977 ){ 891955de52cSdanielk1977 char const *zType = 0; 892955de52cSdanielk1977 char const *zOriginDb = 0; 893955de52cSdanielk1977 char const *zOriginTab = 0; 894955de52cSdanielk1977 char const *zOriginCol = 0; 895517eb646Sdanielk1977 int j; 896b3bce662Sdanielk1977 if( pExpr==0 || pNC->pSrcList==0 ) return 0; 8975338a5f7Sdanielk1977 89800e279d9Sdanielk1977 switch( pExpr->op ){ 89930bcf5dbSdrh case TK_AGG_COLUMN: 90000e279d9Sdanielk1977 case TK_COLUMN: { 901955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 902955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 903955de52cSdanielk1977 ** database table or a subquery. 904955de52cSdanielk1977 */ 905955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 906955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 907955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 908b3bce662Sdanielk1977 while( pNC && !pTab ){ 909b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 910b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 911b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 9126a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 913955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 914b3bce662Sdanielk1977 }else{ 915b3bce662Sdanielk1977 pNC = pNC->pNext; 916b3bce662Sdanielk1977 } 917b3bce662Sdanielk1977 } 918955de52cSdanielk1977 9197e62779aSdrh if( pTab==0 ){ 9207e62779aSdrh /* FIX ME: 9217e62779aSdrh ** This can occurs if you have something like "SELECT new.x;" inside 9227e62779aSdrh ** a trigger. In other words, if you reference the special "new" 9237e62779aSdrh ** table in the result set of a select. We do not have a good way 9247e62779aSdrh ** to find the actual table type, so call it "TEXT". This is really 9257e62779aSdrh ** something of a bug, but I do not know how to fix it. 9267e62779aSdrh ** 9277e62779aSdrh ** This code does not produce the correct answer - it just prevents 9287e62779aSdrh ** a segfault. See ticket #1229. 9297e62779aSdrh */ 9307e62779aSdrh zType = "TEXT"; 9317e62779aSdrh break; 9327e62779aSdrh } 933955de52cSdanielk1977 934b3bce662Sdanielk1977 assert( pTab ); 935955de52cSdanielk1977 if( pS ){ 936955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 937955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 938955de52cSdanielk1977 ** data for the result-set column of the sub-select. 939955de52cSdanielk1977 */ 940955de52cSdanielk1977 if( iCol>=0 && iCol<pS->pEList->nExpr ){ 941955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 942955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 943955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 944955de52cSdanielk1977 */ 945955de52cSdanielk1977 NameContext sNC; 946955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 947955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 948955de52cSdanielk1977 sNC.pNext = 0; 949955de52cSdanielk1977 sNC.pParse = pNC->pParse; 950955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 951955de52cSdanielk1977 } 9524b2688abSdanielk1977 }else if( pTab->pSchema ){ 953955de52cSdanielk1977 /* A real table */ 954955de52cSdanielk1977 assert( !pS ); 955fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 956fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 957fcb78a49Sdrh if( iCol<0 ){ 958fcb78a49Sdrh zType = "INTEGER"; 959955de52cSdanielk1977 zOriginCol = "rowid"; 960fcb78a49Sdrh }else{ 961fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 962955de52cSdanielk1977 zOriginCol = pTab->aCol[iCol].zName; 963955de52cSdanielk1977 } 964955de52cSdanielk1977 zOriginTab = pTab->zName; 965955de52cSdanielk1977 if( pNC->pParse ){ 966955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 967955de52cSdanielk1977 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 968955de52cSdanielk1977 } 969fcb78a49Sdrh } 97000e279d9Sdanielk1977 break; 971736c22b8Sdrh } 97293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 97300e279d9Sdanielk1977 case TK_SELECT: { 974955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 975955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 976955de52cSdanielk1977 ** statement. 977955de52cSdanielk1977 */ 978b3bce662Sdanielk1977 NameContext sNC; 97900e279d9Sdanielk1977 Select *pS = pExpr->pSelect; 980955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 981955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 982b3bce662Sdanielk1977 sNC.pNext = pNC; 983955de52cSdanielk1977 sNC.pParse = pNC->pParse; 984955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 98500e279d9Sdanielk1977 break; 986fcb78a49Sdrh } 98793758c8dSdanielk1977 #endif 98800e279d9Sdanielk1977 } 98900e279d9Sdanielk1977 990955de52cSdanielk1977 if( pzOriginDb ){ 991955de52cSdanielk1977 assert( pzOriginTab && pzOriginCol ); 992955de52cSdanielk1977 *pzOriginDb = zOriginDb; 993955de52cSdanielk1977 *pzOriginTab = zOriginTab; 994955de52cSdanielk1977 *pzOriginCol = zOriginCol; 995955de52cSdanielk1977 } 996517eb646Sdanielk1977 return zType; 997517eb646Sdanielk1977 } 998517eb646Sdanielk1977 999517eb646Sdanielk1977 /* 1000517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1001517eb646Sdanielk1977 ** in the result set. 1002517eb646Sdanielk1977 */ 1003517eb646Sdanielk1977 static void generateColumnTypes( 1004517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1005517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1006517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1007517eb646Sdanielk1977 ){ 1008517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1009517eb646Sdanielk1977 int i; 1010b3bce662Sdanielk1977 NameContext sNC; 1011b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1012955de52cSdanielk1977 sNC.pParse = pParse; 1013517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1014517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 1015955de52cSdanielk1977 const char *zOrigDb = 0; 1016955de52cSdanielk1977 const char *zOrigTab = 0; 1017955de52cSdanielk1977 const char *zOrigCol = 0; 1018955de52cSdanielk1977 const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1019955de52cSdanielk1977 102085b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 10214b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 10224b1ae99dSdanielk1977 ** virtual machine is deleted. 1023fbcd585fSdanielk1977 */ 102466a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT); 102566a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT); 102666a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT); 102766a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT); 1028fcb78a49Sdrh } 1029fcb78a49Sdrh } 1030fcb78a49Sdrh 1031fcb78a49Sdrh /* 1032fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1033fcb78a49Sdrh ** in the result set. This information is used to provide the 1034fcabd464Sdrh ** azCol[] values in the callback. 103582c3d636Sdrh */ 1036832508b7Sdrh static void generateColumnNames( 1037832508b7Sdrh Parse *pParse, /* Parser context */ 1038ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1039832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1040832508b7Sdrh ){ 1041d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 10426a3ea0e6Sdrh int i, j; 10439bb575fdSdrh sqlite3 *db = pParse->db; 1044fcabd464Sdrh int fullNames, shortNames; 1045fcabd464Sdrh 1046fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 10473cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 10483cf86063Sdanielk1977 if( pParse->explain ){ 104961de0d1bSdanielk1977 return; 10503cf86063Sdanielk1977 } 10515338a5f7Sdanielk1977 #endif 10523cf86063Sdanielk1977 1053d6502758Sdrh assert( v!=0 ); 105417435752Sdrh if( pParse->colNamesSet || v==0 || db->mallocFailed ) return; 1055d8bc7086Sdrh pParse->colNamesSet = 1; 1056fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1057fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 105822322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 105982c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 106082c3d636Sdrh Expr *p; 10615a38705eSdrh p = pEList->a[i].pExpr; 10625a38705eSdrh if( p==0 ) continue; 106382c3d636Sdrh if( pEList->a[i].zName ){ 106482c3d636Sdrh char *zName = pEList->a[i].zName; 1065955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName)); 106682c3d636Sdrh continue; 106782c3d636Sdrh } 1068fa173a76Sdrh if( p->op==TK_COLUMN && pTabList ){ 10696a3ea0e6Sdrh Table *pTab; 107097665873Sdrh char *zCol; 10718aff1015Sdrh int iCol = p->iColumn; 10726a3ea0e6Sdrh for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 10736a3ea0e6Sdrh assert( j<pTabList->nSrc ); 10746a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 10758aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 107697665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1077b1363206Sdrh if( iCol<0 ){ 107847a6db2bSdrh zCol = "rowid"; 1079b1363206Sdrh }else{ 1080b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1081b1363206Sdrh } 1082fcabd464Sdrh if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ 1083955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 1084fcabd464Sdrh }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ 108582c3d636Sdrh char *zName = 0; 108682c3d636Sdrh char *zTab; 108782c3d636Sdrh 10886a3ea0e6Sdrh zTab = pTabList->a[j].zAlias; 1089fcabd464Sdrh if( fullNames || zTab==0 ) zTab = pTab->zName; 1090f93339deSdrh sqlite3SetString(&zName, zTab, ".", zCol, (char*)0); 109166a5167bSdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC); 109282c3d636Sdrh }else{ 1093955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol)); 109482c3d636Sdrh } 10956977fea8Sdrh }else if( p->span.z && p->span.z[0] ){ 1096955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 10973cf86063Sdanielk1977 /* sqlite3VdbeCompressSpace(v, addr); */ 10981bee3d7bSdrh }else{ 10991bee3d7bSdrh char zName[30]; 11001bee3d7bSdrh assert( p->op!=TK_COLUMN || pTabList==0 ); 11015bb3eb9bSdrh sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1); 1102955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0); 110382c3d636Sdrh } 110482c3d636Sdrh } 110576d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 11065080aaa7Sdrh } 110782c3d636Sdrh 110893758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 110982c3d636Sdrh /* 1110d8bc7086Sdrh ** Name of the connection operator, used for error messages. 1111d8bc7086Sdrh */ 1112d8bc7086Sdrh static const char *selectOpName(int id){ 1113d8bc7086Sdrh char *z; 1114d8bc7086Sdrh switch( id ){ 1115d8bc7086Sdrh case TK_ALL: z = "UNION ALL"; break; 1116d8bc7086Sdrh case TK_INTERSECT: z = "INTERSECT"; break; 1117d8bc7086Sdrh case TK_EXCEPT: z = "EXCEPT"; break; 1118d8bc7086Sdrh default: z = "UNION"; break; 1119d8bc7086Sdrh } 1120d8bc7086Sdrh return z; 1121d8bc7086Sdrh } 112293758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1123d8bc7086Sdrh 1124d8bc7086Sdrh /* 1125315555caSdrh ** Forward declaration 1126315555caSdrh */ 11279b3187e1Sdrh static int prepSelectStmt(Parse*, Select*); 1128315555caSdrh 1129315555caSdrh /* 113022f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes 113122f70c32Sdrh ** the result set of that SELECT. 113222f70c32Sdrh */ 11334adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 113422f70c32Sdrh Table *pTab; 1135b733d037Sdrh int i, j; 113622f70c32Sdrh ExprList *pEList; 1137290c1948Sdrh Column *aCol, *pCol; 113817435752Sdrh sqlite3 *db = pParse->db; 113922f70c32Sdrh 114092378253Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 11419b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 114222f70c32Sdrh return 0; 114322f70c32Sdrh } 1144142bdf40Sdanielk1977 if( sqlite3SelectResolve(pParse, pSelect, 0) ){ 1145142bdf40Sdanielk1977 return 0; 1146142bdf40Sdanielk1977 } 114717435752Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 114822f70c32Sdrh if( pTab==0 ){ 114922f70c32Sdrh return 0; 115022f70c32Sdrh } 1151ed8a3bb1Sdrh pTab->nRef = 1; 115217435752Sdrh pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0; 115322f70c32Sdrh pEList = pSelect->pEList; 115422f70c32Sdrh pTab->nCol = pEList->nExpr; 1155417be79cSdrh assert( pTab->nCol>0 ); 115617435752Sdrh pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol); 1157290c1948Sdrh for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){ 115879d5f63fSdrh Expr *p, *pR; 1159517eb646Sdanielk1977 char *zType; 116091bb0eedSdrh char *zName; 11612564ef97Sdrh int nName; 1162b3bf556eSdanielk1977 CollSeq *pColl; 116379d5f63fSdrh int cnt; 1164b3bce662Sdanielk1977 NameContext sNC; 116579d5f63fSdrh 116679d5f63fSdrh /* Get an appropriate name for the column 116779d5f63fSdrh */ 116879d5f63fSdrh p = pEList->a[i].pExpr; 1169290c1948Sdrh assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 ); 117091bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 117179d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 117217435752Sdrh zName = sqlite3DbStrDup(db, zName); 1173517eb646Sdanielk1977 }else if( p->op==TK_DOT 1174b733d037Sdrh && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ 117579d5f63fSdrh /* For columns of the from A.B use B as the name */ 117617435752Sdrh zName = sqlite3MPrintf(db, "%T", &pR->token); 1177b733d037Sdrh }else if( p->span.z && p->span.z[0] ){ 117879d5f63fSdrh /* Use the original text of the column expression as its name */ 117917435752Sdrh zName = sqlite3MPrintf(db, "%T", &p->span); 118022f70c32Sdrh }else{ 118179d5f63fSdrh /* If all else fails, make up a name */ 118217435752Sdrh zName = sqlite3MPrintf(db, "column%d", i+1); 118322f70c32Sdrh } 11847751940dSdanielk1977 if( !zName || db->mallocFailed ){ 11857751940dSdanielk1977 db->mallocFailed = 1; 118617435752Sdrh sqlite3_free(zName); 1187a04a34ffSdanielk1977 sqlite3DeleteTable(pTab); 1188dd5b2fa5Sdrh return 0; 1189dd5b2fa5Sdrh } 11907751940dSdanielk1977 sqlite3Dequote(zName); 119179d5f63fSdrh 119279d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 119379d5f63fSdrh ** append a integer to the name so that it becomes unique. 119479d5f63fSdrh */ 11952564ef97Sdrh nName = strlen(zName); 119679d5f63fSdrh for(j=cnt=0; j<i; j++){ 119779d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 11982564ef97Sdrh zName[nName] = 0; 11991e536953Sdanielk1977 zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt); 120079d5f63fSdrh j = -1; 1201dd5b2fa5Sdrh if( zName==0 ) break; 120279d5f63fSdrh } 120379d5f63fSdrh } 120491bb0eedSdrh pCol->zName = zName; 1205e014a838Sdanielk1977 120679d5f63fSdrh /* Get the typename, type affinity, and collating sequence for the 120779d5f63fSdrh ** column. 120879d5f63fSdrh */ 1209c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1210b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 121117435752Sdrh zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); 1212290c1948Sdrh pCol->zType = zType; 1213c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1214b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1215b3bf556eSdanielk1977 if( pColl ){ 121617435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 12170202b29eSdanielk1977 } 121822f70c32Sdrh } 121922f70c32Sdrh pTab->iPKey = -1; 122022f70c32Sdrh return pTab; 122122f70c32Sdrh } 122222f70c32Sdrh 122322f70c32Sdrh /* 12249b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following 12259b3187e1Sdrh ** things: 1226d8bc7086Sdrh ** 12279b3187e1Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 12289b3187e1Sdrh ** element of the FROM clause. 12299b3187e1Sdrh ** 12309b3187e1Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 12319b3187e1Sdrh ** defines FROM clause. When views appear in the FROM clause, 123263eb5f29Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 123363eb5f29Sdrh ** that implements the view. A copy is made of the view's SELECT 123463eb5f29Sdrh ** statement so that we can freely modify or delete that statement 123563eb5f29Sdrh ** without worrying about messing up the presistent representation 123663eb5f29Sdrh ** of the view. 1237d8bc7086Sdrh ** 12389b3187e1Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 1239ad2d8307Sdrh ** on joins and the ON and USING clause of joins. 1240ad2d8307Sdrh ** 12419b3187e1Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 124254473229Sdrh ** for instances of the "*" operator or the TABLE.* operator. 124354473229Sdrh ** If found, expand each "*" to be every column in every table 124454473229Sdrh ** and TABLE.* to be every column in TABLE. 1245d8bc7086Sdrh ** 1246d8bc7086Sdrh ** Return 0 on success. If there are problems, leave an error message 1247d8bc7086Sdrh ** in pParse and return non-zero. 1248d8bc7086Sdrh */ 12499b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){ 125054473229Sdrh int i, j, k, rc; 1251ad3cab52Sdrh SrcList *pTabList; 1252daffd0e5Sdrh ExprList *pEList; 1253290c1948Sdrh struct SrcList_item *pFrom; 125417435752Sdrh sqlite3 *db = pParse->db; 1255daffd0e5Sdrh 125617435752Sdrh if( p==0 || p->pSrc==0 || db->mallocFailed ){ 12576f7adc8aSdrh return 1; 12586f7adc8aSdrh } 1259daffd0e5Sdrh pTabList = p->pSrc; 1260daffd0e5Sdrh pEList = p->pEList; 1261d8bc7086Sdrh 12629b3187e1Sdrh /* Make sure cursor numbers have been assigned to all entries in 12639b3187e1Sdrh ** the FROM clause of the SELECT statement. 12649b3187e1Sdrh */ 12659b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, p->pSrc); 12669b3187e1Sdrh 12679b3187e1Sdrh /* Look up every table named in the FROM clause of the select. If 12689b3187e1Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 12699b3187e1Sdrh ** then create a transient table structure to describe the subquery. 1270d8bc7086Sdrh */ 1271290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1272f0113000Sdanielk1977 Table *pTab; 12739b3187e1Sdrh if( pFrom->pTab!=0 ){ 12749b3187e1Sdrh /* This statement has already been prepared. There is no need 12759b3187e1Sdrh ** to go further. */ 12769b3187e1Sdrh assert( i==0 ); 1277d8bc7086Sdrh return 0; 1278d8bc7086Sdrh } 1279290c1948Sdrh if( pFrom->zName==0 ){ 128093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 128122f70c32Sdrh /* A sub-query in the FROM clause of a SELECT */ 1282290c1948Sdrh assert( pFrom->pSelect!=0 ); 1283290c1948Sdrh if( pFrom->zAlias==0 ){ 128491bb0eedSdrh pFrom->zAlias = 12851e536953Sdanielk1977 sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect); 1286ad2d8307Sdrh } 1287ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1288290c1948Sdrh pFrom->pTab = pTab = 1289290c1948Sdrh sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect); 129022f70c32Sdrh if( pTab==0 ){ 1291daffd0e5Sdrh return 1; 1292daffd0e5Sdrh } 1293b9bb7c18Sdrh /* The isEphem flag indicates that the Table structure has been 12945cf590c1Sdrh ** dynamically allocated and may be freed at any time. In other words, 12955cf590c1Sdrh ** pTab is not pointing to a persistent table structure that defines 12965cf590c1Sdrh ** part of the schema. */ 1297b9bb7c18Sdrh pTab->isEphem = 1; 129893758c8dSdanielk1977 #endif 129922f70c32Sdrh }else{ 1300a76b5dfcSdrh /* An ordinary table or view name in the FROM clause */ 1301ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1302290c1948Sdrh pFrom->pTab = pTab = 1303ca424114Sdrh sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase); 1304a76b5dfcSdrh if( pTab==0 ){ 1305d8bc7086Sdrh return 1; 1306d8bc7086Sdrh } 1307ed8a3bb1Sdrh pTab->nRef++; 130893626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 130993626f48Sdanielk1977 if( pTab->pSelect || IsVirtual(pTab) ){ 131063eb5f29Sdrh /* We reach here if the named table is a really a view */ 13114adee20fSdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 1312417be79cSdrh return 1; 1313417be79cSdrh } 1314290c1948Sdrh /* If pFrom->pSelect!=0 it means we are dealing with a 131563eb5f29Sdrh ** view within a view. The SELECT structure has already been 131663eb5f29Sdrh ** copied by the outer view so we can skip the copy step here 131763eb5f29Sdrh ** in the inner view. 131863eb5f29Sdrh */ 1319290c1948Sdrh if( pFrom->pSelect==0 ){ 132017435752Sdrh pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect); 1321a76b5dfcSdrh } 1322d8bc7086Sdrh } 132393758c8dSdanielk1977 #endif 132422f70c32Sdrh } 132563eb5f29Sdrh } 1326d8bc7086Sdrh 1327ad2d8307Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 1328ad2d8307Sdrh */ 1329ad2d8307Sdrh if( sqliteProcessJoin(pParse, p) ) return 1; 1330ad2d8307Sdrh 13317c917d19Sdrh /* For every "*" that occurs in the column list, insert the names of 133254473229Sdrh ** all columns in all tables. And for every TABLE.* insert the names 133354473229Sdrh ** of all columns in TABLE. The parser inserted a special expression 13347c917d19Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 13357c917d19Sdrh ** The following code just has to locate the TK_ALL expressions and expand 13367c917d19Sdrh ** each one to the list of all columns in all tables. 133754473229Sdrh ** 133854473229Sdrh ** The first loop just checks to see if there are any "*" operators 133954473229Sdrh ** that need expanding. 1340d8bc7086Sdrh */ 13417c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 134254473229Sdrh Expr *pE = pEList->a[k].pExpr; 134354473229Sdrh if( pE->op==TK_ALL ) break; 134454473229Sdrh if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 134554473229Sdrh && pE->pLeft && pE->pLeft->op==TK_ID ) break; 13467c917d19Sdrh } 134754473229Sdrh rc = 0; 13487c917d19Sdrh if( k<pEList->nExpr ){ 134954473229Sdrh /* 135054473229Sdrh ** If we get here it means the result set contains one or more "*" 135154473229Sdrh ** operators that need to be expanded. Loop through each expression 135254473229Sdrh ** in the result set and expand them one by one. 135354473229Sdrh */ 13547c917d19Sdrh struct ExprList_item *a = pEList->a; 13557c917d19Sdrh ExprList *pNew = 0; 1356d70dc52dSdrh int flags = pParse->db->flags; 1357d70dc52dSdrh int longNames = (flags & SQLITE_FullColNames)!=0 && 1358d70dc52dSdrh (flags & SQLITE_ShortColNames)==0; 1359d70dc52dSdrh 13607c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 136154473229Sdrh Expr *pE = a[k].pExpr; 136254473229Sdrh if( pE->op!=TK_ALL && 136354473229Sdrh (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 136454473229Sdrh /* This particular expression does not need to be expanded. 136554473229Sdrh */ 136617435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0); 1367261919ccSdanielk1977 if( pNew ){ 13687c917d19Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 1369261919ccSdanielk1977 }else{ 1370261919ccSdanielk1977 rc = 1; 1371261919ccSdanielk1977 } 13727c917d19Sdrh a[k].pExpr = 0; 13737c917d19Sdrh a[k].zName = 0; 13747c917d19Sdrh }else{ 137554473229Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 137654473229Sdrh ** expanded. */ 137754473229Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 1378cf55b7aeSdrh char *zTName; /* text of name of TABLE */ 137954473229Sdrh if( pE->op==TK_DOT && pE->pLeft ){ 138017435752Sdrh zTName = sqlite3NameFromToken(db, &pE->pLeft->token); 138154473229Sdrh }else{ 1382cf55b7aeSdrh zTName = 0; 138354473229Sdrh } 1384290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1385290c1948Sdrh Table *pTab = pFrom->pTab; 1386290c1948Sdrh char *zTabName = pFrom->zAlias; 138754473229Sdrh if( zTabName==0 || zTabName[0]==0 ){ 138854473229Sdrh zTabName = pTab->zName; 138954473229Sdrh } 1390cf55b7aeSdrh if( zTName && (zTabName==0 || zTabName[0]==0 || 1391cf55b7aeSdrh sqlite3StrICmp(zTName, zTabName)!=0) ){ 139254473229Sdrh continue; 139354473229Sdrh } 139454473229Sdrh tableSeen = 1; 1395d8bc7086Sdrh for(j=0; j<pTab->nCol; j++){ 1396f0113000Sdanielk1977 Expr *pExpr, *pRight; 1397ad2d8307Sdrh char *zName = pTab->aCol[j].zName; 1398ad2d8307Sdrh 1399034ca14fSdanielk1977 /* If a column is marked as 'hidden' (currently only possible 1400034ca14fSdanielk1977 ** for virtual tables), do not include it in the expanded 1401034ca14fSdanielk1977 ** result-set list. 1402034ca14fSdanielk1977 */ 1403034ca14fSdanielk1977 if( IsHiddenColumn(&pTab->aCol[j]) ){ 1404034ca14fSdanielk1977 assert(IsVirtual(pTab)); 1405034ca14fSdanielk1977 continue; 1406034ca14fSdanielk1977 } 1407034ca14fSdanielk1977 140891bb0eedSdrh if( i>0 ){ 140991bb0eedSdrh struct SrcList_item *pLeft = &pTabList->a[i-1]; 141061dfc31dSdrh if( (pLeft[1].jointype & JT_NATURAL)!=0 && 141191bb0eedSdrh columnIndex(pLeft->pTab, zName)>=0 ){ 1412ad2d8307Sdrh /* In a NATURAL join, omit the join columns from the 1413ad2d8307Sdrh ** table on the right */ 1414ad2d8307Sdrh continue; 1415ad2d8307Sdrh } 141661dfc31dSdrh if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){ 1417ad2d8307Sdrh /* In a join with a USING clause, omit columns in the 1418ad2d8307Sdrh ** using clause from the table on the right. */ 1419ad2d8307Sdrh continue; 1420ad2d8307Sdrh } 142191bb0eedSdrh } 1422a1644fd8Sdanielk1977 pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); 142322f70c32Sdrh if( pRight==0 ) break; 14241e536953Sdanielk1977 setQuotedToken(pParse, &pRight->token, zName); 1425d70dc52dSdrh if( zTabName && (longNames || pTabList->nSrc>1) ){ 1426a1644fd8Sdanielk1977 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); 1427a1644fd8Sdanielk1977 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 142822f70c32Sdrh if( pExpr==0 ) break; 14291e536953Sdanielk1977 setQuotedToken(pParse, &pLeft->token, zTabName); 14301e536953Sdanielk1977 setToken(&pExpr->span, 14311e536953Sdanielk1977 sqlite3MPrintf(db, "%s.%s", zTabName, zName)); 14326977fea8Sdrh pExpr->span.dyn = 1; 14336977fea8Sdrh pExpr->token.z = 0; 14346977fea8Sdrh pExpr->token.n = 0; 14356977fea8Sdrh pExpr->token.dyn = 0; 143622f70c32Sdrh }else{ 143722f70c32Sdrh pExpr = pRight; 14386977fea8Sdrh pExpr->span = pExpr->token; 1439f3b863edSdanielk1977 pExpr->span.dyn = 0; 144022f70c32Sdrh } 1441d70dc52dSdrh if( longNames ){ 144217435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span); 1443d70dc52dSdrh }else{ 144417435752Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token); 1445d8bc7086Sdrh } 1446d8bc7086Sdrh } 1447d70dc52dSdrh } 144854473229Sdrh if( !tableSeen ){ 1449cf55b7aeSdrh if( zTName ){ 1450cf55b7aeSdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 1451f5db2d3eSdrh }else{ 14524adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no tables specified"); 1453f5db2d3eSdrh } 145454473229Sdrh rc = 1; 145554473229Sdrh } 145617435752Sdrh sqlite3_free(zTName); 14577c917d19Sdrh } 14587c917d19Sdrh } 14594adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 14607c917d19Sdrh p->pEList = pNew; 1461d8bc7086Sdrh } 1462*bb4957f8Sdrh #if SQLITE_MAX_COLUMN 1463*bb4957f8Sdrh if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1464e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 1465e5c941b8Sdrh rc = SQLITE_ERROR; 1466e5c941b8Sdrh } 1467*bb4957f8Sdrh #endif 146817435752Sdrh if( db->mallocFailed ){ 1469f3b863edSdanielk1977 rc = SQLITE_NOMEM; 1470f3b863edSdanielk1977 } 147154473229Sdrh return rc; 1472d8bc7086Sdrh } 1473d8bc7086Sdrh 1474ff78bd2fSdrh /* 14759a99334dSdrh ** pE is a pointer to an expression which is a single term in 14769a99334dSdrh ** ORDER BY or GROUP BY clause. 1477d8bc7086Sdrh ** 14789a99334dSdrh ** If pE evaluates to an integer constant i, then return i. 14799a99334dSdrh ** This is an indication to the caller that it should sort 14809a99334dSdrh ** by the i-th column of the result set. 14819a99334dSdrh ** 14829a99334dSdrh ** If pE is a well-formed expression and the SELECT statement 14839a99334dSdrh ** is not compound, then return 0. This indicates to the 14849a99334dSdrh ** caller that it should sort by the value of the ORDER BY 14859a99334dSdrh ** expression. 14869a99334dSdrh ** 14879a99334dSdrh ** If the SELECT is compound, then attempt to match pE against 14889a99334dSdrh ** result set columns in the left-most SELECT statement. Return 14899a99334dSdrh ** the index i of the matching column, as an indication to the 14909a99334dSdrh ** caller that it should sort by the i-th column. If there is 14919a99334dSdrh ** no match, return -1 and leave an error message in pParse. 1492d8bc7086Sdrh */ 14939a99334dSdrh static int matchOrderByTermToExprList( 14949a99334dSdrh Parse *pParse, /* Parsing context for error messages */ 14959a99334dSdrh Select *pSelect, /* The SELECT statement with the ORDER BY clause */ 14969a99334dSdrh Expr *pE, /* The specific ORDER BY term */ 14979a99334dSdrh int idx, /* When ORDER BY term is this */ 14989a99334dSdrh int isCompound, /* True if this is a compound SELECT */ 14999a99334dSdrh u8 *pHasAgg /* True if expression contains aggregate functions */ 1500d8bc7086Sdrh ){ 15019a99334dSdrh int i; /* Loop counter */ 15029a99334dSdrh ExprList *pEList; /* The columns of the result set */ 15039a99334dSdrh NameContext nc; /* Name context for resolving pE */ 15049a99334dSdrh 15059a99334dSdrh 15069a99334dSdrh /* If the term is an integer constant, return the value of that 15079a99334dSdrh ** constant */ 15089a99334dSdrh pEList = pSelect->pEList; 15099a99334dSdrh if( sqlite3ExprIsInteger(pE, &i) ){ 15109a99334dSdrh if( i<=0 ){ 15119a99334dSdrh /* If i is too small, make it too big. That way the calling 15129a99334dSdrh ** function still sees a value that is out of range, but does 15139a99334dSdrh ** not confuse the column number with 0 or -1 result code. 15149a99334dSdrh */ 15159a99334dSdrh i = pEList->nExpr+1; 15169a99334dSdrh } 15179a99334dSdrh return i; 15189a99334dSdrh } 15199a99334dSdrh 15209a99334dSdrh /* If the term is a simple identifier that try to match that identifier 15219a99334dSdrh ** against a column name in the result set. 15229a99334dSdrh */ 15239a99334dSdrh if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){ 152417435752Sdrh sqlite3 *db = pParse->db; 15259a99334dSdrh char *zCol = sqlite3NameFromToken(db, &pE->token); 1526ef0bea92Sdrh if( zCol==0 ){ 15279a99334dSdrh return -1; 15289a99334dSdrh } 15299a99334dSdrh for(i=0; i<pEList->nExpr; i++){ 15309a99334dSdrh char *zAs = pEList->a[i].zName; 15319a99334dSdrh if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 15329a99334dSdrh sqlite3_free(zCol); 15339a99334dSdrh return i+1; 15349a99334dSdrh } 15359a99334dSdrh } 15369a99334dSdrh sqlite3_free(zCol); 15374c774314Sdrh } 153870517ab9Sdanielk1977 15399a99334dSdrh /* Resolve all names in the ORDER BY term expression 15409a99334dSdrh */ 154170517ab9Sdanielk1977 memset(&nc, 0, sizeof(nc)); 154270517ab9Sdanielk1977 nc.pParse = pParse; 15439a99334dSdrh nc.pSrcList = pSelect->pSrc; 154470517ab9Sdanielk1977 nc.pEList = pEList; 154570517ab9Sdanielk1977 nc.allowAgg = 1; 15464c774314Sdrh nc.nErr = 0; 15479a99334dSdrh if( sqlite3ExprResolveNames(&nc, pE) ){ 15481e281291Sdrh if( isCompound ){ 15491e281291Sdrh sqlite3ErrorClear(pParse); 15501e281291Sdrh return 0; 15511e281291Sdrh }else{ 15529a99334dSdrh return -1; 15539a99334dSdrh } 15541e281291Sdrh } 15559a99334dSdrh if( nc.hasAgg && pHasAgg ){ 15569a99334dSdrh *pHasAgg = 1; 15579a99334dSdrh } 15589a99334dSdrh 15599a99334dSdrh /* For a compound SELECT, we need to try to match the ORDER BY 15609a99334dSdrh ** expression against an expression in the result set 15619a99334dSdrh */ 15629a99334dSdrh if( isCompound ){ 15639a99334dSdrh for(i=0; i<pEList->nExpr; i++){ 15649a99334dSdrh if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){ 15659a99334dSdrh return i+1; 15669a99334dSdrh } 15679a99334dSdrh } 15684c774314Sdrh } 15691e281291Sdrh return 0; 157070517ab9Sdanielk1977 } 157170517ab9Sdanielk1977 15729a99334dSdrh 15739a99334dSdrh /* 15749a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement. 15759a99334dSdrh ** Return the number of errors seen. 15769a99334dSdrh ** 15779a99334dSdrh ** Every term of the ORDER BY or GROUP BY clause needs to be an 15789a99334dSdrh ** expression. If any expression is an integer constant, then 15799a99334dSdrh ** that expression is replaced by the corresponding 15809a99334dSdrh ** expression from the result set. 15819a99334dSdrh */ 15829a99334dSdrh static int processOrderGroupBy( 15839a99334dSdrh Parse *pParse, /* Parsing context. Leave error messages here */ 15849a99334dSdrh Select *pSelect, /* The SELECT statement containing the clause */ 15859a99334dSdrh ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 15869a99334dSdrh int isOrder, /* 1 for ORDER BY. 0 for GROUP BY */ 15879a99334dSdrh u8 *pHasAgg /* Set to TRUE if any term contains an aggregate */ 15889a99334dSdrh ){ 15899a99334dSdrh int i; 15909a99334dSdrh sqlite3 *db = pParse->db; 15919a99334dSdrh ExprList *pEList; 15929a99334dSdrh 159315cdbebeSdanielk1977 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; 1594*bb4957f8Sdrh #if SQLITE_MAX_COLUMN 1595*bb4957f8Sdrh if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 15969a99334dSdrh const char *zType = isOrder ? "ORDER" : "GROUP"; 15979a99334dSdrh sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 15989a99334dSdrh return 1; 15999a99334dSdrh } 1600*bb4957f8Sdrh #endif 16019a99334dSdrh pEList = pSelect->pEList; 16029a99334dSdrh if( pEList==0 ){ 16039a99334dSdrh return 0; 16049a99334dSdrh } 16059a99334dSdrh for(i=0; i<pOrderBy->nExpr; i++){ 16069a99334dSdrh int iCol; 16079a99334dSdrh Expr *pE = pOrderBy->a[i].pExpr; 16089a99334dSdrh iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg); 160970517ab9Sdanielk1977 if( iCol<0 ){ 16109a99334dSdrh return 1; 16119a99334dSdrh } 16129a99334dSdrh if( iCol>pEList->nExpr ){ 16139a99334dSdrh const char *zType = isOrder ? "ORDER" : "GROUP"; 161470517ab9Sdanielk1977 sqlite3ErrorMsg(pParse, 16159a99334dSdrh "%r %s BY term out of range - should be " 16169a99334dSdrh "between 1 and %d", i+1, zType, pEList->nExpr); 16179a99334dSdrh return 1; 16189a99334dSdrh } 16199a99334dSdrh if( iCol>0 ){ 16209a99334dSdrh CollSeq *pColl = pE->pColl; 16219a99334dSdrh int flags = pE->flags & EP_ExpCollate; 16229a99334dSdrh sqlite3ExprDelete(pE); 16239a99334dSdrh pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr); 16249a99334dSdrh pOrderBy->a[i].pExpr = pE; 162515cdbebeSdanielk1977 if( pE && pColl && flags ){ 16269a99334dSdrh pE->pColl = pColl; 16279a99334dSdrh pE->flags |= flags; 16289a99334dSdrh } 16299a99334dSdrh } 16309a99334dSdrh } 16319a99334dSdrh return 0; 16329a99334dSdrh } 16339a99334dSdrh 16349a99334dSdrh /* 16359a99334dSdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return 16369a99334dSdrh ** the number of errors seen. 16379a99334dSdrh ** 16389a99334dSdrh ** The processing depends on whether the SELECT is simple or compound. 16399a99334dSdrh ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY 16409a99334dSdrh ** clause needs to be an expression. If any expression is an integer 16419a99334dSdrh ** constant, then that expression is replaced by the corresponding 16429a99334dSdrh ** expression from the result set. 16439a99334dSdrh ** 16449a99334dSdrh ** For compound SELECT statements, every expression needs to be of 16459a99334dSdrh ** type TK_COLUMN with a iTable value as given in the 4th parameter. 16469a99334dSdrh ** If any expression is an integer, that becomes the column number. 16479a99334dSdrh ** Otherwise, match the expression against result set columns from 16489a99334dSdrh ** the left-most SELECT. 16499a99334dSdrh */ 16509a99334dSdrh static int processCompoundOrderBy( 16519a99334dSdrh Parse *pParse, /* Parsing context. Leave error messages here */ 16529a99334dSdrh Select *pSelect, /* The SELECT statement containing the ORDER BY */ 16539a99334dSdrh int iTable /* Output table for compound SELECT statements */ 16549a99334dSdrh ){ 16559a99334dSdrh int i; 16569a99334dSdrh ExprList *pOrderBy; 16579a99334dSdrh ExprList *pEList; 16581e281291Sdrh sqlite3 *db; 16591e281291Sdrh int moreToDo = 1; 16609a99334dSdrh 16619a99334dSdrh pOrderBy = pSelect->pOrderBy; 16629a99334dSdrh if( pOrderBy==0 ) return 0; 1663*bb4957f8Sdrh db = pParse->db; 1664*bb4957f8Sdrh #if SQLITE_MAX_COLUMN 1665*bb4957f8Sdrh if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 16669a99334dSdrh sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); 16679a99334dSdrh return 1; 16689a99334dSdrh } 1669*bb4957f8Sdrh #endif 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++){ 1679ac559264Sdanielk1977 int iCol = -1; 16808f0ecaaeSdrh Expr *pE, *pDup; 16811e281291Sdrh if( pOrderBy->a[i].done ) continue; 16821e281291Sdrh pE = pOrderBy->a[i].pExpr; 16838f0ecaaeSdrh pDup = sqlite3ExprDup(db, pE); 1684ac559264Sdanielk1977 if( !db->mallocFailed ){ 1685ac559264Sdanielk1977 assert(pDup); 16861e281291Sdrh iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0); 1687ac559264Sdanielk1977 } 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 ** 2426c52e355dSdrh ** (16) The outer query is not an aggregate or the subquery does 2427c52e355dSdrh ** not contain ORDER BY. (Ticket #2942) This used to not matter 2428c52e355dSdrh ** until we introduced the group_concat() function. 2429c52e355dSdrh ** 2430832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 2431832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2432832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2433832508b7Sdrh ** 2434665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 2435832508b7Sdrh ** If flattening is attempted this routine returns 1. 2436832508b7Sdrh ** 2437832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 2438832508b7Sdrh ** the subquery before this routine runs. 24391350b030Sdrh */ 24408c74a8caSdrh static int flattenSubquery( 244117435752Sdrh sqlite3 *db, /* Database connection */ 24428c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 24438c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 24448c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 24458c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 24468c74a8caSdrh ){ 24470bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2448ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2449ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 24500bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 24516a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 245291bb0eedSdrh int i; /* Loop counter */ 245391bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 245491bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 24551350b030Sdrh 2456832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2457832508b7Sdrh */ 2458832508b7Sdrh if( p==0 ) return 0; 2459832508b7Sdrh pSrc = p->pSrc; 2460ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 246191bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 246291bb0eedSdrh pSub = pSubitem->pSelect; 2463832508b7Sdrh assert( pSub!=0 ); 2464ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2465ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2466832508b7Sdrh pSubSrc = pSub->pSrc; 2467832508b7Sdrh assert( pSubSrc ); 2468ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2469ac83963aSdrh ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2470ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 2471ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 2472ac83963aSdrh ** and (14). */ 2473ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2474ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 2475ad91c6cdSdrh if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){ 2476ad91c6cdSdrh return 0; /* Restriction (15) */ 2477ad91c6cdSdrh } 2478ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 2479ac83963aSdrh if( (pSub->isDistinct || pSub->pLimit) 2480ac83963aSdrh && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */ 2481df199a25Sdrh return 0; 2482df199a25Sdrh } 2483ac83963aSdrh if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */ 2484ac83963aSdrh if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){ 2485ac83963aSdrh return 0; /* Restriction (11) */ 2486ac83963aSdrh } 2487c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 2488832508b7Sdrh 24898af4d3acSdrh /* Restriction 3: If the subquery is a join, make sure the subquery is 24908af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 24918af4d3acSdrh ** is not allowed: 24928af4d3acSdrh ** 24938af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 24948af4d3acSdrh ** 24958af4d3acSdrh ** If we flatten the above, we would get 24968af4d3acSdrh ** 24978af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 24988af4d3acSdrh ** 24998af4d3acSdrh ** which is not at all the same thing. 25008af4d3acSdrh */ 250161dfc31dSdrh if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){ 25028af4d3acSdrh return 0; 25038af4d3acSdrh } 25048af4d3acSdrh 25053fc673e6Sdrh /* Restriction 12: If the subquery is the right operand of a left outer 25063fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 25073fc673e6Sdrh ** An examples of why this is not allowed: 25083fc673e6Sdrh ** 25093fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 25103fc673e6Sdrh ** 25113fc673e6Sdrh ** If we flatten the above, we would get 25123fc673e6Sdrh ** 25133fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 25143fc673e6Sdrh ** 25153fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 25163fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 25173fc673e6Sdrh */ 251861dfc31dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){ 25193fc673e6Sdrh return 0; 25203fc673e6Sdrh } 25213fc673e6Sdrh 25220bb28106Sdrh /* If we reach this point, it means flattening is permitted for the 252363eb5f29Sdrh ** iFrom-th entry of the FROM clause in the outer query. 2524832508b7Sdrh */ 2525c31c2eb8Sdrh 2526c31c2eb8Sdrh /* Move all of the FROM elements of the subquery into the 2527c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2528c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2529c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2530c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2531c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2532c31c2eb8Sdrh ** elements we are now copying in. 2533c31c2eb8Sdrh */ 253491bb0eedSdrh iParent = pSubitem->iCursor; 2535c31c2eb8Sdrh { 2536c31c2eb8Sdrh int nSubSrc = pSubSrc->nSrc; 253791bb0eedSdrh int jointype = pSubitem->jointype; 2538c31c2eb8Sdrh 2539a04a34ffSdanielk1977 sqlite3DeleteTable(pSubitem->pTab); 254017435752Sdrh sqlite3_free(pSubitem->zDatabase); 254117435752Sdrh sqlite3_free(pSubitem->zName); 254217435752Sdrh sqlite3_free(pSubitem->zAlias); 2543cfa063b3Sdrh pSubitem->pTab = 0; 2544cfa063b3Sdrh pSubitem->zDatabase = 0; 2545cfa063b3Sdrh pSubitem->zName = 0; 2546cfa063b3Sdrh pSubitem->zAlias = 0; 2547c31c2eb8Sdrh if( nSubSrc>1 ){ 2548c31c2eb8Sdrh int extra = nSubSrc - 1; 2549c31c2eb8Sdrh for(i=1; i<nSubSrc; i++){ 255017435752Sdrh pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0); 2551cfa063b3Sdrh if( pSrc==0 ){ 2552cfa063b3Sdrh p->pSrc = 0; 2553cfa063b3Sdrh return 1; 2554cfa063b3Sdrh } 2555c31c2eb8Sdrh } 2556c31c2eb8Sdrh p->pSrc = pSrc; 2557c31c2eb8Sdrh for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 2558c31c2eb8Sdrh pSrc->a[i] = pSrc->a[i-extra]; 2559c31c2eb8Sdrh } 2560c31c2eb8Sdrh } 2561c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2562c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2563c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2564c31c2eb8Sdrh } 256561dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 2566c31c2eb8Sdrh } 2567c31c2eb8Sdrh 2568c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2569c31c2eb8Sdrh ** references to the iParent in the outer query. 2570c31c2eb8Sdrh ** 2571c31c2eb8Sdrh ** Example: 2572c31c2eb8Sdrh ** 2573c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2574c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 2575c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 2576c31c2eb8Sdrh ** 2577c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 2578c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2579c31c2eb8Sdrh */ 2580832508b7Sdrh pList = p->pEList; 2581832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 25826977fea8Sdrh Expr *pExpr; 25836977fea8Sdrh if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 258417435752Sdrh pList->a[i].zName = 258517435752Sdrh sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n); 2586832508b7Sdrh } 2587832508b7Sdrh } 25881e536953Sdanielk1977 substExprList(db, p->pEList, iParent, pSub->pEList); 25891b2e0329Sdrh if( isAgg ){ 25901e536953Sdanielk1977 substExprList(db, p->pGroupBy, iParent, pSub->pEList); 25911e536953Sdanielk1977 substExpr(db, p->pHaving, iParent, pSub->pEList); 25921b2e0329Sdrh } 2593174b6195Sdrh if( pSub->pOrderBy ){ 2594174b6195Sdrh assert( p->pOrderBy==0 ); 2595174b6195Sdrh p->pOrderBy = pSub->pOrderBy; 2596174b6195Sdrh pSub->pOrderBy = 0; 2597174b6195Sdrh }else if( p->pOrderBy ){ 25981e536953Sdanielk1977 substExprList(db, p->pOrderBy, iParent, pSub->pEList); 2599174b6195Sdrh } 2600832508b7Sdrh if( pSub->pWhere ){ 260117435752Sdrh pWhere = sqlite3ExprDup(db, pSub->pWhere); 2602832508b7Sdrh }else{ 2603832508b7Sdrh pWhere = 0; 2604832508b7Sdrh } 2605832508b7Sdrh if( subqueryIsAgg ){ 2606832508b7Sdrh assert( p->pHaving==0 ); 26071b2e0329Sdrh p->pHaving = p->pWhere; 26081b2e0329Sdrh p->pWhere = pWhere; 26091e536953Sdanielk1977 substExpr(db, p->pHaving, iParent, pSub->pEList); 261017435752Sdrh p->pHaving = sqlite3ExprAnd(db, p->pHaving, 261117435752Sdrh sqlite3ExprDup(db, pSub->pHaving)); 26121b2e0329Sdrh assert( p->pGroupBy==0 ); 261317435752Sdrh p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy); 2614832508b7Sdrh }else{ 26151e536953Sdanielk1977 substExpr(db, p->pWhere, iParent, pSub->pEList); 261617435752Sdrh p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere); 2617832508b7Sdrh } 2618c31c2eb8Sdrh 2619c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 2620c31c2eb8Sdrh ** outer query is distinct. 2621c31c2eb8Sdrh */ 2622832508b7Sdrh p->isDistinct = p->isDistinct || pSub->isDistinct; 26238c74a8caSdrh 2624a58fdfb1Sdanielk1977 /* 2625a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 2626ac83963aSdrh ** 2627ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 2628ac83963aSdrh ** does not work if either limit is negative. 2629a58fdfb1Sdanielk1977 */ 2630a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 2631a2dc3b1aSdanielk1977 p->pLimit = pSub->pLimit; 2632a2dc3b1aSdanielk1977 pSub->pLimit = 0; 2633df199a25Sdrh } 26348c74a8caSdrh 2635c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 2636c31c2eb8Sdrh ** success. 2637c31c2eb8Sdrh */ 26384adee20fSdanielk1977 sqlite3SelectDelete(pSub); 2639832508b7Sdrh return 1; 26401350b030Sdrh } 2641b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 26421350b030Sdrh 26431350b030Sdrh /* 2644a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it 2645a9d1ccb9Sdanielk1977 ** is a min() or max() query. Return ORDERBY_MIN or ORDERBY_MAX if 2646a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be 2647a9d1ccb9Sdanielk1977 ** a min()/max() query if: 2648a9d1ccb9Sdanielk1977 ** 2649738bdcfbSdanielk1977 ** 1. There is a single object in the FROM clause. 2650738bdcfbSdanielk1977 ** 2651738bdcfbSdanielk1977 ** 2. There is a single expression in the result set, and it is 2652738bdcfbSdanielk1977 ** either min(x) or max(x), where x is a column reference. 2653a9d1ccb9Sdanielk1977 */ 2654a9d1ccb9Sdanielk1977 static int minMaxQuery(Parse *pParse, Select *p){ 2655a9d1ccb9Sdanielk1977 Expr *pExpr; 2656a9d1ccb9Sdanielk1977 ExprList *pEList = p->pEList; 2657a9d1ccb9Sdanielk1977 2658a9d1ccb9Sdanielk1977 if( pEList->nExpr!=1 ) return ORDERBY_NORMAL; 2659a9d1ccb9Sdanielk1977 pExpr = pEList->a[0].pExpr; 2660a9d1ccb9Sdanielk1977 pEList = pExpr->pList; 2661a9d1ccb9Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0; 2662a9d1ccb9Sdanielk1977 if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return ORDERBY_NORMAL; 2663a9d1ccb9Sdanielk1977 if( pExpr->token.n!=3 ) return ORDERBY_NORMAL; 2664a9d1ccb9Sdanielk1977 if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ 2665a9d1ccb9Sdanielk1977 return ORDERBY_MIN; 2666a9d1ccb9Sdanielk1977 }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ 2667a9d1ccb9Sdanielk1977 return ORDERBY_MAX; 2668a9d1ccb9Sdanielk1977 } 2669a9d1ccb9Sdanielk1977 return ORDERBY_NORMAL; 2670a9d1ccb9Sdanielk1977 } 2671a9d1ccb9Sdanielk1977 2672a9d1ccb9Sdanielk1977 /* 2673b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the 2674b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved 2675b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext 2676b3bce662Sdanielk1977 ** of the parent SELECT. 2677b3bce662Sdanielk1977 */ 2678b3bce662Sdanielk1977 int sqlite3SelectResolve( 2679b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 2680b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 2681b3bce662Sdanielk1977 NameContext *pOuterNC /* The outer name context. May be NULL. */ 2682b3bce662Sdanielk1977 ){ 2683b3bce662Sdanielk1977 ExprList *pEList; /* Result set. */ 2684b3bce662Sdanielk1977 int i; /* For-loop variable used in multiple places */ 2685b3bce662Sdanielk1977 NameContext sNC; /* Local name-context */ 268613449892Sdrh ExprList *pGroupBy; /* The group by clause */ 2687b3bce662Sdanielk1977 2688b3bce662Sdanielk1977 /* If this routine has run before, return immediately. */ 2689b3bce662Sdanielk1977 if( p->isResolved ){ 2690b3bce662Sdanielk1977 assert( !pOuterNC ); 2691b3bce662Sdanielk1977 return SQLITE_OK; 2692b3bce662Sdanielk1977 } 2693b3bce662Sdanielk1977 p->isResolved = 1; 2694b3bce662Sdanielk1977 2695b3bce662Sdanielk1977 /* If there have already been errors, do nothing. */ 2696b3bce662Sdanielk1977 if( pParse->nErr>0 ){ 2697b3bce662Sdanielk1977 return SQLITE_ERROR; 2698b3bce662Sdanielk1977 } 2699b3bce662Sdanielk1977 2700b3bce662Sdanielk1977 /* Prepare the select statement. This call will allocate all cursors 2701b3bce662Sdanielk1977 ** required to handle the tables and subqueries in the FROM clause. 2702b3bce662Sdanielk1977 */ 2703b3bce662Sdanielk1977 if( prepSelectStmt(pParse, p) ){ 2704b3bce662Sdanielk1977 return SQLITE_ERROR; 2705b3bce662Sdanielk1977 } 2706b3bce662Sdanielk1977 2707a2dc3b1aSdanielk1977 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 2708a2dc3b1aSdanielk1977 ** are not allowed to refer to any names, so pass an empty NameContext. 2709a2dc3b1aSdanielk1977 */ 2710ffe07b2dSdrh memset(&sNC, 0, sizeof(sNC)); 2711b3bce662Sdanielk1977 sNC.pParse = pParse; 2712a2dc3b1aSdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pLimit) || 2713a2dc3b1aSdanielk1977 sqlite3ExprResolveNames(&sNC, p->pOffset) ){ 2714a2dc3b1aSdanielk1977 return SQLITE_ERROR; 2715a2dc3b1aSdanielk1977 } 2716a2dc3b1aSdanielk1977 2717a2dc3b1aSdanielk1977 /* Set up the local name-context to pass to ExprResolveNames() to 2718a2dc3b1aSdanielk1977 ** resolve the expression-list. 2719a2dc3b1aSdanielk1977 */ 2720a2dc3b1aSdanielk1977 sNC.allowAgg = 1; 2721a2dc3b1aSdanielk1977 sNC.pSrcList = p->pSrc; 2722a2dc3b1aSdanielk1977 sNC.pNext = pOuterNC; 2723b3bce662Sdanielk1977 2724b3bce662Sdanielk1977 /* Resolve names in the result set. */ 2725b3bce662Sdanielk1977 pEList = p->pEList; 2726b3bce662Sdanielk1977 if( !pEList ) return SQLITE_ERROR; 2727b3bce662Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 2728b3bce662Sdanielk1977 Expr *pX = pEList->a[i].pExpr; 2729b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pX) ){ 2730b3bce662Sdanielk1977 return SQLITE_ERROR; 2731b3bce662Sdanielk1977 } 2732b3bce662Sdanielk1977 } 2733b3bce662Sdanielk1977 2734b3bce662Sdanielk1977 /* If there are no aggregate functions in the result-set, and no GROUP BY 2735b3bce662Sdanielk1977 ** expression, do not allow aggregates in any of the other expressions. 2736b3bce662Sdanielk1977 */ 2737b3bce662Sdanielk1977 assert( !p->isAgg ); 273813449892Sdrh pGroupBy = p->pGroupBy; 273913449892Sdrh if( pGroupBy || sNC.hasAgg ){ 2740b3bce662Sdanielk1977 p->isAgg = 1; 2741b3bce662Sdanielk1977 }else{ 2742b3bce662Sdanielk1977 sNC.allowAgg = 0; 2743b3bce662Sdanielk1977 } 2744b3bce662Sdanielk1977 2745b3bce662Sdanielk1977 /* If a HAVING clause is present, then there must be a GROUP BY clause. 2746b3bce662Sdanielk1977 */ 274713449892Sdrh if( p->pHaving && !pGroupBy ){ 2748b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2749b3bce662Sdanielk1977 return SQLITE_ERROR; 2750b3bce662Sdanielk1977 } 2751b3bce662Sdanielk1977 2752b3bce662Sdanielk1977 /* Add the expression list to the name-context before parsing the 2753b3bce662Sdanielk1977 ** other expressions in the SELECT statement. This is so that 2754b3bce662Sdanielk1977 ** expressions in the WHERE clause (etc.) can refer to expressions by 2755b3bce662Sdanielk1977 ** aliases in the result set. 2756b3bce662Sdanielk1977 ** 2757b3bce662Sdanielk1977 ** Minor point: If this is the case, then the expression will be 2758b3bce662Sdanielk1977 ** re-evaluated for each reference to it. 2759b3bce662Sdanielk1977 */ 2760b3bce662Sdanielk1977 sNC.pEList = p->pEList; 2761b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pWhere) || 2762994c80afSdrh sqlite3ExprResolveNames(&sNC, p->pHaving) ){ 2763b3bce662Sdanielk1977 return SQLITE_ERROR; 2764b3bce662Sdanielk1977 } 27659a99334dSdrh if( p->pPrior==0 ){ 276601874bfcSdanielk1977 if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){ 2767994c80afSdrh return SQLITE_ERROR; 2768994c80afSdrh } 27699a99334dSdrh } 27709a99334dSdrh if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){ 27714c774314Sdrh return SQLITE_ERROR; 2772994c80afSdrh } 2773b3bce662Sdanielk1977 27741e536953Sdanielk1977 if( pParse->db->mallocFailed ){ 27759afe689eSdanielk1977 return SQLITE_NOMEM; 27769afe689eSdanielk1977 } 27779afe689eSdanielk1977 277813449892Sdrh /* Make sure the GROUP BY clause does not contain aggregate functions. 277913449892Sdrh */ 278013449892Sdrh if( pGroupBy ){ 278113449892Sdrh struct ExprList_item *pItem; 278213449892Sdrh 278313449892Sdrh for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 278413449892Sdrh if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 278513449892Sdrh sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 278613449892Sdrh "the GROUP BY clause"); 278713449892Sdrh return SQLITE_ERROR; 278813449892Sdrh } 278913449892Sdrh } 279013449892Sdrh } 279113449892Sdrh 2792f6bbe022Sdrh /* If this is one SELECT of a compound, be sure to resolve names 2793f6bbe022Sdrh ** in the other SELECTs. 2794f6bbe022Sdrh */ 2795f6bbe022Sdrh if( p->pPrior ){ 2796f6bbe022Sdrh return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC); 2797f6bbe022Sdrh }else{ 2798b3bce662Sdanielk1977 return SQLITE_OK; 2799b3bce662Sdanielk1977 } 2800f6bbe022Sdrh } 2801b3bce662Sdanielk1977 2802b3bce662Sdanielk1977 /* 280313449892Sdrh ** Reset the aggregate accumulator. 280413449892Sdrh ** 280513449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 280613449892Sdrh ** intermediate results while calculating an aggregate. This 280713449892Sdrh ** routine simply stores NULLs in all of those memory cells. 2808b3bce662Sdanielk1977 */ 280913449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 281013449892Sdrh Vdbe *v = pParse->pVdbe; 281113449892Sdrh int i; 2812c99130fdSdrh struct AggInfo_func *pFunc; 281313449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 281413449892Sdrh return; 281513449892Sdrh } 281613449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 28174c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); 281813449892Sdrh } 2819c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 28204c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); 2821c99130fdSdrh if( pFunc->iDistinct>=0 ){ 2822c99130fdSdrh Expr *pE = pFunc->pExpr; 2823c99130fdSdrh if( pE->pList==0 || pE->pList->nExpr!=1 ){ 2824c99130fdSdrh sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " 2825c99130fdSdrh "by an expression"); 2826c99130fdSdrh pFunc->iDistinct = -1; 2827c99130fdSdrh }else{ 2828c99130fdSdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); 282966a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 283066a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 2831c99130fdSdrh } 2832c99130fdSdrh } 283313449892Sdrh } 2834b3bce662Sdanielk1977 } 2835b3bce662Sdanielk1977 2836b3bce662Sdanielk1977 /* 283713449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 283813449892Sdrh ** in the AggInfo structure. 2839b3bce662Sdanielk1977 */ 284013449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 284113449892Sdrh Vdbe *v = pParse->pVdbe; 284213449892Sdrh int i; 284313449892Sdrh struct AggInfo_func *pF; 284413449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 2845a10a34b8Sdrh ExprList *pList = pF->pExpr->pList; 284666a5167bSdrh sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 284766a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 2848b3bce662Sdanielk1977 } 284913449892Sdrh } 285013449892Sdrh 285113449892Sdrh /* 285213449892Sdrh ** Update the accumulator memory cells for an aggregate based on 285313449892Sdrh ** the current cursor position. 285413449892Sdrh */ 285513449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 285613449892Sdrh Vdbe *v = pParse->pVdbe; 285713449892Sdrh int i; 285813449892Sdrh struct AggInfo_func *pF; 285913449892Sdrh struct AggInfo_col *pC; 286013449892Sdrh 286113449892Sdrh pAggInfo->directMode = 1; 286213449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 286313449892Sdrh int nArg; 2864c99130fdSdrh int addrNext = 0; 286598757157Sdrh int regAgg; 286613449892Sdrh ExprList *pList = pF->pExpr->pList; 286713449892Sdrh if( pList ){ 286813449892Sdrh nArg = pList->nExpr; 2869892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 2870892d3179Sdrh sqlite3ExprCodeExprList(pParse, pList, regAgg); 287113449892Sdrh }else{ 287213449892Sdrh nArg = 0; 287398757157Sdrh regAgg = 0; 287413449892Sdrh } 2875c99130fdSdrh if( pF->iDistinct>=0 ){ 2876c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 2877c99130fdSdrh assert( nArg==1 ); 28782dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 2879c99130fdSdrh } 288013449892Sdrh if( pF->pFunc->needCollSeq ){ 288113449892Sdrh CollSeq *pColl = 0; 288213449892Sdrh struct ExprList_item *pItem; 288313449892Sdrh int j; 288443617e9aSdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */ 288543617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 288613449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 288713449892Sdrh } 288813449892Sdrh if( !pColl ){ 288913449892Sdrh pColl = pParse->db->pDfltColl; 289013449892Sdrh } 289166a5167bSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 289213449892Sdrh } 289398757157Sdrh sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 289466a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 289598757157Sdrh sqlite3VdbeChangeP5(v, nArg); 2896892d3179Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 2897c99130fdSdrh if( addrNext ){ 2898c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 2899c99130fdSdrh } 290013449892Sdrh } 290113449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 2902389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 290313449892Sdrh } 290413449892Sdrh pAggInfo->directMode = 0; 290513449892Sdrh } 290613449892Sdrh 29078f2c54e6Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER 29088f2c54e6Sdanielk1977 /* 29098f2c54e6Sdanielk1977 ** This function is used when a SELECT statement is used to create a 29108f2c54e6Sdanielk1977 ** temporary table for iterating through when running an INSTEAD OF 29118f2c54e6Sdanielk1977 ** UPDATE or INSTEAD OF DELETE trigger. 29128f2c54e6Sdanielk1977 ** 29138f2c54e6Sdanielk1977 ** If possible, the SELECT statement is modified so that NULL values 29148f2c54e6Sdanielk1977 ** are stored in the temporary table for all columns for which the 29158f2c54e6Sdanielk1977 ** corresponding bit in argument mask is not set. If mask takes the 29168f2c54e6Sdanielk1977 ** special value 0xffffffff, then all columns are populated. 29178f2c54e6Sdanielk1977 */ 2918d2b3e23bSdrh void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){ 2919cdf3020cSdanielk1977 if( p && !p->pPrior && !p->isDistinct && mask!=0xffffffff ){ 29208f2c54e6Sdanielk1977 ExprList *pEList; 29218f2c54e6Sdanielk1977 int i; 2922d2b3e23bSdrh sqlite3SelectResolve(pParse, p, 0); 29238f2c54e6Sdanielk1977 pEList = p->pEList; 2924cdf3020cSdanielk1977 for(i=0; pEList && i<pEList->nExpr && i<32; i++){ 29258f2c54e6Sdanielk1977 if( !(mask&((u32)1<<i)) ){ 29268f2c54e6Sdanielk1977 sqlite3ExprDelete(pEList->a[i].pExpr); 29278f2c54e6Sdanielk1977 pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0); 29288f2c54e6Sdanielk1977 } 29298f2c54e6Sdanielk1977 } 29308f2c54e6Sdanielk1977 } 29318f2c54e6Sdanielk1977 } 29328f2c54e6Sdanielk1977 #endif 2933b3bce662Sdanielk1977 2934b3bce662Sdanielk1977 /* 29359bb61fe7Sdrh ** Generate code for the given SELECT statement. 29369bb61fe7Sdrh ** 2937fef5208cSdrh ** The results are distributed in various ways depending on the 29386c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest 29396c8c8ce0Sdanielk1977 ** as follows: 2940fef5208cSdrh ** 29416c8c8ce0Sdanielk1977 ** pDest->eDest Result 2942fef5208cSdrh ** ------------ ------------------------------------------- 2943fef5208cSdrh ** SRT_Callback Invoke the callback for each row of the result. 2944fef5208cSdrh ** 29456c8c8ce0Sdanielk1977 ** SRT_Mem Store first result in memory cell pDest->iParm 2946fef5208cSdrh ** 29476c8c8ce0Sdanielk1977 ** SRT_Set Store non-null results as keys of table pDest->iParm. 29486c8c8ce0Sdanielk1977 ** Apply the affinity pDest->affinity before storing them. 2949fef5208cSdrh ** 29506c8c8ce0Sdanielk1977 ** SRT_Union Store results as a key in a temporary table pDest->iParm. 295182c3d636Sdrh ** 29526c8c8ce0Sdanielk1977 ** SRT_Except Remove results from the temporary table pDest->iParm. 2953c4a3c779Sdrh ** 29546c8c8ce0Sdanielk1977 ** SRT_Table Store results in temporary table pDest->iParm 29559bb61fe7Sdrh ** 29566c8c8ce0Sdanielk1977 ** SRT_EphemTab Create an temporary table pDest->iParm and store 29576c8c8ce0Sdanielk1977 ** the result there. The cursor is left open after 29586c8c8ce0Sdanielk1977 ** returning. 29596c8c8ce0Sdanielk1977 ** 29606c8c8ce0Sdanielk1977 ** SRT_Subroutine For each row returned, push the results onto the 29616c8c8ce0Sdanielk1977 ** vdbe stack and call the subroutine (via OP_Gosub) 29626c8c8ce0Sdanielk1977 ** at address pDest->iParm. 29636c8c8ce0Sdanielk1977 ** 29646c8c8ce0Sdanielk1977 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result 29656c8c8ce0Sdanielk1977 ** set is not empty. 29666c8c8ce0Sdanielk1977 ** 29676c8c8ce0Sdanielk1977 ** SRT_Discard Throw the results away. 29686c8c8ce0Sdanielk1977 ** 29696c8c8ce0Sdanielk1977 ** See the selectInnerLoop() function for a canonical listing of the 29706c8c8ce0Sdanielk1977 ** allowed values of eDest and their meanings. 2971e78e8284Sdrh ** 29729bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 29739bb61fe7Sdrh ** encountered, then an appropriate error message is left in 29749bb61fe7Sdrh ** pParse->zErrMsg. 29759bb61fe7Sdrh ** 29769bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 29779bb61fe7Sdrh ** calling function needs to do that. 29781b2e0329Sdrh ** 29791b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this 29801b2e0329Sdrh ** SELECT is a subquery. This routine may try to combine this SELECT 29811b2e0329Sdrh ** with its parent to form a single flat query. In so doing, it might 29821b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query. 29831b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it 29841b2e0329Sdrh ** can be changed. 2985e78e8284Sdrh ** 2986e78e8284Sdrh ** Example 1: The meaning of the pParent parameter. 2987e78e8284Sdrh ** 2988e78e8284Sdrh ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2989e78e8284Sdrh ** \ \_______ subquery _______/ / 2990e78e8284Sdrh ** \ / 2991e78e8284Sdrh ** \____________________ outer query ___________________/ 2992e78e8284Sdrh ** 2993e78e8284Sdrh ** This routine is called for the outer query first. For that call, 2994e78e8284Sdrh ** pParent will be NULL. During the processing of the outer query, this 2995e78e8284Sdrh ** routine is called recursively to handle the subquery. For the recursive 2996e78e8284Sdrh ** call, pParent will point to the outer query. Because the subquery is 2997e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will 2998e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.) 29999bb61fe7Sdrh */ 30004adee20fSdanielk1977 int sqlite3Select( 3001cce7d176Sdrh Parse *pParse, /* The parser context */ 30029bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 30036c8c8ce0Sdanielk1977 SelectDest *pDest, /* What to do with the query results */ 3004832508b7Sdrh Select *pParent, /* Another SELECT for which this is a sub-query */ 3005832508b7Sdrh int parentTab, /* Index in pParent->pSrc of this query */ 300684ac9d02Sdanielk1977 int *pParentAgg, /* True if pParent uses aggregate functions */ 3007b3bce662Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 3008cce7d176Sdrh ){ 300913449892Sdrh int i, j; /* Loop counters */ 301013449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 301113449892Sdrh Vdbe *v; /* The virtual machine under construction */ 3012b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 3013a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 3014ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 30159bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 30169bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 30172282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 30182282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 301919a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 302019a775c2Sdrh int distinct; /* Table to use for the distinct set */ 30211d83f052Sdrh int rc = 1; /* Value to return from this function */ 3022b9bb7c18Sdrh int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 302313449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 3024ec7429aeSdrh int iEnd; /* Address of the end of the query */ 302517435752Sdrh sqlite3 *db; /* The database connection */ 30269bb61fe7Sdrh 302717435752Sdrh db = pParse->db; 302817435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 30296f7adc8aSdrh return 1; 30306f7adc8aSdrh } 30314adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 303213449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 3033daffd0e5Sdrh 30349a99334dSdrh pOrderBy = p->pOrderBy; 30356c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 30369a99334dSdrh p->pOrderBy = 0; 30379ed1dfa8Sdanielk1977 30389ed1dfa8Sdanielk1977 /* In these cases the DISTINCT operator makes no difference to the 30399ed1dfa8Sdanielk1977 ** results, so remove it if it were specified. 30409ed1dfa8Sdanielk1977 */ 30419ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 30429ed1dfa8Sdanielk1977 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); 30439ed1dfa8Sdanielk1977 p->isDistinct = 0; 30449a99334dSdrh } 30459a99334dSdrh if( sqlite3SelectResolve(pParse, p, 0) ){ 30469a99334dSdrh goto select_end; 30479a99334dSdrh } 30489a99334dSdrh p->pOrderBy = pOrderBy; 30499a99334dSdrh 3050b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 305182c3d636Sdrh /* If there is are a sequence of queries, do the earlier ones first. 305282c3d636Sdrh */ 305382c3d636Sdrh if( p->pPrior ){ 30540342b1f5Sdrh if( p->pRightmost==0 ){ 30551e281291Sdrh Select *pLoop, *pRight = 0; 30560325d873Sdrh int cnt = 0; 3057*bb4957f8Sdrh int mxSelect; 30580325d873Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 30590342b1f5Sdrh pLoop->pRightmost = p; 30601e281291Sdrh pLoop->pNext = pRight; 30611e281291Sdrh pRight = pLoop; 30620342b1f5Sdrh } 3063*bb4957f8Sdrh mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; 3064*bb4957f8Sdrh if( mxSelect && cnt>mxSelect ){ 30650325d873Sdrh sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 30660325d873Sdrh return 1; 30670325d873Sdrh } 30680342b1f5Sdrh } 30696c8c8ce0Sdanielk1977 return multiSelect(pParse, p, pDest, aff); 307082c3d636Sdrh } 3071b7f9164eSdrh #endif 307282c3d636Sdrh 307382c3d636Sdrh /* Make local copies of the parameters for this query. 307482c3d636Sdrh */ 30759bb61fe7Sdrh pTabList = p->pSrc; 30769bb61fe7Sdrh pWhere = p->pWhere; 30772282792aSdrh pGroupBy = p->pGroupBy; 30782282792aSdrh pHaving = p->pHaving; 3079b3bce662Sdanielk1977 isAgg = p->isAgg; 308019a775c2Sdrh isDistinct = p->isDistinct; 3081b3bce662Sdanielk1977 pEList = p->pEList; 3082b3bce662Sdanielk1977 if( pEList==0 ) goto select_end; 30839bb61fe7Sdrh 30849bb61fe7Sdrh /* 30859bb61fe7Sdrh ** Do not even attempt to generate any code if we have already seen 30869bb61fe7Sdrh ** errors before this routine starts. 30879bb61fe7Sdrh */ 30881d83f052Sdrh if( pParse->nErr>0 ) goto select_end; 3089cce7d176Sdrh 30902282792aSdrh /* If writing to memory or generating a set 30912282792aSdrh ** only a single column may be output. 309219a775c2Sdrh */ 309393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 30946c8c8ce0Sdanielk1977 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 30951d83f052Sdrh goto select_end; 309619a775c2Sdrh } 309793758c8dSdanielk1977 #endif 309819a775c2Sdrh 3099c926afbcSdrh /* ORDER BY is ignored for some destinations. 31002282792aSdrh */ 31016c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 3102acd4c695Sdrh pOrderBy = 0; 31032282792aSdrh } 31042282792aSdrh 3105d820cb1bSdrh /* Begin generating code. 3106d820cb1bSdrh */ 31074adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 3108d820cb1bSdrh if( v==0 ) goto select_end; 3109d820cb1bSdrh 3110d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 3111d820cb1bSdrh */ 311251522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3113ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 3114742f947bSdanielk1977 const char *zSavedAuthContext = 0; 3115c31c2eb8Sdrh int needRestoreContext; 311613449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 31171013c932Sdrh SelectDest dest; 3118c31c2eb8Sdrh 31191787ccabSdanielk1977 if( pItem->pSelect==0 || pItem->isPopulated ) continue; 312013449892Sdrh if( pItem->zName!=0 ){ 31215cf590c1Sdrh zSavedAuthContext = pParse->zAuthContext; 312213449892Sdrh pParse->zAuthContext = pItem->zName; 3123c31c2eb8Sdrh needRestoreContext = 1; 3124c31c2eb8Sdrh }else{ 3125c31c2eb8Sdrh needRestoreContext = 0; 31265cf590c1Sdrh } 3127fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 3128fc976065Sdanielk1977 ** tree refered to by this, the parent select. The child select 3129fc976065Sdanielk1977 ** may contain expression trees of at most 3130fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 3131fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 3132fc976065Sdanielk1977 ** an exact limit. 3133fc976065Sdanielk1977 */ 3134fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 31351013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 31366c8c8ce0Sdanielk1977 sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0); 3137cfa063b3Sdrh if( db->mallocFailed ){ 3138cfa063b3Sdrh goto select_end; 3139cfa063b3Sdrh } 3140fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 3141c31c2eb8Sdrh if( needRestoreContext ){ 31425cf590c1Sdrh pParse->zAuthContext = zSavedAuthContext; 31435cf590c1Sdrh } 3144832508b7Sdrh pTabList = p->pSrc; 3145832508b7Sdrh pWhere = p->pWhere; 31466c8c8ce0Sdanielk1977 if( !IgnorableOrderby(pDest) ){ 3147832508b7Sdrh pOrderBy = p->pOrderBy; 3148acd4c695Sdrh } 3149832508b7Sdrh pGroupBy = p->pGroupBy; 3150832508b7Sdrh pHaving = p->pHaving; 3151832508b7Sdrh isDistinct = p->isDistinct; 31521b2e0329Sdrh } 315351522cd3Sdrh #endif 31541b2e0329Sdrh 31551b2e0329Sdrh /* Check to see if this is a subquery that can be "flattened" into its parent. 31561b2e0329Sdrh ** If flattening is a possiblity, do so and return immediately. 31571b2e0329Sdrh */ 3158b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 31591b2e0329Sdrh if( pParent && pParentAgg && 316017435752Sdrh flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){ 31611b2e0329Sdrh if( isAgg ) *pParentAgg = 1; 3162b3bce662Sdanielk1977 goto select_end; 31631b2e0329Sdrh } 3164b7f9164eSdrh #endif 3165832508b7Sdrh 31660318d441Sdanielk1977 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT. 31670318d441Sdanielk1977 ** GROUP BY may use an index, DISTINCT never does. 31683c4809a2Sdanielk1977 */ 31693c4809a2Sdanielk1977 if( p->isDistinct && !p->isAgg && !p->pGroupBy ){ 31703c4809a2Sdanielk1977 p->pGroupBy = sqlite3ExprListDup(db, p->pEList); 31713c4809a2Sdanielk1977 pGroupBy = p->pGroupBy; 31723c4809a2Sdanielk1977 p->isDistinct = 0; 31733c4809a2Sdanielk1977 isDistinct = 0; 31743c4809a2Sdanielk1977 } 31753c4809a2Sdanielk1977 31768b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 31778b4c40d8Sdrh ** index might end up being unused if the data can be 31789d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 3179b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 31809d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 31819d2985c7Sdrh ** variable is used to facilitate that change. 31827cedc8d4Sdanielk1977 */ 31837cedc8d4Sdanielk1977 if( pOrderBy ){ 31840342b1f5Sdrh KeyInfo *pKeyInfo; 31850342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 31869d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 3187b9bb7c18Sdrh p->addrOpenEphm[2] = addrSortIndex = 318866a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 318966a5167bSdrh pOrderBy->iECursor, pOrderBy->nExpr+2, 0, 319066a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 31919d2985c7Sdrh }else{ 31929d2985c7Sdrh addrSortIndex = -1; 31937cedc8d4Sdanielk1977 } 31947cedc8d4Sdanielk1977 31952d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 31962d0794e3Sdrh */ 31976c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 319866a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr); 31992d0794e3Sdrh } 32002d0794e3Sdrh 3201f42bacc2Sdrh /* Set the limiter. 3202f42bacc2Sdrh */ 3203f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 3204f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 3205f42bacc2Sdrh 3206dece1a84Sdrh /* Open a virtual index to use for the distinct set. 3207cce7d176Sdrh */ 320819a775c2Sdrh if( isDistinct ){ 32090342b1f5Sdrh KeyInfo *pKeyInfo; 32103c4809a2Sdanielk1977 assert( isAgg || pGroupBy ); 3211832508b7Sdrh distinct = pParse->nTab++; 32120342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 321366a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0, 321466a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3215832508b7Sdrh }else{ 3216832508b7Sdrh distinct = -1; 3217efb7251dSdrh } 3218832508b7Sdrh 321913449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 322013449892Sdrh if( !isAgg && pGroupBy==0 ){ 322113449892Sdrh /* This case is for non-aggregate queries 322213449892Sdrh ** Begin the database scan 3223832508b7Sdrh */ 3224a9d1ccb9Sdanielk1977 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0); 32251d83f052Sdrh if( pWInfo==0 ) goto select_end; 3226cce7d176Sdrh 3227b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 3228b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 32299d2985c7Sdrh ** into an OP_Noop. 32309d2985c7Sdrh */ 32319d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 3232f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortIndex, 1); 3233b9bb7c18Sdrh p->addrOpenEphm[2] = -1; 32349d2985c7Sdrh } 32359d2985c7Sdrh 323613449892Sdrh /* Use the standard inner loop 3237cce7d176Sdrh */ 32383c4809a2Sdanielk1977 assert(!isDistinct); 3239d2b3e23bSdrh selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest, 3240d2b3e23bSdrh pWInfo->iContinue, pWInfo->iBreak, aff); 32412282792aSdrh 3242cce7d176Sdrh /* End the database scan loop. 3243cce7d176Sdrh */ 32444adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 324513449892Sdrh }else{ 324613449892Sdrh /* This is the processing for aggregate queries */ 324713449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 324813449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 324913449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 325013449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 325113449892Sdrh ** one row of the input to the aggregator has been 325213449892Sdrh ** processed */ 325313449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 325413449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 3255cce7d176Sdrh 325613449892Sdrh 325713449892Sdrh /* The following variables hold addresses or labels for parts of the 325813449892Sdrh ** virtual machine program we are putting together */ 325913449892Sdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 326013449892Sdrh int addrSetAbort; /* Set the abort flag and return */ 326113449892Sdrh int addrInitializeLoop; /* Start of code that initializes the input loop */ 326213449892Sdrh int addrTopOfLoop; /* Top of the input loop */ 326313449892Sdrh int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ 326413449892Sdrh int addrProcessRow; /* Code to process a single input row */ 326513449892Sdrh int addrEnd; /* End of all processing */ 3266b9bb7c18Sdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 3267e313382eSdrh int addrReset; /* Subroutine for resetting the accumulator */ 326813449892Sdrh 326913449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 327013449892Sdrh 327113449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 327213449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 327313449892Sdrh ** SELECT statement. 32742282792aSdrh */ 327513449892Sdrh memset(&sNC, 0, sizeof(sNC)); 327613449892Sdrh sNC.pParse = pParse; 327713449892Sdrh sNC.pSrcList = pTabList; 327813449892Sdrh sNC.pAggInfo = &sAggInfo; 327913449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 32809d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 3281d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 3282d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); 3283d2b3e23bSdrh if( pHaving ){ 3284d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 328513449892Sdrh } 328613449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 328713449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 3288d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList); 328913449892Sdrh } 329017435752Sdrh if( db->mallocFailed ) goto select_end; 329113449892Sdrh 329213449892Sdrh /* Processing for aggregates with GROUP BY is very different and 32933c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 329413449892Sdrh */ 329513449892Sdrh if( pGroupBy ){ 329613449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 329713449892Sdrh 329813449892Sdrh /* Create labels that we will be needing 329913449892Sdrh */ 330013449892Sdrh 330113449892Sdrh addrInitializeLoop = sqlite3VdbeMakeLabel(v); 330213449892Sdrh addrGroupByChange = sqlite3VdbeMakeLabel(v); 330313449892Sdrh addrProcessRow = sqlite3VdbeMakeLabel(v); 330413449892Sdrh 330513449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 330613449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 3307b9bb7c18Sdrh ** that we do not need it after all, the OpenEphemeral instruction 330813449892Sdrh ** will be converted into a Noop. 330913449892Sdrh */ 331013449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 331113449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 331213449892Sdrh addrSortingIdx = 331366a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sAggInfo.sortingIdx, 331466a5167bSdrh sAggInfo.nSortingColumn, 0, 331566a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 331613449892Sdrh 331713449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 331813449892Sdrh */ 33190a07c107Sdrh iUseFlag = ++pParse->nMem; 33200a07c107Sdrh iAbortFlag = ++pParse->nMem; 33210a07c107Sdrh iAMem = pParse->nMem + 1; 332213449892Sdrh pParse->nMem += pGroupBy->nExpr; 33230a07c107Sdrh iBMem = pParse->nMem + 1; 332413449892Sdrh pParse->nMem += pGroupBy->nExpr; 33254c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 3326d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 33274c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 3328d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 332966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop); 333013449892Sdrh 333113449892Sdrh /* Generate a subroutine that outputs a single row of the result 333213449892Sdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 333313449892Sdrh ** is less than or equal to zero, the subroutine is a no-op. If 333413449892Sdrh ** the processing calls for the query to abort, this subroutine 333513449892Sdrh ** increments the iAbortFlag memory location before returning in 333613449892Sdrh ** order to signal the caller to abort. 333713449892Sdrh */ 333813449892Sdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 33394c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 3340d4e70ebdSdrh VdbeComment((v, "set abort flag")); 334166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 334213449892Sdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 33433c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 3344d4e70ebdSdrh VdbeComment((v, "Groupby result generator entry point")); 334566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 334613449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 334713449892Sdrh if( pHaving ){ 334835573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 334913449892Sdrh } 3350d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 33516c8c8ce0Sdanielk1977 distinct, pDest, 335213449892Sdrh addrOutputRow+1, addrSetAbort, aff); 335366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 3354d4e70ebdSdrh VdbeComment((v, "end groupby result generator")); 335513449892Sdrh 3356e313382eSdrh /* Generate a subroutine that will reset the group-by accumulator 3357e313382eSdrh */ 3358e313382eSdrh addrReset = sqlite3VdbeCurrentAddr(v); 3359e313382eSdrh resetAccumulator(pParse, &sAggInfo); 336066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 3361e313382eSdrh 336213449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 336313449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 336413449892Sdrh ** it might be a single loop that uses an index to extract information 336513449892Sdrh ** in the right order to begin with. 336613449892Sdrh */ 336713449892Sdrh sqlite3VdbeResolveLabel(v, addrInitializeLoop); 336866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset); 3369a9d1ccb9Sdanielk1977 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0); 33705360ad34Sdrh if( pWInfo==0 ) goto select_end; 337113449892Sdrh if( pGroupBy==0 ){ 337213449892Sdrh /* The optimizer is able to deliver rows in group by order so 3373b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 337413449892Sdrh ** cancelled later because we still need to use the pKeyInfo 337513449892Sdrh */ 337613449892Sdrh pGroupBy = p->pGroupBy; 337713449892Sdrh groupBySort = 0; 337813449892Sdrh }else{ 337913449892Sdrh /* Rows are coming out in undetermined order. We have to push 338013449892Sdrh ** each row into a sorting index, terminate the first loop, 338113449892Sdrh ** then loop over the sorting index in order to get the output 338213449892Sdrh ** in sorted order 338313449892Sdrh */ 3384892d3179Sdrh int regBase; 3385892d3179Sdrh int regRecord; 3386892d3179Sdrh int nCol; 3387892d3179Sdrh int nGroupBy; 3388892d3179Sdrh 338913449892Sdrh groupBySort = 1; 3390892d3179Sdrh nGroupBy = pGroupBy->nExpr; 3391892d3179Sdrh nCol = nGroupBy + 1; 3392892d3179Sdrh j = nGroupBy+1; 339313449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 3394892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 3395892d3179Sdrh nCol++; 339613449892Sdrh j++; 339713449892Sdrh } 3398892d3179Sdrh } 3399892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 3400892d3179Sdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase); 3401892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); 3402892d3179Sdrh j = nGroupBy+1; 3403892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 3404892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 3405892d3179Sdrh if( pCol->iSorterColumn>=j ){ 3406892d3179Sdrh sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable, 3407892d3179Sdrh j + regBase); 3408892d3179Sdrh j++; 3409892d3179Sdrh } 3410892d3179Sdrh } 3411892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 34121db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 3413892d3179Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord); 3414892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 3415892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 341613449892Sdrh sqlite3WhereEnd(pWInfo); 341766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); 3418d4e70ebdSdrh VdbeComment((v, "GROUP BY sort")); 341913449892Sdrh sAggInfo.useSortingIdx = 1; 342013449892Sdrh } 342113449892Sdrh 342213449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 342313449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 342413449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 342513449892Sdrh ** from the previous row currently stored in a0, a1, a2... 342613449892Sdrh */ 342713449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 342813449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 342913449892Sdrh if( groupBySort ){ 34302dcef11bSdrh sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j); 343113449892Sdrh }else{ 343213449892Sdrh sAggInfo.directMode = 1; 34332dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 343413449892Sdrh } 343513449892Sdrh } 343613449892Sdrh for(j=pGroupBy->nExpr-1; j>=0; j--){ 343713449892Sdrh if( j==0 ){ 34382dcef11bSdrh sqlite3VdbeAddOp3(v, OP_Eq, iAMem+j, addrProcessRow, iBMem+j); 343913449892Sdrh }else{ 34402dcef11bSdrh sqlite3VdbeAddOp3(v, OP_Ne, iAMem+j, addrGroupByChange, iBMem+j); 344113449892Sdrh } 344266a5167bSdrh sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ); 344335573356Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQUAL); 344413449892Sdrh } 344513449892Sdrh 344613449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 344713449892Sdrh ** Change in the GROUP BY are detected by the previous code 344813449892Sdrh ** block. If there were no changes, this block is skipped. 344913449892Sdrh ** 345013449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 345113449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 345213449892Sdrh ** and resets the aggregate accumulator registers in preparation 345313449892Sdrh ** for the next GROUP BY batch. 345413449892Sdrh */ 345513449892Sdrh sqlite3VdbeResolveLabel(v, addrGroupByChange); 345613449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 3457b1fdb2adSdrh sqlite3VdbeAddOp2(v, OP_Move, iBMem+j, iAMem+j); 345813449892Sdrh } 345966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow); 3460d4e70ebdSdrh VdbeComment((v, "output one row")); 34613c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); 3462d4e70ebdSdrh VdbeComment((v, "check abort flag")); 346366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset); 3464d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 346513449892Sdrh 346613449892Sdrh /* Update the aggregate accumulators based on the content of 346713449892Sdrh ** the current row 346813449892Sdrh */ 346913449892Sdrh sqlite3VdbeResolveLabel(v, addrProcessRow); 347013449892Sdrh updateAccumulator(pParse, &sAggInfo); 34714c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 3472d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 347313449892Sdrh 347413449892Sdrh /* End of the loop 347513449892Sdrh */ 347613449892Sdrh if( groupBySort ){ 347766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); 347813449892Sdrh }else{ 347913449892Sdrh sqlite3WhereEnd(pWInfo); 3480f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); 348113449892Sdrh } 348213449892Sdrh 348313449892Sdrh /* Output the final row of result 348413449892Sdrh */ 348566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow); 3486d4e70ebdSdrh VdbeComment((v, "output final row")); 348713449892Sdrh 348813449892Sdrh } /* endif pGroupBy */ 348913449892Sdrh else { 3490a9d1ccb9Sdanielk1977 ExprList *pMinMax = 0; 3491dba0137eSdanielk1977 ExprList *pDel = 0; 3492a9d1ccb9Sdanielk1977 u8 flag; 3493a9d1ccb9Sdanielk1977 3494738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 3495738bdcfbSdanielk1977 ** 3496738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 3497738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 3498738bdcfbSdanielk1977 ** 3499738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 3500738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 3501738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 3502738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 3503738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 3504738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 3505738bdcfbSdanielk1977 ** value of x, the only row required). 3506738bdcfbSdanielk1977 ** 3507738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 3508738bdcfbSdanielk1977 ** modify behaviour as follows: 3509738bdcfbSdanielk1977 ** 3510738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 3511738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 3512738bdcfbSdanielk1977 ** for x. 3513738bdcfbSdanielk1977 ** 3514738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 3515738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 3516738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 3517738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 3518738bdcfbSdanielk1977 */ 3519a9d1ccb9Sdanielk1977 flag = minMaxQuery(pParse, p); 3520a9d1ccb9Sdanielk1977 if( flag ){ 35218cc74322Sdrh pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList); 35220e359b30Sdrh if( pMinMax && !db->mallocFailed ){ 3523a9d1ccb9Sdanielk1977 pMinMax->a[0].sortOrder = ((flag==ORDERBY_MIN)?0:1); 3524a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 3525a9d1ccb9Sdanielk1977 } 35261013c932Sdrh } 3527a9d1ccb9Sdanielk1977 352813449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 352913449892Sdrh ** processing is much simpler since there is only a single row 353013449892Sdrh ** of output. 353113449892Sdrh */ 353213449892Sdrh resetAccumulator(pParse, &sAggInfo); 3533a9d1ccb9Sdanielk1977 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag); 3534dba0137eSdanielk1977 if( pWInfo==0 ){ 35351013c932Sdrh sqlite3ExprListDelete(pDel); 3536dba0137eSdanielk1977 goto select_end; 3537dba0137eSdanielk1977 } 353813449892Sdrh updateAccumulator(pParse, &sAggInfo); 3539a9d1ccb9Sdanielk1977 if( !pMinMax && flag ){ 3540a9d1ccb9Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); 3541a9d1ccb9Sdanielk1977 VdbeComment((v, "%s() by index", (flag==ORDERBY_MIN?"min":"max"))); 3542a9d1ccb9Sdanielk1977 } 354313449892Sdrh sqlite3WhereEnd(pWInfo); 354413449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 354513449892Sdrh pOrderBy = 0; 35465774b806Sdrh if( pHaving ){ 354735573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 35485774b806Sdrh } 354913449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 35506c8c8ce0Sdanielk1977 pDest, addrEnd, addrEnd, aff); 3551a9d1ccb9Sdanielk1977 3552dba0137eSdanielk1977 sqlite3ExprListDelete(pDel); 355313449892Sdrh } 355413449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 355513449892Sdrh 355613449892Sdrh } /* endif aggregate query */ 35572282792aSdrh 3558cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 3559cce7d176Sdrh ** and send them to the callback one by one. 3560cce7d176Sdrh */ 3561cce7d176Sdrh if( pOrderBy ){ 35626c8c8ce0Sdanielk1977 generateSortTail(pParse, p, v, pEList->nExpr, pDest); 3563cce7d176Sdrh } 35646a535340Sdrh 356593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 3566f620b4e2Sdrh /* If this was a subquery, we have now converted the subquery into a 35671787ccabSdanielk1977 ** temporary table. So set the SrcList_item.isPopulated flag to prevent 35681787ccabSdanielk1977 ** this subquery from being evaluated again and to force the use of 35691787ccabSdanielk1977 ** the temporary table. 3570f620b4e2Sdrh */ 3571f620b4e2Sdrh if( pParent ){ 3572f620b4e2Sdrh assert( pParent->pSrc->nSrc>parentTab ); 3573f620b4e2Sdrh assert( pParent->pSrc->a[parentTab].pSelect==p ); 35741787ccabSdanielk1977 pParent->pSrc->a[parentTab].isPopulated = 1; 3575f620b4e2Sdrh } 357693758c8dSdanielk1977 #endif 3577f620b4e2Sdrh 3578ec7429aeSdrh /* Jump here to skip this query 3579ec7429aeSdrh */ 3580ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 3581ec7429aeSdrh 35821d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 35831d83f052Sdrh ** to indicate no errors. 35841d83f052Sdrh */ 35851d83f052Sdrh rc = 0; 35861d83f052Sdrh 35871d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 35881d83f052Sdrh ** successful coding of the SELECT. 35891d83f052Sdrh */ 35901d83f052Sdrh select_end: 3591955de52cSdanielk1977 3592955de52cSdanielk1977 /* Identify column names if we will be using them in a callback. This 3593955de52cSdanielk1977 ** step is skipped if the output is going to some other destination. 3594955de52cSdanielk1977 */ 35956c8c8ce0Sdanielk1977 if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){ 3596955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 3597955de52cSdanielk1977 } 3598955de52cSdanielk1977 359917435752Sdrh sqlite3_free(sAggInfo.aCol); 360017435752Sdrh sqlite3_free(sAggInfo.aFunc); 36011d83f052Sdrh return rc; 3602cce7d176Sdrh } 3603485f0039Sdrh 360477a2a5e7Sdrh #if defined(SQLITE_DEBUG) 3605485f0039Sdrh /* 3606485f0039Sdrh ******************************************************************************* 3607485f0039Sdrh ** The following code is used for testing and debugging only. The code 3608485f0039Sdrh ** that follows does not appear in normal builds. 3609485f0039Sdrh ** 3610485f0039Sdrh ** These routines are used to print out the content of all or part of a 3611485f0039Sdrh ** parse structures such as Select or Expr. Such printouts are useful 3612485f0039Sdrh ** for helping to understand what is happening inside the code generator 3613485f0039Sdrh ** during the execution of complex SELECT statements. 3614485f0039Sdrh ** 3615485f0039Sdrh ** These routine are not called anywhere from within the normal 3616485f0039Sdrh ** code base. Then are intended to be called from within the debugger 3617485f0039Sdrh ** or from temporary "printf" statements inserted for debugging. 3618485f0039Sdrh */ 36193a00f907Smlcreech static void sqlite3PrintExpr(Expr *p){ 3620485f0039Sdrh if( p->token.z && p->token.n>0 ){ 3621485f0039Sdrh sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z); 3622485f0039Sdrh }else{ 3623485f0039Sdrh sqlite3DebugPrintf("(%d", p->op); 3624485f0039Sdrh } 3625485f0039Sdrh if( p->pLeft ){ 3626485f0039Sdrh sqlite3DebugPrintf(" "); 3627485f0039Sdrh sqlite3PrintExpr(p->pLeft); 3628485f0039Sdrh } 3629485f0039Sdrh if( p->pRight ){ 3630485f0039Sdrh sqlite3DebugPrintf(" "); 3631485f0039Sdrh sqlite3PrintExpr(p->pRight); 3632485f0039Sdrh } 3633485f0039Sdrh sqlite3DebugPrintf(")"); 3634485f0039Sdrh } 36353a00f907Smlcreech static void sqlite3PrintExprList(ExprList *pList){ 3636485f0039Sdrh int i; 3637485f0039Sdrh for(i=0; i<pList->nExpr; i++){ 3638485f0039Sdrh sqlite3PrintExpr(pList->a[i].pExpr); 3639485f0039Sdrh if( i<pList->nExpr-1 ){ 3640485f0039Sdrh sqlite3DebugPrintf(", "); 3641485f0039Sdrh } 3642485f0039Sdrh } 3643485f0039Sdrh } 36443a00f907Smlcreech static void sqlite3PrintSelect(Select *p, int indent){ 3645485f0039Sdrh sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p); 3646485f0039Sdrh sqlite3PrintExprList(p->pEList); 3647485f0039Sdrh sqlite3DebugPrintf("\n"); 3648485f0039Sdrh if( p->pSrc ){ 3649485f0039Sdrh char *zPrefix; 3650485f0039Sdrh int i; 3651485f0039Sdrh zPrefix = "FROM"; 3652485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 3653485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 3654485f0039Sdrh sqlite3DebugPrintf("%*s ", indent+6, zPrefix); 3655485f0039Sdrh zPrefix = ""; 3656485f0039Sdrh if( pItem->pSelect ){ 3657485f0039Sdrh sqlite3DebugPrintf("(\n"); 3658485f0039Sdrh sqlite3PrintSelect(pItem->pSelect, indent+10); 3659485f0039Sdrh sqlite3DebugPrintf("%*s)", indent+8, ""); 3660485f0039Sdrh }else if( pItem->zName ){ 3661485f0039Sdrh sqlite3DebugPrintf("%s", pItem->zName); 3662485f0039Sdrh } 3663485f0039Sdrh if( pItem->pTab ){ 3664485f0039Sdrh sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName); 3665485f0039Sdrh } 3666485f0039Sdrh if( pItem->zAlias ){ 3667485f0039Sdrh sqlite3DebugPrintf(" AS %s", pItem->zAlias); 3668485f0039Sdrh } 3669485f0039Sdrh if( i<p->pSrc->nSrc-1 ){ 3670485f0039Sdrh sqlite3DebugPrintf(","); 3671485f0039Sdrh } 3672485f0039Sdrh sqlite3DebugPrintf("\n"); 3673485f0039Sdrh } 3674485f0039Sdrh } 3675485f0039Sdrh if( p->pWhere ){ 3676485f0039Sdrh sqlite3DebugPrintf("%*s WHERE ", indent, ""); 3677485f0039Sdrh sqlite3PrintExpr(p->pWhere); 3678485f0039Sdrh sqlite3DebugPrintf("\n"); 3679485f0039Sdrh } 3680485f0039Sdrh if( p->pGroupBy ){ 3681485f0039Sdrh sqlite3DebugPrintf("%*s GROUP BY ", indent, ""); 3682485f0039Sdrh sqlite3PrintExprList(p->pGroupBy); 3683485f0039Sdrh sqlite3DebugPrintf("\n"); 3684485f0039Sdrh } 3685485f0039Sdrh if( p->pHaving ){ 3686485f0039Sdrh sqlite3DebugPrintf("%*s HAVING ", indent, ""); 3687485f0039Sdrh sqlite3PrintExpr(p->pHaving); 3688485f0039Sdrh sqlite3DebugPrintf("\n"); 3689485f0039Sdrh } 3690485f0039Sdrh if( p->pOrderBy ){ 3691485f0039Sdrh sqlite3DebugPrintf("%*s ORDER BY ", indent, ""); 3692485f0039Sdrh sqlite3PrintExprList(p->pOrderBy); 3693485f0039Sdrh sqlite3DebugPrintf("\n"); 3694485f0039Sdrh } 3695485f0039Sdrh } 3696485f0039Sdrh /* End of the structure debug printing code 3697485f0039Sdrh *****************************************************************************/ 3698485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ 3699