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 */ 15cce7d176Sdrh #include "sqliteInt.h" 16cce7d176Sdrh 17315555caSdrh 18cce7d176Sdrh /* 19eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate 20eda639e1Sdrh ** the select structure itself. 21eda639e1Sdrh */ 22633e6d57Sdrh static void clearSelect(sqlite3 *db, Select *p){ 23633e6d57Sdrh sqlite3ExprListDelete(db, p->pEList); 24633e6d57Sdrh sqlite3SrcListDelete(db, p->pSrc); 25633e6d57Sdrh sqlite3ExprDelete(db, p->pWhere); 26633e6d57Sdrh sqlite3ExprListDelete(db, p->pGroupBy); 27633e6d57Sdrh sqlite3ExprDelete(db, p->pHaving); 28633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 29633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 30633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 31633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 32eda639e1Sdrh } 33eda639e1Sdrh 341013c932Sdrh /* 351013c932Sdrh ** Initialize a SelectDest structure. 361013c932Sdrh */ 371013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 38ea678832Sdrh pDest->eDest = (u8)eDest; 391013c932Sdrh pDest->iParm = iParm; 401013c932Sdrh pDest->affinity = 0; 411013c932Sdrh pDest->iMem = 0; 42ad27e761Sdrh pDest->nMem = 0; 431013c932Sdrh } 441013c932Sdrh 45eda639e1Sdrh 46eda639e1Sdrh /* 479bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 489bb61fe7Sdrh ** structure. 49cce7d176Sdrh */ 504adee20fSdanielk1977 Select *sqlite3SelectNew( 5117435752Sdrh Parse *pParse, /* Parsing context */ 52daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 53ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 54daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 55daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 56daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 57daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 589bbca4c1Sdrh int isDistinct, /* true if the DISTINCT keyword is present */ 59a2dc3b1aSdanielk1977 Expr *pLimit, /* LIMIT value. NULL means not used */ 60a2dc3b1aSdanielk1977 Expr *pOffset /* OFFSET value. NULL means no offset */ 619bb61fe7Sdrh ){ 629bb61fe7Sdrh Select *pNew; 63eda639e1Sdrh Select standin; 6417435752Sdrh sqlite3 *db = pParse->db; 6517435752Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 66d72a276eSdrh assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */ 67daffd0e5Sdrh if( pNew==0 ){ 68eda639e1Sdrh pNew = &standin; 69eda639e1Sdrh memset(pNew, 0, sizeof(*pNew)); 70eda639e1Sdrh } 71b733d037Sdrh if( pEList==0 ){ 72b7916a78Sdrh pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0)); 73b733d037Sdrh } 749bb61fe7Sdrh pNew->pEList = pEList; 759bb61fe7Sdrh pNew->pSrc = pSrc; 769bb61fe7Sdrh pNew->pWhere = pWhere; 779bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 789bb61fe7Sdrh pNew->pHaving = pHaving; 799bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 807d10d5a6Sdrh pNew->selFlags = isDistinct ? SF_Distinct : 0; 8182c3d636Sdrh pNew->op = TK_SELECT; 82a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 83a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 84373cc2ddSdrh assert( pOffset==0 || pLimit!=0 ); 85b9bb7c18Sdrh pNew->addrOpenEphm[0] = -1; 86b9bb7c18Sdrh pNew->addrOpenEphm[1] = -1; 87b9bb7c18Sdrh pNew->addrOpenEphm[2] = -1; 880a846f96Sdrh if( db->mallocFailed ) { 89633e6d57Sdrh clearSelect(db, pNew); 900a846f96Sdrh if( pNew!=&standin ) sqlite3DbFree(db, pNew); 91eda639e1Sdrh pNew = 0; 92daffd0e5Sdrh } 939bb61fe7Sdrh return pNew; 949bb61fe7Sdrh } 959bb61fe7Sdrh 969bb61fe7Sdrh /* 97eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 98eda639e1Sdrh */ 99633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 100eda639e1Sdrh if( p ){ 101633e6d57Sdrh clearSelect(db, p); 102633e6d57Sdrh sqlite3DbFree(db, p); 103eda639e1Sdrh } 104eda639e1Sdrh } 105eda639e1Sdrh 106eda639e1Sdrh /* 10701f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 10801f3f253Sdrh ** type of join. Return an integer constant that expresses that type 10901f3f253Sdrh ** in terms of the following bit values: 11001f3f253Sdrh ** 11101f3f253Sdrh ** JT_INNER 1123dec223cSdrh ** JT_CROSS 11301f3f253Sdrh ** JT_OUTER 11401f3f253Sdrh ** JT_NATURAL 11501f3f253Sdrh ** JT_LEFT 11601f3f253Sdrh ** JT_RIGHT 11701f3f253Sdrh ** 11801f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 11901f3f253Sdrh ** 12001f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 12101f3f253Sdrh ** a join type, but put an error in the pParse structure. 12201f3f253Sdrh */ 1234adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 12401f3f253Sdrh int jointype = 0; 12501f3f253Sdrh Token *apAll[3]; 12601f3f253Sdrh Token *p; 127373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 128373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 1295719628aSdrh static const struct { 130373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 131373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 132373cc2ddSdrh u8 code; /* Join type mask */ 133373cc2ddSdrh } aKeyword[] = { 134373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 135373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 136373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 137373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 138373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 139373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 140373cc2ddSdrh /* cross */ { 28, 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]; 148373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 149373cc2ddSdrh if( p->n==aKeyword[j].nChar 150373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 151373cc2ddSdrh jointype |= aKeyword[j].code; 15201f3f253Sdrh break; 15301f3f253Sdrh } 15401f3f253Sdrh } 155373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 156373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 15701f3f253Sdrh jointype |= JT_ERROR; 15801f3f253Sdrh break; 15901f3f253Sdrh } 16001f3f253Sdrh } 161ad2d8307Sdrh if( 162ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 163195e6967Sdrh (jointype & JT_ERROR)!=0 164ad2d8307Sdrh ){ 165a9671a22Sdrh const char *zSp = " "; 166a9671a22Sdrh assert( pB!=0 ); 167a9671a22Sdrh if( pC==0 ){ zSp++; } 168ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 169a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 17001f3f253Sdrh jointype = JT_INNER; 171373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 172373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 1734adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 174da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 175195e6967Sdrh jointype = JT_INNER; 17601f3f253Sdrh } 17701f3f253Sdrh return jointype; 17801f3f253Sdrh } 17901f3f253Sdrh 18001f3f253Sdrh /* 181ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 182ad2d8307Sdrh ** is not contained in the table. 183ad2d8307Sdrh */ 184ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 185ad2d8307Sdrh int i; 186ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1874adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 188ad2d8307Sdrh } 189ad2d8307Sdrh return -1; 190ad2d8307Sdrh } 191ad2d8307Sdrh 192ad2d8307Sdrh /* 1932179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 1942179b434Sdrh ** table that has a column named zCol. 1952179b434Sdrh ** 1962179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 1972179b434Sdrh ** of the matching column and return TRUE. 1982179b434Sdrh ** 1992179b434Sdrh ** If not found, return FALSE. 2002179b434Sdrh */ 2012179b434Sdrh static int tableAndColumnIndex( 2022179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 2032179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 2042179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 2052179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 2062179b434Sdrh int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 2072179b434Sdrh ){ 2082179b434Sdrh int i; /* For looping over tables in pSrc */ 2092179b434Sdrh int iCol; /* Index of column matching zCol */ 2102179b434Sdrh 2112179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 2122179b434Sdrh for(i=0; i<N; i++){ 2132179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 2142179b434Sdrh if( iCol>=0 ){ 2152179b434Sdrh if( piTab ){ 2162179b434Sdrh *piTab = i; 2172179b434Sdrh *piCol = iCol; 2182179b434Sdrh } 2192179b434Sdrh return 1; 2202179b434Sdrh } 2212179b434Sdrh } 2222179b434Sdrh return 0; 2232179b434Sdrh } 2242179b434Sdrh 2252179b434Sdrh /* 226f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 227f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 228f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 229f7b0b0adSdan ** 230f7b0b0adSdan ** (tab1.col1 = tab2.col2) 231f7b0b0adSdan ** 232f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 233f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 234f7b0b0adSdan ** column iColRight of tab2. 235ad2d8307Sdrh */ 236ad2d8307Sdrh static void addWhereTerm( 23717435752Sdrh Parse *pParse, /* Parsing context */ 238f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 2392179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 240f7b0b0adSdan int iColLeft, /* Index of column in first table */ 2412179b434Sdrh int iRight, /* Index of second table in pSrc */ 242f7b0b0adSdan int iColRight, /* Index of column in second table */ 243f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 244f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 245ad2d8307Sdrh ){ 246f7b0b0adSdan sqlite3 *db = pParse->db; 247f7b0b0adSdan Expr *pE1; 248f7b0b0adSdan Expr *pE2; 249f7b0b0adSdan Expr *pEq; 250ad2d8307Sdrh 2512179b434Sdrh assert( iLeft<iRight ); 2522179b434Sdrh assert( pSrc->nSrc>iRight ); 2532179b434Sdrh assert( pSrc->a[iLeft].pTab ); 2542179b434Sdrh assert( pSrc->a[iRight].pTab ); 255f7b0b0adSdan 2562179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 2572179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 258f7b0b0adSdan 259f7b0b0adSdan pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0); 260f7b0b0adSdan if( pEq && isOuterJoin ){ 261f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 262f7b0b0adSdan assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) ); 263f7b0b0adSdan ExprSetIrreducible(pEq); 264f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 265030530deSdrh } 266f7b0b0adSdan *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); 267ad2d8307Sdrh } 268ad2d8307Sdrh 269ad2d8307Sdrh /* 2701f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 27122d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 27222d6a53aSdrh ** expression. 2731cc093c2Sdrh ** 274e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 2751cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 2761f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 2771f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 2781f16230bSdrh ** WHERE clause during join processing but we need to remember that they 2791f16230bSdrh ** originated in the ON or USING clause. 28022d6a53aSdrh ** 28122d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 28222d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 28322d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 28422d6a53aSdrh ** for cases like this: 28522d6a53aSdrh ** 28622d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 28722d6a53aSdrh ** 28822d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 28922d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 29022d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 29122d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 29222d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 29322d6a53aSdrh ** the output, which is incorrect. 2941cc093c2Sdrh */ 29522d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 2961cc093c2Sdrh while( p ){ 2971f16230bSdrh ExprSetProperty(p, EP_FromJoin); 29833e619fcSdrh assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) ); 29933e619fcSdrh ExprSetIrreducible(p); 300cf697396Sshane p->iRightJoinTable = (i16)iTable; 30122d6a53aSdrh setJoinExpr(p->pLeft, iTable); 3021cc093c2Sdrh p = p->pRight; 3031cc093c2Sdrh } 3041cc093c2Sdrh } 3051cc093c2Sdrh 3061cc093c2Sdrh /* 307ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 308ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 309ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 310ad2d8307Sdrh ** 31191bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 31291bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 31391bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 31491bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 31591bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 31691bb0eedSdrh ** also attached to the left entry. 31791bb0eedSdrh ** 318ad2d8307Sdrh ** This routine returns the number of errors encountered. 319ad2d8307Sdrh */ 320ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 32191bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 32291bb0eedSdrh int i, j; /* Loop counters */ 32391bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 32491bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 325ad2d8307Sdrh 32691bb0eedSdrh pSrc = p->pSrc; 32791bb0eedSdrh pLeft = &pSrc->a[0]; 32891bb0eedSdrh pRight = &pLeft[1]; 32991bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 33091bb0eedSdrh Table *pLeftTab = pLeft->pTab; 33191bb0eedSdrh Table *pRightTab = pRight->pTab; 332ad27e761Sdrh int isOuter; 33391bb0eedSdrh 3341c767f0dSdrh if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; 335ad27e761Sdrh isOuter = (pRight->jointype & JT_OUTER)!=0; 336ad2d8307Sdrh 337ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 338ad2d8307Sdrh ** every column that the two tables have in common. 339ad2d8307Sdrh */ 34061dfc31dSdrh if( pRight->jointype & JT_NATURAL ){ 34161dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 3424adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 343ad2d8307Sdrh "an ON or USING clause", 0); 344ad2d8307Sdrh return 1; 345ad2d8307Sdrh } 3462179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 3472179b434Sdrh char *zName; /* Name of column in the right table */ 3482179b434Sdrh int iLeft; /* Matching left table */ 3492179b434Sdrh int iLeftCol; /* Matching column in the left table */ 3502179b434Sdrh 3512179b434Sdrh zName = pRightTab->aCol[j].zName; 3522179b434Sdrh if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ 3532179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 3542179b434Sdrh isOuter, &p->pWhere); 355ad2d8307Sdrh } 356ad2d8307Sdrh } 357ad2d8307Sdrh } 358ad2d8307Sdrh 359ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 360ad2d8307Sdrh */ 36161dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 3624adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 363da93d238Sdrh "clauses in the same join"); 364ad2d8307Sdrh return 1; 365ad2d8307Sdrh } 366ad2d8307Sdrh 367ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 36891bb0eedSdrh ** an AND operator. 369ad2d8307Sdrh */ 37061dfc31dSdrh if( pRight->pOn ){ 371ad27e761Sdrh if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 37217435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 37361dfc31dSdrh pRight->pOn = 0; 374ad2d8307Sdrh } 375ad2d8307Sdrh 376ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 377ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 378ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 379ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 380ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 381ad2d8307Sdrh ** not contained in both tables to be joined. 382ad2d8307Sdrh */ 38361dfc31dSdrh if( pRight->pUsing ){ 38461dfc31dSdrh IdList *pList = pRight->pUsing; 385ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 3862179b434Sdrh char *zName; /* Name of the term in the USING clause */ 3872179b434Sdrh int iLeft; /* Table on the left with matching column name */ 3882179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 3892179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 3902179b434Sdrh 3912179b434Sdrh zName = pList->a[j].zName; 3922179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 3932179b434Sdrh if( iRightCol<0 3942179b434Sdrh || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) 3952179b434Sdrh ){ 3964adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 39791bb0eedSdrh "not present in both tables", zName); 398ad2d8307Sdrh return 1; 399ad2d8307Sdrh } 4002179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 4012179b434Sdrh isOuter, &p->pWhere); 402ad2d8307Sdrh } 403ad2d8307Sdrh } 404ad2d8307Sdrh } 405ad2d8307Sdrh return 0; 406ad2d8307Sdrh } 407ad2d8307Sdrh 408ad2d8307Sdrh /* 409c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 410c926afbcSdrh ** stack into the sorter. 411c926afbcSdrh */ 412d59ba6ceSdrh static void pushOntoSorter( 413d59ba6ceSdrh Parse *pParse, /* Parser context */ 414d59ba6ceSdrh ExprList *pOrderBy, /* The ORDER BY clause */ 415b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 416b7654111Sdrh int regData /* Register holding data to be sorted */ 417d59ba6ceSdrh ){ 418d59ba6ceSdrh Vdbe *v = pParse->pVdbe; 419892d3179Sdrh int nExpr = pOrderBy->nExpr; 420892d3179Sdrh int regBase = sqlite3GetTempRange(pParse, nExpr+2); 421892d3179Sdrh int regRecord = sqlite3GetTempReg(pParse); 422ceea3321Sdrh sqlite3ExprCacheClear(pParse); 423191b54cbSdrh sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0); 424892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); 425b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1); 4261db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord); 427892d3179Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord); 428892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 429892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nExpr+2); 43092b01d53Sdrh if( pSelect->iLimit ){ 43115007a99Sdrh int addr1, addr2; 432b7654111Sdrh int iLimit; 4330acb7e48Sdrh if( pSelect->iOffset ){ 434b7654111Sdrh iLimit = pSelect->iOffset+1; 435b7654111Sdrh }else{ 436b7654111Sdrh iLimit = pSelect->iLimit; 437b7654111Sdrh } 438b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); 439b7654111Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); 4403c84ddffSdrh addr2 = sqlite3VdbeAddOp0(v, OP_Goto); 441d59ba6ceSdrh sqlite3VdbeJumpHere(v, addr1); 4423c84ddffSdrh sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); 4433c84ddffSdrh sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); 44415007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 445d59ba6ceSdrh } 446c926afbcSdrh } 447c926afbcSdrh 448c926afbcSdrh /* 449ec7429aeSdrh ** Add code to implement the OFFSET 450ea48eb2eSdrh */ 451ec7429aeSdrh static void codeOffset( 452bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 453ea48eb2eSdrh Select *p, /* The SELECT statement being coded */ 454b7654111Sdrh int iContinue /* Jump here to skip the current record */ 455ea48eb2eSdrh ){ 45692b01d53Sdrh if( p->iOffset && iContinue!=0 ){ 45715007a99Sdrh int addr; 4588558cde1Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1); 4593c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset); 46066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); 461d4e70ebdSdrh VdbeComment((v, "skip OFFSET records")); 46215007a99Sdrh sqlite3VdbeJumpHere(v, addr); 463ea48eb2eSdrh } 464ea48eb2eSdrh } 465ea48eb2eSdrh 466ea48eb2eSdrh /* 46798757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 46898757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 469a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 470a2a49dc9Sdrh ** if the current N values are new. 471a2a49dc9Sdrh ** 472a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 473a2a49dc9Sdrh ** stack if the top N elements are not distinct. 474a2a49dc9Sdrh */ 475a2a49dc9Sdrh static void codeDistinct( 4762dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 477a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 478a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 479477df4b3Sdrh int N, /* Number of elements */ 480a2a49dc9Sdrh int iMem /* First element */ 481a2a49dc9Sdrh ){ 4822dcef11bSdrh Vdbe *v; 4832dcef11bSdrh int r1; 4842dcef11bSdrh 4852dcef11bSdrh v = pParse->pVdbe; 4862dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 48791fc4a0cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); 4881db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 4892dcef11bSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); 4902dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 491a2a49dc9Sdrh } 492a2a49dc9Sdrh 493bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY 494a2a49dc9Sdrh /* 495e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression 496e305f43fSdrh ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 497bb7dd683Sdrh ** column. We do this in a subroutine because the error used to occur 498bb7dd683Sdrh ** in multiple places. (The error only occurs in one place now, but we 499bb7dd683Sdrh ** retain the subroutine to minimize code disruption.) 500e305f43fSdrh */ 5016c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError( 5026c8c8ce0Sdanielk1977 Parse *pParse, /* Parse context. */ 5036c8c8ce0Sdanielk1977 SelectDest *pDest, /* Destination of SELECT results */ 5046c8c8ce0Sdanielk1977 int nExpr /* Number of result columns returned by SELECT */ 5056c8c8ce0Sdanielk1977 ){ 5066c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 507e305f43fSdrh if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 508e305f43fSdrh sqlite3ErrorMsg(pParse, "only a single result allowed for " 509e305f43fSdrh "a SELECT that is part of an expression"); 510e305f43fSdrh return 1; 511e305f43fSdrh }else{ 512e305f43fSdrh return 0; 513e305f43fSdrh } 514e305f43fSdrh } 515bb7dd683Sdrh #endif 516c99130fdSdrh 517c99130fdSdrh /* 5182282792aSdrh ** This routine generates the code for the inside of the inner loop 5192282792aSdrh ** of a SELECT. 52082c3d636Sdrh ** 52138640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 52238640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 52338640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 52438640e15Sdrh ** datatypes for each column. 5252282792aSdrh */ 526d2b3e23bSdrh static void selectInnerLoop( 5272282792aSdrh Parse *pParse, /* The parser context */ 528df199a25Sdrh Select *p, /* The complete select statement being coded */ 5292282792aSdrh ExprList *pEList, /* List of values being extracted */ 53082c3d636Sdrh int srcTab, /* Pull data from this table */ 531967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 5322282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 5332282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 5346c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 5352282792aSdrh int iContinue, /* Jump here to continue with next row */ 536a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 5372282792aSdrh ){ 5382282792aSdrh Vdbe *v = pParse->pVdbe; 539d847eaadSdrh int i; 540ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 541d847eaadSdrh int regResult; /* Start of memory holding result set */ 542d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 543d847eaadSdrh int iParm = pDest->iParm; /* First argument to disposal method */ 544d847eaadSdrh int nResultCol; /* Number of result columns */ 54538640e15Sdrh 5461c767f0dSdrh assert( v ); 5471c767f0dSdrh if( NEVER(v==0) ) return; 54838640e15Sdrh assert( pEList!=0 ); 549e49b146fSdrh hasDistinct = distinct>=0; 550ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 551b7654111Sdrh codeOffset(v, p, iContinue); 552df199a25Sdrh } 553df199a25Sdrh 554967e8b73Sdrh /* Pull the requested columns. 5552282792aSdrh */ 55638640e15Sdrh if( nColumn>0 ){ 557d847eaadSdrh nResultCol = nColumn; 558a2a49dc9Sdrh }else{ 559d847eaadSdrh nResultCol = pEList->nExpr; 560a2a49dc9Sdrh } 5611ece7325Sdrh if( pDest->iMem==0 ){ 5620acb7e48Sdrh pDest->iMem = pParse->nMem+1; 563ad27e761Sdrh pDest->nMem = nResultCol; 5640acb7e48Sdrh pParse->nMem += nResultCol; 5651c767f0dSdrh }else{ 5661c767f0dSdrh assert( pDest->nMem==nResultCol ); 5671013c932Sdrh } 5681ece7325Sdrh regResult = pDest->iMem; 569a2a49dc9Sdrh if( nColumn>0 ){ 570967e8b73Sdrh for(i=0; i<nColumn; i++){ 571d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 57282c3d636Sdrh } 5739ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 5749ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 5759ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 5769ed1dfa8Sdanielk1977 */ 577ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5787d10d5a6Sdrh sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output); 579a2a49dc9Sdrh } 580d847eaadSdrh nColumn = nResultCol; 5812282792aSdrh 582daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 583daffd0e5Sdrh ** and this row has been seen before, then do not make this row 584daffd0e5Sdrh ** part of the result. 5852282792aSdrh */ 586ea48eb2eSdrh if( hasDistinct ){ 587f8875400Sdrh assert( pEList!=0 ); 588f8875400Sdrh assert( pEList->nExpr==nColumn ); 589d847eaadSdrh codeDistinct(pParse, distinct, iContinue, nColumn, regResult); 590ea48eb2eSdrh if( pOrderBy==0 ){ 591b7654111Sdrh codeOffset(v, p, iContinue); 592ea48eb2eSdrh } 5932282792aSdrh } 59482c3d636Sdrh 595c926afbcSdrh switch( eDest ){ 59682c3d636Sdrh /* In this mode, write each query result to the key of the temporary 59782c3d636Sdrh ** table iParm. 5982282792aSdrh */ 59913449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 600c926afbcSdrh case SRT_Union: { 6019cbf3425Sdrh int r1; 6029cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 603d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6049cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 6059cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 606c926afbcSdrh break; 607c926afbcSdrh } 60882c3d636Sdrh 60982c3d636Sdrh /* Construct a record from the query result, but instead of 61082c3d636Sdrh ** saving that record, use it as a key to delete elements from 61182c3d636Sdrh ** the temporary table iParm. 61282c3d636Sdrh */ 613c926afbcSdrh case SRT_Except: { 614e14006d0Sdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn); 615c926afbcSdrh break; 616c926afbcSdrh } 6175338a5f7Sdanielk1977 #endif 6185338a5f7Sdanielk1977 6195338a5f7Sdanielk1977 /* Store the result as data using a unique key. 6205338a5f7Sdanielk1977 */ 6215338a5f7Sdanielk1977 case SRT_Table: 622b9bb7c18Sdrh case SRT_EphemTab: { 623b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 624373cc2ddSdrh testcase( eDest==SRT_Table ); 625373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 626d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6275338a5f7Sdanielk1977 if( pOrderBy ){ 628b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 6295338a5f7Sdanielk1977 }else{ 630b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 631b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 632b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 633b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 634b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 6355338a5f7Sdanielk1977 } 636b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 6375338a5f7Sdanielk1977 break; 6385338a5f7Sdanielk1977 } 6392282792aSdrh 64093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 6412282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 6422282792aSdrh ** then there should be a single item on the stack. Write this 6432282792aSdrh ** item into the set table with bogus data. 6442282792aSdrh */ 645c926afbcSdrh case SRT_Set: { 646967e8b73Sdrh assert( nColumn==1 ); 6476c8c8ce0Sdanielk1977 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity); 648c926afbcSdrh if( pOrderBy ){ 649de941c60Sdrh /* At first glance you would think we could optimize out the 650de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 651de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 652de941c60Sdrh ** case the order does matter */ 653d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 654c926afbcSdrh }else{ 655b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 656d847eaadSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1); 657da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, 1); 658b7654111Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 659b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 660c926afbcSdrh } 661c926afbcSdrh break; 662c926afbcSdrh } 66382c3d636Sdrh 664504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 665ec7429aeSdrh */ 666ec7429aeSdrh case SRT_Exists: { 6674c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 668ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 669ec7429aeSdrh break; 670ec7429aeSdrh } 671ec7429aeSdrh 6722282792aSdrh /* If this is a scalar select that is part of an expression, then 6732282792aSdrh ** store the results in the appropriate memory cell and break out 6742282792aSdrh ** of the scan loop. 6752282792aSdrh */ 676c926afbcSdrh case SRT_Mem: { 677967e8b73Sdrh assert( nColumn==1 ); 678c926afbcSdrh if( pOrderBy ){ 679d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 680c926afbcSdrh }else{ 681b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regResult, iParm, 1); 682ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 683c926afbcSdrh } 684c926afbcSdrh break; 685c926afbcSdrh } 68693758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 6872282792aSdrh 688c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 689c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 690c182d163Sdrh ** popping the data from the stack. 691f46f905aSdrh */ 692e00ee6ebSdrh case SRT_Coroutine: 6937d10d5a6Sdrh case SRT_Output: { 694373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 695373cc2ddSdrh testcase( eDest==SRT_Output ); 696f46f905aSdrh if( pOrderBy ){ 697b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 698d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 699b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 700b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 701e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 70292b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 703c182d163Sdrh }else{ 704d847eaadSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); 705da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn); 706ac82fcf5Sdrh } 707142e30dfSdrh break; 708142e30dfSdrh } 709142e30dfSdrh 7106a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 711d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 712d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 713d7489c39Sdrh ** user-defined functions that have side effects. We do not care 714d7489c39Sdrh ** about the actual results of the select. 715d7489c39Sdrh */ 716c926afbcSdrh default: { 717f46f905aSdrh assert( eDest==SRT_Discard ); 718c926afbcSdrh break; 719c926afbcSdrh } 72093758c8dSdanielk1977 #endif 721c926afbcSdrh } 722ec7429aeSdrh 7235e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 7245e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 7255e87be87Sdrh ** the output for us. 726ec7429aeSdrh */ 7275e87be87Sdrh if( pOrderBy==0 && p->iLimit ){ 7289b918ed1Sdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); 729ec7429aeSdrh } 73082c3d636Sdrh } 73182c3d636Sdrh 73282c3d636Sdrh /* 733dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 734dece1a84Sdrh ** the collating sequence for each expression in that expression list. 735dece1a84Sdrh ** 7360342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 7370342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 7380342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 7390342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 7400342b1f5Sdrh ** index to implement a DISTINCT test. 7410342b1f5Sdrh ** 742dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 743dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 74466a5167bSdrh ** freed. Add the KeyInfo structure to the P4 field of an opcode using 74566a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. 746dece1a84Sdrh */ 747dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 748dece1a84Sdrh sqlite3 *db = pParse->db; 749dece1a84Sdrh int nExpr; 750dece1a84Sdrh KeyInfo *pInfo; 751dece1a84Sdrh struct ExprList_item *pItem; 752dece1a84Sdrh int i; 753dece1a84Sdrh 754dece1a84Sdrh nExpr = pList->nExpr; 75517435752Sdrh pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 756dece1a84Sdrh if( pInfo ){ 7572646da7eSdrh pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 758ea678832Sdrh pInfo->nField = (u16)nExpr; 75914db2665Sdanielk1977 pInfo->enc = ENC(db); 7602aca5846Sdrh pInfo->db = db; 761dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 762dece1a84Sdrh CollSeq *pColl; 763dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 764dece1a84Sdrh if( !pColl ){ 765dece1a84Sdrh pColl = db->pDfltColl; 766dece1a84Sdrh } 767dece1a84Sdrh pInfo->aColl[i] = pColl; 768dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 769dece1a84Sdrh } 770dece1a84Sdrh } 771dece1a84Sdrh return pInfo; 772dece1a84Sdrh } 773dece1a84Sdrh 7747f61e92cSdan #ifndef SQLITE_OMIT_COMPOUND_SELECT 7757f61e92cSdan /* 7767f61e92cSdan ** Name of the connection operator, used for error messages. 7777f61e92cSdan */ 7787f61e92cSdan static const char *selectOpName(int id){ 7797f61e92cSdan char *z; 7807f61e92cSdan switch( id ){ 7817f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 7827f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 7837f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 7847f61e92cSdan default: z = "UNION"; break; 7857f61e92cSdan } 7867f61e92cSdan return z; 7877f61e92cSdan } 7887f61e92cSdan #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 7897f61e92cSdan 7902ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 79117c0bc0cSdan /* 79217c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 79317c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 79417c0bc0cSdan ** where the caption is of the form: 79517c0bc0cSdan ** 79617c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 79717c0bc0cSdan ** 79817c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 79917c0bc0cSdan ** is determined by the zUsage argument. 80017c0bc0cSdan */ 8012ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 8022ce22453Sdan if( pParse->explain==2 ){ 8032ce22453Sdan Vdbe *v = pParse->pVdbe; 8042ce22453Sdan char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); 8052ce22453Sdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 8062ce22453Sdan } 8072ce22453Sdan } 80817c0bc0cSdan 80917c0bc0cSdan /* 810*bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 811*bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 812*bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 813*bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 814*bb2b4418Sdan ** code with #ifndef directives. 815*bb2b4418Sdan */ 816*bb2b4418Sdan # define explainSetInteger(a, b) a = b 817*bb2b4418Sdan 818*bb2b4418Sdan #else 819*bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 820*bb2b4418Sdan # define explainTempTable(y,z) 821*bb2b4418Sdan # define explainSetInteger(y,z) 822*bb2b4418Sdan #endif 823*bb2b4418Sdan 824*bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) 825*bb2b4418Sdan /* 8267f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 8277f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 8287f61e92cSdan ** where the caption is of one of the two forms: 8297f61e92cSdan ** 8307f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" 8317f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" 8327f61e92cSdan ** 8337f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding 8347f61e92cSdan ** function parameters, and op is the text representation of the parameter 8357f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, 8367f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 8377f61e92cSdan ** false, or the second form if it is true. 8387f61e92cSdan */ 8397f61e92cSdan static void explainComposite( 8407f61e92cSdan Parse *pParse, /* Parse context */ 8417f61e92cSdan int op, /* One of TK_UNION, TK_EXCEPT etc. */ 8427f61e92cSdan int iSub1, /* Subquery id 1 */ 8437f61e92cSdan int iSub2, /* Subquery id 2 */ 8447f61e92cSdan int bUseTmp /* True if a temp table was used */ 8457f61e92cSdan ){ 8467f61e92cSdan assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); 8477f61e92cSdan if( pParse->explain==2 ){ 8487f61e92cSdan Vdbe *v = pParse->pVdbe; 8497f61e92cSdan char *zMsg = sqlite3MPrintf( 85030969d3fSdan pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, 8517f61e92cSdan bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) 8527f61e92cSdan ); 8537f61e92cSdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 8547f61e92cSdan } 8557f61e92cSdan } 8562ce22453Sdan #else 85717c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */ 8587f61e92cSdan # define explainComposite(v,w,x,y,z) 8592ce22453Sdan #endif 860dece1a84Sdrh 861dece1a84Sdrh /* 862d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 863d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 864d8bc7086Sdrh ** we need to run the sorter and output the results. The following 865d8bc7086Sdrh ** routine generates the code needed to do that. 866d8bc7086Sdrh */ 867c926afbcSdrh static void generateSortTail( 868cdd536f0Sdrh Parse *pParse, /* Parsing context */ 869c926afbcSdrh Select *p, /* The SELECT statement */ 870c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 871c926afbcSdrh int nColumn, /* Number of columns of data */ 8726c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 873c926afbcSdrh ){ 874dc5ea5c7Sdrh int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ 875dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 876d8bc7086Sdrh int addr; 8770342b1f5Sdrh int iTab; 87861fc595fSdrh int pseudoTab = 0; 8790342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 880ffbc3088Sdrh 8816c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 8826c8c8ce0Sdanielk1977 int iParm = pDest->iParm; 8836c8c8ce0Sdanielk1977 8842d401ab8Sdrh int regRow; 8852d401ab8Sdrh int regRowid; 8862d401ab8Sdrh 8879d2985c7Sdrh iTab = pOrderBy->iECursor; 8883e9ca094Sdrh regRow = sqlite3GetTempReg(pParse); 8897d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 890cdd536f0Sdrh pseudoTab = pParse->nTab++; 8913e9ca094Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn); 8923e9ca094Sdrh regRowid = 0; 8933e9ca094Sdrh }else{ 8943e9ca094Sdrh regRowid = sqlite3GetTempReg(pParse); 895cdd536f0Sdrh } 896dc5ea5c7Sdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); 897dc5ea5c7Sdrh codeOffset(v, p, addrContinue); 8982d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow); 899c926afbcSdrh switch( eDest ){ 900c926afbcSdrh case SRT_Table: 901b9bb7c18Sdrh case SRT_EphemTab: { 9021c767f0dSdrh testcase( eDest==SRT_Table ); 9031c767f0dSdrh testcase( eDest==SRT_EphemTab ); 9042d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 9052d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 9062d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 907c926afbcSdrh break; 908c926afbcSdrh } 90993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 910c926afbcSdrh case SRT_Set: { 911c926afbcSdrh assert( nColumn==1 ); 912a7a8e14bSdanielk1977 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1); 913da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regRow, 1); 914a7a8e14bSdanielk1977 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); 915c926afbcSdrh break; 916c926afbcSdrh } 917c926afbcSdrh case SRT_Mem: { 918c926afbcSdrh assert( nColumn==1 ); 919b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regRow, iParm, 1); 920ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 921c926afbcSdrh break; 922c926afbcSdrh } 92393758c8dSdanielk1977 #endif 924373cc2ddSdrh default: { 925ac82fcf5Sdrh int i; 926373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 9271c767f0dSdrh testcase( eDest==SRT_Output ); 9281c767f0dSdrh testcase( eDest==SRT_Coroutine ); 929ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 9309882d999Sdanielk1977 assert( regRow!=pDest->iMem+i ); 9311013c932Sdrh sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i); 9323e9ca094Sdrh if( i==0 ){ 9333e9ca094Sdrh sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 9343e9ca094Sdrh } 935ac82fcf5Sdrh } 9367d10d5a6Sdrh if( eDest==SRT_Output ){ 9371013c932Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn); 938da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn); 939a9671a22Sdrh }else{ 94092b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 941ce665cf6Sdrh } 942ac82fcf5Sdrh break; 943ac82fcf5Sdrh } 944c926afbcSdrh } 9452d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 9462d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 947ec7429aeSdrh 948ec7429aeSdrh /* The bottom of the loop 949ec7429aeSdrh */ 950dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 95166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); 952dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 9537d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 95466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); 955cdd536f0Sdrh } 956d8bc7086Sdrh } 957d8bc7086Sdrh 958d8bc7086Sdrh /* 959517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 960517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 961e78e8284Sdrh ** 962955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 963955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 964955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 965955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 966955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 967955de52cSdanielk1977 ** considered a column by this function. 968e78e8284Sdrh ** 969955de52cSdanielk1977 ** SELECT col FROM tbl; 970955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 971955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 972955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 973955de52cSdanielk1977 ** 974955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 975fcb78a49Sdrh */ 976955de52cSdanielk1977 static const char *columnType( 977955de52cSdanielk1977 NameContext *pNC, 978955de52cSdanielk1977 Expr *pExpr, 979955de52cSdanielk1977 const char **pzOriginDb, 980955de52cSdanielk1977 const char **pzOriginTab, 981955de52cSdanielk1977 const char **pzOriginCol 982955de52cSdanielk1977 ){ 983955de52cSdanielk1977 char const *zType = 0; 984955de52cSdanielk1977 char const *zOriginDb = 0; 985955de52cSdanielk1977 char const *zOriginTab = 0; 986955de52cSdanielk1977 char const *zOriginCol = 0; 987517eb646Sdanielk1977 int j; 988373cc2ddSdrh if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; 9895338a5f7Sdanielk1977 99000e279d9Sdanielk1977 switch( pExpr->op ){ 99130bcf5dbSdrh case TK_AGG_COLUMN: 99200e279d9Sdanielk1977 case TK_COLUMN: { 993955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 994955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 995955de52cSdanielk1977 ** database table or a subquery. 996955de52cSdanielk1977 */ 997955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 998955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 999955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 1000373cc2ddSdrh testcase( pExpr->op==TK_AGG_COLUMN ); 1001373cc2ddSdrh testcase( pExpr->op==TK_COLUMN ); 100243bc88bbSdan while( pNC && !pTab ){ 1003b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1004b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1005b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 10066a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1007955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1008b3bce662Sdanielk1977 }else{ 1009b3bce662Sdanielk1977 pNC = pNC->pNext; 1010b3bce662Sdanielk1977 } 1011b3bce662Sdanielk1977 } 1012955de52cSdanielk1977 101343bc88bbSdan if( pTab==0 ){ 1014417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1015417168adSdrh ** cause this condition to run. Since then, we have restructured how 1016417168adSdrh ** trigger code is generated and so this condition is no longer 101743bc88bbSdan ** possible. However, it can still be true for statements like 101843bc88bbSdan ** the following: 101943bc88bbSdan ** 102043bc88bbSdan ** CREATE TABLE t1(col INTEGER); 102143bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 102243bc88bbSdan ** 102343bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 102443bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 102543bc88bbSdan ** though it should really be "INTEGER". 102643bc88bbSdan ** 102743bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 102843bc88bbSdan ** used. When columnType() is called on the expression 102943bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 103043bc88bbSdan ** branch below. */ 10317e62779aSdrh break; 10327e62779aSdrh } 1033955de52cSdanielk1977 103443bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1035955de52cSdanielk1977 if( pS ){ 1036955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1037955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1038955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1039955de52cSdanielk1977 */ 10407b688edeSdrh if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ 1041955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1042955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1043955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1044955de52cSdanielk1977 */ 1045955de52cSdanielk1977 NameContext sNC; 1046955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1047955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 104843bc88bbSdan sNC.pNext = pNC; 1049955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1050955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 1051955de52cSdanielk1977 } 10521c767f0dSdrh }else if( ALWAYS(pTab->pSchema) ){ 1053955de52cSdanielk1977 /* A real table */ 1054955de52cSdanielk1977 assert( !pS ); 1055fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1056fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1057fcb78a49Sdrh if( iCol<0 ){ 1058fcb78a49Sdrh zType = "INTEGER"; 1059955de52cSdanielk1977 zOriginCol = "rowid"; 1060fcb78a49Sdrh }else{ 1061fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 1062955de52cSdanielk1977 zOriginCol = pTab->aCol[iCol].zName; 1063955de52cSdanielk1977 } 1064955de52cSdanielk1977 zOriginTab = pTab->zName; 1065955de52cSdanielk1977 if( pNC->pParse ){ 1066955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1067955de52cSdanielk1977 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 1068955de52cSdanielk1977 } 1069fcb78a49Sdrh } 107000e279d9Sdanielk1977 break; 1071736c22b8Sdrh } 107293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 107300e279d9Sdanielk1977 case TK_SELECT: { 1074955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1075955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1076955de52cSdanielk1977 ** statement. 1077955de52cSdanielk1977 */ 1078b3bce662Sdanielk1977 NameContext sNC; 10796ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1080955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 10816ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1082955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1083b3bce662Sdanielk1977 sNC.pNext = pNC; 1084955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1085955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 108600e279d9Sdanielk1977 break; 1087fcb78a49Sdrh } 108893758c8dSdanielk1977 #endif 108900e279d9Sdanielk1977 } 109000e279d9Sdanielk1977 1091955de52cSdanielk1977 if( pzOriginDb ){ 1092955de52cSdanielk1977 assert( pzOriginTab && pzOriginCol ); 1093955de52cSdanielk1977 *pzOriginDb = zOriginDb; 1094955de52cSdanielk1977 *pzOriginTab = zOriginTab; 1095955de52cSdanielk1977 *pzOriginCol = zOriginCol; 1096955de52cSdanielk1977 } 1097517eb646Sdanielk1977 return zType; 1098517eb646Sdanielk1977 } 1099517eb646Sdanielk1977 1100517eb646Sdanielk1977 /* 1101517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1102517eb646Sdanielk1977 ** in the result set. 1103517eb646Sdanielk1977 */ 1104517eb646Sdanielk1977 static void generateColumnTypes( 1105517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1106517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1107517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1108517eb646Sdanielk1977 ){ 11093f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1110517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1111517eb646Sdanielk1977 int i; 1112b3bce662Sdanielk1977 NameContext sNC; 1113b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1114955de52cSdanielk1977 sNC.pParse = pParse; 1115517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1116517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 11173f913576Sdrh const char *zType; 11183f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1119955de52cSdanielk1977 const char *zOrigDb = 0; 1120955de52cSdanielk1977 const char *zOrigTab = 0; 1121955de52cSdanielk1977 const char *zOrigCol = 0; 11223f913576Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1123955de52cSdanielk1977 112485b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 11254b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 11264b1ae99dSdanielk1977 ** virtual machine is deleted. 1127fbcd585fSdanielk1977 */ 112810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 112910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 113010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 11313f913576Sdrh #else 11323f913576Sdrh zType = columnType(&sNC, p, 0, 0, 0); 11333f913576Sdrh #endif 113410fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1135fcb78a49Sdrh } 11363f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */ 1137fcb78a49Sdrh } 1138fcb78a49Sdrh 1139fcb78a49Sdrh /* 1140fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1141fcb78a49Sdrh ** in the result set. This information is used to provide the 1142fcabd464Sdrh ** azCol[] values in the callback. 114382c3d636Sdrh */ 1144832508b7Sdrh static void generateColumnNames( 1145832508b7Sdrh Parse *pParse, /* Parser context */ 1146ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1147832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1148832508b7Sdrh ){ 1149d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 11506a3ea0e6Sdrh int i, j; 11519bb575fdSdrh sqlite3 *db = pParse->db; 1152fcabd464Sdrh int fullNames, shortNames; 1153fcabd464Sdrh 1154fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 11553cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 11563cf86063Sdanielk1977 if( pParse->explain ){ 115761de0d1bSdanielk1977 return; 11583cf86063Sdanielk1977 } 11595338a5f7Sdanielk1977 #endif 11603cf86063Sdanielk1977 1161e2f02bacSdrh if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; 1162d8bc7086Sdrh pParse->colNamesSet = 1; 1163fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1164fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 116522322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 116682c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 116782c3d636Sdrh Expr *p; 11685a38705eSdrh p = pEList->a[i].pExpr; 1169373cc2ddSdrh if( NEVER(p==0) ) continue; 117082c3d636Sdrh if( pEList->a[i].zName ){ 117182c3d636Sdrh char *zName = pEList->a[i].zName; 117210fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1173f018cc2eSdrh }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ 11746a3ea0e6Sdrh Table *pTab; 117597665873Sdrh char *zCol; 11768aff1015Sdrh int iCol = p->iColumn; 1177e2f02bacSdrh for(j=0; ALWAYS(j<pTabList->nSrc); j++){ 1178e2f02bacSdrh if( pTabList->a[j].iCursor==p->iTable ) break; 1179e2f02bacSdrh } 11806a3ea0e6Sdrh assert( j<pTabList->nSrc ); 11816a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 11828aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 118397665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1184b1363206Sdrh if( iCol<0 ){ 118547a6db2bSdrh zCol = "rowid"; 1186b1363206Sdrh }else{ 1187b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1188b1363206Sdrh } 1189e49b146fSdrh if( !shortNames && !fullNames ){ 119010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1191b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 11921c767f0dSdrh }else if( fullNames ){ 119382c3d636Sdrh char *zName = 0; 11941c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 119510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 119682c3d636Sdrh }else{ 119710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 119882c3d636Sdrh } 11991bee3d7bSdrh }else{ 120010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1201b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 120282c3d636Sdrh } 120382c3d636Sdrh } 120476d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 12055080aaa7Sdrh } 120682c3d636Sdrh 1207d8bc7086Sdrh /* 12087d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions 12097d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 12107d10d5a6Sdrh ** column names for a table that would hold the expression list. 12117d10d5a6Sdrh ** 12127d10d5a6Sdrh ** All column names will be unique. 12137d10d5a6Sdrh ** 12147d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 12157d10d5a6Sdrh ** and other fields of Column are zeroed. 12167d10d5a6Sdrh ** 12177d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 12187d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1219315555caSdrh */ 12207d10d5a6Sdrh static int selectColumnsFromExprList( 12217d10d5a6Sdrh Parse *pParse, /* Parsing context */ 12227d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 12237d10d5a6Sdrh int *pnCol, /* Write the number of columns here */ 12247d10d5a6Sdrh Column **paCol /* Write the new column list here */ 12257d10d5a6Sdrh ){ 1226dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1227dc5ea5c7Sdrh int i, j; /* Loop counters */ 1228dc5ea5c7Sdrh int cnt; /* Index added to make the name unique */ 1229dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1230dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1231dc5ea5c7Sdrh Expr *p; /* Expression for a single result column */ 1232dc5ea5c7Sdrh char *zName; /* Column name */ 1233dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 123479d5f63fSdrh 12357d10d5a6Sdrh *pnCol = nCol = pEList->nExpr; 12367d10d5a6Sdrh aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 12377d10d5a6Sdrh if( aCol==0 ) return SQLITE_NOMEM; 12387d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 123979d5f63fSdrh /* Get an appropriate name for the column 124079d5f63fSdrh */ 124179d5f63fSdrh p = pEList->a[i].pExpr; 124233e619fcSdrh assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue) 124333e619fcSdrh || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 ); 124491bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 124579d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 124617435752Sdrh zName = sqlite3DbStrDup(db, zName); 12477d10d5a6Sdrh }else{ 1248dc5ea5c7Sdrh Expr *pColExpr = p; /* The expression that is the result column name */ 1249dc5ea5c7Sdrh Table *pTab; /* Table associated with this expression */ 1250dc5ea5c7Sdrh while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight; 1251373cc2ddSdrh if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ 125293a960a0Sdrh /* For columns use the column name name */ 1253dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1254373cc2ddSdrh pTab = pColExpr->pTab; 1255f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1256f0209f74Sdrh zName = sqlite3MPrintf(db, "%s", 1257f0209f74Sdrh iCol>=0 ? pTab->aCol[iCol].zName : "rowid"); 1258b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 125933e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 126033e619fcSdrh zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); 126193a960a0Sdrh }else{ 126279d5f63fSdrh /* Use the original text of the column expression as its name */ 1263b7916a78Sdrh zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); 12647d10d5a6Sdrh } 126522f70c32Sdrh } 12667ce72f69Sdrh if( db->mallocFailed ){ 1267633e6d57Sdrh sqlite3DbFree(db, zName); 12687ce72f69Sdrh break; 1269dd5b2fa5Sdrh } 127079d5f63fSdrh 127179d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 127279d5f63fSdrh ** append a integer to the name so that it becomes unique. 127379d5f63fSdrh */ 1274ea678832Sdrh nName = sqlite3Strlen30(zName); 127579d5f63fSdrh for(j=cnt=0; j<i; j++){ 127679d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 1277633e6d57Sdrh char *zNewName; 12782564ef97Sdrh zName[nName] = 0; 1279633e6d57Sdrh zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt); 1280633e6d57Sdrh sqlite3DbFree(db, zName); 1281633e6d57Sdrh zName = zNewName; 128279d5f63fSdrh j = -1; 1283dd5b2fa5Sdrh if( zName==0 ) break; 128479d5f63fSdrh } 128579d5f63fSdrh } 128691bb0eedSdrh pCol->zName = zName; 12877d10d5a6Sdrh } 12887d10d5a6Sdrh if( db->mallocFailed ){ 12897d10d5a6Sdrh for(j=0; j<i; j++){ 12907d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 12917d10d5a6Sdrh } 12927d10d5a6Sdrh sqlite3DbFree(db, aCol); 12937d10d5a6Sdrh *paCol = 0; 12947d10d5a6Sdrh *pnCol = 0; 12957d10d5a6Sdrh return SQLITE_NOMEM; 12967d10d5a6Sdrh } 12977d10d5a6Sdrh return SQLITE_OK; 12987d10d5a6Sdrh } 1299e014a838Sdanielk1977 13007d10d5a6Sdrh /* 13017d10d5a6Sdrh ** Add type and collation information to a column list based on 13027d10d5a6Sdrh ** a SELECT statement. 13037d10d5a6Sdrh ** 13047d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 13057d10d5a6Sdrh ** The column list has only names, not types or collations. This 13067d10d5a6Sdrh ** routine goes through and adds the types and collations. 13077d10d5a6Sdrh ** 1308b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 13097d10d5a6Sdrh ** statement be resolved. 131079d5f63fSdrh */ 13117d10d5a6Sdrh static void selectAddColumnTypeAndCollation( 13127d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 13137d10d5a6Sdrh int nCol, /* Number of columns */ 13147d10d5a6Sdrh Column *aCol, /* List of columns */ 13157d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 13167d10d5a6Sdrh ){ 13177d10d5a6Sdrh sqlite3 *db = pParse->db; 13187d10d5a6Sdrh NameContext sNC; 13197d10d5a6Sdrh Column *pCol; 13207d10d5a6Sdrh CollSeq *pColl; 13217d10d5a6Sdrh int i; 13227d10d5a6Sdrh Expr *p; 13237d10d5a6Sdrh struct ExprList_item *a; 13247d10d5a6Sdrh 13257d10d5a6Sdrh assert( pSelect!=0 ); 13267d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 13277d10d5a6Sdrh assert( nCol==pSelect->pEList->nExpr || db->mallocFailed ); 13287d10d5a6Sdrh if( db->mallocFailed ) return; 1329c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1330b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 13317d10d5a6Sdrh a = pSelect->pEList->a; 13327d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 13337d10d5a6Sdrh p = a[i].pExpr; 13347d10d5a6Sdrh pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); 1335c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1336c4a64facSdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE; 1337b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1338b3bf556eSdanielk1977 if( pColl ){ 133917435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 13400202b29eSdanielk1977 } 134122f70c32Sdrh } 13427d10d5a6Sdrh } 13437d10d5a6Sdrh 13447d10d5a6Sdrh /* 13457d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 13467d10d5a6Sdrh ** the result set of that SELECT. 13477d10d5a6Sdrh */ 13487d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 13497d10d5a6Sdrh Table *pTab; 13507d10d5a6Sdrh sqlite3 *db = pParse->db; 13517d10d5a6Sdrh int savedFlags; 13527d10d5a6Sdrh 13537d10d5a6Sdrh savedFlags = db->flags; 13547d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 13557d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 13567d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 13577d10d5a6Sdrh if( pParse->nErr ) return 0; 13587d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 13597d10d5a6Sdrh db->flags = savedFlags; 13607d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 13617d10d5a6Sdrh if( pTab==0 ){ 13627d10d5a6Sdrh return 0; 13637d10d5a6Sdrh } 1364373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 1365b2468954Sdrh ** is disabled */ 1366373cc2ddSdrh assert( db->lookaside.bEnabled==0 ); 13677d10d5a6Sdrh pTab->nRef = 1; 13687d10d5a6Sdrh pTab->zName = 0; 13691ea87012Sdrh pTab->nRowEst = 1000000; 13707d10d5a6Sdrh selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 13717d10d5a6Sdrh selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect); 137222f70c32Sdrh pTab->iPKey = -1; 13737ce72f69Sdrh if( db->mallocFailed ){ 13741feeaed2Sdan sqlite3DeleteTable(db, pTab); 13757ce72f69Sdrh return 0; 13767ce72f69Sdrh } 137722f70c32Sdrh return pTab; 137822f70c32Sdrh } 137922f70c32Sdrh 138022f70c32Sdrh /* 1381d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1382d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1383d8bc7086Sdrh */ 13844adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1385d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1386d8bc7086Sdrh if( v==0 ){ 13874adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1388949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE 1389949f9cd5Sdrh if( v ){ 1390949f9cd5Sdrh sqlite3VdbeAddOp0(v, OP_Trace); 1391949f9cd5Sdrh } 1392949f9cd5Sdrh #endif 1393d8bc7086Sdrh } 1394d8bc7086Sdrh return v; 1395d8bc7086Sdrh } 1396d8bc7086Sdrh 139715007a99Sdrh 1398d8bc7086Sdrh /* 13997b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1400ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 14017b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1402a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1403a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1404a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1405a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 14067b58daeaSdrh ** 1407d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1408ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 14097b58daeaSdrh ** iOffset should have been preset to appropriate default values 14107b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1411ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 14127b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 14137b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 14147b58daeaSdrh ** SELECT statements. 14157b58daeaSdrh */ 1416ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 141702afc861Sdrh Vdbe *v = 0; 141802afc861Sdrh int iLimit = 0; 141915007a99Sdrh int iOffset; 14209b918ed1Sdrh int addr1, n; 14210acb7e48Sdrh if( p->iLimit ) return; 142215007a99Sdrh 14237b58daeaSdrh /* 14247b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 14257b58daeaSdrh ** contraversy about what the correct behavior should be. 14267b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 14277b58daeaSdrh ** no rows. 14287b58daeaSdrh */ 1429ceea3321Sdrh sqlite3ExprCacheClear(pParse); 1430373cc2ddSdrh assert( p->pOffset==0 || p->pLimit!=0 ); 1431a2dc3b1aSdanielk1977 if( p->pLimit ){ 14320a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 143315007a99Sdrh v = sqlite3GetVdbe(pParse); 1434373cc2ddSdrh if( NEVER(v==0) ) return; /* VDBE should have already been allocated */ 14359b918ed1Sdrh if( sqlite3ExprIsInteger(p->pLimit, &n) ){ 14369b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 14379b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 1438456e4e4fSdrh if( n==0 ){ 1439456e4e4fSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 144095aa47b1Sdrh }else{ 144195aa47b1Sdrh if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n; 14429b918ed1Sdrh } 14439b918ed1Sdrh }else{ 1444b7654111Sdrh sqlite3ExprCode(pParse, p->pLimit, iLimit); 1445b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); 1446d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 14473c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); 14489b918ed1Sdrh } 1449a2dc3b1aSdanielk1977 if( p->pOffset ){ 14500a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 1451b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 1452b7654111Sdrh sqlite3ExprCode(pParse, p->pOffset, iOffset); 1453b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); 1454d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 14553c84ddffSdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); 1456b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); 145715007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 1458b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1459d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 1460b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); 1461b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); 1462b7654111Sdrh sqlite3VdbeJumpHere(v, addr1); 1463b7654111Sdrh } 1464d59ba6ceSdrh } 14657b58daeaSdrh } 14667b58daeaSdrh 1467b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1468fbc4ee7bSdrh /* 1469fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1470fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1471fbc4ee7bSdrh ** the column has no default collating sequence. 1472fbc4ee7bSdrh ** 1473fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1474fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1475fbc4ee7bSdrh */ 1476dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1477fbc4ee7bSdrh CollSeq *pRet; 1478dc1bdc4fSdanielk1977 if( p->pPrior ){ 1479dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1480fbc4ee7bSdrh }else{ 1481fbc4ee7bSdrh pRet = 0; 1482dc1bdc4fSdanielk1977 } 148310c081adSdrh assert( iCol>=0 ); 148410c081adSdrh if( pRet==0 && iCol<p->pEList->nExpr ){ 1485dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1486dc1bdc4fSdanielk1977 } 1487dc1bdc4fSdanielk1977 return pRet; 1488d3d39e93Sdrh } 1489b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1490d3d39e93Sdrh 1491b21e7c70Sdrh /* Forward reference */ 1492b21e7c70Sdrh static int multiSelectOrderBy( 1493b21e7c70Sdrh Parse *pParse, /* Parsing context */ 1494b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 1495a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 1496b21e7c70Sdrh ); 1497b21e7c70Sdrh 1498b21e7c70Sdrh 1499b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1500d3d39e93Sdrh /* 150116ee60ffSdrh ** This routine is called to process a compound query form from 150216ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 150316ee60ffSdrh ** INTERSECT 1504c926afbcSdrh ** 1505e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1506e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1507e78e8284Sdrh ** in which case this routine will be called recursively. 1508e78e8284Sdrh ** 1509e78e8284Sdrh ** The results of the total query are to be written into a destination 1510e78e8284Sdrh ** of type eDest with parameter iParm. 1511e78e8284Sdrh ** 1512e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1513e78e8284Sdrh ** 1514e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1515e78e8284Sdrh ** 1516e78e8284Sdrh ** This statement is parsed up as follows: 1517e78e8284Sdrh ** 1518e78e8284Sdrh ** SELECT c FROM t3 1519e78e8284Sdrh ** | 1520e78e8284Sdrh ** `-----> SELECT b FROM t2 1521e78e8284Sdrh ** | 15224b11c6d3Sjplyon ** `------> SELECT a FROM t1 1523e78e8284Sdrh ** 1524e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1525e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1526e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1527e78e8284Sdrh ** 1528e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1529e78e8284Sdrh ** individual selects always group from left to right. 153082c3d636Sdrh */ 153184ac9d02Sdanielk1977 static int multiSelect( 1532fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1533fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1534a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 153584ac9d02Sdanielk1977 ){ 153684ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 153710e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 153810e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 15391013c932Sdrh SelectDest dest; /* Alternative data destination */ 1540eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 1541633e6d57Sdrh sqlite3 *db; /* Database connection */ 15427f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 15437f61e92cSdan int iSub1; /* EQP id of left-hand query */ 15447f61e92cSdan int iSub2; /* EQP id of right-hand query */ 15457f61e92cSdan #endif 154682c3d636Sdrh 15477b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1548fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 154982c3d636Sdrh */ 1550701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 1551633e6d57Sdrh db = pParse->db; 1552d8bc7086Sdrh pPrior = p->pPrior; 15530342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 15540342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1555bc10377aSdrh dest = *pDest; 1556d8bc7086Sdrh if( pPrior->pOrderBy ){ 15574adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1558da93d238Sdrh selectOpName(p->op)); 155984ac9d02Sdanielk1977 rc = 1; 156084ac9d02Sdanielk1977 goto multi_select_end; 156182c3d636Sdrh } 1562a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 15634adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 15647b58daeaSdrh selectOpName(p->op)); 156584ac9d02Sdanielk1977 rc = 1; 156684ac9d02Sdanielk1977 goto multi_select_end; 15677b58daeaSdrh } 156882c3d636Sdrh 15694adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 1570701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 1571d8bc7086Sdrh 15721cc3d75fSdrh /* Create the destination temporary table if necessary 15731cc3d75fSdrh */ 15746c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 1575b4964b72Sdanielk1977 assert( p->pEList ); 1576f6e369a1Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr); 1577d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 15786c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 15791cc3d75fSdrh } 15801cc3d75fSdrh 1581f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 1582f6e369a1Sdrh ** in their result sets. 1583f6e369a1Sdrh */ 1584f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 1585f6e369a1Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 1586f6e369a1Sdrh sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1587f6e369a1Sdrh " do not have the same number of result columns", selectOpName(p->op)); 1588f6e369a1Sdrh rc = 1; 1589f6e369a1Sdrh goto multi_select_end; 1590f6e369a1Sdrh } 1591f6e369a1Sdrh 1592a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 1593a9671a22Sdrh */ 1594f6e369a1Sdrh if( p->pOrderBy ){ 1595a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 1596f6e369a1Sdrh } 1597f6e369a1Sdrh 1598f46f905aSdrh /* Generate code for the left and right SELECT statements. 1599d8bc7086Sdrh */ 160082c3d636Sdrh switch( p->op ){ 1601f46f905aSdrh case TK_ALL: { 1602ec7429aeSdrh int addr = 0; 160395aa47b1Sdrh int nLimit; 1604a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1605a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1606a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 16077f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 16087d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 1609ad68cb6bSdanielk1977 p->pLimit = 0; 1610ad68cb6bSdanielk1977 p->pOffset = 0; 161184ac9d02Sdanielk1977 if( rc ){ 161284ac9d02Sdanielk1977 goto multi_select_end; 161384ac9d02Sdanielk1977 } 1614f46f905aSdrh p->pPrior = 0; 16157b58daeaSdrh p->iLimit = pPrior->iLimit; 16167b58daeaSdrh p->iOffset = pPrior->iOffset; 161792b01d53Sdrh if( p->iLimit ){ 16183c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); 1619d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 1620ec7429aeSdrh } 16217f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 16227d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 1623373cc2ddSdrh testcase( rc!=SQLITE_OK ); 1624eca7e01aSdanielk1977 pDelete = p->pPrior; 1625f46f905aSdrh p->pPrior = pPrior; 162695aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 162795aa47b1Sdrh if( pPrior->pLimit 162895aa47b1Sdrh && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) 162995aa47b1Sdrh && p->nSelectRow > (double)nLimit 163095aa47b1Sdrh ){ 163195aa47b1Sdrh p->nSelectRow = (double)nLimit; 163295aa47b1Sdrh } 1633ec7429aeSdrh if( addr ){ 1634ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1635ec7429aeSdrh } 1636f46f905aSdrh break; 1637f46f905aSdrh } 163882c3d636Sdrh case TK_EXCEPT: 163982c3d636Sdrh case TK_UNION: { 1640d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1641ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 1642d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1643a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1644dc1bdc4fSdanielk1977 int addr; 16456c8c8ce0Sdanielk1977 SelectDest uniondest; 164682c3d636Sdrh 1647373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 1648373cc2ddSdrh testcase( p->op==TK_UNION ); 164993a960a0Sdrh priorOp = SRT_Union; 1650e2f02bacSdrh if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){ 1651d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1652c926afbcSdrh ** right. 1653d8bc7086Sdrh */ 1654e2f02bacSdrh assert( p->pRightmost!=p ); /* Can only happen for leftward elements 1655e2f02bacSdrh ** of a 3-way or more compound */ 1656e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 1657e2f02bacSdrh assert( p->pOffset==0 ); /* Not allowed on leftward elements */ 16586c8c8ce0Sdanielk1977 unionTab = dest.iParm; 165982c3d636Sdrh }else{ 1660d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1661d8bc7086Sdrh ** intermediate results. 1662d8bc7086Sdrh */ 166382c3d636Sdrh unionTab = pParse->nTab++; 166493a960a0Sdrh assert( p->pOrderBy==0 ); 166566a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 1666b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1667b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 16687d10d5a6Sdrh p->pRightmost->selFlags |= SF_UsesEphemeral; 166984ac9d02Sdanielk1977 assert( p->pEList ); 1670d8bc7086Sdrh } 1671d8bc7086Sdrh 1672d8bc7086Sdrh /* Code the SELECT statements to our left 1673d8bc7086Sdrh */ 1674b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 16751013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 16767f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 16777d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 167884ac9d02Sdanielk1977 if( rc ){ 167984ac9d02Sdanielk1977 goto multi_select_end; 168084ac9d02Sdanielk1977 } 1681d8bc7086Sdrh 1682d8bc7086Sdrh /* Code the current SELECT statement 1683d8bc7086Sdrh */ 16844cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 16854cfb22f7Sdrh op = SRT_Except; 16864cfb22f7Sdrh }else{ 16874cfb22f7Sdrh assert( p->op==TK_UNION ); 16884cfb22f7Sdrh op = SRT_Union; 1689d8bc7086Sdrh } 169082c3d636Sdrh p->pPrior = 0; 1691a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1692a2dc3b1aSdanielk1977 p->pLimit = 0; 1693a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1694a2dc3b1aSdanielk1977 p->pOffset = 0; 16956c8c8ce0Sdanielk1977 uniondest.eDest = op; 16967f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 16977d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 1698373cc2ddSdrh testcase( rc!=SQLITE_OK ); 16995bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 17005bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 1701633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 1702eca7e01aSdanielk1977 pDelete = p->pPrior; 170382c3d636Sdrh p->pPrior = pPrior; 1704a9671a22Sdrh p->pOrderBy = 0; 170595aa47b1Sdrh if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow; 1706633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 1707a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1708a2dc3b1aSdanielk1977 p->pOffset = pOffset; 170992b01d53Sdrh p->iLimit = 0; 171092b01d53Sdrh p->iOffset = 0; 1711d8bc7086Sdrh 1712d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1713d8bc7086Sdrh ** it is that we currently need. 1714d8bc7086Sdrh */ 1715373cc2ddSdrh assert( unionTab==dest.iParm || dest.eDest!=priorOp ); 1716373cc2ddSdrh if( dest.eDest!=priorOp ){ 17176b56344dSdrh int iCont, iBreak, iStart; 171882c3d636Sdrh assert( p->pEList ); 17197d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 172092378253Sdrh Select *pFirst = p; 172192378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 172292378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 172341202ccaSdrh } 17244adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 17254adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1726ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 172766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); 17284adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 1729d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 1730a9671a22Sdrh 0, -1, &dest, iCont, iBreak); 17314adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 173266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); 17334adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 173466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 173582c3d636Sdrh } 173682c3d636Sdrh break; 173782c3d636Sdrh } 1738373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 173982c3d636Sdrh int tab1, tab2; 17406b56344dSdrh int iCont, iBreak, iStart; 1741a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 1742dc1bdc4fSdanielk1977 int addr; 17431013c932Sdrh SelectDest intersectdest; 17449cbf3425Sdrh int r1; 174582c3d636Sdrh 1746d8bc7086Sdrh /* INTERSECT is different from the others since it requires 17476206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1748d8bc7086Sdrh ** by allocating the tables we will need. 1749d8bc7086Sdrh */ 175082c3d636Sdrh tab1 = pParse->nTab++; 175182c3d636Sdrh tab2 = pParse->nTab++; 175293a960a0Sdrh assert( p->pOrderBy==0 ); 1753dc1bdc4fSdanielk1977 175466a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 1755b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1756b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 17577d10d5a6Sdrh p->pRightmost->selFlags |= SF_UsesEphemeral; 175884ac9d02Sdanielk1977 assert( p->pEList ); 1759d8bc7086Sdrh 1760d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1761d8bc7086Sdrh */ 17621013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 17637f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 17647d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 176584ac9d02Sdanielk1977 if( rc ){ 176684ac9d02Sdanielk1977 goto multi_select_end; 176784ac9d02Sdanielk1977 } 1768d8bc7086Sdrh 1769d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1770d8bc7086Sdrh */ 177166a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 1772b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 1773b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 177482c3d636Sdrh p->pPrior = 0; 1775a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1776a2dc3b1aSdanielk1977 p->pLimit = 0; 1777a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1778a2dc3b1aSdanielk1977 p->pOffset = 0; 17796c8c8ce0Sdanielk1977 intersectdest.iParm = tab2; 17807f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 17817d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 1782373cc2ddSdrh testcase( rc!=SQLITE_OK ); 1783eca7e01aSdanielk1977 pDelete = p->pPrior; 178482c3d636Sdrh p->pPrior = pPrior; 178595aa47b1Sdrh if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 1786633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 1787a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1788a2dc3b1aSdanielk1977 p->pOffset = pOffset; 1789d8bc7086Sdrh 1790d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1791d8bc7086Sdrh ** tables. 1792d8bc7086Sdrh */ 179382c3d636Sdrh assert( p->pEList ); 17947d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 179592378253Sdrh Select *pFirst = p; 179692378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 179792378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 179841202ccaSdrh } 17994adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 18004adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1801ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 180266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); 18039cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 18049cbf3425Sdrh iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 18058cff69dfSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); 18069cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 1807d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 1808a9671a22Sdrh 0, -1, &dest, iCont, iBreak); 18094adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 181066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); 18114adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 181266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 181366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 181482c3d636Sdrh break; 181582c3d636Sdrh } 181682c3d636Sdrh } 18178cdbf836Sdrh 18187f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); 18197f61e92cSdan 1820a9671a22Sdrh /* Compute collating sequences used by 1821a9671a22Sdrh ** temporary tables needed to implement the compound select. 1822a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 18238cdbf836Sdrh ** 18248cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 18258cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 18268cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 18278cdbf836Sdrh ** no temp tables are required. 1828fbc4ee7bSdrh */ 18297d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 1830fbc4ee7bSdrh int i; /* Loop counter */ 1831fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 18320342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 1833f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 183493a960a0Sdrh int nCol; /* Number of columns in result set */ 1835fbc4ee7bSdrh 18360342b1f5Sdrh assert( p->pRightmost==p ); 183793a960a0Sdrh nCol = p->pEList->nExpr; 1838633e6d57Sdrh pKeyInfo = sqlite3DbMallocZero(db, 1839a9671a22Sdrh sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1)); 1840dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1841dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1842dc1bdc4fSdanielk1977 goto multi_select_end; 1843dc1bdc4fSdanielk1977 } 1844dc1bdc4fSdanielk1977 1845633e6d57Sdrh pKeyInfo->enc = ENC(db); 1846ea678832Sdrh pKeyInfo->nField = (u16)nCol; 1847dc1bdc4fSdanielk1977 18480342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 18490342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 18500342b1f5Sdrh if( 0==*apColl ){ 1851633e6d57Sdrh *apColl = db->pDfltColl; 1852dc1bdc4fSdanielk1977 } 1853dc1bdc4fSdanielk1977 } 1854dc1bdc4fSdanielk1977 18550342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 18560342b1f5Sdrh for(i=0; i<2; i++){ 1857b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 18580342b1f5Sdrh if( addr<0 ){ 18590342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 18600342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 1861b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 18620342b1f5Sdrh break; 18630342b1f5Sdrh } 18640342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 186566a5167bSdrh sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); 18660ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 18670342b1f5Sdrh } 1868dc1bdc4fSdanielk1977 } 1869633e6d57Sdrh sqlite3DbFree(db, pKeyInfo); 1870dc1bdc4fSdanielk1977 } 1871dc1bdc4fSdanielk1977 1872dc1bdc4fSdanielk1977 multi_select_end: 18731013c932Sdrh pDest->iMem = dest.iMem; 1874ad27e761Sdrh pDest->nMem = dest.nMem; 1875633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 187684ac9d02Sdanielk1977 return rc; 18772282792aSdrh } 1878b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 18792282792aSdrh 1880b21e7c70Sdrh /* 1881b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 1882b21e7c70Sdrh ** SELECT statment. 18830acb7e48Sdrh ** 18840acb7e48Sdrh ** The data to be output is contained in pIn->iMem. There are 18850acb7e48Sdrh ** pIn->nMem columns to be output. pDest is where the output should 18860acb7e48Sdrh ** be sent. 18870acb7e48Sdrh ** 18880acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 18890acb7e48Sdrh ** return address. 18900acb7e48Sdrh ** 1891f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 18920acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 18930acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 18940acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 18950acb7e48Sdrh ** keys. 18960acb7e48Sdrh ** 18970acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 18980acb7e48Sdrh ** iBreak. 1899b21e7c70Sdrh */ 19000acb7e48Sdrh static int generateOutputSubroutine( 190192b01d53Sdrh Parse *pParse, /* Parsing context */ 190292b01d53Sdrh Select *p, /* The SELECT statement */ 190392b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 190492b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 190592b01d53Sdrh int regReturn, /* The return address register */ 19060acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 19070acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 19080acb7e48Sdrh int p4type, /* The p4 type for pKeyInfo */ 190992b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 1910b21e7c70Sdrh ){ 1911b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 191292b01d53Sdrh int iContinue; 191392b01d53Sdrh int addr; 1914b21e7c70Sdrh 191592b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 191692b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 19170acb7e48Sdrh 19180acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 19190acb7e48Sdrh */ 19200acb7e48Sdrh if( regPrev ){ 19210acb7e48Sdrh int j1, j2; 19220acb7e48Sdrh j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); 19230acb7e48Sdrh j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem, 19240acb7e48Sdrh (char*)pKeyInfo, p4type); 19250acb7e48Sdrh sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); 19260acb7e48Sdrh sqlite3VdbeJumpHere(v, j1); 19270acb7e48Sdrh sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem); 19280acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 19290acb7e48Sdrh } 19301f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 19310acb7e48Sdrh 19320acb7e48Sdrh /* Suppress the the first OFFSET entries if there is an OFFSET clause 19330acb7e48Sdrh */ 193492b01d53Sdrh codeOffset(v, p, iContinue); 1935b21e7c70Sdrh 1936b21e7c70Sdrh switch( pDest->eDest ){ 1937b21e7c70Sdrh /* Store the result as data using a unique key. 1938b21e7c70Sdrh */ 1939b21e7c70Sdrh case SRT_Table: 1940b21e7c70Sdrh case SRT_EphemTab: { 1941b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 1942b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 1943373cc2ddSdrh testcase( pDest->eDest==SRT_Table ); 1944373cc2ddSdrh testcase( pDest->eDest==SRT_EphemTab ); 194592b01d53Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1); 194692b01d53Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2); 194792b01d53Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2); 1948b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1949b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 1950b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 1951b21e7c70Sdrh break; 1952b21e7c70Sdrh } 1953b21e7c70Sdrh 1954b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 1955b21e7c70Sdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 1956b21e7c70Sdrh ** then there should be a single item on the stack. Write this 1957b21e7c70Sdrh ** item into the set table with bogus data. 1958b21e7c70Sdrh */ 1959b21e7c70Sdrh case SRT_Set: { 19606fccc35aSdrh int r1; 196192b01d53Sdrh assert( pIn->nMem==1 ); 196292b01d53Sdrh p->affinity = 196392b01d53Sdrh sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity); 1964b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 196592b01d53Sdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1); 196692b01d53Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1); 196792b01d53Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1); 1968b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 1969b21e7c70Sdrh break; 1970b21e7c70Sdrh } 1971b21e7c70Sdrh 197285e9e22bSdrh #if 0 /* Never occurs on an ORDER BY query */ 1973b21e7c70Sdrh /* If any row exist in the result set, record that fact and abort. 1974b21e7c70Sdrh */ 1975b21e7c70Sdrh case SRT_Exists: { 197692b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm); 1977b21e7c70Sdrh /* The LIMIT clause will terminate the loop for us */ 1978b21e7c70Sdrh break; 1979b21e7c70Sdrh } 198085e9e22bSdrh #endif 1981b21e7c70Sdrh 1982b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 1983b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 1984b21e7c70Sdrh ** of the scan loop. 1985b21e7c70Sdrh */ 1986b21e7c70Sdrh case SRT_Mem: { 198792b01d53Sdrh assert( pIn->nMem==1 ); 198892b01d53Sdrh sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1); 1989b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 1990b21e7c70Sdrh break; 1991b21e7c70Sdrh } 1992b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 1993b21e7c70Sdrh 19947d10d5a6Sdrh /* The results are stored in a sequence of registers 19957d10d5a6Sdrh ** starting at pDest->iMem. Then the co-routine yields. 1996b21e7c70Sdrh */ 199792b01d53Sdrh case SRT_Coroutine: { 199892b01d53Sdrh if( pDest->iMem==0 ){ 199992b01d53Sdrh pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem); 200092b01d53Sdrh pDest->nMem = pIn->nMem; 2001b21e7c70Sdrh } 200292b01d53Sdrh sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem); 200392b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 200492b01d53Sdrh break; 200592b01d53Sdrh } 200692b01d53Sdrh 2007ccfcbceaSdrh /* If none of the above, then the result destination must be 2008ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2009ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2010ccfcbceaSdrh ** 2011ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2012ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2013ccfcbceaSdrh ** return the next row of result. 20147d10d5a6Sdrh */ 2015ccfcbceaSdrh default: { 2016ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 201792b01d53Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem); 201892b01d53Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem); 2019b21e7c70Sdrh break; 2020b21e7c70Sdrh } 2021b21e7c70Sdrh } 202292b01d53Sdrh 202392b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 202492b01d53Sdrh */ 202592b01d53Sdrh if( p->iLimit ){ 20269b918ed1Sdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); 202792b01d53Sdrh } 202892b01d53Sdrh 202992b01d53Sdrh /* Generate the subroutine return 203092b01d53Sdrh */ 20310acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 203292b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 203392b01d53Sdrh 203492b01d53Sdrh return addr; 2035b21e7c70Sdrh } 2036b21e7c70Sdrh 2037b21e7c70Sdrh /* 2038b21e7c70Sdrh ** Alternative compound select code generator for cases when there 2039b21e7c70Sdrh ** is an ORDER BY clause. 2040b21e7c70Sdrh ** 2041b21e7c70Sdrh ** We assume a query of the following form: 2042b21e7c70Sdrh ** 2043b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 2044b21e7c70Sdrh ** 2045b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 2046b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 2047b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 2048b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 2049b21e7c70Sdrh ** selectB) there are 7 subroutines: 2050b21e7c70Sdrh ** 2051b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 2052b21e7c70Sdrh ** of the compound query. 2053b21e7c70Sdrh ** 2054b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 2055b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 2056b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 2057b21e7c70Sdrh ** appears only in B.) 2058b21e7c70Sdrh ** 2059b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 2060b21e7c70Sdrh ** 2061b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 2062b21e7c70Sdrh ** 2063b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 2064b21e7c70Sdrh ** 2065b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 2066b21e7c70Sdrh ** 2067b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 2068b21e7c70Sdrh ** 2069b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 2070b21e7c70Sdrh ** <operator> is used: 2071b21e7c70Sdrh ** 2072b21e7c70Sdrh ** 2073b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 2074b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 2075b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 2076b21e7c70Sdrh ** 20770acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 2078b21e7c70Sdrh ** 2079b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 2080b21e7c70Sdrh ** 20810acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 2082b21e7c70Sdrh ** 20830acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 20840acb7e48Sdrh ** 20850acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 20860acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 20870acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 20880acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 20890acb7e48Sdrh ** 20900acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 20910acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 20920acb7e48Sdrh ** output value. A comparison is made against this value and the output 20930acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 2094b21e7c70Sdrh ** 2095b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 2096b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 2097b21e7c70Sdrh ** 2098b21e7c70Sdrh ** goto Init 2099b21e7c70Sdrh ** coA: coroutine for left query (A) 2100b21e7c70Sdrh ** coB: coroutine for right query (B) 2101b21e7c70Sdrh ** outA: output one row of A 2102b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 2103b21e7c70Sdrh ** EofA: ... 2104b21e7c70Sdrh ** EofB: ... 2105b21e7c70Sdrh ** AltB: ... 2106b21e7c70Sdrh ** AeqB: ... 2107b21e7c70Sdrh ** AgtB: ... 2108b21e7c70Sdrh ** Init: initialize coroutine registers 2109b21e7c70Sdrh ** yield coA 2110b21e7c70Sdrh ** if eof(A) goto EofA 2111b21e7c70Sdrh ** yield coB 2112b21e7c70Sdrh ** if eof(B) goto EofB 2113b21e7c70Sdrh ** Cmpr: Compare A, B 2114b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 2115b21e7c70Sdrh ** End: ... 2116b21e7c70Sdrh ** 2117b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 2118b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 2119b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 2120b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 2121b21e7c70Sdrh */ 2122de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 2123b21e7c70Sdrh static int multiSelectOrderBy( 2124b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2125b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2126a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2127b21e7c70Sdrh ){ 21280acb7e48Sdrh int i, j; /* Loop counters */ 2129b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 2130b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 2131b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 2132b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 213392b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 213492b01d53Sdrh int regEofA; /* Flag to indicate when select-A is complete */ 213592b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 213692b01d53Sdrh int regEofB; /* Flag to indicate when select-B is complete */ 213792b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 213892b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 213992b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 214092b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 214192b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 2142b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 214392b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 214492b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 214592b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 214692b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 214792b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 214892b01d53Sdrh int regLimitA; /* Limit register for select-A */ 214992b01d53Sdrh int regLimitB; /* Limit register for select-A */ 21500acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 215192b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 215292b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 215392b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 215492b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 21550acb7e48Sdrh int j1; /* Jump instructions that get retargetted */ 215692b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 215796067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 21580acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 21590acb7e48Sdrh sqlite3 *db; /* Database connection */ 21600acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 21610acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 21620acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 21637f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 21647f61e92cSdan int iSub1; /* EQP id of left-hand query */ 21657f61e92cSdan int iSub2; /* EQP id of right-hand query */ 21667f61e92cSdan #endif 2167b21e7c70Sdrh 216892b01d53Sdrh assert( p->pOrderBy!=0 ); 216996067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 21700acb7e48Sdrh db = pParse->db; 217192b01d53Sdrh v = pParse->pVdbe; 2172ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 217392b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 217492b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 21750acb7e48Sdrh 2176b21e7c70Sdrh 217792b01d53Sdrh /* Patch up the ORDER BY clause 217892b01d53Sdrh */ 217992b01d53Sdrh op = p->op; 2180b21e7c70Sdrh pPrior = p->pPrior; 218192b01d53Sdrh assert( pPrior->pOrderBy==0 ); 21820acb7e48Sdrh pOrderBy = p->pOrderBy; 218393a960a0Sdrh assert( pOrderBy ); 21840acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 218593a960a0Sdrh 21860acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 21870acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 21880acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 21890acb7e48Sdrh */ 21900acb7e48Sdrh if( op!=TK_ALL ){ 21910acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 21927d10d5a6Sdrh struct ExprList_item *pItem; 21937d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 21947d10d5a6Sdrh assert( pItem->iCol>0 ); 21957d10d5a6Sdrh if( pItem->iCol==i ) break; 21960acb7e48Sdrh } 21970acb7e48Sdrh if( j==nOrderBy ){ 2198b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 21990acb7e48Sdrh if( pNew==0 ) return SQLITE_NOMEM; 22000acb7e48Sdrh pNew->flags |= EP_IntValue; 220133e619fcSdrh pNew->u.iValue = i; 2202b7916a78Sdrh pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 2203ea678832Sdrh pOrderBy->a[nOrderBy++].iCol = (u16)i; 22040acb7e48Sdrh } 22050acb7e48Sdrh } 22060acb7e48Sdrh } 22070acb7e48Sdrh 22080acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 220910c081adSdrh ** the permutation used to determine if the next 22100acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 22110acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 22120acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 22130acb7e48Sdrh ** collation. 22140acb7e48Sdrh */ 22150acb7e48Sdrh aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); 22160acb7e48Sdrh if( aPermute ){ 22177d10d5a6Sdrh struct ExprList_item *pItem; 22187d10d5a6Sdrh for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){ 22197d10d5a6Sdrh assert( pItem->iCol>0 && pItem->iCol<=p->pEList->nExpr ); 22207d10d5a6Sdrh aPermute[i] = pItem->iCol - 1; 22210acb7e48Sdrh } 22220acb7e48Sdrh pKeyMerge = 22230acb7e48Sdrh sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1)); 22240acb7e48Sdrh if( pKeyMerge ){ 22250acb7e48Sdrh pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy]; 2226ea678832Sdrh pKeyMerge->nField = (u16)nOrderBy; 22270acb7e48Sdrh pKeyMerge->enc = ENC(db); 22280acb7e48Sdrh for(i=0; i<nOrderBy; i++){ 22290acb7e48Sdrh CollSeq *pColl; 22300acb7e48Sdrh Expr *pTerm = pOrderBy->a[i].pExpr; 22310acb7e48Sdrh if( pTerm->flags & EP_ExpCollate ){ 22320acb7e48Sdrh pColl = pTerm->pColl; 22330acb7e48Sdrh }else{ 22340acb7e48Sdrh pColl = multiSelectCollSeq(pParse, p, aPermute[i]); 22350acb7e48Sdrh pTerm->flags |= EP_ExpCollate; 22360acb7e48Sdrh pTerm->pColl = pColl; 22370acb7e48Sdrh } 22380acb7e48Sdrh pKeyMerge->aColl[i] = pColl; 22390acb7e48Sdrh pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder; 22400acb7e48Sdrh } 22410acb7e48Sdrh } 22420acb7e48Sdrh }else{ 22430acb7e48Sdrh pKeyMerge = 0; 22440acb7e48Sdrh } 22450acb7e48Sdrh 22460acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 22470acb7e48Sdrh */ 22480acb7e48Sdrh p->pOrderBy = pOrderBy; 22496ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 22500acb7e48Sdrh 22510acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 22520acb7e48Sdrh ** for the logic that removes duplicate result rows when the 22530acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 22540acb7e48Sdrh */ 22550acb7e48Sdrh if( op==TK_ALL ){ 22560acb7e48Sdrh regPrev = 0; 22570acb7e48Sdrh }else{ 22580acb7e48Sdrh int nExpr = p->pEList->nExpr; 22591c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 22600acb7e48Sdrh regPrev = sqlite3GetTempRange(pParse, nExpr+1); 22610acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 22620acb7e48Sdrh pKeyDup = sqlite3DbMallocZero(db, 22630acb7e48Sdrh sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) ); 22640acb7e48Sdrh if( pKeyDup ){ 22650acb7e48Sdrh pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr]; 2266ea678832Sdrh pKeyDup->nField = (u16)nExpr; 22670acb7e48Sdrh pKeyDup->enc = ENC(db); 22680acb7e48Sdrh for(i=0; i<nExpr; i++){ 22690acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 22700acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 22710acb7e48Sdrh } 22720acb7e48Sdrh } 22730acb7e48Sdrh } 227492b01d53Sdrh 227592b01d53Sdrh /* Separate the left and the right query from one another 227692b01d53Sdrh */ 227792b01d53Sdrh p->pPrior = 0; 22787d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 22790acb7e48Sdrh if( pPrior->pPrior==0 ){ 22807d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 22810acb7e48Sdrh } 228292b01d53Sdrh 228392b01d53Sdrh /* Compute the limit registers */ 228492b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 22850acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 228692b01d53Sdrh regLimitA = ++pParse->nMem; 228792b01d53Sdrh regLimitB = ++pParse->nMem; 228892b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 228992b01d53Sdrh regLimitA); 229092b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 229192b01d53Sdrh }else{ 229292b01d53Sdrh regLimitA = regLimitB = 0; 229392b01d53Sdrh } 2294633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 22950acb7e48Sdrh p->pLimit = 0; 2296633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 22970acb7e48Sdrh p->pOffset = 0; 229892b01d53Sdrh 2299b21e7c70Sdrh regAddrA = ++pParse->nMem; 2300b21e7c70Sdrh regEofA = ++pParse->nMem; 2301b21e7c70Sdrh regAddrB = ++pParse->nMem; 2302b21e7c70Sdrh regEofB = ++pParse->nMem; 2303b21e7c70Sdrh regOutA = ++pParse->nMem; 2304b21e7c70Sdrh regOutB = ++pParse->nMem; 2305b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 2306b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 2307b21e7c70Sdrh 230892b01d53Sdrh /* Jump past the various subroutines and coroutines to the main 230992b01d53Sdrh ** merge loop 231092b01d53Sdrh */ 2311b21e7c70Sdrh j1 = sqlite3VdbeAddOp0(v, OP_Goto); 2312b21e7c70Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v); 231392b01d53Sdrh 23140acb7e48Sdrh 231592b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 23160acb7e48Sdrh ** left of the compound operator - the "A" select. 23170acb7e48Sdrh */ 2318b21e7c70Sdrh VdbeNoopComment((v, "Begin coroutine for left SELECT")); 231992b01d53Sdrh pPrior->iLimit = regLimitA; 23207f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 23217d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 2322b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA); 232392b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 2324b21e7c70Sdrh VdbeNoopComment((v, "End coroutine for left SELECT")); 2325b21e7c70Sdrh 232692b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 232792b01d53Sdrh ** the right - the "B" select 232892b01d53Sdrh */ 2329b21e7c70Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v); 2330b21e7c70Sdrh VdbeNoopComment((v, "Begin coroutine for right SELECT")); 233192b01d53Sdrh savedLimit = p->iLimit; 233292b01d53Sdrh savedOffset = p->iOffset; 233392b01d53Sdrh p->iLimit = regLimitB; 233492b01d53Sdrh p->iOffset = 0; 23357f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 23367d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 233792b01d53Sdrh p->iLimit = savedLimit; 233892b01d53Sdrh p->iOffset = savedOffset; 2339b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB); 234092b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 2341b21e7c70Sdrh VdbeNoopComment((v, "End coroutine for right SELECT")); 2342b21e7c70Sdrh 234392b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 23440acb7e48Sdrh ** select as the next output row of the compound select. 234592b01d53Sdrh */ 2346b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 23470acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 23480acb7e48Sdrh p, &destA, pDest, regOutA, 23490acb7e48Sdrh regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd); 2350b21e7c70Sdrh 235192b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 23520acb7e48Sdrh ** select as the next output row of the compound select. 235392b01d53Sdrh */ 23540acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 2355b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 23560acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 23570acb7e48Sdrh p, &destB, pDest, regOutB, 23580acb7e48Sdrh regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd); 23590acb7e48Sdrh } 2360b21e7c70Sdrh 236192b01d53Sdrh /* Generate a subroutine to run when the results from select A 236292b01d53Sdrh ** are exhausted and only data in select B remains. 236392b01d53Sdrh */ 236492b01d53Sdrh VdbeNoopComment((v, "eof-A subroutine")); 236592b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 23660acb7e48Sdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd); 236792b01d53Sdrh }else{ 23680acb7e48Sdrh addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd); 2369b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 237092b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 23710acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); 237295aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 2373b21e7c70Sdrh } 2374b21e7c70Sdrh 237592b01d53Sdrh /* Generate a subroutine to run when the results from select B 237692b01d53Sdrh ** are exhausted and only data in select A remains. 237792b01d53Sdrh */ 2378b21e7c70Sdrh if( op==TK_INTERSECT ){ 237992b01d53Sdrh addrEofB = addrEofA; 238095aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 2381b21e7c70Sdrh }else{ 238292b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 23830acb7e48Sdrh addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd); 2384b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 238592b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 23860acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); 2387b21e7c70Sdrh } 2388b21e7c70Sdrh 238992b01d53Sdrh /* Generate code to handle the case of A<B 239092b01d53Sdrh */ 2391b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 23920acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 239392b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 2394b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 239592b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 2396b21e7c70Sdrh 239792b01d53Sdrh /* Generate code to handle the case of A==B 239892b01d53Sdrh */ 2399b21e7c70Sdrh if( op==TK_ALL ){ 2400b21e7c70Sdrh addrAeqB = addrAltB; 24010acb7e48Sdrh }else if( op==TK_INTERSECT ){ 24020acb7e48Sdrh addrAeqB = addrAltB; 24030acb7e48Sdrh addrAltB++; 240492b01d53Sdrh }else{ 2405b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 24060acb7e48Sdrh addrAeqB = 240792b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 240892b01d53Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 240992b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 241092b01d53Sdrh } 2411b21e7c70Sdrh 241292b01d53Sdrh /* Generate code to handle the case of A>B 241392b01d53Sdrh */ 2414b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 2415b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 2416b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 2417b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 241892b01d53Sdrh } 24190acb7e48Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 2420b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); 242192b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 2422b21e7c70Sdrh 242392b01d53Sdrh /* This code runs once to initialize everything. 242492b01d53Sdrh */ 2425b21e7c70Sdrh sqlite3VdbeJumpHere(v, j1); 2426b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA); 2427b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB); 242892b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA); 24290acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB); 2430b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 2431b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); 243292b01d53Sdrh 243392b01d53Sdrh /* Implement the main merge loop 243492b01d53Sdrh */ 243592b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 24360acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 24370acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy, 24380acb7e48Sdrh (char*)pKeyMerge, P4_KEYINFO_HANDOFF); 2439b21e7c70Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); 244092b01d53Sdrh 24410acb7e48Sdrh /* Release temporary registers 24420acb7e48Sdrh */ 24430acb7e48Sdrh if( regPrev ){ 24440acb7e48Sdrh sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1); 24450acb7e48Sdrh } 24460acb7e48Sdrh 244792b01d53Sdrh /* Jump to the this point in order to terminate the query. 244892b01d53Sdrh */ 2449b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 2450b21e7c70Sdrh 245192b01d53Sdrh /* Set the number of output columns 245292b01d53Sdrh */ 24537d10d5a6Sdrh if( pDest->eDest==SRT_Output ){ 24540acb7e48Sdrh Select *pFirst = pPrior; 245592b01d53Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 245692b01d53Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 2457b21e7c70Sdrh } 245892b01d53Sdrh 24590acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 24600acb7e48Sdrh ** by the calling function */ 24615e7ad508Sdanielk1977 if( p->pPrior ){ 2462633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 24635e7ad508Sdanielk1977 } 24640acb7e48Sdrh p->pPrior = pPrior; 246592b01d53Sdrh 246692b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 246792b01d53Sdrh **** subqueries ****/ 24687f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, 0); 246992b01d53Sdrh return SQLITE_OK; 247092b01d53Sdrh } 2471de3e41e3Sdanielk1977 #endif 2472b21e7c70Sdrh 24733514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 247417435752Sdrh /* Forward Declarations */ 247517435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*); 247617435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *); 247717435752Sdrh 24782282792aSdrh /* 2479832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 24806a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 248184e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 24826a3ea0e6Sdrh ** unchanged.) 2483832508b7Sdrh ** 2484832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 2485832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 2486832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 2487832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 2488832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 2489832508b7Sdrh ** of the subquery rather the result set of the subquery. 2490832508b7Sdrh */ 2491b7916a78Sdrh static Expr *substExpr( 249217435752Sdrh sqlite3 *db, /* Report malloc errors to this connection */ 249317435752Sdrh Expr *pExpr, /* Expr in which substitution occurs */ 249417435752Sdrh int iTable, /* Table to be substituted */ 249517435752Sdrh ExprList *pEList /* Substitute expressions */ 249617435752Sdrh ){ 2497b7916a78Sdrh if( pExpr==0 ) return 0; 249850350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 249950350a15Sdrh if( pExpr->iColumn<0 ){ 250050350a15Sdrh pExpr->op = TK_NULL; 250150350a15Sdrh }else{ 2502832508b7Sdrh Expr *pNew; 250384e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 25046ab3a2ecSdanielk1977 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 2505b7916a78Sdrh pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); 250638210ac5Sdrh if( pNew && pExpr->pColl ){ 25070a458e5eSdanielk1977 pNew->pColl = pExpr->pColl; 25080a458e5eSdanielk1977 } 2509b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 2510b7916a78Sdrh pExpr = pNew; 251150350a15Sdrh } 2512832508b7Sdrh }else{ 2513b7916a78Sdrh pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); 2514b7916a78Sdrh pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); 25156ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 25166ab3a2ecSdanielk1977 substSelect(db, pExpr->x.pSelect, iTable, pEList); 25176ab3a2ecSdanielk1977 }else{ 25186ab3a2ecSdanielk1977 substExprList(db, pExpr->x.pList, iTable, pEList); 25196ab3a2ecSdanielk1977 } 2520832508b7Sdrh } 2521b7916a78Sdrh return pExpr; 2522832508b7Sdrh } 252317435752Sdrh static void substExprList( 252417435752Sdrh sqlite3 *db, /* Report malloc errors here */ 252517435752Sdrh ExprList *pList, /* List to scan and in which to make substitutes */ 252617435752Sdrh int iTable, /* Table to be substituted */ 252717435752Sdrh ExprList *pEList /* Substitute values */ 252817435752Sdrh ){ 2529832508b7Sdrh int i; 2530832508b7Sdrh if( pList==0 ) return; 2531832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 2532b7916a78Sdrh pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); 2533832508b7Sdrh } 2534832508b7Sdrh } 253517435752Sdrh static void substSelect( 253617435752Sdrh sqlite3 *db, /* Report malloc errors here */ 253717435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 253817435752Sdrh int iTable, /* Table to be replaced */ 253917435752Sdrh ExprList *pEList /* Substitute values */ 254017435752Sdrh ){ 2541588a9a1aSdrh SrcList *pSrc; 2542588a9a1aSdrh struct SrcList_item *pItem; 2543588a9a1aSdrh int i; 2544b3bce662Sdanielk1977 if( !p ) return; 254517435752Sdrh substExprList(db, p->pEList, iTable, pEList); 254617435752Sdrh substExprList(db, p->pGroupBy, iTable, pEList); 254717435752Sdrh substExprList(db, p->pOrderBy, iTable, pEList); 2548b7916a78Sdrh p->pHaving = substExpr(db, p->pHaving, iTable, pEList); 2549b7916a78Sdrh p->pWhere = substExpr(db, p->pWhere, iTable, pEList); 255017435752Sdrh substSelect(db, p->pPrior, iTable, pEList); 2551588a9a1aSdrh pSrc = p->pSrc; 2552e2f02bacSdrh assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ 2553e2f02bacSdrh if( ALWAYS(pSrc) ){ 2554588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 2555588a9a1aSdrh substSelect(db, pItem->pSelect, iTable, pEList); 2556588a9a1aSdrh } 2557588a9a1aSdrh } 2558b3bce662Sdanielk1977 } 25593514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 2560832508b7Sdrh 25613514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 2562832508b7Sdrh /* 25631350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 25641350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 25651350b030Sdrh ** occurs. 25661350b030Sdrh ** 25671350b030Sdrh ** To understand the concept of flattening, consider the following 25681350b030Sdrh ** query: 25691350b030Sdrh ** 25701350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 25711350b030Sdrh ** 25721350b030Sdrh ** The default way of implementing this query is to execute the 25731350b030Sdrh ** subquery first and store the results in a temporary table, then 25741350b030Sdrh ** run the outer query on that temporary table. This requires two 25751350b030Sdrh ** passes over the data. Furthermore, because the temporary table 25761350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 2577832508b7Sdrh ** optimized. 25781350b030Sdrh ** 2579832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 25801350b030Sdrh ** a single flat select, like this: 25811350b030Sdrh ** 25821350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 25831350b030Sdrh ** 25841350b030Sdrh ** The code generated for this simpification gives the same result 2585832508b7Sdrh ** but only has to scan the data once. And because indices might 2586832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 2587832508b7Sdrh ** avoided. 25881350b030Sdrh ** 2589832508b7Sdrh ** Flattening is only attempted if all of the following are true: 25901350b030Sdrh ** 2591832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 25921350b030Sdrh ** 2593832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 2594832508b7Sdrh ** 25952b300d5dSdrh ** (3) The subquery is not the right operand of a left outer join 259649ad330dSdan ** (Originally ticket #306. Strengthened by ticket #3300) 2597832508b7Sdrh ** 259849ad330dSdan ** (4) The subquery is not DISTINCT. 2599832508b7Sdrh ** 260049ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 260149ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 260249ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 2603832508b7Sdrh ** 2604832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 2605832508b7Sdrh ** DISTINCT. 2606832508b7Sdrh ** 260708192d5fSdrh ** (7) The subquery has a FROM clause. 260808192d5fSdrh ** 2609df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 2610df199a25Sdrh ** 2611df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 2612df199a25Sdrh ** aggregates. 2613df199a25Sdrh ** 2614df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 2615df199a25Sdrh ** use LIMIT. 2616df199a25Sdrh ** 2617174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 2618174b6195Sdrh ** 26197b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 26202b300d5dSdrh ** a separate restriction deriving from ticket #350. 26213fc673e6Sdrh ** 262249ad330dSdan ** (13) The subquery and outer query do not both use LIMIT. 2623ac83963aSdrh ** 262449ad330dSdan ** (14) The subquery does not use OFFSET. 2625ac83963aSdrh ** 2626ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 2627f3913278Sdrh ** subquery does not have a LIMIT clause. 2628f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 2629ad91c6cdSdrh ** 2630c52e355dSdrh ** (16) The outer query is not an aggregate or the subquery does 2631c52e355dSdrh ** not contain ORDER BY. (Ticket #2942) This used to not matter 2632c52e355dSdrh ** until we introduced the group_concat() function. 2633c52e355dSdrh ** 2634f23329a2Sdanielk1977 ** (17) The sub-query is not a compound select, or it is a UNION ALL 26354914cf92Sdanielk1977 ** compound clause made up entirely of non-aggregate queries, and 2636f23329a2Sdanielk1977 ** the parent query: 2637f23329a2Sdanielk1977 ** 2638f23329a2Sdanielk1977 ** * is not itself part of a compound select, 2639f23329a2Sdanielk1977 ** * is not an aggregate or DISTINCT query, and 2640f23329a2Sdanielk1977 ** * has no other tables or sub-selects in the FROM clause. 2641f23329a2Sdanielk1977 ** 26424914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 26434914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 26444914cf92Sdanielk1977 ** LIMIT and OFFSET clauses. 2645f23329a2Sdanielk1977 ** 264649fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 264749fc1f60Sdanielk1977 ** ORDER by clause of the parent must be simple references to 264849fc1f60Sdanielk1977 ** columns of the sub-query. 264949fc1f60Sdanielk1977 ** 2650229cf702Sdrh ** (19) The subquery does not use LIMIT or the outer query does not 2651229cf702Sdrh ** have a WHERE clause. 2652229cf702Sdrh ** 2653e8902a70Sdrh ** (20) If the sub-query is a compound select, then it must not use 2654e8902a70Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 2655e8902a70Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 2656e8902a70Sdrh ** appear as unmodified result columns in the outer query. But 2657e8902a70Sdrh ** have other optimizations in mind to deal with that case. 2658e8902a70Sdrh ** 2659a91491e5Sshaneh ** (21) The subquery does not use LIMIT or the outer query is not 2660a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 2661a91491e5Sshaneh ** 2662832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 2663832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2664832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2665832508b7Sdrh ** 2666665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 2667832508b7Sdrh ** If flattening is attempted this routine returns 1. 2668832508b7Sdrh ** 2669832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 2670832508b7Sdrh ** the subquery before this routine runs. 26711350b030Sdrh */ 26728c74a8caSdrh static int flattenSubquery( 2673524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 26748c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 26758c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 26768c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 26778c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 26788c74a8caSdrh ){ 2679524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 2680f23329a2Sdanielk1977 Select *pParent; 26810bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2682f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 2683ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2684ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 26850bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 26866a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 268791bb0eedSdrh int i; /* Loop counter */ 268891bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 268991bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 2690524cc21eSdanielk1977 sqlite3 *db = pParse->db; 26911350b030Sdrh 2692832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2693832508b7Sdrh */ 2694a78c22c4Sdrh assert( p!=0 ); 2695a78c22c4Sdrh assert( p->pPrior==0 ); /* Unable to flatten compound queries */ 269607096f68Sdrh if( db->flags & SQLITE_QueryFlattener ) return 0; 2697832508b7Sdrh pSrc = p->pSrc; 2698ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 269991bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 270049fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 270191bb0eedSdrh pSub = pSubitem->pSelect; 2702832508b7Sdrh assert( pSub!=0 ); 2703ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2704ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2705832508b7Sdrh pSubSrc = pSub->pSrc; 2706832508b7Sdrh assert( pSubSrc ); 2707ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2708ac83963aSdrh ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2709ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 2710ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 2711ac83963aSdrh ** and (14). */ 2712ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2713ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 2714f3913278Sdrh if( p->pRightmost && pSub->pLimit ){ 2715ad91c6cdSdrh return 0; /* Restriction (15) */ 2716ad91c6cdSdrh } 2717ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 271849ad330dSdan if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ 271949ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 272049ad330dSdan return 0; /* Restrictions (8)(9) */ 2721df199a25Sdrh } 27227d10d5a6Sdrh if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ 27237d10d5a6Sdrh return 0; /* Restriction (6) */ 27247d10d5a6Sdrh } 27257d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 2726ac83963aSdrh return 0; /* Restriction (11) */ 2727ac83963aSdrh } 2728c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 2729229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 2730a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 2731a91491e5Sshaneh return 0; /* Restriction (21) */ 2732a91491e5Sshaneh } 2733832508b7Sdrh 27342b300d5dSdrh /* OBSOLETE COMMENT 1: 27352b300d5dSdrh ** Restriction 3: If the subquery is a join, make sure the subquery is 27368af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 27378af4d3acSdrh ** is not allowed: 27388af4d3acSdrh ** 27398af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 27408af4d3acSdrh ** 27418af4d3acSdrh ** If we flatten the above, we would get 27428af4d3acSdrh ** 27438af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 27448af4d3acSdrh ** 27458af4d3acSdrh ** which is not at all the same thing. 27462b300d5dSdrh ** 27472b300d5dSdrh ** OBSOLETE COMMENT 2: 27482b300d5dSdrh ** Restriction 12: If the subquery is the right operand of a left outer 27493fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 27503fc673e6Sdrh ** An examples of why this is not allowed: 27513fc673e6Sdrh ** 27523fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 27533fc673e6Sdrh ** 27543fc673e6Sdrh ** If we flatten the above, we would get 27553fc673e6Sdrh ** 27563fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 27573fc673e6Sdrh ** 27583fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 27593fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 27602b300d5dSdrh ** 27612b300d5dSdrh ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: 27622b300d5dSdrh ** Ticket #3300 shows that flattening the right term of a LEFT JOIN 27632b300d5dSdrh ** is fraught with danger. Best to avoid the whole thing. If the 27642b300d5dSdrh ** subquery is the right term of a LEFT JOIN, then do not flatten. 27653fc673e6Sdrh */ 27662b300d5dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 ){ 27673fc673e6Sdrh return 0; 27683fc673e6Sdrh } 27693fc673e6Sdrh 2770f23329a2Sdanielk1977 /* Restriction 17: If the sub-query is a compound SELECT, then it must 2771f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 2772f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 2773f23329a2Sdanielk1977 ** queries. 2774f23329a2Sdanielk1977 */ 2775f23329a2Sdanielk1977 if( pSub->pPrior ){ 2776e8902a70Sdrh if( pSub->pOrderBy ){ 2777e8902a70Sdrh return 0; /* Restriction 20 */ 2778e8902a70Sdrh } 2779e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 2780f23329a2Sdanielk1977 return 0; 2781f23329a2Sdanielk1977 } 2782f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 2783ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 2784ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 27857d10d5a6Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 278680b3c548Sdanielk1977 || (pSub1->pPrior && pSub1->op!=TK_ALL) 2787ccfcbceaSdrh || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1 278880b3c548Sdanielk1977 ){ 2789f23329a2Sdanielk1977 return 0; 2790f23329a2Sdanielk1977 } 2791f23329a2Sdanielk1977 } 279249fc1f60Sdanielk1977 279349fc1f60Sdanielk1977 /* Restriction 18. */ 279449fc1f60Sdanielk1977 if( p->pOrderBy ){ 279549fc1f60Sdanielk1977 int ii; 279649fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 27977d10d5a6Sdrh if( p->pOrderBy->a[ii].iCol==0 ) return 0; 279849fc1f60Sdanielk1977 } 279949fc1f60Sdanielk1977 } 2800f23329a2Sdanielk1977 } 2801f23329a2Sdanielk1977 28027d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 28037d10d5a6Sdrh 28047d10d5a6Sdrh /* Authorize the subquery */ 2805524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 2806524cc21eSdanielk1977 sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 2807524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 2808524cc21eSdanielk1977 28097d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 28107d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 28117d10d5a6Sdrh ** be of the form: 2812f23329a2Sdanielk1977 ** 2813f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 2814f23329a2Sdanielk1977 ** 2815f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 2816a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 2817f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 2818f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 2819f23329a2Sdanielk1977 ** select statements in the compound sub-query. 2820a78c22c4Sdrh ** 2821a78c22c4Sdrh ** Example: 2822a78c22c4Sdrh ** 2823a78c22c4Sdrh ** SELECT a+1 FROM ( 2824a78c22c4Sdrh ** SELECT x FROM tab 2825a78c22c4Sdrh ** UNION ALL 2826a78c22c4Sdrh ** SELECT y FROM tab 2827a78c22c4Sdrh ** UNION ALL 2828a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 2829a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 2830a78c22c4Sdrh ** 2831a78c22c4Sdrh ** Transformed into: 2832a78c22c4Sdrh ** 2833a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 2834a78c22c4Sdrh ** UNION ALL 2835a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 2836a78c22c4Sdrh ** UNION ALL 2837a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 2838a78c22c4Sdrh ** ORDER BY 1 2839a78c22c4Sdrh ** 2840a78c22c4Sdrh ** We call this the "compound-subquery flattening". 2841f23329a2Sdanielk1977 */ 2842f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 2843f23329a2Sdanielk1977 Select *pNew; 2844f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 28454b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 2846f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 2847f23329a2Sdanielk1977 p->pOrderBy = 0; 2848f23329a2Sdanielk1977 p->pSrc = 0; 2849f23329a2Sdanielk1977 p->pPrior = 0; 28504b86ef1dSdanielk1977 p->pLimit = 0; 28516ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 28524b86ef1dSdanielk1977 p->pLimit = pLimit; 2853a78c22c4Sdrh p->pOrderBy = pOrderBy; 2854a78c22c4Sdrh p->pSrc = pSrc; 2855a78c22c4Sdrh p->op = TK_ALL; 2856f23329a2Sdanielk1977 p->pRightmost = 0; 2857a78c22c4Sdrh if( pNew==0 ){ 2858a78c22c4Sdrh pNew = pPrior; 2859a78c22c4Sdrh }else{ 2860a78c22c4Sdrh pNew->pPrior = pPrior; 2861f23329a2Sdanielk1977 pNew->pRightmost = 0; 2862f23329a2Sdanielk1977 } 2863a78c22c4Sdrh p->pPrior = pNew; 2864a78c22c4Sdrh if( db->mallocFailed ) return 1; 2865a78c22c4Sdrh } 2866f23329a2Sdanielk1977 28677d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 28687d10d5a6Sdrh ** in the outer query. 2869832508b7Sdrh */ 2870f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 2871c31c2eb8Sdrh 2872a78c22c4Sdrh /* Delete the transient table structure associated with the 2873a78c22c4Sdrh ** subquery 2874a78c22c4Sdrh */ 2875a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 2876a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 2877a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 2878a78c22c4Sdrh pSubitem->zDatabase = 0; 2879a78c22c4Sdrh pSubitem->zName = 0; 2880a78c22c4Sdrh pSubitem->zAlias = 0; 2881a78c22c4Sdrh pSubitem->pSelect = 0; 2882a78c22c4Sdrh 2883a78c22c4Sdrh /* Defer deleting the Table object associated with the 2884a78c22c4Sdrh ** subquery until code generation is 2885a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 2886a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 2887ccfcbceaSdrh ** 2888ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 2889a78c22c4Sdrh */ 2890ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 2891a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 2892a78c22c4Sdrh if( pTabToDel->nRef==1 ){ 289365a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 289465a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 289565a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 2896a78c22c4Sdrh }else{ 2897a78c22c4Sdrh pTabToDel->nRef--; 2898a78c22c4Sdrh } 2899a78c22c4Sdrh pSubitem->pTab = 0; 2900a78c22c4Sdrh } 2901a78c22c4Sdrh 2902a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 2903a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 2904a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 2905a78c22c4Sdrh ** then this loop only runs once. 2906a78c22c4Sdrh ** 2907a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 2908c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2909c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2910c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2911c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2912c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2913c31c2eb8Sdrh ** elements we are now copying in. 2914c31c2eb8Sdrh */ 2915a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 2916a78c22c4Sdrh int nSubSrc; 2917ea678832Sdrh u8 jointype = 0; 2918a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 2919a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 2920a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 2921588a9a1aSdrh 2922a78c22c4Sdrh if( pSrc ){ 2923a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 2924a78c22c4Sdrh jointype = pSubitem->jointype; 2925588a9a1aSdrh }else{ 2926a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 2927a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 2928cfa063b3Sdrh if( pSrc==0 ){ 2929a78c22c4Sdrh assert( db->mallocFailed ); 2930a78c22c4Sdrh break; 2931cfa063b3Sdrh } 2932c31c2eb8Sdrh } 2933a78c22c4Sdrh 2934a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 2935a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 2936a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 2937a78c22c4Sdrh ** of the subquery. 2938a78c22c4Sdrh ** 2939a78c22c4Sdrh ** Example: 2940a78c22c4Sdrh ** 2941a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 2942a78c22c4Sdrh ** 2943a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 2944a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 2945a78c22c4Sdrh ** block of code will expand the out query to 4 slots. The middle 2946a78c22c4Sdrh ** slot is expanded to two slots in order to make space for the 2947a78c22c4Sdrh ** two elements in the FROM clause of the subquery. 2948a78c22c4Sdrh */ 2949a78c22c4Sdrh if( nSubSrc>1 ){ 2950a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 2951a78c22c4Sdrh if( db->mallocFailed ){ 2952a78c22c4Sdrh break; 2953c31c2eb8Sdrh } 2954c31c2eb8Sdrh } 2955a78c22c4Sdrh 2956a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 2957a78c22c4Sdrh ** outer query. 2958a78c22c4Sdrh */ 2959c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2960c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 2961c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2962c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2963c31c2eb8Sdrh } 296461dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 2965c31c2eb8Sdrh 2966c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2967c31c2eb8Sdrh ** references to the iParent in the outer query. 2968c31c2eb8Sdrh ** 2969c31c2eb8Sdrh ** Example: 2970c31c2eb8Sdrh ** 2971c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2972c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 2973c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 2974c31c2eb8Sdrh ** 2975c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 2976c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2977c31c2eb8Sdrh */ 2978f23329a2Sdanielk1977 pList = pParent->pEList; 2979832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 2980ccfcbceaSdrh if( pList->a[i].zName==0 ){ 2981b7916a78Sdrh const char *zSpan = pList->a[i].zSpan; 2982d6b8c434Sdrh if( ALWAYS(zSpan) ){ 2983b7916a78Sdrh pList->a[i].zName = sqlite3DbStrDup(db, zSpan); 2984832508b7Sdrh } 2985832508b7Sdrh } 2986ccfcbceaSdrh } 2987f23329a2Sdanielk1977 substExprList(db, pParent->pEList, iParent, pSub->pEList); 29881b2e0329Sdrh if( isAgg ){ 2989f23329a2Sdanielk1977 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList); 2990b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 29911b2e0329Sdrh } 2992174b6195Sdrh if( pSub->pOrderBy ){ 2993f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 2994f23329a2Sdanielk1977 pParent->pOrderBy = pSub->pOrderBy; 2995174b6195Sdrh pSub->pOrderBy = 0; 2996f23329a2Sdanielk1977 }else if( pParent->pOrderBy ){ 2997f23329a2Sdanielk1977 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList); 2998174b6195Sdrh } 2999832508b7Sdrh if( pSub->pWhere ){ 30006ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 3001832508b7Sdrh }else{ 3002832508b7Sdrh pWhere = 0; 3003832508b7Sdrh } 3004832508b7Sdrh if( subqueryIsAgg ){ 3005f23329a2Sdanielk1977 assert( pParent->pHaving==0 ); 3006f23329a2Sdanielk1977 pParent->pHaving = pParent->pWhere; 3007f23329a2Sdanielk1977 pParent->pWhere = pWhere; 3008b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 3009f23329a2Sdanielk1977 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 30106ab3a2ecSdanielk1977 sqlite3ExprDup(db, pSub->pHaving, 0)); 3011f23329a2Sdanielk1977 assert( pParent->pGroupBy==0 ); 30126ab3a2ecSdanielk1977 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); 3013832508b7Sdrh }else{ 3014b7916a78Sdrh pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList); 3015f23329a2Sdanielk1977 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); 3016832508b7Sdrh } 3017c31c2eb8Sdrh 3018c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 3019c31c2eb8Sdrh ** outer query is distinct. 3020c31c2eb8Sdrh */ 30217d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 30228c74a8caSdrh 3023a58fdfb1Sdanielk1977 /* 3024a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3025ac83963aSdrh ** 3026ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 3027ac83963aSdrh ** does not work if either limit is negative. 3028a58fdfb1Sdanielk1977 */ 3029a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 3030f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 3031a2dc3b1aSdanielk1977 pSub->pLimit = 0; 3032df199a25Sdrh } 3033f23329a2Sdanielk1977 } 30348c74a8caSdrh 3035c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 3036c31c2eb8Sdrh ** success. 3037c31c2eb8Sdrh */ 3038633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 3039f23329a2Sdanielk1977 3040832508b7Sdrh return 1; 30411350b030Sdrh } 30423514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 30431350b030Sdrh 30441350b030Sdrh /* 3045a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it 304608c88eb0Sdrh ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 3047a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be 3048a9d1ccb9Sdanielk1977 ** a min()/max() query if: 3049a9d1ccb9Sdanielk1977 ** 3050738bdcfbSdanielk1977 ** 1. There is a single object in the FROM clause. 3051738bdcfbSdanielk1977 ** 3052738bdcfbSdanielk1977 ** 2. There is a single expression in the result set, and it is 3053738bdcfbSdanielk1977 ** either min(x) or max(x), where x is a column reference. 3054a9d1ccb9Sdanielk1977 */ 30554f21c4afSdrh static u8 minMaxQuery(Select *p){ 3056a9d1ccb9Sdanielk1977 Expr *pExpr; 3057a9d1ccb9Sdanielk1977 ExprList *pEList = p->pEList; 3058a9d1ccb9Sdanielk1977 305908c88eb0Sdrh if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL; 3060a9d1ccb9Sdanielk1977 pExpr = pEList->a[0].pExpr; 306143152cf8Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 306243152cf8Sdrh if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0; 30636ab3a2ecSdanielk1977 pEList = pExpr->x.pList; 306443152cf8Sdrh if( pEList==0 || pEList->nExpr!=1 ) return 0; 306508c88eb0Sdrh if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL; 306633e619fcSdrh assert( !ExprHasProperty(pExpr, EP_IntValue) ); 306733e619fcSdrh if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){ 306808c88eb0Sdrh return WHERE_ORDERBY_MIN; 306933e619fcSdrh }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){ 307008c88eb0Sdrh return WHERE_ORDERBY_MAX; 3071a9d1ccb9Sdanielk1977 } 307208c88eb0Sdrh return WHERE_ORDERBY_NORMAL; 3073a9d1ccb9Sdanielk1977 } 3074a9d1ccb9Sdanielk1977 3075a9d1ccb9Sdanielk1977 /* 3076a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 3077a5533162Sdanielk1977 ** The second argment is the associated aggregate-info object. This 3078a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 3079a5533162Sdanielk1977 ** 3080a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 3081a5533162Sdanielk1977 ** 3082a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 3083a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 3084a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 3085a5533162Sdanielk1977 */ 3086a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 3087a5533162Sdanielk1977 Table *pTab; 3088a5533162Sdanielk1977 Expr *pExpr; 3089a5533162Sdanielk1977 3090a5533162Sdanielk1977 assert( !p->pGroupBy ); 3091a5533162Sdanielk1977 30927a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 3093a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 3094a5533162Sdanielk1977 ){ 3095a5533162Sdanielk1977 return 0; 3096a5533162Sdanielk1977 } 3097a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 3098a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 309902f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 310002f33725Sdanielk1977 310102f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 3102a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 3103a5533162Sdanielk1977 if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0; 3104a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 3105a5533162Sdanielk1977 3106a5533162Sdanielk1977 return pTab; 3107a5533162Sdanielk1977 } 3108a5533162Sdanielk1977 3109a5533162Sdanielk1977 /* 3110b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 3111b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 3112b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 3113b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 3114b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 3115b1c685b0Sdanielk1977 */ 3116b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 3117b1c685b0Sdanielk1977 if( pFrom->pTab && pFrom->zIndex ){ 3118b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 3119b1c685b0Sdanielk1977 char *zIndex = pFrom->zIndex; 3120b1c685b0Sdanielk1977 Index *pIdx; 3121b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 3122b1c685b0Sdanielk1977 pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 3123b1c685b0Sdanielk1977 pIdx=pIdx->pNext 3124b1c685b0Sdanielk1977 ); 3125b1c685b0Sdanielk1977 if( !pIdx ){ 3126b1c685b0Sdanielk1977 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0); 31271db95106Sdan pParse->checkSchema = 1; 3128b1c685b0Sdanielk1977 return SQLITE_ERROR; 3129b1c685b0Sdanielk1977 } 3130b1c685b0Sdanielk1977 pFrom->pIndex = pIdx; 3131b1c685b0Sdanielk1977 } 3132b1c685b0Sdanielk1977 return SQLITE_OK; 3133b1c685b0Sdanielk1977 } 3134b1c685b0Sdanielk1977 3135b1c685b0Sdanielk1977 /* 31367d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 31377d10d5a6Sdrh ** "Expanding" means to do the following: 31387d10d5a6Sdrh ** 31397d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 31407d10d5a6Sdrh ** element of the FROM clause. 31417d10d5a6Sdrh ** 31427d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 31437d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 31447d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 31457d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 31467d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 31477d10d5a6Sdrh ** without worrying about messing up the presistent representation 31487d10d5a6Sdrh ** of the view. 31497d10d5a6Sdrh ** 31507d10d5a6Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 31517d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 31527d10d5a6Sdrh ** 31537d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 31547d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 31557d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 31567d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 31577d10d5a6Sdrh ** 3158b3bce662Sdanielk1977 */ 31597d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 31607d10d5a6Sdrh Parse *pParse = pWalker->pParse; 31617d10d5a6Sdrh int i, j, k; 31627d10d5a6Sdrh SrcList *pTabList; 31637d10d5a6Sdrh ExprList *pEList; 31647d10d5a6Sdrh struct SrcList_item *pFrom; 31657d10d5a6Sdrh sqlite3 *db = pParse->db; 31667d10d5a6Sdrh 31677d10d5a6Sdrh if( db->mallocFailed ){ 31687d10d5a6Sdrh return WRC_Abort; 31697d10d5a6Sdrh } 317043152cf8Sdrh if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){ 31717d10d5a6Sdrh return WRC_Prune; 31727d10d5a6Sdrh } 31737d10d5a6Sdrh p->selFlags |= SF_Expanded; 31747d10d5a6Sdrh pTabList = p->pSrc; 31757d10d5a6Sdrh pEList = p->pEList; 31767d10d5a6Sdrh 31777d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 31787d10d5a6Sdrh ** the FROM clause of the SELECT statement. 31797d10d5a6Sdrh */ 31807d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 31817d10d5a6Sdrh 31827d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 31837d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 31847d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 31857d10d5a6Sdrh */ 31867d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 31877d10d5a6Sdrh Table *pTab; 31887d10d5a6Sdrh if( pFrom->pTab!=0 ){ 31897d10d5a6Sdrh /* This statement has already been prepared. There is no need 31907d10d5a6Sdrh ** to go further. */ 31917d10d5a6Sdrh assert( i==0 ); 31927d10d5a6Sdrh return WRC_Prune; 31937d10d5a6Sdrh } 31947d10d5a6Sdrh if( pFrom->zName==0 ){ 31957d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 31967d10d5a6Sdrh Select *pSel = pFrom->pSelect; 31977d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 31987d10d5a6Sdrh assert( pSel!=0 ); 31997d10d5a6Sdrh assert( pFrom->pTab==0 ); 32007d10d5a6Sdrh sqlite3WalkSelect(pWalker, pSel); 32017d10d5a6Sdrh pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 32027d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 32037d10d5a6Sdrh pTab->nRef = 1; 32047d10d5a6Sdrh pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab); 32057d10d5a6Sdrh while( pSel->pPrior ){ pSel = pSel->pPrior; } 32067d10d5a6Sdrh selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol); 32077d10d5a6Sdrh pTab->iPKey = -1; 32081ea87012Sdrh pTab->nRowEst = 1000000; 32097d10d5a6Sdrh pTab->tabFlags |= TF_Ephemeral; 32107d10d5a6Sdrh #endif 32117d10d5a6Sdrh }else{ 32127d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 32137d10d5a6Sdrh assert( pFrom->pTab==0 ); 32147d10d5a6Sdrh pFrom->pTab = pTab = 32157d10d5a6Sdrh sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase); 32167d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 32177d10d5a6Sdrh pTab->nRef++; 32187d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 32197d10d5a6Sdrh if( pTab->pSelect || IsVirtual(pTab) ){ 32207d10d5a6Sdrh /* We reach here if the named table is a really a view */ 32217d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 322243152cf8Sdrh assert( pFrom->pSelect==0 ); 32236ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 32247d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 32257d10d5a6Sdrh } 32267d10d5a6Sdrh #endif 32277d10d5a6Sdrh } 322885574e31Sdanielk1977 322985574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 3230b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 323185574e31Sdanielk1977 return WRC_Abort; 323285574e31Sdanielk1977 } 32337d10d5a6Sdrh } 32347d10d5a6Sdrh 32357d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 32367d10d5a6Sdrh */ 32377d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 32387d10d5a6Sdrh return WRC_Abort; 32397d10d5a6Sdrh } 32407d10d5a6Sdrh 32417d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 32427d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 32437d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 32447d10d5a6Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 32457d10d5a6Sdrh ** The following code just has to locate the TK_ALL expressions and expand 32467d10d5a6Sdrh ** each one to the list of all columns in all tables. 32477d10d5a6Sdrh ** 32487d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 32497d10d5a6Sdrh ** that need expanding. 32507d10d5a6Sdrh */ 32517d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 32527d10d5a6Sdrh Expr *pE = pEList->a[k].pExpr; 32537d10d5a6Sdrh if( pE->op==TK_ALL ) break; 325443152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 325543152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 325643152cf8Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; 32577d10d5a6Sdrh } 32587d10d5a6Sdrh if( k<pEList->nExpr ){ 32597d10d5a6Sdrh /* 32607d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 32617d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 32627d10d5a6Sdrh ** in the result set and expand them one by one. 32637d10d5a6Sdrh */ 32647d10d5a6Sdrh struct ExprList_item *a = pEList->a; 32657d10d5a6Sdrh ExprList *pNew = 0; 32667d10d5a6Sdrh int flags = pParse->db->flags; 32677d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 32687d10d5a6Sdrh && (flags & SQLITE_ShortColNames)==0; 32697d10d5a6Sdrh 32707d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 32717d10d5a6Sdrh Expr *pE = a[k].pExpr; 327243152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 327343152cf8Sdrh if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){ 32747d10d5a6Sdrh /* This particular expression does not need to be expanded. 32757d10d5a6Sdrh */ 3276b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 32777d10d5a6Sdrh if( pNew ){ 32787d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 3279b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 3280b7916a78Sdrh a[k].zName = 0; 3281b7916a78Sdrh a[k].zSpan = 0; 32827d10d5a6Sdrh } 32837d10d5a6Sdrh a[k].pExpr = 0; 32847d10d5a6Sdrh }else{ 32857d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 32867d10d5a6Sdrh ** expanded. */ 32877d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 32887d10d5a6Sdrh char *zTName; /* text of name of TABLE */ 328943152cf8Sdrh if( pE->op==TK_DOT ){ 329043152cf8Sdrh assert( pE->pLeft!=0 ); 329133e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 329233e619fcSdrh zTName = pE->pLeft->u.zToken; 32937d10d5a6Sdrh }else{ 32947d10d5a6Sdrh zTName = 0; 32957d10d5a6Sdrh } 32967d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 32977d10d5a6Sdrh Table *pTab = pFrom->pTab; 32987d10d5a6Sdrh char *zTabName = pFrom->zAlias; 329943152cf8Sdrh if( zTabName==0 ){ 33007d10d5a6Sdrh zTabName = pTab->zName; 33017d10d5a6Sdrh } 33027d10d5a6Sdrh if( db->mallocFailed ) break; 33037d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 33047d10d5a6Sdrh continue; 33057d10d5a6Sdrh } 33067d10d5a6Sdrh tableSeen = 1; 33077d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 33087d10d5a6Sdrh Expr *pExpr, *pRight; 33097d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 3310b7916a78Sdrh char *zColname; /* The computed column name */ 3311b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 3312b7916a78Sdrh Token sColname; /* Computed column name as a token */ 33137d10d5a6Sdrh 33147d10d5a6Sdrh /* If a column is marked as 'hidden' (currently only possible 33157d10d5a6Sdrh ** for virtual tables), do not include it in the expanded 33167d10d5a6Sdrh ** result-set list. 33177d10d5a6Sdrh */ 33187d10d5a6Sdrh if( IsHiddenColumn(&pTab->aCol[j]) ){ 33197d10d5a6Sdrh assert(IsVirtual(pTab)); 33207d10d5a6Sdrh continue; 33217d10d5a6Sdrh } 33227d10d5a6Sdrh 3323da55c48aSdrh if( i>0 && zTName==0 ){ 33242179b434Sdrh if( (pFrom->jointype & JT_NATURAL)!=0 33252179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 33262179b434Sdrh ){ 33277d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 33282179b434Sdrh ** table to the right of the join */ 33297d10d5a6Sdrh continue; 33307d10d5a6Sdrh } 33312179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 33327d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 33337d10d5a6Sdrh ** using clause from the table on the right. */ 33347d10d5a6Sdrh continue; 33357d10d5a6Sdrh } 33367d10d5a6Sdrh } 3337b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 3338b7916a78Sdrh zColname = zName; 3339b7916a78Sdrh zToFree = 0; 33407d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 3341b7916a78Sdrh Expr *pLeft; 3342b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 33437d10d5a6Sdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 3344b7916a78Sdrh if( longNames ){ 3345b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 3346b7916a78Sdrh zToFree = zColname; 3347b7916a78Sdrh } 33487d10d5a6Sdrh }else{ 33497d10d5a6Sdrh pExpr = pRight; 33507d10d5a6Sdrh } 3351b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 3352b7916a78Sdrh sColname.z = zColname; 3353b7916a78Sdrh sColname.n = sqlite3Strlen30(zColname); 3354b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 3355b7916a78Sdrh sqlite3DbFree(db, zToFree); 33567d10d5a6Sdrh } 33577d10d5a6Sdrh } 33587d10d5a6Sdrh if( !tableSeen ){ 33597d10d5a6Sdrh if( zTName ){ 33607d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 33617d10d5a6Sdrh }else{ 33627d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 33637d10d5a6Sdrh } 33647d10d5a6Sdrh } 33657d10d5a6Sdrh } 33667d10d5a6Sdrh } 33677d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 33687d10d5a6Sdrh p->pEList = pNew; 33697d10d5a6Sdrh } 33707d10d5a6Sdrh #if SQLITE_MAX_COLUMN 33717d10d5a6Sdrh if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 33727d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 33737d10d5a6Sdrh } 33747d10d5a6Sdrh #endif 33757d10d5a6Sdrh return WRC_Continue; 33767d10d5a6Sdrh } 33777d10d5a6Sdrh 33787d10d5a6Sdrh /* 33797d10d5a6Sdrh ** No-op routine for the parse-tree walker. 33807d10d5a6Sdrh ** 33817d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 33827d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 33837d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 33847d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 33857d10d5a6Sdrh ** subquery in the parser tree. 33867d10d5a6Sdrh */ 338762c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 338862c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 33897d10d5a6Sdrh return WRC_Continue; 33907d10d5a6Sdrh } 33917d10d5a6Sdrh 33927d10d5a6Sdrh /* 33937d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 33947d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 33957d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 33967d10d5a6Sdrh ** 33977d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 33987d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 33997d10d5a6Sdrh ** name resolution is performed. 34007d10d5a6Sdrh ** 34017d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 34027d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 34037d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 34047d10d5a6Sdrh */ 34057d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 34067d10d5a6Sdrh Walker w; 34077d10d5a6Sdrh w.xSelectCallback = selectExpander; 34087d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 34097d10d5a6Sdrh w.pParse = pParse; 34107d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 34117d10d5a6Sdrh } 34127d10d5a6Sdrh 34137d10d5a6Sdrh 34147d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 34157d10d5a6Sdrh /* 34167d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 34177d10d5a6Sdrh ** interface. 34187d10d5a6Sdrh ** 34197d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 34207d10d5a6Sdrh ** information to the Table structure that represents the result set 34217d10d5a6Sdrh ** of that subquery. 34227d10d5a6Sdrh ** 34237d10d5a6Sdrh ** The Table structure that represents the result set was constructed 34247d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 34257d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 34267d10d5a6Sdrh ** routine is called after identifier resolution. 34277d10d5a6Sdrh */ 34287d10d5a6Sdrh static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 34297d10d5a6Sdrh Parse *pParse; 34307d10d5a6Sdrh int i; 34317d10d5a6Sdrh SrcList *pTabList; 34327d10d5a6Sdrh struct SrcList_item *pFrom; 34337d10d5a6Sdrh 34349d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 34355a29d9cbSdrh if( (p->selFlags & SF_HasTypeInfo)==0 ){ 34367d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 34377d10d5a6Sdrh pParse = pWalker->pParse; 34387d10d5a6Sdrh pTabList = p->pSrc; 34397d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 34407d10d5a6Sdrh Table *pTab = pFrom->pTab; 344143152cf8Sdrh if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){ 34427d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 34437d10d5a6Sdrh Select *pSel = pFrom->pSelect; 34447d10d5a6Sdrh assert( pSel ); 34457d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 34467d10d5a6Sdrh selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel); 34477d10d5a6Sdrh } 34487d10d5a6Sdrh } 34495a29d9cbSdrh } 34507d10d5a6Sdrh return WRC_Continue; 34517d10d5a6Sdrh } 34527d10d5a6Sdrh #endif 34537d10d5a6Sdrh 34547d10d5a6Sdrh 34557d10d5a6Sdrh /* 34567d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 34577d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 34587d10d5a6Sdrh ** SELECT statement. 34597d10d5a6Sdrh ** 34607d10d5a6Sdrh ** Use this routine after name resolution. 34617d10d5a6Sdrh */ 34627d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 34637d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 34647d10d5a6Sdrh Walker w; 34657d10d5a6Sdrh w.xSelectCallback = selectAddSubqueryTypeInfo; 34667d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 34677d10d5a6Sdrh w.pParse = pParse; 34687d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 34697d10d5a6Sdrh #endif 34707d10d5a6Sdrh } 34717d10d5a6Sdrh 34727d10d5a6Sdrh 34737d10d5a6Sdrh /* 34747d10d5a6Sdrh ** This routine sets of a SELECT statement for processing. The 34757d10d5a6Sdrh ** following is accomplished: 34767d10d5a6Sdrh ** 34777d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 34787d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 34797d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 34807d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 34817d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 34827d10d5a6Sdrh ** 34837d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 34847d10d5a6Sdrh */ 34857d10d5a6Sdrh void sqlite3SelectPrep( 3486b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 3487b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 34887d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 3489b3bce662Sdanielk1977 ){ 34907d10d5a6Sdrh sqlite3 *db; 349143152cf8Sdrh if( NEVER(p==0) ) return; 34927d10d5a6Sdrh db = pParse->db; 34937d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 34947d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 34957d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 34967d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 34977d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 34987d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 3499f6bbe022Sdrh } 3500b3bce662Sdanielk1977 3501b3bce662Sdanielk1977 /* 350213449892Sdrh ** Reset the aggregate accumulator. 350313449892Sdrh ** 350413449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 350513449892Sdrh ** intermediate results while calculating an aggregate. This 350613449892Sdrh ** routine simply stores NULLs in all of those memory cells. 3507b3bce662Sdanielk1977 */ 350813449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 350913449892Sdrh Vdbe *v = pParse->pVdbe; 351013449892Sdrh int i; 3511c99130fdSdrh struct AggInfo_func *pFunc; 351213449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 351313449892Sdrh return; 351413449892Sdrh } 351513449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 35164c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); 351713449892Sdrh } 3518c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 35194c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); 3520c99130fdSdrh if( pFunc->iDistinct>=0 ){ 3521c99130fdSdrh Expr *pE = pFunc->pExpr; 35226ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 35236ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 35240daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 35250daa002cSdrh "argument"); 3526c99130fdSdrh pFunc->iDistinct = -1; 3527c99130fdSdrh }else{ 35286ab3a2ecSdanielk1977 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList); 352966a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 353066a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3531c99130fdSdrh } 3532c99130fdSdrh } 353313449892Sdrh } 3534b3bce662Sdanielk1977 } 3535b3bce662Sdanielk1977 3536b3bce662Sdanielk1977 /* 353713449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 353813449892Sdrh ** in the AggInfo structure. 3539b3bce662Sdanielk1977 */ 354013449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 354113449892Sdrh Vdbe *v = pParse->pVdbe; 354213449892Sdrh int i; 354313449892Sdrh struct AggInfo_func *pF; 354413449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 35456ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 35466ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 354766a5167bSdrh sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 354866a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 3549b3bce662Sdanielk1977 } 355013449892Sdrh } 355113449892Sdrh 355213449892Sdrh /* 355313449892Sdrh ** Update the accumulator memory cells for an aggregate based on 355413449892Sdrh ** the current cursor position. 355513449892Sdrh */ 355613449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 355713449892Sdrh Vdbe *v = pParse->pVdbe; 355813449892Sdrh int i; 355913449892Sdrh struct AggInfo_func *pF; 356013449892Sdrh struct AggInfo_col *pC; 356113449892Sdrh 356213449892Sdrh pAggInfo->directMode = 1; 3563ceea3321Sdrh sqlite3ExprCacheClear(pParse); 356413449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 356513449892Sdrh int nArg; 3566c99130fdSdrh int addrNext = 0; 356798757157Sdrh int regAgg; 35686ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 35696ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 357013449892Sdrh if( pList ){ 357113449892Sdrh nArg = pList->nExpr; 3572892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 35737153d1fbSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 1); 357413449892Sdrh }else{ 357513449892Sdrh nArg = 0; 357698757157Sdrh regAgg = 0; 357713449892Sdrh } 3578c99130fdSdrh if( pF->iDistinct>=0 ){ 3579c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 3580c99130fdSdrh assert( nArg==1 ); 35812dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 3582c99130fdSdrh } 3583e82f5d04Sdrh if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){ 358413449892Sdrh CollSeq *pColl = 0; 358513449892Sdrh struct ExprList_item *pItem; 358613449892Sdrh int j; 3587e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 358843617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 358913449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 359013449892Sdrh } 359113449892Sdrh if( !pColl ){ 359213449892Sdrh pColl = pParse->db->pDfltColl; 359313449892Sdrh } 359466a5167bSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 359513449892Sdrh } 359698757157Sdrh sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 359766a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 3598ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 3599da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 3600f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 3601c99130fdSdrh if( addrNext ){ 3602c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 3603ceea3321Sdrh sqlite3ExprCacheClear(pParse); 3604c99130fdSdrh } 360513449892Sdrh } 360667a6a40cSdan 360767a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 360867a6a40cSdan ** Otherwise, if any of the required column values are already present 360967a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 361067a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 361167a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 361267a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 361367a6a40cSdan ** 361467a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 361567a6a40cSdan ** values to an OP_Copy. 361667a6a40cSdan */ 361767a6a40cSdan sqlite3ExprCacheClear(pParse); 361813449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 3619389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 362013449892Sdrh } 362113449892Sdrh pAggInfo->directMode = 0; 3622ceea3321Sdrh sqlite3ExprCacheClear(pParse); 362313449892Sdrh } 362413449892Sdrh 3625b3bce662Sdanielk1977 /* 3626ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 3627ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 3628ef7075deSdan */ 3629ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 3630ef7075deSdan static void explainSimpleCount( 3631ef7075deSdan Parse *pParse, /* Parse context */ 3632ef7075deSdan Table *pTab, /* Table being queried */ 3633ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 3634ef7075deSdan ){ 3635ef7075deSdan if( pParse->explain==2 ){ 3636ef7075deSdan char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)", 3637ef7075deSdan pTab->zName, 3638ef7075deSdan pIdx ? "USING COVERING INDEX " : "", 3639ef7075deSdan pIdx ? pIdx->zName : "", 3640ef7075deSdan pTab->nRowEst 3641ef7075deSdan ); 3642ef7075deSdan sqlite3VdbeAddOp4( 3643ef7075deSdan pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC 3644ef7075deSdan ); 3645ef7075deSdan } 3646ef7075deSdan } 3647ef7075deSdan #else 3648ef7075deSdan # define explainSimpleCount(a,b,c) 3649ef7075deSdan #endif 3650ef7075deSdan 3651ef7075deSdan /* 36527d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 36539bb61fe7Sdrh ** 3654fef5208cSdrh ** The results are distributed in various ways depending on the 36556c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest 36566c8c8ce0Sdanielk1977 ** as follows: 3657fef5208cSdrh ** 36586c8c8ce0Sdanielk1977 ** pDest->eDest Result 3659fef5208cSdrh ** ------------ ------------------------------------------- 36607d10d5a6Sdrh ** SRT_Output Generate a row of output (using the OP_ResultRow 36617d10d5a6Sdrh ** opcode) for each row in the result set. 3662fef5208cSdrh ** 36637d10d5a6Sdrh ** SRT_Mem Only valid if the result is a single column. 36647d10d5a6Sdrh ** Store the first column of the first result row 36657d10d5a6Sdrh ** in register pDest->iParm then abandon the rest 36667d10d5a6Sdrh ** of the query. This destination implies "LIMIT 1". 3667fef5208cSdrh ** 36687d10d5a6Sdrh ** SRT_Set The result must be a single column. Store each 36697d10d5a6Sdrh ** row of result as the key in table pDest->iParm. 36707d10d5a6Sdrh ** Apply the affinity pDest->affinity before storing 36717d10d5a6Sdrh ** results. Used to implement "IN (SELECT ...)". 3672fef5208cSdrh ** 36736c8c8ce0Sdanielk1977 ** SRT_Union Store results as a key in a temporary table pDest->iParm. 367482c3d636Sdrh ** 36756c8c8ce0Sdanielk1977 ** SRT_Except Remove results from the temporary table pDest->iParm. 3676c4a3c779Sdrh ** 36777d10d5a6Sdrh ** SRT_Table Store results in temporary table pDest->iParm. 36787d10d5a6Sdrh ** This is like SRT_EphemTab except that the table 36797d10d5a6Sdrh ** is assumed to already be open. 36809bb61fe7Sdrh ** 36816c8c8ce0Sdanielk1977 ** SRT_EphemTab Create an temporary table pDest->iParm and store 36826c8c8ce0Sdanielk1977 ** the result there. The cursor is left open after 36837d10d5a6Sdrh ** returning. This is like SRT_Table except that 36847d10d5a6Sdrh ** this destination uses OP_OpenEphemeral to create 36857d10d5a6Sdrh ** the table first. 36866c8c8ce0Sdanielk1977 ** 36877d10d5a6Sdrh ** SRT_Coroutine Generate a co-routine that returns a new row of 36887d10d5a6Sdrh ** results each time it is invoked. The entry point 36897d10d5a6Sdrh ** of the co-routine is stored in register pDest->iParm. 36906c8c8ce0Sdanielk1977 ** 36916c8c8ce0Sdanielk1977 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result 36926c8c8ce0Sdanielk1977 ** set is not empty. 36936c8c8ce0Sdanielk1977 ** 36947d10d5a6Sdrh ** SRT_Discard Throw the results away. This is used by SELECT 36957d10d5a6Sdrh ** statements within triggers whose only purpose is 36967d10d5a6Sdrh ** the side-effects of functions. 3697e78e8284Sdrh ** 36989bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 36999bb61fe7Sdrh ** encountered, then an appropriate error message is left in 37009bb61fe7Sdrh ** pParse->zErrMsg. 37019bb61fe7Sdrh ** 37029bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 37039bb61fe7Sdrh ** calling function needs to do that. 37049bb61fe7Sdrh */ 37054adee20fSdanielk1977 int sqlite3Select( 3706cce7d176Sdrh Parse *pParse, /* The parser context */ 37079bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 37087d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 3709cce7d176Sdrh ){ 371013449892Sdrh int i, j; /* Loop counters */ 371113449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 371213449892Sdrh Vdbe *v; /* The virtual machine under construction */ 3713b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 3714a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 3715ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 37169bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 37179bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 37182282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 37192282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 372019a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 372119a775c2Sdrh int distinct; /* Table to use for the distinct set */ 37221d83f052Sdrh int rc = 1; /* Value to return from this function */ 3723b9bb7c18Sdrh int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 372413449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 3725ec7429aeSdrh int iEnd; /* Address of the end of the query */ 372617435752Sdrh sqlite3 *db; /* The database connection */ 37279bb61fe7Sdrh 37282ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 37292ce22453Sdan int iRestoreSelectId = pParse->iSelectId; 37302ce22453Sdan pParse->iSelectId = pParse->iNextSelectId++; 37312ce22453Sdan #endif 37322ce22453Sdan 373317435752Sdrh db = pParse->db; 373417435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 37356f7adc8aSdrh return 1; 37366f7adc8aSdrh } 37374adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 373813449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 3739daffd0e5Sdrh 37406c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 37419ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 37429ed1dfa8Sdanielk1977 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); 3743ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 3744ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 3745ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 3746ccfcbceaSdrh p->pOrderBy = 0; 37477d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 37489a99334dSdrh } 37497d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 3750ccfcbceaSdrh pOrderBy = p->pOrderBy; 3751b27b7f5dSdrh pTabList = p->pSrc; 3752b27b7f5dSdrh pEList = p->pEList; 3753956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 37549a99334dSdrh goto select_end; 37559a99334dSdrh } 37567d10d5a6Sdrh isAgg = (p->selFlags & SF_Aggregate)!=0; 375743152cf8Sdrh assert( pEList!=0 ); 3758cce7d176Sdrh 3759d820cb1bSdrh /* Begin generating code. 3760d820cb1bSdrh */ 37614adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 3762d820cb1bSdrh if( v==0 ) goto select_end; 3763d820cb1bSdrh 376474b617b2Sdan /* If writing to memory or generating a set 376574b617b2Sdan ** only a single column may be output. 376674b617b2Sdan */ 376774b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY 376874b617b2Sdan if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 376974b617b2Sdan goto select_end; 377074b617b2Sdan } 377174b617b2Sdan #endif 377274b617b2Sdan 3773d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 3774d820cb1bSdrh */ 377551522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3776f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 377713449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 37781013c932Sdrh SelectDest dest; 3779daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 3780f23329a2Sdanielk1977 int isAggSub; 3781c31c2eb8Sdrh 3782daf79acbSdanielk1977 if( pSub==0 || pItem->isPopulated ) continue; 3783daf79acbSdanielk1977 3784fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 3785fc976065Sdanielk1977 ** tree refered to by this, the parent select. The child select 3786fc976065Sdanielk1977 ** may contain expression trees of at most 3787fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 3788fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 3789fc976065Sdanielk1977 ** an exact limit. 3790fc976065Sdanielk1977 */ 3791fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 3792daf79acbSdanielk1977 3793daf79acbSdanielk1977 /* Check to see if the subquery can be absorbed into the parent. */ 37947d10d5a6Sdrh isAggSub = (pSub->selFlags & SF_Aggregate)!=0; 3795524cc21eSdanielk1977 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ 3796f23329a2Sdanielk1977 if( isAggSub ){ 37977d10d5a6Sdrh isAgg = 1; 37987d10d5a6Sdrh p->selFlags |= SF_Aggregate; 3799daf79acbSdanielk1977 } 3800daf79acbSdanielk1977 i = -1; 3801daf79acbSdanielk1977 }else{ 38021013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 38037d10d5a6Sdrh assert( pItem->isPopulated==0 ); 3804ce7e189dSdan explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 38057d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 38067d10d5a6Sdrh pItem->isPopulated = 1; 380795aa47b1Sdrh pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow; 3808daf79acbSdanielk1977 } 380943152cf8Sdrh if( /*pParse->nErr ||*/ db->mallocFailed ){ 3810cfa063b3Sdrh goto select_end; 3811cfa063b3Sdrh } 3812fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 3813832508b7Sdrh pTabList = p->pSrc; 38146c8c8ce0Sdanielk1977 if( !IgnorableOrderby(pDest) ){ 3815832508b7Sdrh pOrderBy = p->pOrderBy; 3816acd4c695Sdrh } 3817daf79acbSdanielk1977 } 3818daf79acbSdanielk1977 pEList = p->pEList; 3819daf79acbSdanielk1977 #endif 3820daf79acbSdanielk1977 pWhere = p->pWhere; 3821832508b7Sdrh pGroupBy = p->pGroupBy; 3822832508b7Sdrh pHaving = p->pHaving; 38237d10d5a6Sdrh isDistinct = (p->selFlags & SF_Distinct)!=0; 3824832508b7Sdrh 3825f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3826f23329a2Sdanielk1977 /* If there is are a sequence of queries, do the earlier ones first. 3827f23329a2Sdanielk1977 */ 3828f23329a2Sdanielk1977 if( p->pPrior ){ 3829f23329a2Sdanielk1977 if( p->pRightmost==0 ){ 3830f23329a2Sdanielk1977 Select *pLoop, *pRight = 0; 3831f23329a2Sdanielk1977 int cnt = 0; 3832f23329a2Sdanielk1977 int mxSelect; 3833f23329a2Sdanielk1977 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 3834f23329a2Sdanielk1977 pLoop->pRightmost = p; 3835f23329a2Sdanielk1977 pLoop->pNext = pRight; 3836f23329a2Sdanielk1977 pRight = pLoop; 3837f23329a2Sdanielk1977 } 3838f23329a2Sdanielk1977 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; 3839f23329a2Sdanielk1977 if( mxSelect && cnt>mxSelect ){ 3840f23329a2Sdanielk1977 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 38412ce22453Sdan goto select_end; 3842f23329a2Sdanielk1977 } 3843f23329a2Sdanielk1977 } 38447f61e92cSdan rc = multiSelect(pParse, p, pDest); 384517c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 38467f61e92cSdan return rc; 3847f23329a2Sdanielk1977 } 3848f23329a2Sdanielk1977 #endif 3849f23329a2Sdanielk1977 38500318d441Sdanielk1977 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT. 38517d10d5a6Sdrh ** GROUP BY might use an index, DISTINCT never does. 38523c4809a2Sdanielk1977 */ 385343152cf8Sdrh assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 ); 385443152cf8Sdrh if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){ 38556ab3a2ecSdanielk1977 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0); 38563c4809a2Sdanielk1977 pGroupBy = p->pGroupBy; 38577d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 38583c4809a2Sdanielk1977 } 38593c4809a2Sdanielk1977 38608c6f666bSdrh /* If there is both a GROUP BY and an ORDER BY clause and they are 38618c6f666bSdrh ** identical, then disable the ORDER BY clause since the GROUP BY 38628c6f666bSdrh ** will cause elements to come out in the correct order. This is 38638c6f666bSdrh ** an optimization - the correct answer should result regardless. 38648c6f666bSdrh ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER 38658c6f666bSdrh ** to disable this optimization for testing purposes. 38668c6f666bSdrh */ 38678c6f666bSdrh if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0 38688c6f666bSdrh && (db->flags & SQLITE_GroupByOrder)==0 ){ 38698c6f666bSdrh pOrderBy = 0; 38708c6f666bSdrh } 38718c6f666bSdrh 38728b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 38738b4c40d8Sdrh ** index might end up being unused if the data can be 38749d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 3875b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 38769d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 38779d2985c7Sdrh ** variable is used to facilitate that change. 38787cedc8d4Sdanielk1977 */ 38797cedc8d4Sdanielk1977 if( pOrderBy ){ 38800342b1f5Sdrh KeyInfo *pKeyInfo; 38810342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 38829d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 3883b9bb7c18Sdrh p->addrOpenEphm[2] = addrSortIndex = 388466a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 388566a5167bSdrh pOrderBy->iECursor, pOrderBy->nExpr+2, 0, 388666a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 38879d2985c7Sdrh }else{ 38889d2985c7Sdrh addrSortIndex = -1; 38897cedc8d4Sdanielk1977 } 38907cedc8d4Sdanielk1977 38912d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 38922d0794e3Sdrh */ 38936c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 389466a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr); 38952d0794e3Sdrh } 38962d0794e3Sdrh 3897f42bacc2Sdrh /* Set the limiter. 3898f42bacc2Sdrh */ 3899f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 390095aa47b1Sdrh p->nSelectRow = (double)LARGEST_INT64; 3901f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 3902f42bacc2Sdrh 3903dece1a84Sdrh /* Open a virtual index to use for the distinct set. 3904cce7d176Sdrh */ 39052ce22453Sdan if( p->selFlags & SF_Distinct ){ 39060342b1f5Sdrh KeyInfo *pKeyInfo; 39073c4809a2Sdanielk1977 assert( isAgg || pGroupBy ); 3908832508b7Sdrh distinct = pParse->nTab++; 39090342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 391066a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0, 391166a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3912d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 3913832508b7Sdrh }else{ 3914832508b7Sdrh distinct = -1; 3915efb7251dSdrh } 3916832508b7Sdrh 391713449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 391813449892Sdrh if( !isAgg && pGroupBy==0 ){ 391913449892Sdrh /* This case is for non-aggregate queries 392013449892Sdrh ** Begin the database scan 3921832508b7Sdrh */ 3922336a5300Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0); 39231d83f052Sdrh if( pWInfo==0 ) goto select_end; 392495aa47b1Sdrh if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut; 3925cce7d176Sdrh 3926b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 3927b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 39289d2985c7Sdrh ** into an OP_Noop. 39299d2985c7Sdrh */ 39309d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 3931f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortIndex, 1); 3932b9bb7c18Sdrh p->addrOpenEphm[2] = -1; 39339d2985c7Sdrh } 39349d2985c7Sdrh 393513449892Sdrh /* Use the standard inner loop 3936cce7d176Sdrh */ 39373c4809a2Sdanielk1977 assert(!isDistinct); 3938d2b3e23bSdrh selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest, 3939a9671a22Sdrh pWInfo->iContinue, pWInfo->iBreak); 39402282792aSdrh 3941cce7d176Sdrh /* End the database scan loop. 3942cce7d176Sdrh */ 39434adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 394413449892Sdrh }else{ 394513449892Sdrh /* This is the processing for aggregate queries */ 394613449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 394713449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 394813449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 394913449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 395013449892Sdrh ** one row of the input to the aggregator has been 395113449892Sdrh ** processed */ 395213449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 395313449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 3954d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 3955d176611bSdrh 3956d176611bSdrh /* Remove any and all aliases between the result set and the 3957d176611bSdrh ** GROUP BY clause. 3958d176611bSdrh */ 3959d176611bSdrh if( pGroupBy ){ 3960dc5ea5c7Sdrh int k; /* Loop counter */ 3961d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 3962d176611bSdrh 3963dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 3964d176611bSdrh pItem->iAlias = 0; 3965d176611bSdrh } 3966dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 3967d176611bSdrh pItem->iAlias = 0; 3968d176611bSdrh } 396995aa47b1Sdrh if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100; 397095aa47b1Sdrh }else{ 397195aa47b1Sdrh p->nSelectRow = (double)1; 3972d176611bSdrh } 3973cce7d176Sdrh 397413449892Sdrh 3975d176611bSdrh /* Create a label to jump to when we want to abort the query */ 397613449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 397713449892Sdrh 397813449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 397913449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 398013449892Sdrh ** SELECT statement. 39812282792aSdrh */ 398213449892Sdrh memset(&sNC, 0, sizeof(sNC)); 398313449892Sdrh sNC.pParse = pParse; 398413449892Sdrh sNC.pSrcList = pTabList; 398513449892Sdrh sNC.pAggInfo = &sAggInfo; 398613449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 39879d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 3988d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 3989d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); 3990d2b3e23bSdrh if( pHaving ){ 3991d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 399213449892Sdrh } 399313449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 399413449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 39956ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 39966ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 399713449892Sdrh } 399817435752Sdrh if( db->mallocFailed ) goto select_end; 399913449892Sdrh 400013449892Sdrh /* Processing for aggregates with GROUP BY is very different and 40013c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 400213449892Sdrh */ 400313449892Sdrh if( pGroupBy ){ 400413449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 4005d176611bSdrh int j1; /* A-vs-B comparision jump */ 4006d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 4007d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 4008d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 4009d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 4010d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 4011d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 4012d176611bSdrh int regReset; /* Return address register for reset subroutine */ 401313449892Sdrh 401413449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 401513449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 4016b9bb7c18Sdrh ** that we do not need it after all, the OpenEphemeral instruction 401713449892Sdrh ** will be converted into a Noop. 401813449892Sdrh */ 401913449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 402013449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 4021cd3e8f7cSdanielk1977 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 4022cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 4023cd3e8f7cSdanielk1977 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 402413449892Sdrh 402513449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 402613449892Sdrh */ 40270a07c107Sdrh iUseFlag = ++pParse->nMem; 40280a07c107Sdrh iAbortFlag = ++pParse->nMem; 4029d176611bSdrh regOutputRow = ++pParse->nMem; 4030d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 4031d176611bSdrh regReset = ++pParse->nMem; 4032d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 40330a07c107Sdrh iAMem = pParse->nMem + 1; 403413449892Sdrh pParse->nMem += pGroupBy->nExpr; 40350a07c107Sdrh iBMem = pParse->nMem + 1; 403613449892Sdrh pParse->nMem += pGroupBy->nExpr; 40374c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 4038d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 40394c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 4040d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 4041e313382eSdrh 404213449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 404313449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 404413449892Sdrh ** it might be a single loop that uses an index to extract information 404513449892Sdrh ** in the right order to begin with. 404613449892Sdrh */ 40472eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 4048336a5300Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0); 40495360ad34Sdrh if( pWInfo==0 ) goto select_end; 405013449892Sdrh if( pGroupBy==0 ){ 405113449892Sdrh /* The optimizer is able to deliver rows in group by order so 4052b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 405313449892Sdrh ** cancelled later because we still need to use the pKeyInfo 405413449892Sdrh */ 405513449892Sdrh pGroupBy = p->pGroupBy; 405613449892Sdrh groupBySort = 0; 405713449892Sdrh }else{ 405813449892Sdrh /* Rows are coming out in undetermined order. We have to push 405913449892Sdrh ** each row into a sorting index, terminate the first loop, 406013449892Sdrh ** then loop over the sorting index in order to get the output 406113449892Sdrh ** in sorted order 406213449892Sdrh */ 4063892d3179Sdrh int regBase; 4064892d3179Sdrh int regRecord; 4065892d3179Sdrh int nCol; 4066892d3179Sdrh int nGroupBy; 4067892d3179Sdrh 40682ce22453Sdan explainTempTable(pParse, 40692ce22453Sdan isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY"); 40702ce22453Sdan 407113449892Sdrh groupBySort = 1; 4072892d3179Sdrh nGroupBy = pGroupBy->nExpr; 4073892d3179Sdrh nCol = nGroupBy + 1; 4074892d3179Sdrh j = nGroupBy+1; 407513449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 4076892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 4077892d3179Sdrh nCol++; 407813449892Sdrh j++; 407913449892Sdrh } 4080892d3179Sdrh } 4081892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 4082ceea3321Sdrh sqlite3ExprCacheClear(pParse); 4083191b54cbSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); 4084892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); 4085892d3179Sdrh j = nGroupBy+1; 4086892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 4087892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 4088892d3179Sdrh if( pCol->iSorterColumn>=j ){ 4089e55cbd72Sdrh int r1 = j + regBase; 40906a012f04Sdrh int r2; 4091701bb3b4Sdrh 40926a012f04Sdrh r2 = sqlite3ExprCodeGetColumn(pParse, 4093b6da74ebSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1); 40946a012f04Sdrh if( r1!=r2 ){ 40956a012f04Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); 40966a012f04Sdrh } 40976a012f04Sdrh j++; 4098892d3179Sdrh } 4099892d3179Sdrh } 4100892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 41011db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 4102892d3179Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord); 4103892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 4104892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 410513449892Sdrh sqlite3WhereEnd(pWInfo); 410666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); 4107d4e70ebdSdrh VdbeComment((v, "GROUP BY sort")); 410813449892Sdrh sAggInfo.useSortingIdx = 1; 4109ceea3321Sdrh sqlite3ExprCacheClear(pParse); 411013449892Sdrh } 411113449892Sdrh 411213449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 411313449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 411413449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 411513449892Sdrh ** from the previous row currently stored in a0, a1, a2... 411613449892Sdrh */ 411713449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 4118ceea3321Sdrh sqlite3ExprCacheClear(pParse); 411913449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 412013449892Sdrh if( groupBySort ){ 41212dcef11bSdrh sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j); 412213449892Sdrh }else{ 412313449892Sdrh sAggInfo.directMode = 1; 41242dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 412513449892Sdrh } 412613449892Sdrh } 412716ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 4128b21e7c70Sdrh (char*)pKeyInfo, P4_KEYINFO); 412916ee60ffSdrh j1 = sqlite3VdbeCurrentAddr(v); 413016ee60ffSdrh sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); 413113449892Sdrh 413213449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 4133e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 413413449892Sdrh ** block. If there were no changes, this block is skipped. 413513449892Sdrh ** 413613449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 413713449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 413813449892Sdrh ** and resets the aggregate accumulator registers in preparation 413913449892Sdrh ** for the next GROUP BY batch. 414013449892Sdrh */ 4141b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 41422eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 4143d4e70ebdSdrh VdbeComment((v, "output one row")); 41443c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); 4145d4e70ebdSdrh VdbeComment((v, "check abort flag")); 41462eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 4147d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 414813449892Sdrh 414913449892Sdrh /* Update the aggregate accumulators based on the content of 415013449892Sdrh ** the current row 415113449892Sdrh */ 415216ee60ffSdrh sqlite3VdbeJumpHere(v, j1); 415313449892Sdrh updateAccumulator(pParse, &sAggInfo); 41544c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 4155d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 415613449892Sdrh 415713449892Sdrh /* End of the loop 415813449892Sdrh */ 415913449892Sdrh if( groupBySort ){ 416066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); 416113449892Sdrh }else{ 416213449892Sdrh sqlite3WhereEnd(pWInfo); 4163f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); 416413449892Sdrh } 416513449892Sdrh 416613449892Sdrh /* Output the final row of result 416713449892Sdrh */ 41682eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 4169d4e70ebdSdrh VdbeComment((v, "output final row")); 417013449892Sdrh 4171d176611bSdrh /* Jump over the subroutines 4172d176611bSdrh */ 4173d176611bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd); 4174d176611bSdrh 4175d176611bSdrh /* Generate a subroutine that outputs a single row of the result 4176d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 4177d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 4178d176611bSdrh ** the processing calls for the query to abort, this subroutine 4179d176611bSdrh ** increments the iAbortFlag memory location before returning in 4180d176611bSdrh ** order to signal the caller to abort. 4181d176611bSdrh */ 4182d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 4183d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 4184d176611bSdrh VdbeComment((v, "set abort flag")); 4185d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4186d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 4187d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 4188d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 4189d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 4190d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4191d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 4192d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 4193d176611bSdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 4194d176611bSdrh distinct, pDest, 4195d176611bSdrh addrOutputRow+1, addrSetAbort); 4196d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4197d176611bSdrh VdbeComment((v, "end groupby result generator")); 4198d176611bSdrh 4199d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 4200d176611bSdrh */ 4201d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 4202d176611bSdrh resetAccumulator(pParse, &sAggInfo); 4203d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 4204d176611bSdrh 420543152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 420613449892Sdrh else { 4207dba0137eSdanielk1977 ExprList *pDel = 0; 4208a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 4209a5533162Sdanielk1977 Table *pTab; 4210a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 4211a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 4212a5533162Sdanielk1977 ** the SQL statement is of the form: 4213a5533162Sdanielk1977 ** 4214a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 4215a5533162Sdanielk1977 ** 4216a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 4217a5533162Sdanielk1977 ** 4218a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 4219a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 4220a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 4221a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 4222a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 4223a5533162Sdanielk1977 */ 4224a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 4225a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 4226a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 4227a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 4228a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 4229a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 4230a9d1ccb9Sdanielk1977 4231a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 4232a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 4233a5533162Sdanielk1977 4234a5533162Sdanielk1977 /* Search for the index that has the least amount of columns. If 4235a5533162Sdanielk1977 ** there is such an index, and it has less columns than the table 4236a5533162Sdanielk1977 ** does, then we can assume that it consumes less space on disk and 4237a5533162Sdanielk1977 ** will therefore be cheaper to scan to determine the query result. 4238a5533162Sdanielk1977 ** In this case set iRoot to the root page number of the index b-tree 4239a5533162Sdanielk1977 ** and pKeyInfo to the KeyInfo structure required to navigate the 4240a5533162Sdanielk1977 ** index. 4241a5533162Sdanielk1977 ** 4242a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 4243a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 4244a5533162Sdanielk1977 */ 4245a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 4246a5533162Sdanielk1977 if( !pBest || pIdx->nColumn<pBest->nColumn ){ 4247a5533162Sdanielk1977 pBest = pIdx; 4248a5533162Sdanielk1977 } 4249a5533162Sdanielk1977 } 4250a5533162Sdanielk1977 if( pBest && pBest->nColumn<pTab->nCol ){ 4251a5533162Sdanielk1977 iRoot = pBest->tnum; 4252a5533162Sdanielk1977 pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest); 4253a5533162Sdanielk1977 } 4254a5533162Sdanielk1977 4255a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 4256a5533162Sdanielk1977 sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb); 4257a5533162Sdanielk1977 if( pKeyInfo ){ 4258a5533162Sdanielk1977 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF); 4259a5533162Sdanielk1977 } 4260a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 4261a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 4262ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 4263a5533162Sdanielk1977 }else 4264a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 4265a5533162Sdanielk1977 { 4266738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 4267738bdcfbSdanielk1977 ** 4268738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 4269738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 4270738bdcfbSdanielk1977 ** 4271738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 4272738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 4273738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 4274738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 4275738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 4276738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 4277738bdcfbSdanielk1977 ** value of x, the only row required). 4278738bdcfbSdanielk1977 ** 4279738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 4280738bdcfbSdanielk1977 ** modify behaviour as follows: 4281738bdcfbSdanielk1977 ** 4282738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 4283738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 4284738bdcfbSdanielk1977 ** for x. 4285738bdcfbSdanielk1977 ** 4286738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 4287738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 4288738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 4289738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 4290738bdcfbSdanielk1977 */ 4291a5533162Sdanielk1977 ExprList *pMinMax = 0; 4292a5533162Sdanielk1977 u8 flag = minMaxQuery(p); 4293a9d1ccb9Sdanielk1977 if( flag ){ 42946ab3a2ecSdanielk1977 assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) ); 42956ab3a2ecSdanielk1977 pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0); 42966ab3a2ecSdanielk1977 pDel = pMinMax; 42970e359b30Sdrh if( pMinMax && !db->mallocFailed ){ 4298ea678832Sdrh pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; 4299a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 4300a9d1ccb9Sdanielk1977 } 43011013c932Sdrh } 4302a9d1ccb9Sdanielk1977 430313449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 430413449892Sdrh ** processing is much simpler since there is only a single row 430513449892Sdrh ** of output. 430613449892Sdrh */ 430713449892Sdrh resetAccumulator(pParse, &sAggInfo); 4308336a5300Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag); 4309dba0137eSdanielk1977 if( pWInfo==0 ){ 4310633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 4311dba0137eSdanielk1977 goto select_end; 4312dba0137eSdanielk1977 } 431313449892Sdrh updateAccumulator(pParse, &sAggInfo); 4314a9d1ccb9Sdanielk1977 if( !pMinMax && flag ){ 4315a9d1ccb9Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); 4316a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 4317a5533162Sdanielk1977 (flag==WHERE_ORDERBY_MIN?"min":"max"))); 4318a9d1ccb9Sdanielk1977 } 431913449892Sdrh sqlite3WhereEnd(pWInfo); 432013449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 43217a895a80Sdanielk1977 } 43227a895a80Sdanielk1977 432313449892Sdrh pOrderBy = 0; 432435573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 432513449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 4326a9671a22Sdrh pDest, addrEnd, addrEnd); 4327633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 432813449892Sdrh } 432913449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 433013449892Sdrh 433113449892Sdrh } /* endif aggregate query */ 43322282792aSdrh 43332ce22453Sdan if( distinct>=0 ){ 43342ce22453Sdan explainTempTable(pParse, "DISTINCT"); 43352ce22453Sdan } 43362ce22453Sdan 4337cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 4338cce7d176Sdrh ** and send them to the callback one by one. 4339cce7d176Sdrh */ 4340cce7d176Sdrh if( pOrderBy ){ 43412ce22453Sdan explainTempTable(pParse, "ORDER BY"); 43426c8c8ce0Sdanielk1977 generateSortTail(pParse, p, v, pEList->nExpr, pDest); 4343cce7d176Sdrh } 43446a535340Sdrh 4345ec7429aeSdrh /* Jump here to skip this query 4346ec7429aeSdrh */ 4347ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 4348ec7429aeSdrh 43491d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 43501d83f052Sdrh ** to indicate no errors. 43511d83f052Sdrh */ 43521d83f052Sdrh rc = 0; 43531d83f052Sdrh 43541d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 43551d83f052Sdrh ** successful coding of the SELECT. 43561d83f052Sdrh */ 43571d83f052Sdrh select_end: 435817c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 4359955de52cSdanielk1977 43607d10d5a6Sdrh /* Identify column names if results of the SELECT are to be output. 4361955de52cSdanielk1977 */ 43627d10d5a6Sdrh if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ 4363955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 4364955de52cSdanielk1977 } 4365955de52cSdanielk1977 4366633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 4367633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 43681d83f052Sdrh return rc; 4369cce7d176Sdrh } 4370485f0039Sdrh 437177a2a5e7Sdrh #if defined(SQLITE_DEBUG) 4372485f0039Sdrh /* 4373485f0039Sdrh ******************************************************************************* 4374485f0039Sdrh ** The following code is used for testing and debugging only. The code 4375485f0039Sdrh ** that follows does not appear in normal builds. 4376485f0039Sdrh ** 4377485f0039Sdrh ** These routines are used to print out the content of all or part of a 4378485f0039Sdrh ** parse structures such as Select or Expr. Such printouts are useful 4379485f0039Sdrh ** for helping to understand what is happening inside the code generator 4380485f0039Sdrh ** during the execution of complex SELECT statements. 4381485f0039Sdrh ** 4382485f0039Sdrh ** These routine are not called anywhere from within the normal 4383485f0039Sdrh ** code base. Then are intended to be called from within the debugger 4384485f0039Sdrh ** or from temporary "printf" statements inserted for debugging. 4385485f0039Sdrh */ 4386dafc0ce8Sdrh void sqlite3PrintExpr(Expr *p){ 438733e619fcSdrh if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 438833e619fcSdrh sqlite3DebugPrintf("(%s", p->u.zToken); 4389485f0039Sdrh }else{ 4390485f0039Sdrh sqlite3DebugPrintf("(%d", p->op); 4391485f0039Sdrh } 4392485f0039Sdrh if( p->pLeft ){ 4393485f0039Sdrh sqlite3DebugPrintf(" "); 4394485f0039Sdrh sqlite3PrintExpr(p->pLeft); 4395485f0039Sdrh } 4396485f0039Sdrh if( p->pRight ){ 4397485f0039Sdrh sqlite3DebugPrintf(" "); 4398485f0039Sdrh sqlite3PrintExpr(p->pRight); 4399485f0039Sdrh } 4400485f0039Sdrh sqlite3DebugPrintf(")"); 4401485f0039Sdrh } 4402dafc0ce8Sdrh void sqlite3PrintExprList(ExprList *pList){ 4403485f0039Sdrh int i; 4404485f0039Sdrh for(i=0; i<pList->nExpr; i++){ 4405485f0039Sdrh sqlite3PrintExpr(pList->a[i].pExpr); 4406485f0039Sdrh if( i<pList->nExpr-1 ){ 4407485f0039Sdrh sqlite3DebugPrintf(", "); 4408485f0039Sdrh } 4409485f0039Sdrh } 4410485f0039Sdrh } 4411dafc0ce8Sdrh void sqlite3PrintSelect(Select *p, int indent){ 4412485f0039Sdrh sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p); 4413485f0039Sdrh sqlite3PrintExprList(p->pEList); 4414485f0039Sdrh sqlite3DebugPrintf("\n"); 4415485f0039Sdrh if( p->pSrc ){ 4416485f0039Sdrh char *zPrefix; 4417485f0039Sdrh int i; 4418485f0039Sdrh zPrefix = "FROM"; 4419485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 4420485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 4421485f0039Sdrh sqlite3DebugPrintf("%*s ", indent+6, zPrefix); 4422485f0039Sdrh zPrefix = ""; 4423485f0039Sdrh if( pItem->pSelect ){ 4424485f0039Sdrh sqlite3DebugPrintf("(\n"); 4425485f0039Sdrh sqlite3PrintSelect(pItem->pSelect, indent+10); 4426485f0039Sdrh sqlite3DebugPrintf("%*s)", indent+8, ""); 4427485f0039Sdrh }else if( pItem->zName ){ 4428485f0039Sdrh sqlite3DebugPrintf("%s", pItem->zName); 4429485f0039Sdrh } 4430485f0039Sdrh if( pItem->pTab ){ 4431485f0039Sdrh sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName); 4432485f0039Sdrh } 4433485f0039Sdrh if( pItem->zAlias ){ 4434485f0039Sdrh sqlite3DebugPrintf(" AS %s", pItem->zAlias); 4435485f0039Sdrh } 4436485f0039Sdrh if( i<p->pSrc->nSrc-1 ){ 4437485f0039Sdrh sqlite3DebugPrintf(","); 4438485f0039Sdrh } 4439485f0039Sdrh sqlite3DebugPrintf("\n"); 4440485f0039Sdrh } 4441485f0039Sdrh } 4442485f0039Sdrh if( p->pWhere ){ 4443485f0039Sdrh sqlite3DebugPrintf("%*s WHERE ", indent, ""); 4444485f0039Sdrh sqlite3PrintExpr(p->pWhere); 4445485f0039Sdrh sqlite3DebugPrintf("\n"); 4446485f0039Sdrh } 4447485f0039Sdrh if( p->pGroupBy ){ 4448485f0039Sdrh sqlite3DebugPrintf("%*s GROUP BY ", indent, ""); 4449485f0039Sdrh sqlite3PrintExprList(p->pGroupBy); 4450485f0039Sdrh sqlite3DebugPrintf("\n"); 4451485f0039Sdrh } 4452485f0039Sdrh if( p->pHaving ){ 4453485f0039Sdrh sqlite3DebugPrintf("%*s HAVING ", indent, ""); 4454485f0039Sdrh sqlite3PrintExpr(p->pHaving); 4455485f0039Sdrh sqlite3DebugPrintf("\n"); 4456485f0039Sdrh } 4457485f0039Sdrh if( p->pOrderBy ){ 4458485f0039Sdrh sqlite3DebugPrintf("%*s ORDER BY ", indent, ""); 4459485f0039Sdrh sqlite3PrintExprList(p->pOrderBy); 4460485f0039Sdrh sqlite3DebugPrintf("\n"); 4461485f0039Sdrh } 4462485f0039Sdrh } 4463485f0039Sdrh /* End of the structure debug printing code 4464485f0039Sdrh *****************************************************************************/ 4465485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ 4466