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 ){ 68338ec3e1Sdrh assert( db->mallocFailed ); 69eda639e1Sdrh pNew = &standin; 70eda639e1Sdrh memset(pNew, 0, sizeof(*pNew)); 71eda639e1Sdrh } 72b733d037Sdrh if( pEList==0 ){ 73b7916a78Sdrh pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0)); 74b733d037Sdrh } 759bb61fe7Sdrh pNew->pEList = pEList; 769bb61fe7Sdrh pNew->pSrc = pSrc; 779bb61fe7Sdrh pNew->pWhere = pWhere; 789bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 799bb61fe7Sdrh pNew->pHaving = pHaving; 809bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 817d10d5a6Sdrh pNew->selFlags = isDistinct ? SF_Distinct : 0; 8282c3d636Sdrh pNew->op = TK_SELECT; 83a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 84a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 85373cc2ddSdrh assert( pOffset==0 || pLimit!=0 ); 86b9bb7c18Sdrh pNew->addrOpenEphm[0] = -1; 87b9bb7c18Sdrh pNew->addrOpenEphm[1] = -1; 88b9bb7c18Sdrh pNew->addrOpenEphm[2] = -1; 890a846f96Sdrh if( db->mallocFailed ) { 90633e6d57Sdrh clearSelect(db, pNew); 910a846f96Sdrh if( pNew!=&standin ) sqlite3DbFree(db, pNew); 92eda639e1Sdrh pNew = 0; 93a464c234Sdrh }else{ 94a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 95daffd0e5Sdrh } 96338ec3e1Sdrh assert( pNew!=&standin ); 979bb61fe7Sdrh return pNew; 989bb61fe7Sdrh } 999bb61fe7Sdrh 1009bb61fe7Sdrh /* 101eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 102eda639e1Sdrh */ 103633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 104eda639e1Sdrh if( p ){ 105633e6d57Sdrh clearSelect(db, p); 106633e6d57Sdrh sqlite3DbFree(db, p); 107eda639e1Sdrh } 108eda639e1Sdrh } 109eda639e1Sdrh 110eda639e1Sdrh /* 11101f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 11201f3f253Sdrh ** type of join. Return an integer constant that expresses that type 11301f3f253Sdrh ** in terms of the following bit values: 11401f3f253Sdrh ** 11501f3f253Sdrh ** JT_INNER 1163dec223cSdrh ** JT_CROSS 11701f3f253Sdrh ** JT_OUTER 11801f3f253Sdrh ** JT_NATURAL 11901f3f253Sdrh ** JT_LEFT 12001f3f253Sdrh ** JT_RIGHT 12101f3f253Sdrh ** 12201f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 12301f3f253Sdrh ** 12401f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 12501f3f253Sdrh ** a join type, but put an error in the pParse structure. 12601f3f253Sdrh */ 1274adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 12801f3f253Sdrh int jointype = 0; 12901f3f253Sdrh Token *apAll[3]; 13001f3f253Sdrh Token *p; 131373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 132373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 1335719628aSdrh static const struct { 134373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 135373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 136373cc2ddSdrh u8 code; /* Join type mask */ 137373cc2ddSdrh } aKeyword[] = { 138373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 139373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 140373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 141373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 142373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 143373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 144373cc2ddSdrh /* cross */ { 28, 5, JT_INNER|JT_CROSS }, 14501f3f253Sdrh }; 14601f3f253Sdrh int i, j; 14701f3f253Sdrh apAll[0] = pA; 14801f3f253Sdrh apAll[1] = pB; 14901f3f253Sdrh apAll[2] = pC; 150195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 15101f3f253Sdrh p = apAll[i]; 152373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 153373cc2ddSdrh if( p->n==aKeyword[j].nChar 154373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 155373cc2ddSdrh jointype |= aKeyword[j].code; 15601f3f253Sdrh break; 15701f3f253Sdrh } 15801f3f253Sdrh } 159373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 160373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 16101f3f253Sdrh jointype |= JT_ERROR; 16201f3f253Sdrh break; 16301f3f253Sdrh } 16401f3f253Sdrh } 165ad2d8307Sdrh if( 166ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 167195e6967Sdrh (jointype & JT_ERROR)!=0 168ad2d8307Sdrh ){ 169a9671a22Sdrh const char *zSp = " "; 170a9671a22Sdrh assert( pB!=0 ); 171a9671a22Sdrh if( pC==0 ){ zSp++; } 172ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 173a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 17401f3f253Sdrh jointype = JT_INNER; 175373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 176373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 1774adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 178da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 179195e6967Sdrh jointype = JT_INNER; 18001f3f253Sdrh } 18101f3f253Sdrh return jointype; 18201f3f253Sdrh } 18301f3f253Sdrh 18401f3f253Sdrh /* 185ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 186ad2d8307Sdrh ** is not contained in the table. 187ad2d8307Sdrh */ 188ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 189ad2d8307Sdrh int i; 190ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1914adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 192ad2d8307Sdrh } 193ad2d8307Sdrh return -1; 194ad2d8307Sdrh } 195ad2d8307Sdrh 196ad2d8307Sdrh /* 1972179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 1982179b434Sdrh ** table that has a column named zCol. 1992179b434Sdrh ** 2002179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 2012179b434Sdrh ** of the matching column and return TRUE. 2022179b434Sdrh ** 2032179b434Sdrh ** If not found, return FALSE. 2042179b434Sdrh */ 2052179b434Sdrh static int tableAndColumnIndex( 2062179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 2072179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 2082179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 2092179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 2102179b434Sdrh int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 2112179b434Sdrh ){ 2122179b434Sdrh int i; /* For looping over tables in pSrc */ 2132179b434Sdrh int iCol; /* Index of column matching zCol */ 2142179b434Sdrh 2152179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 2162179b434Sdrh for(i=0; i<N; i++){ 2172179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 2182179b434Sdrh if( iCol>=0 ){ 2192179b434Sdrh if( piTab ){ 2202179b434Sdrh *piTab = i; 2212179b434Sdrh *piCol = iCol; 2222179b434Sdrh } 2232179b434Sdrh return 1; 2242179b434Sdrh } 2252179b434Sdrh } 2262179b434Sdrh return 0; 2272179b434Sdrh } 2282179b434Sdrh 2292179b434Sdrh /* 230f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 231f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 232f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 233f7b0b0adSdan ** 234f7b0b0adSdan ** (tab1.col1 = tab2.col2) 235f7b0b0adSdan ** 236f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 237f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 238f7b0b0adSdan ** column iColRight of tab2. 239ad2d8307Sdrh */ 240ad2d8307Sdrh static void addWhereTerm( 24117435752Sdrh Parse *pParse, /* Parsing context */ 242f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 2432179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 244f7b0b0adSdan int iColLeft, /* Index of column in first table */ 2452179b434Sdrh int iRight, /* Index of second table in pSrc */ 246f7b0b0adSdan int iColRight, /* Index of column in second table */ 247f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 248f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 249ad2d8307Sdrh ){ 250f7b0b0adSdan sqlite3 *db = pParse->db; 251f7b0b0adSdan Expr *pE1; 252f7b0b0adSdan Expr *pE2; 253f7b0b0adSdan Expr *pEq; 254ad2d8307Sdrh 2552179b434Sdrh assert( iLeft<iRight ); 2562179b434Sdrh assert( pSrc->nSrc>iRight ); 2572179b434Sdrh assert( pSrc->a[iLeft].pTab ); 2582179b434Sdrh assert( pSrc->a[iRight].pTab ); 259f7b0b0adSdan 2602179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 2612179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 262f7b0b0adSdan 263f7b0b0adSdan pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0); 264f7b0b0adSdan if( pEq && isOuterJoin ){ 265f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 266f7b0b0adSdan assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) ); 267f7b0b0adSdan ExprSetIrreducible(pEq); 268f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 269030530deSdrh } 270f7b0b0adSdan *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); 271ad2d8307Sdrh } 272ad2d8307Sdrh 273ad2d8307Sdrh /* 2741f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 27522d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 27622d6a53aSdrh ** expression. 2771cc093c2Sdrh ** 278e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 2791cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 2801f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 2811f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 2821f16230bSdrh ** WHERE clause during join processing but we need to remember that they 2831f16230bSdrh ** originated in the ON or USING clause. 28422d6a53aSdrh ** 28522d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 28622d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 28722d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 28822d6a53aSdrh ** for cases like this: 28922d6a53aSdrh ** 29022d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 29122d6a53aSdrh ** 29222d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 29322d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 29422d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 29522d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 29622d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 29722d6a53aSdrh ** the output, which is incorrect. 2981cc093c2Sdrh */ 29922d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 3001cc093c2Sdrh while( p ){ 3011f16230bSdrh ExprSetProperty(p, EP_FromJoin); 30233e619fcSdrh assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) ); 30333e619fcSdrh ExprSetIrreducible(p); 304cf697396Sshane p->iRightJoinTable = (i16)iTable; 30522d6a53aSdrh setJoinExpr(p->pLeft, iTable); 3061cc093c2Sdrh p = p->pRight; 3071cc093c2Sdrh } 3081cc093c2Sdrh } 3091cc093c2Sdrh 3101cc093c2Sdrh /* 311ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 312ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 313ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 314ad2d8307Sdrh ** 31591bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 31691bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 31791bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 31891bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 31991bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 32091bb0eedSdrh ** also attached to the left entry. 32191bb0eedSdrh ** 322ad2d8307Sdrh ** This routine returns the number of errors encountered. 323ad2d8307Sdrh */ 324ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 32591bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 32691bb0eedSdrh int i, j; /* Loop counters */ 32791bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 32891bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 329ad2d8307Sdrh 33091bb0eedSdrh pSrc = p->pSrc; 33191bb0eedSdrh pLeft = &pSrc->a[0]; 33291bb0eedSdrh pRight = &pLeft[1]; 33391bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 33491bb0eedSdrh Table *pLeftTab = pLeft->pTab; 33591bb0eedSdrh Table *pRightTab = pRight->pTab; 336ad27e761Sdrh int isOuter; 33791bb0eedSdrh 3381c767f0dSdrh if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; 339ad27e761Sdrh isOuter = (pRight->jointype & JT_OUTER)!=0; 340ad2d8307Sdrh 341ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 342ad2d8307Sdrh ** every column that the two tables have in common. 343ad2d8307Sdrh */ 34461dfc31dSdrh if( pRight->jointype & JT_NATURAL ){ 34561dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 3464adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 347ad2d8307Sdrh "an ON or USING clause", 0); 348ad2d8307Sdrh return 1; 349ad2d8307Sdrh } 3502179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 3512179b434Sdrh char *zName; /* Name of column in the right table */ 3522179b434Sdrh int iLeft; /* Matching left table */ 3532179b434Sdrh int iLeftCol; /* Matching column in the left table */ 3542179b434Sdrh 3552179b434Sdrh zName = pRightTab->aCol[j].zName; 3562179b434Sdrh if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ 3572179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 3582179b434Sdrh isOuter, &p->pWhere); 359ad2d8307Sdrh } 360ad2d8307Sdrh } 361ad2d8307Sdrh } 362ad2d8307Sdrh 363ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 364ad2d8307Sdrh */ 36561dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 3664adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 367da93d238Sdrh "clauses in the same join"); 368ad2d8307Sdrh return 1; 369ad2d8307Sdrh } 370ad2d8307Sdrh 371ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 37291bb0eedSdrh ** an AND operator. 373ad2d8307Sdrh */ 37461dfc31dSdrh if( pRight->pOn ){ 375ad27e761Sdrh if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 37617435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 37761dfc31dSdrh pRight->pOn = 0; 378ad2d8307Sdrh } 379ad2d8307Sdrh 380ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 381ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 382ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 383ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 384ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 385ad2d8307Sdrh ** not contained in both tables to be joined. 386ad2d8307Sdrh */ 38761dfc31dSdrh if( pRight->pUsing ){ 38861dfc31dSdrh IdList *pList = pRight->pUsing; 389ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 3902179b434Sdrh char *zName; /* Name of the term in the USING clause */ 3912179b434Sdrh int iLeft; /* Table on the left with matching column name */ 3922179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 3932179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 3942179b434Sdrh 3952179b434Sdrh zName = pList->a[j].zName; 3962179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 3972179b434Sdrh if( iRightCol<0 3982179b434Sdrh || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) 3992179b434Sdrh ){ 4004adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 40191bb0eedSdrh "not present in both tables", zName); 402ad2d8307Sdrh return 1; 403ad2d8307Sdrh } 4042179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 4052179b434Sdrh isOuter, &p->pWhere); 406ad2d8307Sdrh } 407ad2d8307Sdrh } 408ad2d8307Sdrh } 409ad2d8307Sdrh return 0; 410ad2d8307Sdrh } 411ad2d8307Sdrh 412ad2d8307Sdrh /* 413c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 414c926afbcSdrh ** stack into the sorter. 415c926afbcSdrh */ 416d59ba6ceSdrh static void pushOntoSorter( 417d59ba6ceSdrh Parse *pParse, /* Parser context */ 418d59ba6ceSdrh ExprList *pOrderBy, /* The ORDER BY clause */ 419b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 420b7654111Sdrh int regData /* Register holding data to be sorted */ 421d59ba6ceSdrh ){ 422d59ba6ceSdrh Vdbe *v = pParse->pVdbe; 423892d3179Sdrh int nExpr = pOrderBy->nExpr; 424892d3179Sdrh int regBase = sqlite3GetTempRange(pParse, nExpr+2); 425892d3179Sdrh int regRecord = sqlite3GetTempReg(pParse); 426c6aff30cSdrh int op; 427ceea3321Sdrh sqlite3ExprCacheClear(pParse); 428191b54cbSdrh sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0); 429892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); 430b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1); 4311db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord); 432c6aff30cSdrh if( pSelect->selFlags & SF_UseSorter ){ 433c6aff30cSdrh op = OP_SorterInsert; 434c6aff30cSdrh }else{ 435c6aff30cSdrh op = OP_IdxInsert; 436c6aff30cSdrh } 437c6aff30cSdrh sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord); 438892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 439892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nExpr+2); 44092b01d53Sdrh if( pSelect->iLimit ){ 44115007a99Sdrh int addr1, addr2; 442b7654111Sdrh int iLimit; 4430acb7e48Sdrh if( pSelect->iOffset ){ 444b7654111Sdrh iLimit = pSelect->iOffset+1; 445b7654111Sdrh }else{ 446b7654111Sdrh iLimit = pSelect->iLimit; 447b7654111Sdrh } 448b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); 449b7654111Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); 4503c84ddffSdrh addr2 = sqlite3VdbeAddOp0(v, OP_Goto); 451d59ba6ceSdrh sqlite3VdbeJumpHere(v, addr1); 4523c84ddffSdrh sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); 4533c84ddffSdrh sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); 45415007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 455d59ba6ceSdrh } 456c926afbcSdrh } 457c926afbcSdrh 458c926afbcSdrh /* 459ec7429aeSdrh ** Add code to implement the OFFSET 460ea48eb2eSdrh */ 461ec7429aeSdrh static void codeOffset( 462bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 463ea48eb2eSdrh Select *p, /* The SELECT statement being coded */ 464b7654111Sdrh int iContinue /* Jump here to skip the current record */ 465ea48eb2eSdrh ){ 46692b01d53Sdrh if( p->iOffset && iContinue!=0 ){ 46715007a99Sdrh int addr; 4688558cde1Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1); 4693c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset); 47066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); 471d4e70ebdSdrh VdbeComment((v, "skip OFFSET records")); 47215007a99Sdrh sqlite3VdbeJumpHere(v, addr); 473ea48eb2eSdrh } 474ea48eb2eSdrh } 475ea48eb2eSdrh 476ea48eb2eSdrh /* 47798757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 47898757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 479a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 480a2a49dc9Sdrh ** if the current N values are new. 481a2a49dc9Sdrh ** 482a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 483a2a49dc9Sdrh ** stack if the top N elements are not distinct. 484a2a49dc9Sdrh */ 485a2a49dc9Sdrh static void codeDistinct( 4862dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 487a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 488a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 489477df4b3Sdrh int N, /* Number of elements */ 490a2a49dc9Sdrh int iMem /* First element */ 491a2a49dc9Sdrh ){ 4922dcef11bSdrh Vdbe *v; 4932dcef11bSdrh int r1; 4942dcef11bSdrh 4952dcef11bSdrh v = pParse->pVdbe; 4962dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 49791fc4a0cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); 4981db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 4992dcef11bSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); 5002dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 501a2a49dc9Sdrh } 502a2a49dc9Sdrh 503bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY 504a2a49dc9Sdrh /* 505e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression 506e305f43fSdrh ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 507bb7dd683Sdrh ** column. We do this in a subroutine because the error used to occur 508bb7dd683Sdrh ** in multiple places. (The error only occurs in one place now, but we 509bb7dd683Sdrh ** retain the subroutine to minimize code disruption.) 510e305f43fSdrh */ 5116c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError( 5126c8c8ce0Sdanielk1977 Parse *pParse, /* Parse context. */ 5136c8c8ce0Sdanielk1977 SelectDest *pDest, /* Destination of SELECT results */ 5146c8c8ce0Sdanielk1977 int nExpr /* Number of result columns returned by SELECT */ 5156c8c8ce0Sdanielk1977 ){ 5166c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 517e305f43fSdrh if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 518e305f43fSdrh sqlite3ErrorMsg(pParse, "only a single result allowed for " 519e305f43fSdrh "a SELECT that is part of an expression"); 520e305f43fSdrh return 1; 521e305f43fSdrh }else{ 522e305f43fSdrh return 0; 523e305f43fSdrh } 524e305f43fSdrh } 525bb7dd683Sdrh #endif 526c99130fdSdrh 527c99130fdSdrh /* 5282282792aSdrh ** This routine generates the code for the inside of the inner loop 5292282792aSdrh ** of a SELECT. 53082c3d636Sdrh ** 53138640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 53238640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 53338640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 53438640e15Sdrh ** datatypes for each column. 5352282792aSdrh */ 536d2b3e23bSdrh static void selectInnerLoop( 5372282792aSdrh Parse *pParse, /* The parser context */ 538df199a25Sdrh Select *p, /* The complete select statement being coded */ 5392282792aSdrh ExprList *pEList, /* List of values being extracted */ 54082c3d636Sdrh int srcTab, /* Pull data from this table */ 541967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 5422282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 5432282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 5446c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 5452282792aSdrh int iContinue, /* Jump here to continue with next row */ 546a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 5472282792aSdrh ){ 5482282792aSdrh Vdbe *v = pParse->pVdbe; 549d847eaadSdrh int i; 550ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 551d847eaadSdrh int regResult; /* Start of memory holding result set */ 552d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 553d847eaadSdrh int iParm = pDest->iParm; /* First argument to disposal method */ 554d847eaadSdrh int nResultCol; /* Number of result columns */ 55538640e15Sdrh 5561c767f0dSdrh assert( v ); 5571c767f0dSdrh if( NEVER(v==0) ) return; 55838640e15Sdrh assert( pEList!=0 ); 559e49b146fSdrh hasDistinct = distinct>=0; 560ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 561b7654111Sdrh codeOffset(v, p, iContinue); 562df199a25Sdrh } 563df199a25Sdrh 564967e8b73Sdrh /* Pull the requested columns. 5652282792aSdrh */ 56638640e15Sdrh if( nColumn>0 ){ 567d847eaadSdrh nResultCol = nColumn; 568a2a49dc9Sdrh }else{ 569d847eaadSdrh nResultCol = pEList->nExpr; 570a2a49dc9Sdrh } 5711ece7325Sdrh if( pDest->iMem==0 ){ 5720acb7e48Sdrh pDest->iMem = pParse->nMem+1; 573ad27e761Sdrh pDest->nMem = nResultCol; 5740acb7e48Sdrh pParse->nMem += nResultCol; 5751c767f0dSdrh }else{ 5761c767f0dSdrh assert( pDest->nMem==nResultCol ); 5771013c932Sdrh } 5781ece7325Sdrh regResult = pDest->iMem; 579a2a49dc9Sdrh if( nColumn>0 ){ 580967e8b73Sdrh for(i=0; i<nColumn; i++){ 581d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 58282c3d636Sdrh } 5839ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 5849ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 5859ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 5869ed1dfa8Sdanielk1977 */ 587ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5887d10d5a6Sdrh sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output); 589a2a49dc9Sdrh } 590d847eaadSdrh nColumn = nResultCol; 5912282792aSdrh 592daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 593daffd0e5Sdrh ** and this row has been seen before, then do not make this row 594daffd0e5Sdrh ** part of the result. 5952282792aSdrh */ 596ea48eb2eSdrh if( hasDistinct ){ 597f8875400Sdrh assert( pEList!=0 ); 598f8875400Sdrh assert( pEList->nExpr==nColumn ); 599d847eaadSdrh codeDistinct(pParse, distinct, iContinue, nColumn, regResult); 600ea48eb2eSdrh if( pOrderBy==0 ){ 601b7654111Sdrh codeOffset(v, p, iContinue); 602ea48eb2eSdrh } 6032282792aSdrh } 60482c3d636Sdrh 605c926afbcSdrh switch( eDest ){ 60682c3d636Sdrh /* In this mode, write each query result to the key of the temporary 60782c3d636Sdrh ** table iParm. 6082282792aSdrh */ 60913449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 610c926afbcSdrh case SRT_Union: { 6119cbf3425Sdrh int r1; 6129cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 613d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6149cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 6159cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 616c926afbcSdrh break; 617c926afbcSdrh } 61882c3d636Sdrh 61982c3d636Sdrh /* Construct a record from the query result, but instead of 62082c3d636Sdrh ** saving that record, use it as a key to delete elements from 62182c3d636Sdrh ** the temporary table iParm. 62282c3d636Sdrh */ 623c926afbcSdrh case SRT_Except: { 624e14006d0Sdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn); 625c926afbcSdrh break; 626c926afbcSdrh } 6275338a5f7Sdanielk1977 #endif 6285338a5f7Sdanielk1977 6295338a5f7Sdanielk1977 /* Store the result as data using a unique key. 6305338a5f7Sdanielk1977 */ 6315338a5f7Sdanielk1977 case SRT_Table: 632b9bb7c18Sdrh case SRT_EphemTab: { 633b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 634373cc2ddSdrh testcase( eDest==SRT_Table ); 635373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 636d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6375338a5f7Sdanielk1977 if( pOrderBy ){ 638b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 6395338a5f7Sdanielk1977 }else{ 640b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 641b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 642b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 643b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 644b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 6455338a5f7Sdanielk1977 } 646b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 6475338a5f7Sdanielk1977 break; 6485338a5f7Sdanielk1977 } 6492282792aSdrh 65093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 6512282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 6522282792aSdrh ** then there should be a single item on the stack. Write this 6532282792aSdrh ** item into the set table with bogus data. 6542282792aSdrh */ 655c926afbcSdrh case SRT_Set: { 656967e8b73Sdrh assert( nColumn==1 ); 6576c8c8ce0Sdanielk1977 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity); 658c926afbcSdrh if( pOrderBy ){ 659de941c60Sdrh /* At first glance you would think we could optimize out the 660de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 661de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 662de941c60Sdrh ** case the order does matter */ 663d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 664c926afbcSdrh }else{ 665b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 666d847eaadSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1); 667da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, 1); 668b7654111Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 669b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 670c926afbcSdrh } 671c926afbcSdrh break; 672c926afbcSdrh } 67382c3d636Sdrh 674504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 675ec7429aeSdrh */ 676ec7429aeSdrh case SRT_Exists: { 6774c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 678ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 679ec7429aeSdrh break; 680ec7429aeSdrh } 681ec7429aeSdrh 6822282792aSdrh /* If this is a scalar select that is part of an expression, then 6832282792aSdrh ** store the results in the appropriate memory cell and break out 6842282792aSdrh ** of the scan loop. 6852282792aSdrh */ 686c926afbcSdrh case SRT_Mem: { 687967e8b73Sdrh assert( nColumn==1 ); 688c926afbcSdrh if( pOrderBy ){ 689d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 690c926afbcSdrh }else{ 691b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regResult, iParm, 1); 692ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 693c926afbcSdrh } 694c926afbcSdrh break; 695c926afbcSdrh } 69693758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 6972282792aSdrh 698c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 699c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 700c182d163Sdrh ** popping the data from the stack. 701f46f905aSdrh */ 702e00ee6ebSdrh case SRT_Coroutine: 7037d10d5a6Sdrh case SRT_Output: { 704373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 705373cc2ddSdrh testcase( eDest==SRT_Output ); 706f46f905aSdrh if( pOrderBy ){ 707b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 708d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 709b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 710b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 711e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 71292b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 713c182d163Sdrh }else{ 714d847eaadSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); 715da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn); 716ac82fcf5Sdrh } 717142e30dfSdrh break; 718142e30dfSdrh } 719142e30dfSdrh 7206a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 721d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 722d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 723d7489c39Sdrh ** user-defined functions that have side effects. We do not care 724d7489c39Sdrh ** about the actual results of the select. 725d7489c39Sdrh */ 726c926afbcSdrh default: { 727f46f905aSdrh assert( eDest==SRT_Discard ); 728c926afbcSdrh break; 729c926afbcSdrh } 73093758c8dSdanielk1977 #endif 731c926afbcSdrh } 732ec7429aeSdrh 7335e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 7345e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 7355e87be87Sdrh ** the output for us. 736ec7429aeSdrh */ 7375e87be87Sdrh if( pOrderBy==0 && p->iLimit ){ 7389b918ed1Sdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); 739ec7429aeSdrh } 74082c3d636Sdrh } 74182c3d636Sdrh 74282c3d636Sdrh /* 743dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 744dece1a84Sdrh ** the collating sequence for each expression in that expression list. 745dece1a84Sdrh ** 7460342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 7470342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 7480342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 7490342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 7500342b1f5Sdrh ** index to implement a DISTINCT test. 7510342b1f5Sdrh ** 752dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 753dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 75466a5167bSdrh ** freed. Add the KeyInfo structure to the P4 field of an opcode using 75566a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. 756dece1a84Sdrh */ 757dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 758dece1a84Sdrh sqlite3 *db = pParse->db; 759dece1a84Sdrh int nExpr; 760dece1a84Sdrh KeyInfo *pInfo; 761dece1a84Sdrh struct ExprList_item *pItem; 762dece1a84Sdrh int i; 763dece1a84Sdrh 764dece1a84Sdrh nExpr = pList->nExpr; 76517435752Sdrh pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 766dece1a84Sdrh if( pInfo ){ 7672646da7eSdrh pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 768ea678832Sdrh pInfo->nField = (u16)nExpr; 76914db2665Sdanielk1977 pInfo->enc = ENC(db); 7702aca5846Sdrh pInfo->db = db; 771dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 772dece1a84Sdrh CollSeq *pColl; 773dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 774dece1a84Sdrh if( !pColl ){ 775dece1a84Sdrh pColl = db->pDfltColl; 776dece1a84Sdrh } 777dece1a84Sdrh pInfo->aColl[i] = pColl; 778dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 779dece1a84Sdrh } 780dece1a84Sdrh } 781dece1a84Sdrh return pInfo; 782dece1a84Sdrh } 783dece1a84Sdrh 7847f61e92cSdan #ifndef SQLITE_OMIT_COMPOUND_SELECT 7857f61e92cSdan /* 7867f61e92cSdan ** Name of the connection operator, used for error messages. 7877f61e92cSdan */ 7887f61e92cSdan static const char *selectOpName(int id){ 7897f61e92cSdan char *z; 7907f61e92cSdan switch( id ){ 7917f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 7927f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 7937f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 7947f61e92cSdan default: z = "UNION"; break; 7957f61e92cSdan } 7967f61e92cSdan return z; 7977f61e92cSdan } 7987f61e92cSdan #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 7997f61e92cSdan 8002ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 80117c0bc0cSdan /* 80217c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 80317c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 80417c0bc0cSdan ** where the caption is of the form: 80517c0bc0cSdan ** 80617c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 80717c0bc0cSdan ** 80817c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 80917c0bc0cSdan ** is determined by the zUsage argument. 81017c0bc0cSdan */ 8112ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 8122ce22453Sdan if( pParse->explain==2 ){ 8132ce22453Sdan Vdbe *v = pParse->pVdbe; 8142ce22453Sdan char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); 8152ce22453Sdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 8162ce22453Sdan } 8172ce22453Sdan } 81817c0bc0cSdan 81917c0bc0cSdan /* 820bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 821bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 822bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 823bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 824bb2b4418Sdan ** code with #ifndef directives. 825bb2b4418Sdan */ 826bb2b4418Sdan # define explainSetInteger(a, b) a = b 827bb2b4418Sdan 828bb2b4418Sdan #else 829bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 830bb2b4418Sdan # define explainTempTable(y,z) 831bb2b4418Sdan # define explainSetInteger(y,z) 832bb2b4418Sdan #endif 833bb2b4418Sdan 834bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) 835bb2b4418Sdan /* 8367f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 8377f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 8387f61e92cSdan ** where the caption is of one of the two forms: 8397f61e92cSdan ** 8407f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" 8417f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" 8427f61e92cSdan ** 8437f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding 8447f61e92cSdan ** function parameters, and op is the text representation of the parameter 8457f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, 8467f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 8477f61e92cSdan ** false, or the second form if it is true. 8487f61e92cSdan */ 8497f61e92cSdan static void explainComposite( 8507f61e92cSdan Parse *pParse, /* Parse context */ 8517f61e92cSdan int op, /* One of TK_UNION, TK_EXCEPT etc. */ 8527f61e92cSdan int iSub1, /* Subquery id 1 */ 8537f61e92cSdan int iSub2, /* Subquery id 2 */ 8547f61e92cSdan int bUseTmp /* True if a temp table was used */ 8557f61e92cSdan ){ 8567f61e92cSdan assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); 8577f61e92cSdan if( pParse->explain==2 ){ 8587f61e92cSdan Vdbe *v = pParse->pVdbe; 8597f61e92cSdan char *zMsg = sqlite3MPrintf( 86030969d3fSdan pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, 8617f61e92cSdan bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) 8627f61e92cSdan ); 8637f61e92cSdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 8647f61e92cSdan } 8657f61e92cSdan } 8662ce22453Sdan #else 86717c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */ 8687f61e92cSdan # define explainComposite(v,w,x,y,z) 8692ce22453Sdan #endif 870dece1a84Sdrh 871dece1a84Sdrh /* 872d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 873d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 874d8bc7086Sdrh ** we need to run the sorter and output the results. The following 875d8bc7086Sdrh ** routine generates the code needed to do that. 876d8bc7086Sdrh */ 877c926afbcSdrh static void generateSortTail( 878cdd536f0Sdrh Parse *pParse, /* Parsing context */ 879c926afbcSdrh Select *p, /* The SELECT statement */ 880c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 881c926afbcSdrh int nColumn, /* Number of columns of data */ 8826c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 883c926afbcSdrh ){ 884dc5ea5c7Sdrh int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ 885dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 886d8bc7086Sdrh int addr; 8870342b1f5Sdrh int iTab; 88861fc595fSdrh int pseudoTab = 0; 8890342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 890ffbc3088Sdrh 8916c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 8926c8c8ce0Sdanielk1977 int iParm = pDest->iParm; 8936c8c8ce0Sdanielk1977 8942d401ab8Sdrh int regRow; 8952d401ab8Sdrh int regRowid; 8962d401ab8Sdrh 8979d2985c7Sdrh iTab = pOrderBy->iECursor; 8983e9ca094Sdrh regRow = sqlite3GetTempReg(pParse); 8997d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 900cdd536f0Sdrh pseudoTab = pParse->nTab++; 9013e9ca094Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn); 9023e9ca094Sdrh regRowid = 0; 9033e9ca094Sdrh }else{ 9043e9ca094Sdrh regRowid = sqlite3GetTempReg(pParse); 905cdd536f0Sdrh } 906c6aff30cSdrh if( p->selFlags & SF_UseSorter ){ 907c2bb3282Sdrh int regSortOut = ++pParse->nMem; 908c6aff30cSdrh int ptab2 = pParse->nTab++; 909c6aff30cSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2); 910c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 911c6aff30cSdrh codeOffset(v, p, addrContinue); 912c6aff30cSdrh sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut); 913c6aff30cSdrh sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow); 914c6aff30cSdrh sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 915c6aff30cSdrh }else{ 916dc5ea5c7Sdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); 917dc5ea5c7Sdrh codeOffset(v, p, addrContinue); 9182d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow); 919c6aff30cSdrh } 920c926afbcSdrh switch( eDest ){ 921c926afbcSdrh case SRT_Table: 922b9bb7c18Sdrh case SRT_EphemTab: { 9231c767f0dSdrh testcase( eDest==SRT_Table ); 9241c767f0dSdrh testcase( eDest==SRT_EphemTab ); 9252d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 9262d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 9272d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 928c926afbcSdrh break; 929c926afbcSdrh } 93093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 931c926afbcSdrh case SRT_Set: { 932c926afbcSdrh assert( nColumn==1 ); 933a7a8e14bSdanielk1977 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1); 934da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regRow, 1); 935a7a8e14bSdanielk1977 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); 936c926afbcSdrh break; 937c926afbcSdrh } 938c926afbcSdrh case SRT_Mem: { 939c926afbcSdrh assert( nColumn==1 ); 940b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regRow, iParm, 1); 941ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 942c926afbcSdrh break; 943c926afbcSdrh } 94493758c8dSdanielk1977 #endif 945373cc2ddSdrh default: { 946ac82fcf5Sdrh int i; 947373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 9481c767f0dSdrh testcase( eDest==SRT_Output ); 9491c767f0dSdrh testcase( eDest==SRT_Coroutine ); 950ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 9519882d999Sdanielk1977 assert( regRow!=pDest->iMem+i ); 9521013c932Sdrh sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i); 9533e9ca094Sdrh if( i==0 ){ 9543e9ca094Sdrh sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 9553e9ca094Sdrh } 956ac82fcf5Sdrh } 9577d10d5a6Sdrh if( eDest==SRT_Output ){ 9581013c932Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn); 959da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn); 960a9671a22Sdrh }else{ 96192b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 962ce665cf6Sdrh } 963ac82fcf5Sdrh break; 964ac82fcf5Sdrh } 965c926afbcSdrh } 9662d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 9672d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 968ec7429aeSdrh 969ec7429aeSdrh /* The bottom of the loop 970ec7429aeSdrh */ 971dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 972c6aff30cSdrh if( p->selFlags & SF_UseSorter ){ 973c6aff30cSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); 974c6aff30cSdrh }else{ 97566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); 976c6aff30cSdrh } 977dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 9787d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 97966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); 980cdd536f0Sdrh } 981d8bc7086Sdrh } 982d8bc7086Sdrh 983d8bc7086Sdrh /* 984517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 985517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 986e78e8284Sdrh ** 987955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 988955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 989955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 990955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 991955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 992955de52cSdanielk1977 ** considered a column by this function. 993e78e8284Sdrh ** 994955de52cSdanielk1977 ** SELECT col FROM tbl; 995955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 996955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 997955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 998955de52cSdanielk1977 ** 999955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 1000fcb78a49Sdrh */ 1001955de52cSdanielk1977 static const char *columnType( 1002955de52cSdanielk1977 NameContext *pNC, 1003955de52cSdanielk1977 Expr *pExpr, 1004955de52cSdanielk1977 const char **pzOriginDb, 1005955de52cSdanielk1977 const char **pzOriginTab, 1006955de52cSdanielk1977 const char **pzOriginCol 1007955de52cSdanielk1977 ){ 1008955de52cSdanielk1977 char const *zType = 0; 1009955de52cSdanielk1977 char const *zOriginDb = 0; 1010955de52cSdanielk1977 char const *zOriginTab = 0; 1011955de52cSdanielk1977 char const *zOriginCol = 0; 1012517eb646Sdanielk1977 int j; 1013373cc2ddSdrh if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; 10145338a5f7Sdanielk1977 101500e279d9Sdanielk1977 switch( pExpr->op ){ 101630bcf5dbSdrh case TK_AGG_COLUMN: 101700e279d9Sdanielk1977 case TK_COLUMN: { 1018955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1019955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1020955de52cSdanielk1977 ** database table or a subquery. 1021955de52cSdanielk1977 */ 1022955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1023955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1024955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 1025373cc2ddSdrh testcase( pExpr->op==TK_AGG_COLUMN ); 1026373cc2ddSdrh testcase( pExpr->op==TK_COLUMN ); 102743bc88bbSdan while( pNC && !pTab ){ 1028b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1029b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1030b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 10316a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1032955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1033b3bce662Sdanielk1977 }else{ 1034b3bce662Sdanielk1977 pNC = pNC->pNext; 1035b3bce662Sdanielk1977 } 1036b3bce662Sdanielk1977 } 1037955de52cSdanielk1977 103843bc88bbSdan if( pTab==0 ){ 1039417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1040417168adSdrh ** cause this condition to run. Since then, we have restructured how 1041417168adSdrh ** trigger code is generated and so this condition is no longer 104243bc88bbSdan ** possible. However, it can still be true for statements like 104343bc88bbSdan ** the following: 104443bc88bbSdan ** 104543bc88bbSdan ** CREATE TABLE t1(col INTEGER); 104643bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 104743bc88bbSdan ** 104843bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 104943bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 105043bc88bbSdan ** though it should really be "INTEGER". 105143bc88bbSdan ** 105243bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 105343bc88bbSdan ** used. When columnType() is called on the expression 105443bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 105543bc88bbSdan ** branch below. */ 10567e62779aSdrh break; 10577e62779aSdrh } 1058955de52cSdanielk1977 105943bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1060955de52cSdanielk1977 if( pS ){ 1061955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1062955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1063955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1064955de52cSdanielk1977 */ 10657b688edeSdrh if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ 1066955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1067955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1068955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1069955de52cSdanielk1977 */ 1070955de52cSdanielk1977 NameContext sNC; 1071955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1072955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 107343bc88bbSdan sNC.pNext = pNC; 1074955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1075955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 1076955de52cSdanielk1977 } 10771c767f0dSdrh }else if( ALWAYS(pTab->pSchema) ){ 1078955de52cSdanielk1977 /* A real table */ 1079955de52cSdanielk1977 assert( !pS ); 1080fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1081fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1082fcb78a49Sdrh if( iCol<0 ){ 1083fcb78a49Sdrh zType = "INTEGER"; 1084955de52cSdanielk1977 zOriginCol = "rowid"; 1085fcb78a49Sdrh }else{ 1086fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 1087955de52cSdanielk1977 zOriginCol = pTab->aCol[iCol].zName; 1088955de52cSdanielk1977 } 1089955de52cSdanielk1977 zOriginTab = pTab->zName; 1090955de52cSdanielk1977 if( pNC->pParse ){ 1091955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1092955de52cSdanielk1977 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 1093955de52cSdanielk1977 } 1094fcb78a49Sdrh } 109500e279d9Sdanielk1977 break; 1096736c22b8Sdrh } 109793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 109800e279d9Sdanielk1977 case TK_SELECT: { 1099955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1100955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1101955de52cSdanielk1977 ** statement. 1102955de52cSdanielk1977 */ 1103b3bce662Sdanielk1977 NameContext sNC; 11046ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1105955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 11066ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1107955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1108b3bce662Sdanielk1977 sNC.pNext = pNC; 1109955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1110955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 111100e279d9Sdanielk1977 break; 1112fcb78a49Sdrh } 111393758c8dSdanielk1977 #endif 111400e279d9Sdanielk1977 } 111500e279d9Sdanielk1977 1116955de52cSdanielk1977 if( pzOriginDb ){ 1117955de52cSdanielk1977 assert( pzOriginTab && pzOriginCol ); 1118955de52cSdanielk1977 *pzOriginDb = zOriginDb; 1119955de52cSdanielk1977 *pzOriginTab = zOriginTab; 1120955de52cSdanielk1977 *pzOriginCol = zOriginCol; 1121955de52cSdanielk1977 } 1122517eb646Sdanielk1977 return zType; 1123517eb646Sdanielk1977 } 1124517eb646Sdanielk1977 1125517eb646Sdanielk1977 /* 1126517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1127517eb646Sdanielk1977 ** in the result set. 1128517eb646Sdanielk1977 */ 1129517eb646Sdanielk1977 static void generateColumnTypes( 1130517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1131517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1132517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1133517eb646Sdanielk1977 ){ 11343f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1135517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1136517eb646Sdanielk1977 int i; 1137b3bce662Sdanielk1977 NameContext sNC; 1138b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1139955de52cSdanielk1977 sNC.pParse = pParse; 1140517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1141517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 11423f913576Sdrh const char *zType; 11433f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1144955de52cSdanielk1977 const char *zOrigDb = 0; 1145955de52cSdanielk1977 const char *zOrigTab = 0; 1146955de52cSdanielk1977 const char *zOrigCol = 0; 11473f913576Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1148955de52cSdanielk1977 114985b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 11504b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 11514b1ae99dSdanielk1977 ** virtual machine is deleted. 1152fbcd585fSdanielk1977 */ 115310fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 115410fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 115510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 11563f913576Sdrh #else 11573f913576Sdrh zType = columnType(&sNC, p, 0, 0, 0); 11583f913576Sdrh #endif 115910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1160fcb78a49Sdrh } 11613f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */ 1162fcb78a49Sdrh } 1163fcb78a49Sdrh 1164fcb78a49Sdrh /* 1165fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1166fcb78a49Sdrh ** in the result set. This information is used to provide the 1167fcabd464Sdrh ** azCol[] values in the callback. 116882c3d636Sdrh */ 1169832508b7Sdrh static void generateColumnNames( 1170832508b7Sdrh Parse *pParse, /* Parser context */ 1171ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1172832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1173832508b7Sdrh ){ 1174d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 11756a3ea0e6Sdrh int i, j; 11769bb575fdSdrh sqlite3 *db = pParse->db; 1177fcabd464Sdrh int fullNames, shortNames; 1178fcabd464Sdrh 1179fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 11803cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 11813cf86063Sdanielk1977 if( pParse->explain ){ 118261de0d1bSdanielk1977 return; 11833cf86063Sdanielk1977 } 11845338a5f7Sdanielk1977 #endif 11853cf86063Sdanielk1977 1186e2f02bacSdrh if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; 1187d8bc7086Sdrh pParse->colNamesSet = 1; 1188fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1189fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 119022322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 119182c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 119282c3d636Sdrh Expr *p; 11935a38705eSdrh p = pEList->a[i].pExpr; 1194373cc2ddSdrh if( NEVER(p==0) ) continue; 119582c3d636Sdrh if( pEList->a[i].zName ){ 119682c3d636Sdrh char *zName = pEList->a[i].zName; 119710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1198f018cc2eSdrh }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ 11996a3ea0e6Sdrh Table *pTab; 120097665873Sdrh char *zCol; 12018aff1015Sdrh int iCol = p->iColumn; 1202e2f02bacSdrh for(j=0; ALWAYS(j<pTabList->nSrc); j++){ 1203e2f02bacSdrh if( pTabList->a[j].iCursor==p->iTable ) break; 1204e2f02bacSdrh } 12056a3ea0e6Sdrh assert( j<pTabList->nSrc ); 12066a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 12078aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 120897665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1209b1363206Sdrh if( iCol<0 ){ 121047a6db2bSdrh zCol = "rowid"; 1211b1363206Sdrh }else{ 1212b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1213b1363206Sdrh } 1214e49b146fSdrh if( !shortNames && !fullNames ){ 121510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1216b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 12171c767f0dSdrh }else if( fullNames ){ 121882c3d636Sdrh char *zName = 0; 12191c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 122010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 122182c3d636Sdrh }else{ 122210fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 122382c3d636Sdrh } 12241bee3d7bSdrh }else{ 122510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1226b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 122782c3d636Sdrh } 122882c3d636Sdrh } 122976d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 12305080aaa7Sdrh } 123182c3d636Sdrh 1232d8bc7086Sdrh /* 12337d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions 12347d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 12357d10d5a6Sdrh ** column names for a table that would hold the expression list. 12367d10d5a6Sdrh ** 12377d10d5a6Sdrh ** All column names will be unique. 12387d10d5a6Sdrh ** 12397d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 12407d10d5a6Sdrh ** and other fields of Column are zeroed. 12417d10d5a6Sdrh ** 12427d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 12437d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1244315555caSdrh */ 12457d10d5a6Sdrh static int selectColumnsFromExprList( 12467d10d5a6Sdrh Parse *pParse, /* Parsing context */ 12477d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 12487d10d5a6Sdrh int *pnCol, /* Write the number of columns here */ 12497d10d5a6Sdrh Column **paCol /* Write the new column list here */ 12507d10d5a6Sdrh ){ 1251dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1252dc5ea5c7Sdrh int i, j; /* Loop counters */ 1253dc5ea5c7Sdrh int cnt; /* Index added to make the name unique */ 1254dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1255dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1256dc5ea5c7Sdrh Expr *p; /* Expression for a single result column */ 1257dc5ea5c7Sdrh char *zName; /* Column name */ 1258dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 125979d5f63fSdrh 12607d10d5a6Sdrh *pnCol = nCol = pEList->nExpr; 12617d10d5a6Sdrh aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 12627d10d5a6Sdrh if( aCol==0 ) return SQLITE_NOMEM; 12637d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 126479d5f63fSdrh /* Get an appropriate name for the column 126579d5f63fSdrh */ 126679d5f63fSdrh p = pEList->a[i].pExpr; 126733e619fcSdrh assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue) 126833e619fcSdrh || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 ); 126991bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 127079d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 127117435752Sdrh zName = sqlite3DbStrDup(db, zName); 12727d10d5a6Sdrh }else{ 1273dc5ea5c7Sdrh Expr *pColExpr = p; /* The expression that is the result column name */ 1274dc5ea5c7Sdrh Table *pTab; /* Table associated with this expression */ 1275b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1276b07028f7Sdrh pColExpr = pColExpr->pRight; 1277b07028f7Sdrh assert( pColExpr!=0 ); 1278b07028f7Sdrh } 1279373cc2ddSdrh if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ 128093a960a0Sdrh /* For columns use the column name name */ 1281dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1282373cc2ddSdrh pTab = pColExpr->pTab; 1283f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1284f0209f74Sdrh zName = sqlite3MPrintf(db, "%s", 1285f0209f74Sdrh iCol>=0 ? pTab->aCol[iCol].zName : "rowid"); 1286b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 128733e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 128833e619fcSdrh zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); 128993a960a0Sdrh }else{ 129079d5f63fSdrh /* Use the original text of the column expression as its name */ 1291b7916a78Sdrh zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); 12927d10d5a6Sdrh } 129322f70c32Sdrh } 12947ce72f69Sdrh if( db->mallocFailed ){ 1295633e6d57Sdrh sqlite3DbFree(db, zName); 12967ce72f69Sdrh break; 1297dd5b2fa5Sdrh } 129879d5f63fSdrh 129979d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 130079d5f63fSdrh ** append a integer to the name so that it becomes unique. 130179d5f63fSdrh */ 1302ea678832Sdrh nName = sqlite3Strlen30(zName); 130379d5f63fSdrh for(j=cnt=0; j<i; j++){ 130479d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 1305633e6d57Sdrh char *zNewName; 13062564ef97Sdrh zName[nName] = 0; 1307633e6d57Sdrh zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt); 1308633e6d57Sdrh sqlite3DbFree(db, zName); 1309633e6d57Sdrh zName = zNewName; 131079d5f63fSdrh j = -1; 1311dd5b2fa5Sdrh if( zName==0 ) break; 131279d5f63fSdrh } 131379d5f63fSdrh } 131491bb0eedSdrh pCol->zName = zName; 13157d10d5a6Sdrh } 13167d10d5a6Sdrh if( db->mallocFailed ){ 13177d10d5a6Sdrh for(j=0; j<i; j++){ 13187d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 13197d10d5a6Sdrh } 13207d10d5a6Sdrh sqlite3DbFree(db, aCol); 13217d10d5a6Sdrh *paCol = 0; 13227d10d5a6Sdrh *pnCol = 0; 13237d10d5a6Sdrh return SQLITE_NOMEM; 13247d10d5a6Sdrh } 13257d10d5a6Sdrh return SQLITE_OK; 13267d10d5a6Sdrh } 1327e014a838Sdanielk1977 13287d10d5a6Sdrh /* 13297d10d5a6Sdrh ** Add type and collation information to a column list based on 13307d10d5a6Sdrh ** a SELECT statement. 13317d10d5a6Sdrh ** 13327d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 13337d10d5a6Sdrh ** The column list has only names, not types or collations. This 13347d10d5a6Sdrh ** routine goes through and adds the types and collations. 13357d10d5a6Sdrh ** 1336b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 13377d10d5a6Sdrh ** statement be resolved. 133879d5f63fSdrh */ 13397d10d5a6Sdrh static void selectAddColumnTypeAndCollation( 13407d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 13417d10d5a6Sdrh int nCol, /* Number of columns */ 13427d10d5a6Sdrh Column *aCol, /* List of columns */ 13437d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 13447d10d5a6Sdrh ){ 13457d10d5a6Sdrh sqlite3 *db = pParse->db; 13467d10d5a6Sdrh NameContext sNC; 13477d10d5a6Sdrh Column *pCol; 13487d10d5a6Sdrh CollSeq *pColl; 13497d10d5a6Sdrh int i; 13507d10d5a6Sdrh Expr *p; 13517d10d5a6Sdrh struct ExprList_item *a; 13527d10d5a6Sdrh 13537d10d5a6Sdrh assert( pSelect!=0 ); 13547d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 13557d10d5a6Sdrh assert( nCol==pSelect->pEList->nExpr || db->mallocFailed ); 13567d10d5a6Sdrh if( db->mallocFailed ) return; 1357c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1358b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 13597d10d5a6Sdrh a = pSelect->pEList->a; 13607d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 13617d10d5a6Sdrh p = a[i].pExpr; 13627d10d5a6Sdrh pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); 1363c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1364c4a64facSdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE; 1365b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1366b3bf556eSdanielk1977 if( pColl ){ 136717435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 13680202b29eSdanielk1977 } 136922f70c32Sdrh } 13707d10d5a6Sdrh } 13717d10d5a6Sdrh 13727d10d5a6Sdrh /* 13737d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 13747d10d5a6Sdrh ** the result set of that SELECT. 13757d10d5a6Sdrh */ 13767d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 13777d10d5a6Sdrh Table *pTab; 13787d10d5a6Sdrh sqlite3 *db = pParse->db; 13797d10d5a6Sdrh int savedFlags; 13807d10d5a6Sdrh 13817d10d5a6Sdrh savedFlags = db->flags; 13827d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 13837d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 13847d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 13857d10d5a6Sdrh if( pParse->nErr ) return 0; 13867d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 13877d10d5a6Sdrh db->flags = savedFlags; 13887d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 13897d10d5a6Sdrh if( pTab==0 ){ 13907d10d5a6Sdrh return 0; 13917d10d5a6Sdrh } 1392373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 1393b2468954Sdrh ** is disabled */ 1394373cc2ddSdrh assert( db->lookaside.bEnabled==0 ); 13957d10d5a6Sdrh pTab->nRef = 1; 13967d10d5a6Sdrh pTab->zName = 0; 13971ea87012Sdrh pTab->nRowEst = 1000000; 13987d10d5a6Sdrh selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 13997d10d5a6Sdrh selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect); 140022f70c32Sdrh pTab->iPKey = -1; 14017ce72f69Sdrh if( db->mallocFailed ){ 14021feeaed2Sdan sqlite3DeleteTable(db, pTab); 14037ce72f69Sdrh return 0; 14047ce72f69Sdrh } 140522f70c32Sdrh return pTab; 140622f70c32Sdrh } 140722f70c32Sdrh 140822f70c32Sdrh /* 1409d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1410d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1411d8bc7086Sdrh */ 14124adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1413d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1414d8bc7086Sdrh if( v==0 ){ 14154adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1416949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE 1417949f9cd5Sdrh if( v ){ 1418949f9cd5Sdrh sqlite3VdbeAddOp0(v, OP_Trace); 1419949f9cd5Sdrh } 1420949f9cd5Sdrh #endif 1421d8bc7086Sdrh } 1422d8bc7086Sdrh return v; 1423d8bc7086Sdrh } 1424d8bc7086Sdrh 142515007a99Sdrh 1426d8bc7086Sdrh /* 14277b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1428ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 14297b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1430a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1431a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1432a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1433a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 14347b58daeaSdrh ** 1435d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1436ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 14377b58daeaSdrh ** iOffset should have been preset to appropriate default values 14387b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1439ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 14407b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 14417b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 14427b58daeaSdrh ** SELECT statements. 14437b58daeaSdrh */ 1444ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 144502afc861Sdrh Vdbe *v = 0; 144602afc861Sdrh int iLimit = 0; 144715007a99Sdrh int iOffset; 14489b918ed1Sdrh int addr1, n; 14490acb7e48Sdrh if( p->iLimit ) return; 145015007a99Sdrh 14517b58daeaSdrh /* 14527b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 14537b58daeaSdrh ** contraversy about what the correct behavior should be. 14547b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 14557b58daeaSdrh ** no rows. 14567b58daeaSdrh */ 1457ceea3321Sdrh sqlite3ExprCacheClear(pParse); 1458373cc2ddSdrh assert( p->pOffset==0 || p->pLimit!=0 ); 1459a2dc3b1aSdanielk1977 if( p->pLimit ){ 14600a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 146115007a99Sdrh v = sqlite3GetVdbe(pParse); 1462373cc2ddSdrh if( NEVER(v==0) ) return; /* VDBE should have already been allocated */ 14639b918ed1Sdrh if( sqlite3ExprIsInteger(p->pLimit, &n) ){ 14649b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 14659b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 1466456e4e4fSdrh if( n==0 ){ 1467456e4e4fSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 146895aa47b1Sdrh }else{ 146995aa47b1Sdrh if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n; 14709b918ed1Sdrh } 14719b918ed1Sdrh }else{ 1472b7654111Sdrh sqlite3ExprCode(pParse, p->pLimit, iLimit); 1473b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); 1474d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 14753c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); 14769b918ed1Sdrh } 1477a2dc3b1aSdanielk1977 if( p->pOffset ){ 14780a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 1479b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 1480b7654111Sdrh sqlite3ExprCode(pParse, p->pOffset, iOffset); 1481b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); 1482d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 14833c84ddffSdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); 1484b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); 148515007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 1486b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1487d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 1488b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); 1489b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); 1490b7654111Sdrh sqlite3VdbeJumpHere(v, addr1); 1491b7654111Sdrh } 1492d59ba6ceSdrh } 14937b58daeaSdrh } 14947b58daeaSdrh 1495b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1496fbc4ee7bSdrh /* 1497fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1498fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1499fbc4ee7bSdrh ** the column has no default collating sequence. 1500fbc4ee7bSdrh ** 1501fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1502fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1503fbc4ee7bSdrh */ 1504dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1505fbc4ee7bSdrh CollSeq *pRet; 1506dc1bdc4fSdanielk1977 if( p->pPrior ){ 1507dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1508fbc4ee7bSdrh }else{ 1509fbc4ee7bSdrh pRet = 0; 1510dc1bdc4fSdanielk1977 } 151110c081adSdrh assert( iCol>=0 ); 151210c081adSdrh if( pRet==0 && iCol<p->pEList->nExpr ){ 1513dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1514dc1bdc4fSdanielk1977 } 1515dc1bdc4fSdanielk1977 return pRet; 1516d3d39e93Sdrh } 1517b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1518d3d39e93Sdrh 1519b21e7c70Sdrh /* Forward reference */ 1520b21e7c70Sdrh static int multiSelectOrderBy( 1521b21e7c70Sdrh Parse *pParse, /* Parsing context */ 1522b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 1523a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 1524b21e7c70Sdrh ); 1525b21e7c70Sdrh 1526b21e7c70Sdrh 1527b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1528d3d39e93Sdrh /* 152916ee60ffSdrh ** This routine is called to process a compound query form from 153016ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 153116ee60ffSdrh ** INTERSECT 1532c926afbcSdrh ** 1533e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1534e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1535e78e8284Sdrh ** in which case this routine will be called recursively. 1536e78e8284Sdrh ** 1537e78e8284Sdrh ** The results of the total query are to be written into a destination 1538e78e8284Sdrh ** of type eDest with parameter iParm. 1539e78e8284Sdrh ** 1540e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1541e78e8284Sdrh ** 1542e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1543e78e8284Sdrh ** 1544e78e8284Sdrh ** This statement is parsed up as follows: 1545e78e8284Sdrh ** 1546e78e8284Sdrh ** SELECT c FROM t3 1547e78e8284Sdrh ** | 1548e78e8284Sdrh ** `-----> SELECT b FROM t2 1549e78e8284Sdrh ** | 15504b11c6d3Sjplyon ** `------> SELECT a FROM t1 1551e78e8284Sdrh ** 1552e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1553e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1554e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1555e78e8284Sdrh ** 1556e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1557e78e8284Sdrh ** individual selects always group from left to right. 155882c3d636Sdrh */ 155984ac9d02Sdanielk1977 static int multiSelect( 1560fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1561fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1562a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 156384ac9d02Sdanielk1977 ){ 156484ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 156510e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 156610e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 15671013c932Sdrh SelectDest dest; /* Alternative data destination */ 1568eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 1569633e6d57Sdrh sqlite3 *db; /* Database connection */ 15707f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 15717f61e92cSdan int iSub1; /* EQP id of left-hand query */ 15727f61e92cSdan int iSub2; /* EQP id of right-hand query */ 15737f61e92cSdan #endif 157482c3d636Sdrh 15757b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1576fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 157782c3d636Sdrh */ 1578701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 1579633e6d57Sdrh db = pParse->db; 1580d8bc7086Sdrh pPrior = p->pPrior; 15810342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 15820342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1583bc10377aSdrh dest = *pDest; 1584d8bc7086Sdrh if( pPrior->pOrderBy ){ 15854adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1586da93d238Sdrh selectOpName(p->op)); 158784ac9d02Sdanielk1977 rc = 1; 158884ac9d02Sdanielk1977 goto multi_select_end; 158982c3d636Sdrh } 1590a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 15914adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 15927b58daeaSdrh selectOpName(p->op)); 159384ac9d02Sdanielk1977 rc = 1; 159484ac9d02Sdanielk1977 goto multi_select_end; 15957b58daeaSdrh } 159682c3d636Sdrh 15974adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 1598701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 1599d8bc7086Sdrh 16001cc3d75fSdrh /* Create the destination temporary table if necessary 16011cc3d75fSdrh */ 16026c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 1603b4964b72Sdanielk1977 assert( p->pEList ); 1604f6e369a1Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr); 1605d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 16066c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 16071cc3d75fSdrh } 16081cc3d75fSdrh 1609f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 1610f6e369a1Sdrh ** in their result sets. 1611f6e369a1Sdrh */ 1612f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 1613f6e369a1Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 1614f6e369a1Sdrh sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1615f6e369a1Sdrh " do not have the same number of result columns", selectOpName(p->op)); 1616f6e369a1Sdrh rc = 1; 1617f6e369a1Sdrh goto multi_select_end; 1618f6e369a1Sdrh } 1619f6e369a1Sdrh 1620a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 1621a9671a22Sdrh */ 1622f6e369a1Sdrh if( p->pOrderBy ){ 1623a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 1624f6e369a1Sdrh } 1625f6e369a1Sdrh 1626f46f905aSdrh /* Generate code for the left and right SELECT statements. 1627d8bc7086Sdrh */ 162882c3d636Sdrh switch( p->op ){ 1629f46f905aSdrh case TK_ALL: { 1630ec7429aeSdrh int addr = 0; 163195aa47b1Sdrh int nLimit; 1632a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1633a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1634a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 16357f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 16367d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 1637ad68cb6bSdanielk1977 p->pLimit = 0; 1638ad68cb6bSdanielk1977 p->pOffset = 0; 163984ac9d02Sdanielk1977 if( rc ){ 164084ac9d02Sdanielk1977 goto multi_select_end; 164184ac9d02Sdanielk1977 } 1642f46f905aSdrh p->pPrior = 0; 16437b58daeaSdrh p->iLimit = pPrior->iLimit; 16447b58daeaSdrh p->iOffset = pPrior->iOffset; 164592b01d53Sdrh if( p->iLimit ){ 16463c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); 1647d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 1648ec7429aeSdrh } 16497f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 16507d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 1651373cc2ddSdrh testcase( rc!=SQLITE_OK ); 1652eca7e01aSdanielk1977 pDelete = p->pPrior; 1653f46f905aSdrh p->pPrior = pPrior; 165495aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 165595aa47b1Sdrh if( pPrior->pLimit 165695aa47b1Sdrh && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) 165795aa47b1Sdrh && p->nSelectRow > (double)nLimit 165895aa47b1Sdrh ){ 165995aa47b1Sdrh p->nSelectRow = (double)nLimit; 166095aa47b1Sdrh } 1661ec7429aeSdrh if( addr ){ 1662ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1663ec7429aeSdrh } 1664f46f905aSdrh break; 1665f46f905aSdrh } 166682c3d636Sdrh case TK_EXCEPT: 166782c3d636Sdrh case TK_UNION: { 1668d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1669ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 1670d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1671a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1672dc1bdc4fSdanielk1977 int addr; 16736c8c8ce0Sdanielk1977 SelectDest uniondest; 167482c3d636Sdrh 1675373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 1676373cc2ddSdrh testcase( p->op==TK_UNION ); 167793a960a0Sdrh priorOp = SRT_Union; 1678e2f02bacSdrh if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){ 1679d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1680c926afbcSdrh ** right. 1681d8bc7086Sdrh */ 1682e2f02bacSdrh assert( p->pRightmost!=p ); /* Can only happen for leftward elements 1683e2f02bacSdrh ** of a 3-way or more compound */ 1684e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 1685e2f02bacSdrh assert( p->pOffset==0 ); /* Not allowed on leftward elements */ 16866c8c8ce0Sdanielk1977 unionTab = dest.iParm; 168782c3d636Sdrh }else{ 1688d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1689d8bc7086Sdrh ** intermediate results. 1690d8bc7086Sdrh */ 169182c3d636Sdrh unionTab = pParse->nTab++; 169293a960a0Sdrh assert( p->pOrderBy==0 ); 169366a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 1694b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1695b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 16967d10d5a6Sdrh p->pRightmost->selFlags |= SF_UsesEphemeral; 169784ac9d02Sdanielk1977 assert( p->pEList ); 1698d8bc7086Sdrh } 1699d8bc7086Sdrh 1700d8bc7086Sdrh /* Code the SELECT statements to our left 1701d8bc7086Sdrh */ 1702b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 17031013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 17047f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 17057d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 170684ac9d02Sdanielk1977 if( rc ){ 170784ac9d02Sdanielk1977 goto multi_select_end; 170884ac9d02Sdanielk1977 } 1709d8bc7086Sdrh 1710d8bc7086Sdrh /* Code the current SELECT statement 1711d8bc7086Sdrh */ 17124cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 17134cfb22f7Sdrh op = SRT_Except; 17144cfb22f7Sdrh }else{ 17154cfb22f7Sdrh assert( p->op==TK_UNION ); 17164cfb22f7Sdrh op = SRT_Union; 1717d8bc7086Sdrh } 171882c3d636Sdrh p->pPrior = 0; 1719a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1720a2dc3b1aSdanielk1977 p->pLimit = 0; 1721a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1722a2dc3b1aSdanielk1977 p->pOffset = 0; 17236c8c8ce0Sdanielk1977 uniondest.eDest = op; 17247f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 17257d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 1726373cc2ddSdrh testcase( rc!=SQLITE_OK ); 17275bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 17285bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 1729633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 1730eca7e01aSdanielk1977 pDelete = p->pPrior; 173182c3d636Sdrh p->pPrior = pPrior; 1732a9671a22Sdrh p->pOrderBy = 0; 173395aa47b1Sdrh if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow; 1734633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 1735a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1736a2dc3b1aSdanielk1977 p->pOffset = pOffset; 173792b01d53Sdrh p->iLimit = 0; 173892b01d53Sdrh p->iOffset = 0; 1739d8bc7086Sdrh 1740d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1741d8bc7086Sdrh ** it is that we currently need. 1742d8bc7086Sdrh */ 1743373cc2ddSdrh assert( unionTab==dest.iParm || dest.eDest!=priorOp ); 1744373cc2ddSdrh if( dest.eDest!=priorOp ){ 17456b56344dSdrh int iCont, iBreak, iStart; 174682c3d636Sdrh assert( p->pEList ); 17477d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 174892378253Sdrh Select *pFirst = p; 174992378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 175092378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 175141202ccaSdrh } 17524adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 17534adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1754ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 175566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); 17564adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 1757d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 1758a9671a22Sdrh 0, -1, &dest, iCont, iBreak); 17594adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 176066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); 17614adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 176266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 176382c3d636Sdrh } 176482c3d636Sdrh break; 176582c3d636Sdrh } 1766373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 176782c3d636Sdrh int tab1, tab2; 17686b56344dSdrh int iCont, iBreak, iStart; 1769a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 1770dc1bdc4fSdanielk1977 int addr; 17711013c932Sdrh SelectDest intersectdest; 17729cbf3425Sdrh int r1; 177382c3d636Sdrh 1774d8bc7086Sdrh /* INTERSECT is different from the others since it requires 17756206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1776d8bc7086Sdrh ** by allocating the tables we will need. 1777d8bc7086Sdrh */ 177882c3d636Sdrh tab1 = pParse->nTab++; 177982c3d636Sdrh tab2 = pParse->nTab++; 178093a960a0Sdrh assert( p->pOrderBy==0 ); 1781dc1bdc4fSdanielk1977 178266a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 1783b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1784b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 17857d10d5a6Sdrh p->pRightmost->selFlags |= SF_UsesEphemeral; 178684ac9d02Sdanielk1977 assert( p->pEList ); 1787d8bc7086Sdrh 1788d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1789d8bc7086Sdrh */ 17901013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 17917f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 17927d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 179384ac9d02Sdanielk1977 if( rc ){ 179484ac9d02Sdanielk1977 goto multi_select_end; 179584ac9d02Sdanielk1977 } 1796d8bc7086Sdrh 1797d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1798d8bc7086Sdrh */ 179966a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 1800b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 1801b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 180282c3d636Sdrh p->pPrior = 0; 1803a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1804a2dc3b1aSdanielk1977 p->pLimit = 0; 1805a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1806a2dc3b1aSdanielk1977 p->pOffset = 0; 18076c8c8ce0Sdanielk1977 intersectdest.iParm = tab2; 18087f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 18097d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 1810373cc2ddSdrh testcase( rc!=SQLITE_OK ); 1811eca7e01aSdanielk1977 pDelete = p->pPrior; 181282c3d636Sdrh p->pPrior = pPrior; 181395aa47b1Sdrh if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 1814633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 1815a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1816a2dc3b1aSdanielk1977 p->pOffset = pOffset; 1817d8bc7086Sdrh 1818d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1819d8bc7086Sdrh ** tables. 1820d8bc7086Sdrh */ 182182c3d636Sdrh assert( p->pEList ); 18227d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 182392378253Sdrh Select *pFirst = p; 182492378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 182592378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 182641202ccaSdrh } 18274adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 18284adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1829ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 183066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); 18319cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 18329cbf3425Sdrh iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 18338cff69dfSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); 18349cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 1835d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 1836a9671a22Sdrh 0, -1, &dest, iCont, iBreak); 18374adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 183866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); 18394adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 184066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 184166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 184282c3d636Sdrh break; 184382c3d636Sdrh } 184482c3d636Sdrh } 18458cdbf836Sdrh 18467f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); 18477f61e92cSdan 1848a9671a22Sdrh /* Compute collating sequences used by 1849a9671a22Sdrh ** temporary tables needed to implement the compound select. 1850a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 18518cdbf836Sdrh ** 18528cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 18538cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 18548cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 18558cdbf836Sdrh ** no temp tables are required. 1856fbc4ee7bSdrh */ 18577d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 1858fbc4ee7bSdrh int i; /* Loop counter */ 1859fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 18600342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 1861f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 186293a960a0Sdrh int nCol; /* Number of columns in result set */ 1863fbc4ee7bSdrh 18640342b1f5Sdrh assert( p->pRightmost==p ); 186593a960a0Sdrh nCol = p->pEList->nExpr; 1866633e6d57Sdrh pKeyInfo = sqlite3DbMallocZero(db, 1867a9671a22Sdrh sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1)); 1868dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1869dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1870dc1bdc4fSdanielk1977 goto multi_select_end; 1871dc1bdc4fSdanielk1977 } 1872dc1bdc4fSdanielk1977 1873633e6d57Sdrh pKeyInfo->enc = ENC(db); 1874ea678832Sdrh pKeyInfo->nField = (u16)nCol; 1875dc1bdc4fSdanielk1977 18760342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 18770342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 18780342b1f5Sdrh if( 0==*apColl ){ 1879633e6d57Sdrh *apColl = db->pDfltColl; 1880dc1bdc4fSdanielk1977 } 1881dc1bdc4fSdanielk1977 } 1882dc1bdc4fSdanielk1977 18830342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 18840342b1f5Sdrh for(i=0; i<2; i++){ 1885b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 18860342b1f5Sdrh if( addr<0 ){ 18870342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 18880342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 1889b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 18900342b1f5Sdrh break; 18910342b1f5Sdrh } 18920342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 189366a5167bSdrh sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); 18940ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 18950342b1f5Sdrh } 1896dc1bdc4fSdanielk1977 } 1897633e6d57Sdrh sqlite3DbFree(db, pKeyInfo); 1898dc1bdc4fSdanielk1977 } 1899dc1bdc4fSdanielk1977 1900dc1bdc4fSdanielk1977 multi_select_end: 19011013c932Sdrh pDest->iMem = dest.iMem; 1902ad27e761Sdrh pDest->nMem = dest.nMem; 1903633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 190484ac9d02Sdanielk1977 return rc; 19052282792aSdrh } 1906b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 19072282792aSdrh 1908b21e7c70Sdrh /* 1909b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 1910b21e7c70Sdrh ** SELECT statment. 19110acb7e48Sdrh ** 19120acb7e48Sdrh ** The data to be output is contained in pIn->iMem. There are 19130acb7e48Sdrh ** pIn->nMem columns to be output. pDest is where the output should 19140acb7e48Sdrh ** be sent. 19150acb7e48Sdrh ** 19160acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 19170acb7e48Sdrh ** return address. 19180acb7e48Sdrh ** 1919f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 19200acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 19210acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 19220acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 19230acb7e48Sdrh ** keys. 19240acb7e48Sdrh ** 19250acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 19260acb7e48Sdrh ** iBreak. 1927b21e7c70Sdrh */ 19280acb7e48Sdrh static int generateOutputSubroutine( 192992b01d53Sdrh Parse *pParse, /* Parsing context */ 193092b01d53Sdrh Select *p, /* The SELECT statement */ 193192b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 193292b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 193392b01d53Sdrh int regReturn, /* The return address register */ 19340acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 19350acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 19360acb7e48Sdrh int p4type, /* The p4 type for pKeyInfo */ 193792b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 1938b21e7c70Sdrh ){ 1939b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 194092b01d53Sdrh int iContinue; 194192b01d53Sdrh int addr; 1942b21e7c70Sdrh 194392b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 194492b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 19450acb7e48Sdrh 19460acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 19470acb7e48Sdrh */ 19480acb7e48Sdrh if( regPrev ){ 19490acb7e48Sdrh int j1, j2; 19500acb7e48Sdrh j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); 19510acb7e48Sdrh j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem, 19520acb7e48Sdrh (char*)pKeyInfo, p4type); 19530acb7e48Sdrh sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); 19540acb7e48Sdrh sqlite3VdbeJumpHere(v, j1); 19550acb7e48Sdrh sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem); 19560acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 19570acb7e48Sdrh } 19581f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 19590acb7e48Sdrh 19600acb7e48Sdrh /* Suppress the the first OFFSET entries if there is an OFFSET clause 19610acb7e48Sdrh */ 196292b01d53Sdrh codeOffset(v, p, iContinue); 1963b21e7c70Sdrh 1964b21e7c70Sdrh switch( pDest->eDest ){ 1965b21e7c70Sdrh /* Store the result as data using a unique key. 1966b21e7c70Sdrh */ 1967b21e7c70Sdrh case SRT_Table: 1968b21e7c70Sdrh case SRT_EphemTab: { 1969b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 1970b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 1971373cc2ddSdrh testcase( pDest->eDest==SRT_Table ); 1972373cc2ddSdrh testcase( pDest->eDest==SRT_EphemTab ); 197392b01d53Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1); 197492b01d53Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2); 197592b01d53Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2); 1976b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1977b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 1978b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 1979b21e7c70Sdrh break; 1980b21e7c70Sdrh } 1981b21e7c70Sdrh 1982b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 1983b21e7c70Sdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 1984b21e7c70Sdrh ** then there should be a single item on the stack. Write this 1985b21e7c70Sdrh ** item into the set table with bogus data. 1986b21e7c70Sdrh */ 1987b21e7c70Sdrh case SRT_Set: { 19886fccc35aSdrh int r1; 198992b01d53Sdrh assert( pIn->nMem==1 ); 199092b01d53Sdrh p->affinity = 199192b01d53Sdrh sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity); 1992b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 199392b01d53Sdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1); 199492b01d53Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1); 199592b01d53Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1); 1996b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 1997b21e7c70Sdrh break; 1998b21e7c70Sdrh } 1999b21e7c70Sdrh 200085e9e22bSdrh #if 0 /* Never occurs on an ORDER BY query */ 2001b21e7c70Sdrh /* If any row exist in the result set, record that fact and abort. 2002b21e7c70Sdrh */ 2003b21e7c70Sdrh case SRT_Exists: { 200492b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm); 2005b21e7c70Sdrh /* The LIMIT clause will terminate the loop for us */ 2006b21e7c70Sdrh break; 2007b21e7c70Sdrh } 200885e9e22bSdrh #endif 2009b21e7c70Sdrh 2010b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2011b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2012b21e7c70Sdrh ** of the scan loop. 2013b21e7c70Sdrh */ 2014b21e7c70Sdrh case SRT_Mem: { 201592b01d53Sdrh assert( pIn->nMem==1 ); 201692b01d53Sdrh sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1); 2017b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 2018b21e7c70Sdrh break; 2019b21e7c70Sdrh } 2020b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2021b21e7c70Sdrh 20227d10d5a6Sdrh /* The results are stored in a sequence of registers 20237d10d5a6Sdrh ** starting at pDest->iMem. Then the co-routine yields. 2024b21e7c70Sdrh */ 202592b01d53Sdrh case SRT_Coroutine: { 202692b01d53Sdrh if( pDest->iMem==0 ){ 202792b01d53Sdrh pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem); 202892b01d53Sdrh pDest->nMem = pIn->nMem; 2029b21e7c70Sdrh } 203092b01d53Sdrh sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem); 203192b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 203292b01d53Sdrh break; 203392b01d53Sdrh } 203492b01d53Sdrh 2035ccfcbceaSdrh /* If none of the above, then the result destination must be 2036ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2037ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2038ccfcbceaSdrh ** 2039ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2040ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2041ccfcbceaSdrh ** return the next row of result. 20427d10d5a6Sdrh */ 2043ccfcbceaSdrh default: { 2044ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 204592b01d53Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem); 204692b01d53Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem); 2047b21e7c70Sdrh break; 2048b21e7c70Sdrh } 2049b21e7c70Sdrh } 205092b01d53Sdrh 205192b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 205292b01d53Sdrh */ 205392b01d53Sdrh if( p->iLimit ){ 20549b918ed1Sdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); 205592b01d53Sdrh } 205692b01d53Sdrh 205792b01d53Sdrh /* Generate the subroutine return 205892b01d53Sdrh */ 20590acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 206092b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 206192b01d53Sdrh 206292b01d53Sdrh return addr; 2063b21e7c70Sdrh } 2064b21e7c70Sdrh 2065b21e7c70Sdrh /* 2066b21e7c70Sdrh ** Alternative compound select code generator for cases when there 2067b21e7c70Sdrh ** is an ORDER BY clause. 2068b21e7c70Sdrh ** 2069b21e7c70Sdrh ** We assume a query of the following form: 2070b21e7c70Sdrh ** 2071b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 2072b21e7c70Sdrh ** 2073b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 2074b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 2075b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 2076b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 2077b21e7c70Sdrh ** selectB) there are 7 subroutines: 2078b21e7c70Sdrh ** 2079b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 2080b21e7c70Sdrh ** of the compound query. 2081b21e7c70Sdrh ** 2082b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 2083b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 2084b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 2085b21e7c70Sdrh ** appears only in B.) 2086b21e7c70Sdrh ** 2087b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 2088b21e7c70Sdrh ** 2089b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 2090b21e7c70Sdrh ** 2091b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 2092b21e7c70Sdrh ** 2093b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 2094b21e7c70Sdrh ** 2095b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 2096b21e7c70Sdrh ** 2097b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 2098b21e7c70Sdrh ** <operator> is used: 2099b21e7c70Sdrh ** 2100b21e7c70Sdrh ** 2101b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 2102b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 2103b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 2104b21e7c70Sdrh ** 21050acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 2106b21e7c70Sdrh ** 2107b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 2108b21e7c70Sdrh ** 21090acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 2110b21e7c70Sdrh ** 21110acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 21120acb7e48Sdrh ** 21130acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 21140acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 21150acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 21160acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 21170acb7e48Sdrh ** 21180acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 21190acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 21200acb7e48Sdrh ** output value. A comparison is made against this value and the output 21210acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 2122b21e7c70Sdrh ** 2123b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 2124b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 2125b21e7c70Sdrh ** 2126b21e7c70Sdrh ** goto Init 2127b21e7c70Sdrh ** coA: coroutine for left query (A) 2128b21e7c70Sdrh ** coB: coroutine for right query (B) 2129b21e7c70Sdrh ** outA: output one row of A 2130b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 2131b21e7c70Sdrh ** EofA: ... 2132b21e7c70Sdrh ** EofB: ... 2133b21e7c70Sdrh ** AltB: ... 2134b21e7c70Sdrh ** AeqB: ... 2135b21e7c70Sdrh ** AgtB: ... 2136b21e7c70Sdrh ** Init: initialize coroutine registers 2137b21e7c70Sdrh ** yield coA 2138b21e7c70Sdrh ** if eof(A) goto EofA 2139b21e7c70Sdrh ** yield coB 2140b21e7c70Sdrh ** if eof(B) goto EofB 2141b21e7c70Sdrh ** Cmpr: Compare A, B 2142b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 2143b21e7c70Sdrh ** End: ... 2144b21e7c70Sdrh ** 2145b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 2146b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 2147b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 2148b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 2149b21e7c70Sdrh */ 2150de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 2151b21e7c70Sdrh static int multiSelectOrderBy( 2152b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2153b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2154a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2155b21e7c70Sdrh ){ 21560acb7e48Sdrh int i, j; /* Loop counters */ 2157b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 2158b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 2159b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 2160b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 216192b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 216292b01d53Sdrh int regEofA; /* Flag to indicate when select-A is complete */ 216392b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 216492b01d53Sdrh int regEofB; /* Flag to indicate when select-B is complete */ 216592b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 216692b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 216792b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 216892b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 216992b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 2170b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 217192b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 217292b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 217392b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 217492b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 217592b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 217692b01d53Sdrh int regLimitA; /* Limit register for select-A */ 217792b01d53Sdrh int regLimitB; /* Limit register for select-A */ 21780acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 217992b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 218092b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 218192b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 218292b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 21830acb7e48Sdrh int j1; /* Jump instructions that get retargetted */ 218492b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 218596067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 21860acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 21870acb7e48Sdrh sqlite3 *db; /* Database connection */ 21880acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 21890acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 21900acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 21917f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 21927f61e92cSdan int iSub1; /* EQP id of left-hand query */ 21937f61e92cSdan int iSub2; /* EQP id of right-hand query */ 21947f61e92cSdan #endif 2195b21e7c70Sdrh 219692b01d53Sdrh assert( p->pOrderBy!=0 ); 219796067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 21980acb7e48Sdrh db = pParse->db; 219992b01d53Sdrh v = pParse->pVdbe; 2200ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 220192b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 220292b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 22030acb7e48Sdrh 2204b21e7c70Sdrh 220592b01d53Sdrh /* Patch up the ORDER BY clause 220692b01d53Sdrh */ 220792b01d53Sdrh op = p->op; 2208b21e7c70Sdrh pPrior = p->pPrior; 220992b01d53Sdrh assert( pPrior->pOrderBy==0 ); 22100acb7e48Sdrh pOrderBy = p->pOrderBy; 221193a960a0Sdrh assert( pOrderBy ); 22120acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 221393a960a0Sdrh 22140acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 22150acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 22160acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 22170acb7e48Sdrh */ 22180acb7e48Sdrh if( op!=TK_ALL ){ 22190acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 22207d10d5a6Sdrh struct ExprList_item *pItem; 22217d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 22227d10d5a6Sdrh assert( pItem->iCol>0 ); 22237d10d5a6Sdrh if( pItem->iCol==i ) break; 22240acb7e48Sdrh } 22250acb7e48Sdrh if( j==nOrderBy ){ 2226b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 22270acb7e48Sdrh if( pNew==0 ) return SQLITE_NOMEM; 22280acb7e48Sdrh pNew->flags |= EP_IntValue; 222933e619fcSdrh pNew->u.iValue = i; 2230b7916a78Sdrh pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 2231ea678832Sdrh pOrderBy->a[nOrderBy++].iCol = (u16)i; 22320acb7e48Sdrh } 22330acb7e48Sdrh } 22340acb7e48Sdrh } 22350acb7e48Sdrh 22360acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 223710c081adSdrh ** the permutation used to determine if the next 22380acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 22390acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 22400acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 22410acb7e48Sdrh ** collation. 22420acb7e48Sdrh */ 22430acb7e48Sdrh aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); 22440acb7e48Sdrh if( aPermute ){ 22457d10d5a6Sdrh struct ExprList_item *pItem; 22467d10d5a6Sdrh for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){ 22477d10d5a6Sdrh assert( pItem->iCol>0 && pItem->iCol<=p->pEList->nExpr ); 22487d10d5a6Sdrh aPermute[i] = pItem->iCol - 1; 22490acb7e48Sdrh } 22500acb7e48Sdrh pKeyMerge = 22510acb7e48Sdrh sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1)); 22520acb7e48Sdrh if( pKeyMerge ){ 22530acb7e48Sdrh pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy]; 2254ea678832Sdrh pKeyMerge->nField = (u16)nOrderBy; 22550acb7e48Sdrh pKeyMerge->enc = ENC(db); 22560acb7e48Sdrh for(i=0; i<nOrderBy; i++){ 22570acb7e48Sdrh CollSeq *pColl; 22580acb7e48Sdrh Expr *pTerm = pOrderBy->a[i].pExpr; 22590acb7e48Sdrh if( pTerm->flags & EP_ExpCollate ){ 22600acb7e48Sdrh pColl = pTerm->pColl; 22610acb7e48Sdrh }else{ 22620acb7e48Sdrh pColl = multiSelectCollSeq(pParse, p, aPermute[i]); 22630acb7e48Sdrh pTerm->flags |= EP_ExpCollate; 22640acb7e48Sdrh pTerm->pColl = pColl; 22650acb7e48Sdrh } 22660acb7e48Sdrh pKeyMerge->aColl[i] = pColl; 22670acb7e48Sdrh pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder; 22680acb7e48Sdrh } 22690acb7e48Sdrh } 22700acb7e48Sdrh }else{ 22710acb7e48Sdrh pKeyMerge = 0; 22720acb7e48Sdrh } 22730acb7e48Sdrh 22740acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 22750acb7e48Sdrh */ 22760acb7e48Sdrh p->pOrderBy = pOrderBy; 22776ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 22780acb7e48Sdrh 22790acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 22800acb7e48Sdrh ** for the logic that removes duplicate result rows when the 22810acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 22820acb7e48Sdrh */ 22830acb7e48Sdrh if( op==TK_ALL ){ 22840acb7e48Sdrh regPrev = 0; 22850acb7e48Sdrh }else{ 22860acb7e48Sdrh int nExpr = p->pEList->nExpr; 22871c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 22880acb7e48Sdrh regPrev = sqlite3GetTempRange(pParse, nExpr+1); 22890acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 22900acb7e48Sdrh pKeyDup = sqlite3DbMallocZero(db, 22910acb7e48Sdrh sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) ); 22920acb7e48Sdrh if( pKeyDup ){ 22930acb7e48Sdrh pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr]; 2294ea678832Sdrh pKeyDup->nField = (u16)nExpr; 22950acb7e48Sdrh pKeyDup->enc = ENC(db); 22960acb7e48Sdrh for(i=0; i<nExpr; i++){ 22970acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 22980acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 22990acb7e48Sdrh } 23000acb7e48Sdrh } 23010acb7e48Sdrh } 230292b01d53Sdrh 230392b01d53Sdrh /* Separate the left and the right query from one another 230492b01d53Sdrh */ 230592b01d53Sdrh p->pPrior = 0; 23067d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 23070acb7e48Sdrh if( pPrior->pPrior==0 ){ 23087d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 23090acb7e48Sdrh } 231092b01d53Sdrh 231192b01d53Sdrh /* Compute the limit registers */ 231292b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 23130acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 231492b01d53Sdrh regLimitA = ++pParse->nMem; 231592b01d53Sdrh regLimitB = ++pParse->nMem; 231692b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 231792b01d53Sdrh regLimitA); 231892b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 231992b01d53Sdrh }else{ 232092b01d53Sdrh regLimitA = regLimitB = 0; 232192b01d53Sdrh } 2322633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 23230acb7e48Sdrh p->pLimit = 0; 2324633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 23250acb7e48Sdrh p->pOffset = 0; 232692b01d53Sdrh 2327b21e7c70Sdrh regAddrA = ++pParse->nMem; 2328b21e7c70Sdrh regEofA = ++pParse->nMem; 2329b21e7c70Sdrh regAddrB = ++pParse->nMem; 2330b21e7c70Sdrh regEofB = ++pParse->nMem; 2331b21e7c70Sdrh regOutA = ++pParse->nMem; 2332b21e7c70Sdrh regOutB = ++pParse->nMem; 2333b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 2334b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 2335b21e7c70Sdrh 233692b01d53Sdrh /* Jump past the various subroutines and coroutines to the main 233792b01d53Sdrh ** merge loop 233892b01d53Sdrh */ 2339b21e7c70Sdrh j1 = sqlite3VdbeAddOp0(v, OP_Goto); 2340b21e7c70Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v); 234192b01d53Sdrh 23420acb7e48Sdrh 234392b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 23440acb7e48Sdrh ** left of the compound operator - the "A" select. 23450acb7e48Sdrh */ 2346b21e7c70Sdrh VdbeNoopComment((v, "Begin coroutine for left SELECT")); 234792b01d53Sdrh pPrior->iLimit = regLimitA; 23487f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 23497d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 2350b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA); 235192b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 2352b21e7c70Sdrh VdbeNoopComment((v, "End coroutine for left SELECT")); 2353b21e7c70Sdrh 235492b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 235592b01d53Sdrh ** the right - the "B" select 235692b01d53Sdrh */ 2357b21e7c70Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v); 2358b21e7c70Sdrh VdbeNoopComment((v, "Begin coroutine for right SELECT")); 235992b01d53Sdrh savedLimit = p->iLimit; 236092b01d53Sdrh savedOffset = p->iOffset; 236192b01d53Sdrh p->iLimit = regLimitB; 236292b01d53Sdrh p->iOffset = 0; 23637f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 23647d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 236592b01d53Sdrh p->iLimit = savedLimit; 236692b01d53Sdrh p->iOffset = savedOffset; 2367b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB); 236892b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 2369b21e7c70Sdrh VdbeNoopComment((v, "End coroutine for right SELECT")); 2370b21e7c70Sdrh 237192b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 23720acb7e48Sdrh ** select as the next output row of the compound select. 237392b01d53Sdrh */ 2374b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 23750acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 23760acb7e48Sdrh p, &destA, pDest, regOutA, 23770acb7e48Sdrh regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd); 2378b21e7c70Sdrh 237992b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 23800acb7e48Sdrh ** select as the next output row of the compound select. 238192b01d53Sdrh */ 23820acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 2383b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 23840acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 23850acb7e48Sdrh p, &destB, pDest, regOutB, 23860acb7e48Sdrh regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd); 23870acb7e48Sdrh } 2388b21e7c70Sdrh 238992b01d53Sdrh /* Generate a subroutine to run when the results from select A 239092b01d53Sdrh ** are exhausted and only data in select B remains. 239192b01d53Sdrh */ 239292b01d53Sdrh VdbeNoopComment((v, "eof-A subroutine")); 239392b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 23940acb7e48Sdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd); 239592b01d53Sdrh }else{ 23960acb7e48Sdrh addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd); 2397b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 239892b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 23990acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); 240095aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 2401b21e7c70Sdrh } 2402b21e7c70Sdrh 240392b01d53Sdrh /* Generate a subroutine to run when the results from select B 240492b01d53Sdrh ** are exhausted and only data in select A remains. 240592b01d53Sdrh */ 2406b21e7c70Sdrh if( op==TK_INTERSECT ){ 240792b01d53Sdrh addrEofB = addrEofA; 240895aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 2409b21e7c70Sdrh }else{ 241092b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 24110acb7e48Sdrh addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd); 2412b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 241392b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 24140acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); 2415b21e7c70Sdrh } 2416b21e7c70Sdrh 241792b01d53Sdrh /* Generate code to handle the case of A<B 241892b01d53Sdrh */ 2419b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 24200acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 242192b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 2422b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 242392b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 2424b21e7c70Sdrh 242592b01d53Sdrh /* Generate code to handle the case of A==B 242692b01d53Sdrh */ 2427b21e7c70Sdrh if( op==TK_ALL ){ 2428b21e7c70Sdrh addrAeqB = addrAltB; 24290acb7e48Sdrh }else if( op==TK_INTERSECT ){ 24300acb7e48Sdrh addrAeqB = addrAltB; 24310acb7e48Sdrh addrAltB++; 243292b01d53Sdrh }else{ 2433b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 24340acb7e48Sdrh addrAeqB = 243592b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 243692b01d53Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 243792b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 243892b01d53Sdrh } 2439b21e7c70Sdrh 244092b01d53Sdrh /* Generate code to handle the case of A>B 244192b01d53Sdrh */ 2442b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 2443b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 2444b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 2445b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 244692b01d53Sdrh } 24470acb7e48Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 2448b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); 244992b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 2450b21e7c70Sdrh 245192b01d53Sdrh /* This code runs once to initialize everything. 245292b01d53Sdrh */ 2453b21e7c70Sdrh sqlite3VdbeJumpHere(v, j1); 2454b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA); 2455b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB); 245692b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA); 24570acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB); 2458b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 2459b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); 246092b01d53Sdrh 246192b01d53Sdrh /* Implement the main merge loop 246292b01d53Sdrh */ 246392b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 24640acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 24650acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy, 24660acb7e48Sdrh (char*)pKeyMerge, P4_KEYINFO_HANDOFF); 2467b21e7c70Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); 246892b01d53Sdrh 24690acb7e48Sdrh /* Release temporary registers 24700acb7e48Sdrh */ 24710acb7e48Sdrh if( regPrev ){ 24720acb7e48Sdrh sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1); 24730acb7e48Sdrh } 24740acb7e48Sdrh 247592b01d53Sdrh /* Jump to the this point in order to terminate the query. 247692b01d53Sdrh */ 2477b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 2478b21e7c70Sdrh 247992b01d53Sdrh /* Set the number of output columns 248092b01d53Sdrh */ 24817d10d5a6Sdrh if( pDest->eDest==SRT_Output ){ 24820acb7e48Sdrh Select *pFirst = pPrior; 248392b01d53Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 248492b01d53Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 2485b21e7c70Sdrh } 248692b01d53Sdrh 24870acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 24880acb7e48Sdrh ** by the calling function */ 24895e7ad508Sdanielk1977 if( p->pPrior ){ 2490633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 24915e7ad508Sdanielk1977 } 24920acb7e48Sdrh p->pPrior = pPrior; 249392b01d53Sdrh 249492b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 249592b01d53Sdrh **** subqueries ****/ 24967f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, 0); 249792b01d53Sdrh return SQLITE_OK; 249892b01d53Sdrh } 2499de3e41e3Sdanielk1977 #endif 2500b21e7c70Sdrh 25013514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 250217435752Sdrh /* Forward Declarations */ 250317435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*); 250417435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *); 250517435752Sdrh 25062282792aSdrh /* 2507832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 25086a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 250984e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 25106a3ea0e6Sdrh ** unchanged.) 2511832508b7Sdrh ** 2512832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 2513832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 2514832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 2515832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 2516832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 2517832508b7Sdrh ** of the subquery rather the result set of the subquery. 2518832508b7Sdrh */ 2519b7916a78Sdrh static Expr *substExpr( 252017435752Sdrh sqlite3 *db, /* Report malloc errors to this connection */ 252117435752Sdrh Expr *pExpr, /* Expr in which substitution occurs */ 252217435752Sdrh int iTable, /* Table to be substituted */ 252317435752Sdrh ExprList *pEList /* Substitute expressions */ 252417435752Sdrh ){ 2525b7916a78Sdrh if( pExpr==0 ) return 0; 252650350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 252750350a15Sdrh if( pExpr->iColumn<0 ){ 252850350a15Sdrh pExpr->op = TK_NULL; 252950350a15Sdrh }else{ 2530832508b7Sdrh Expr *pNew; 253184e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 25326ab3a2ecSdanielk1977 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 2533b7916a78Sdrh pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); 253438210ac5Sdrh if( pNew && pExpr->pColl ){ 25350a458e5eSdanielk1977 pNew->pColl = pExpr->pColl; 25360a458e5eSdanielk1977 } 2537b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 2538b7916a78Sdrh pExpr = pNew; 253950350a15Sdrh } 2540832508b7Sdrh }else{ 2541b7916a78Sdrh pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); 2542b7916a78Sdrh pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); 25436ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 25446ab3a2ecSdanielk1977 substSelect(db, pExpr->x.pSelect, iTable, pEList); 25456ab3a2ecSdanielk1977 }else{ 25466ab3a2ecSdanielk1977 substExprList(db, pExpr->x.pList, iTable, pEList); 25476ab3a2ecSdanielk1977 } 2548832508b7Sdrh } 2549b7916a78Sdrh return pExpr; 2550832508b7Sdrh } 255117435752Sdrh static void substExprList( 255217435752Sdrh sqlite3 *db, /* Report malloc errors here */ 255317435752Sdrh ExprList *pList, /* List to scan and in which to make substitutes */ 255417435752Sdrh int iTable, /* Table to be substituted */ 255517435752Sdrh ExprList *pEList /* Substitute values */ 255617435752Sdrh ){ 2557832508b7Sdrh int i; 2558832508b7Sdrh if( pList==0 ) return; 2559832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 2560b7916a78Sdrh pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); 2561832508b7Sdrh } 2562832508b7Sdrh } 256317435752Sdrh static void substSelect( 256417435752Sdrh sqlite3 *db, /* Report malloc errors here */ 256517435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 256617435752Sdrh int iTable, /* Table to be replaced */ 256717435752Sdrh ExprList *pEList /* Substitute values */ 256817435752Sdrh ){ 2569588a9a1aSdrh SrcList *pSrc; 2570588a9a1aSdrh struct SrcList_item *pItem; 2571588a9a1aSdrh int i; 2572b3bce662Sdanielk1977 if( !p ) return; 257317435752Sdrh substExprList(db, p->pEList, iTable, pEList); 257417435752Sdrh substExprList(db, p->pGroupBy, iTable, pEList); 257517435752Sdrh substExprList(db, p->pOrderBy, iTable, pEList); 2576b7916a78Sdrh p->pHaving = substExpr(db, p->pHaving, iTable, pEList); 2577b7916a78Sdrh p->pWhere = substExpr(db, p->pWhere, iTable, pEList); 257817435752Sdrh substSelect(db, p->pPrior, iTable, pEList); 2579588a9a1aSdrh pSrc = p->pSrc; 2580e2f02bacSdrh assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ 2581e2f02bacSdrh if( ALWAYS(pSrc) ){ 2582588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 2583588a9a1aSdrh substSelect(db, pItem->pSelect, iTable, pEList); 2584588a9a1aSdrh } 2585588a9a1aSdrh } 2586b3bce662Sdanielk1977 } 25873514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 2588832508b7Sdrh 25893514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 2590832508b7Sdrh /* 25911350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 25921350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 25931350b030Sdrh ** occurs. 25941350b030Sdrh ** 25951350b030Sdrh ** To understand the concept of flattening, consider the following 25961350b030Sdrh ** query: 25971350b030Sdrh ** 25981350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 25991350b030Sdrh ** 26001350b030Sdrh ** The default way of implementing this query is to execute the 26011350b030Sdrh ** subquery first and store the results in a temporary table, then 26021350b030Sdrh ** run the outer query on that temporary table. This requires two 26031350b030Sdrh ** passes over the data. Furthermore, because the temporary table 26041350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 2605832508b7Sdrh ** optimized. 26061350b030Sdrh ** 2607832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 26081350b030Sdrh ** a single flat select, like this: 26091350b030Sdrh ** 26101350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 26111350b030Sdrh ** 26121350b030Sdrh ** The code generated for this simpification gives the same result 2613832508b7Sdrh ** but only has to scan the data once. And because indices might 2614832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 2615832508b7Sdrh ** avoided. 26161350b030Sdrh ** 2617832508b7Sdrh ** Flattening is only attempted if all of the following are true: 26181350b030Sdrh ** 2619832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 26201350b030Sdrh ** 2621832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 2622832508b7Sdrh ** 26232b300d5dSdrh ** (3) The subquery is not the right operand of a left outer join 262449ad330dSdan ** (Originally ticket #306. Strengthened by ticket #3300) 2625832508b7Sdrh ** 262649ad330dSdan ** (4) The subquery is not DISTINCT. 2627832508b7Sdrh ** 262849ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 262949ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 263049ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 2631832508b7Sdrh ** 2632832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 2633832508b7Sdrh ** DISTINCT. 2634832508b7Sdrh ** 263508192d5fSdrh ** (7) The subquery has a FROM clause. 263608192d5fSdrh ** 2637df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 2638df199a25Sdrh ** 2639df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 2640df199a25Sdrh ** aggregates. 2641df199a25Sdrh ** 2642df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 2643df199a25Sdrh ** use LIMIT. 2644df199a25Sdrh ** 2645174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 2646174b6195Sdrh ** 26477b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 26482b300d5dSdrh ** a separate restriction deriving from ticket #350. 26493fc673e6Sdrh ** 265049ad330dSdan ** (13) The subquery and outer query do not both use LIMIT. 2651ac83963aSdrh ** 265249ad330dSdan ** (14) The subquery does not use OFFSET. 2653ac83963aSdrh ** 2654ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 2655f3913278Sdrh ** subquery does not have a LIMIT clause. 2656f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 2657ad91c6cdSdrh ** 2658c52e355dSdrh ** (16) The outer query is not an aggregate or the subquery does 2659c52e355dSdrh ** not contain ORDER BY. (Ticket #2942) This used to not matter 2660c52e355dSdrh ** until we introduced the group_concat() function. 2661c52e355dSdrh ** 2662f23329a2Sdanielk1977 ** (17) The sub-query is not a compound select, or it is a UNION ALL 26634914cf92Sdanielk1977 ** compound clause made up entirely of non-aggregate queries, and 2664f23329a2Sdanielk1977 ** the parent query: 2665f23329a2Sdanielk1977 ** 2666f23329a2Sdanielk1977 ** * is not itself part of a compound select, 2667f23329a2Sdanielk1977 ** * is not an aggregate or DISTINCT query, and 2668f23329a2Sdanielk1977 ** * has no other tables or sub-selects in the FROM clause. 2669f23329a2Sdanielk1977 ** 26704914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 26714914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 26724914cf92Sdanielk1977 ** LIMIT and OFFSET clauses. 2673f23329a2Sdanielk1977 ** 267449fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 267549fc1f60Sdanielk1977 ** ORDER by clause of the parent must be simple references to 267649fc1f60Sdanielk1977 ** columns of the sub-query. 267749fc1f60Sdanielk1977 ** 2678229cf702Sdrh ** (19) The subquery does not use LIMIT or the outer query does not 2679229cf702Sdrh ** have a WHERE clause. 2680229cf702Sdrh ** 2681e8902a70Sdrh ** (20) If the sub-query is a compound select, then it must not use 2682e8902a70Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 2683e8902a70Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 2684e8902a70Sdrh ** appear as unmodified result columns in the outer query. But 2685e8902a70Sdrh ** have other optimizations in mind to deal with that case. 2686e8902a70Sdrh ** 2687a91491e5Sshaneh ** (21) The subquery does not use LIMIT or the outer query is not 2688a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 2689a91491e5Sshaneh ** 2690832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 2691832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2692832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2693832508b7Sdrh ** 2694665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 2695832508b7Sdrh ** If flattening is attempted this routine returns 1. 2696832508b7Sdrh ** 2697832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 2698832508b7Sdrh ** the subquery before this routine runs. 26991350b030Sdrh */ 27008c74a8caSdrh static int flattenSubquery( 2701524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 27028c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 27038c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 27048c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 27058c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 27068c74a8caSdrh ){ 2707524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 2708f23329a2Sdanielk1977 Select *pParent; 27090bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2710f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 2711ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2712ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 27130bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 27146a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 271591bb0eedSdrh int i; /* Loop counter */ 271691bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 271791bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 2718524cc21eSdanielk1977 sqlite3 *db = pParse->db; 27191350b030Sdrh 2720832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2721832508b7Sdrh */ 2722a78c22c4Sdrh assert( p!=0 ); 2723a78c22c4Sdrh assert( p->pPrior==0 ); /* Unable to flatten compound queries */ 272407096f68Sdrh if( db->flags & SQLITE_QueryFlattener ) return 0; 2725832508b7Sdrh pSrc = p->pSrc; 2726ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 272791bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 272849fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 272991bb0eedSdrh pSub = pSubitem->pSelect; 2730832508b7Sdrh assert( pSub!=0 ); 2731ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2732ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2733832508b7Sdrh pSubSrc = pSub->pSrc; 2734832508b7Sdrh assert( pSubSrc ); 2735ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2736ac83963aSdrh ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2737ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 2738ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 2739ac83963aSdrh ** and (14). */ 2740ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2741ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 2742f3913278Sdrh if( p->pRightmost && pSub->pLimit ){ 2743ad91c6cdSdrh return 0; /* Restriction (15) */ 2744ad91c6cdSdrh } 2745ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 274649ad330dSdan if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ 274749ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 274849ad330dSdan return 0; /* Restrictions (8)(9) */ 2749df199a25Sdrh } 27507d10d5a6Sdrh if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ 27517d10d5a6Sdrh return 0; /* Restriction (6) */ 27527d10d5a6Sdrh } 27537d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 2754ac83963aSdrh return 0; /* Restriction (11) */ 2755ac83963aSdrh } 2756c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 2757229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 2758a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 2759a91491e5Sshaneh return 0; /* Restriction (21) */ 2760a91491e5Sshaneh } 2761832508b7Sdrh 27622b300d5dSdrh /* OBSOLETE COMMENT 1: 27632b300d5dSdrh ** Restriction 3: If the subquery is a join, make sure the subquery is 27648af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 27658af4d3acSdrh ** is not allowed: 27668af4d3acSdrh ** 27678af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 27688af4d3acSdrh ** 27698af4d3acSdrh ** If we flatten the above, we would get 27708af4d3acSdrh ** 27718af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 27728af4d3acSdrh ** 27738af4d3acSdrh ** which is not at all the same thing. 27742b300d5dSdrh ** 27752b300d5dSdrh ** OBSOLETE COMMENT 2: 27762b300d5dSdrh ** Restriction 12: If the subquery is the right operand of a left outer 27773fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 27783fc673e6Sdrh ** An examples of why this is not allowed: 27793fc673e6Sdrh ** 27803fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 27813fc673e6Sdrh ** 27823fc673e6Sdrh ** If we flatten the above, we would get 27833fc673e6Sdrh ** 27843fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 27853fc673e6Sdrh ** 27863fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 27873fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 27882b300d5dSdrh ** 27892b300d5dSdrh ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: 27902b300d5dSdrh ** Ticket #3300 shows that flattening the right term of a LEFT JOIN 27912b300d5dSdrh ** is fraught with danger. Best to avoid the whole thing. If the 27922b300d5dSdrh ** subquery is the right term of a LEFT JOIN, then do not flatten. 27933fc673e6Sdrh */ 27942b300d5dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 ){ 27953fc673e6Sdrh return 0; 27963fc673e6Sdrh } 27973fc673e6Sdrh 2798f23329a2Sdanielk1977 /* Restriction 17: If the sub-query is a compound SELECT, then it must 2799f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 2800f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 2801f23329a2Sdanielk1977 ** queries. 2802f23329a2Sdanielk1977 */ 2803f23329a2Sdanielk1977 if( pSub->pPrior ){ 2804e8902a70Sdrh if( pSub->pOrderBy ){ 2805e8902a70Sdrh return 0; /* Restriction 20 */ 2806e8902a70Sdrh } 2807e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 2808f23329a2Sdanielk1977 return 0; 2809f23329a2Sdanielk1977 } 2810f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 2811ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 2812ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 28137d10d5a6Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 281480b3c548Sdanielk1977 || (pSub1->pPrior && pSub1->op!=TK_ALL) 2815ccfcbceaSdrh || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1 281680b3c548Sdanielk1977 ){ 2817f23329a2Sdanielk1977 return 0; 2818f23329a2Sdanielk1977 } 2819f23329a2Sdanielk1977 } 282049fc1f60Sdanielk1977 282149fc1f60Sdanielk1977 /* Restriction 18. */ 282249fc1f60Sdanielk1977 if( p->pOrderBy ){ 282349fc1f60Sdanielk1977 int ii; 282449fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 28257d10d5a6Sdrh if( p->pOrderBy->a[ii].iCol==0 ) return 0; 282649fc1f60Sdanielk1977 } 282749fc1f60Sdanielk1977 } 2828f23329a2Sdanielk1977 } 2829f23329a2Sdanielk1977 28307d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 28317d10d5a6Sdrh 28327d10d5a6Sdrh /* Authorize the subquery */ 2833524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 2834524cc21eSdanielk1977 sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 2835524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 2836524cc21eSdanielk1977 28377d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 28387d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 28397d10d5a6Sdrh ** be of the form: 2840f23329a2Sdanielk1977 ** 2841f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 2842f23329a2Sdanielk1977 ** 2843f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 2844a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 2845f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 2846f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 2847f23329a2Sdanielk1977 ** select statements in the compound sub-query. 2848a78c22c4Sdrh ** 2849a78c22c4Sdrh ** Example: 2850a78c22c4Sdrh ** 2851a78c22c4Sdrh ** SELECT a+1 FROM ( 2852a78c22c4Sdrh ** SELECT x FROM tab 2853a78c22c4Sdrh ** UNION ALL 2854a78c22c4Sdrh ** SELECT y FROM tab 2855a78c22c4Sdrh ** UNION ALL 2856a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 2857a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 2858a78c22c4Sdrh ** 2859a78c22c4Sdrh ** Transformed into: 2860a78c22c4Sdrh ** 2861a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 2862a78c22c4Sdrh ** UNION ALL 2863a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 2864a78c22c4Sdrh ** UNION ALL 2865a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 2866a78c22c4Sdrh ** ORDER BY 1 2867a78c22c4Sdrh ** 2868a78c22c4Sdrh ** We call this the "compound-subquery flattening". 2869f23329a2Sdanielk1977 */ 2870f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 2871f23329a2Sdanielk1977 Select *pNew; 2872f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 28734b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 2874f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 2875f23329a2Sdanielk1977 p->pOrderBy = 0; 2876f23329a2Sdanielk1977 p->pSrc = 0; 2877f23329a2Sdanielk1977 p->pPrior = 0; 28784b86ef1dSdanielk1977 p->pLimit = 0; 28796ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 28804b86ef1dSdanielk1977 p->pLimit = pLimit; 2881a78c22c4Sdrh p->pOrderBy = pOrderBy; 2882a78c22c4Sdrh p->pSrc = pSrc; 2883a78c22c4Sdrh p->op = TK_ALL; 2884f23329a2Sdanielk1977 p->pRightmost = 0; 2885a78c22c4Sdrh if( pNew==0 ){ 2886a78c22c4Sdrh pNew = pPrior; 2887a78c22c4Sdrh }else{ 2888a78c22c4Sdrh pNew->pPrior = pPrior; 2889f23329a2Sdanielk1977 pNew->pRightmost = 0; 2890f23329a2Sdanielk1977 } 2891a78c22c4Sdrh p->pPrior = pNew; 2892a78c22c4Sdrh if( db->mallocFailed ) return 1; 2893a78c22c4Sdrh } 2894f23329a2Sdanielk1977 28957d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 28967d10d5a6Sdrh ** in the outer query. 2897832508b7Sdrh */ 2898f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 2899c31c2eb8Sdrh 2900a78c22c4Sdrh /* Delete the transient table structure associated with the 2901a78c22c4Sdrh ** subquery 2902a78c22c4Sdrh */ 2903a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 2904a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 2905a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 2906a78c22c4Sdrh pSubitem->zDatabase = 0; 2907a78c22c4Sdrh pSubitem->zName = 0; 2908a78c22c4Sdrh pSubitem->zAlias = 0; 2909a78c22c4Sdrh pSubitem->pSelect = 0; 2910a78c22c4Sdrh 2911a78c22c4Sdrh /* Defer deleting the Table object associated with the 2912a78c22c4Sdrh ** subquery until code generation is 2913a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 2914a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 2915ccfcbceaSdrh ** 2916ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 2917a78c22c4Sdrh */ 2918ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 2919a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 2920a78c22c4Sdrh if( pTabToDel->nRef==1 ){ 292165a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 292265a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 292365a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 2924a78c22c4Sdrh }else{ 2925a78c22c4Sdrh pTabToDel->nRef--; 2926a78c22c4Sdrh } 2927a78c22c4Sdrh pSubitem->pTab = 0; 2928a78c22c4Sdrh } 2929a78c22c4Sdrh 2930a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 2931a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 2932a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 2933a78c22c4Sdrh ** then this loop only runs once. 2934a78c22c4Sdrh ** 2935a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 2936c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2937c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2938c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2939c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2940c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2941c31c2eb8Sdrh ** elements we are now copying in. 2942c31c2eb8Sdrh */ 2943a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 2944a78c22c4Sdrh int nSubSrc; 2945ea678832Sdrh u8 jointype = 0; 2946a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 2947a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 2948a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 2949588a9a1aSdrh 2950a78c22c4Sdrh if( pSrc ){ 2951a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 2952a78c22c4Sdrh jointype = pSubitem->jointype; 2953588a9a1aSdrh }else{ 2954a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 2955a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 2956cfa063b3Sdrh if( pSrc==0 ){ 2957a78c22c4Sdrh assert( db->mallocFailed ); 2958a78c22c4Sdrh break; 2959cfa063b3Sdrh } 2960c31c2eb8Sdrh } 2961a78c22c4Sdrh 2962a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 2963a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 2964a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 2965a78c22c4Sdrh ** of the subquery. 2966a78c22c4Sdrh ** 2967a78c22c4Sdrh ** Example: 2968a78c22c4Sdrh ** 2969a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 2970a78c22c4Sdrh ** 2971a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 2972a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 2973a78c22c4Sdrh ** block of code will expand the out query to 4 slots. The middle 2974a78c22c4Sdrh ** slot is expanded to two slots in order to make space for the 2975a78c22c4Sdrh ** two elements in the FROM clause of the subquery. 2976a78c22c4Sdrh */ 2977a78c22c4Sdrh if( nSubSrc>1 ){ 2978a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 2979a78c22c4Sdrh if( db->mallocFailed ){ 2980a78c22c4Sdrh break; 2981c31c2eb8Sdrh } 2982c31c2eb8Sdrh } 2983a78c22c4Sdrh 2984a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 2985a78c22c4Sdrh ** outer query. 2986a78c22c4Sdrh */ 2987c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2988c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 2989c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2990c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2991c31c2eb8Sdrh } 299261dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 2993c31c2eb8Sdrh 2994c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2995c31c2eb8Sdrh ** references to the iParent in the outer query. 2996c31c2eb8Sdrh ** 2997c31c2eb8Sdrh ** Example: 2998c31c2eb8Sdrh ** 2999c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 3000c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 3001c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 3002c31c2eb8Sdrh ** 3003c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 3004c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 3005c31c2eb8Sdrh */ 3006f23329a2Sdanielk1977 pList = pParent->pEList; 3007832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 3008ccfcbceaSdrh if( pList->a[i].zName==0 ){ 3009b7916a78Sdrh const char *zSpan = pList->a[i].zSpan; 3010d6b8c434Sdrh if( ALWAYS(zSpan) ){ 3011b7916a78Sdrh pList->a[i].zName = sqlite3DbStrDup(db, zSpan); 3012832508b7Sdrh } 3013832508b7Sdrh } 3014ccfcbceaSdrh } 3015f23329a2Sdanielk1977 substExprList(db, pParent->pEList, iParent, pSub->pEList); 30161b2e0329Sdrh if( isAgg ){ 3017f23329a2Sdanielk1977 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList); 3018b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 30191b2e0329Sdrh } 3020174b6195Sdrh if( pSub->pOrderBy ){ 3021f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 3022f23329a2Sdanielk1977 pParent->pOrderBy = pSub->pOrderBy; 3023174b6195Sdrh pSub->pOrderBy = 0; 3024f23329a2Sdanielk1977 }else if( pParent->pOrderBy ){ 3025f23329a2Sdanielk1977 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList); 3026174b6195Sdrh } 3027832508b7Sdrh if( pSub->pWhere ){ 30286ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 3029832508b7Sdrh }else{ 3030832508b7Sdrh pWhere = 0; 3031832508b7Sdrh } 3032832508b7Sdrh if( subqueryIsAgg ){ 3033f23329a2Sdanielk1977 assert( pParent->pHaving==0 ); 3034f23329a2Sdanielk1977 pParent->pHaving = pParent->pWhere; 3035f23329a2Sdanielk1977 pParent->pWhere = pWhere; 3036b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 3037f23329a2Sdanielk1977 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 30386ab3a2ecSdanielk1977 sqlite3ExprDup(db, pSub->pHaving, 0)); 3039f23329a2Sdanielk1977 assert( pParent->pGroupBy==0 ); 30406ab3a2ecSdanielk1977 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); 3041832508b7Sdrh }else{ 3042b7916a78Sdrh pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList); 3043f23329a2Sdanielk1977 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); 3044832508b7Sdrh } 3045c31c2eb8Sdrh 3046c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 3047c31c2eb8Sdrh ** outer query is distinct. 3048c31c2eb8Sdrh */ 30497d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 30508c74a8caSdrh 3051a58fdfb1Sdanielk1977 /* 3052a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3053ac83963aSdrh ** 3054ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 3055ac83963aSdrh ** does not work if either limit is negative. 3056a58fdfb1Sdanielk1977 */ 3057a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 3058f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 3059a2dc3b1aSdanielk1977 pSub->pLimit = 0; 3060df199a25Sdrh } 3061f23329a2Sdanielk1977 } 30628c74a8caSdrh 3063c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 3064c31c2eb8Sdrh ** success. 3065c31c2eb8Sdrh */ 3066633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 3067f23329a2Sdanielk1977 3068832508b7Sdrh return 1; 30691350b030Sdrh } 30703514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 30711350b030Sdrh 30721350b030Sdrh /* 3073a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it 307408c88eb0Sdrh ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 3075a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be 3076a9d1ccb9Sdanielk1977 ** a min()/max() query if: 3077a9d1ccb9Sdanielk1977 ** 3078738bdcfbSdanielk1977 ** 1. There is a single object in the FROM clause. 3079738bdcfbSdanielk1977 ** 3080738bdcfbSdanielk1977 ** 2. There is a single expression in the result set, and it is 3081738bdcfbSdanielk1977 ** either min(x) or max(x), where x is a column reference. 3082a9d1ccb9Sdanielk1977 */ 30834f21c4afSdrh static u8 minMaxQuery(Select *p){ 3084a9d1ccb9Sdanielk1977 Expr *pExpr; 3085a9d1ccb9Sdanielk1977 ExprList *pEList = p->pEList; 3086a9d1ccb9Sdanielk1977 308708c88eb0Sdrh if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL; 3088a9d1ccb9Sdanielk1977 pExpr = pEList->a[0].pExpr; 308943152cf8Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 309043152cf8Sdrh if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0; 30916ab3a2ecSdanielk1977 pEList = pExpr->x.pList; 309243152cf8Sdrh if( pEList==0 || pEList->nExpr!=1 ) return 0; 309308c88eb0Sdrh if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL; 309433e619fcSdrh assert( !ExprHasProperty(pExpr, EP_IntValue) ); 309533e619fcSdrh if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){ 309608c88eb0Sdrh return WHERE_ORDERBY_MIN; 309733e619fcSdrh }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){ 309808c88eb0Sdrh return WHERE_ORDERBY_MAX; 3099a9d1ccb9Sdanielk1977 } 310008c88eb0Sdrh return WHERE_ORDERBY_NORMAL; 3101a9d1ccb9Sdanielk1977 } 3102a9d1ccb9Sdanielk1977 3103a9d1ccb9Sdanielk1977 /* 3104a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 3105a5533162Sdanielk1977 ** The second argment is the associated aggregate-info object. This 3106a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 3107a5533162Sdanielk1977 ** 3108a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 3109a5533162Sdanielk1977 ** 3110a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 3111a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 3112a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 3113a5533162Sdanielk1977 */ 3114a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 3115a5533162Sdanielk1977 Table *pTab; 3116a5533162Sdanielk1977 Expr *pExpr; 3117a5533162Sdanielk1977 3118a5533162Sdanielk1977 assert( !p->pGroupBy ); 3119a5533162Sdanielk1977 31207a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 3121a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 3122a5533162Sdanielk1977 ){ 3123a5533162Sdanielk1977 return 0; 3124a5533162Sdanielk1977 } 3125a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 3126a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 312702f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 312802f33725Sdanielk1977 312902f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 3130a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 3131a5533162Sdanielk1977 if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0; 3132a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 3133a5533162Sdanielk1977 3134a5533162Sdanielk1977 return pTab; 3135a5533162Sdanielk1977 } 3136a5533162Sdanielk1977 3137a5533162Sdanielk1977 /* 3138b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 3139b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 3140b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 3141b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 3142b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 3143b1c685b0Sdanielk1977 */ 3144b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 3145b1c685b0Sdanielk1977 if( pFrom->pTab && pFrom->zIndex ){ 3146b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 3147b1c685b0Sdanielk1977 char *zIndex = pFrom->zIndex; 3148b1c685b0Sdanielk1977 Index *pIdx; 3149b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 3150b1c685b0Sdanielk1977 pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 3151b1c685b0Sdanielk1977 pIdx=pIdx->pNext 3152b1c685b0Sdanielk1977 ); 3153b1c685b0Sdanielk1977 if( !pIdx ){ 3154b1c685b0Sdanielk1977 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0); 31551db95106Sdan pParse->checkSchema = 1; 3156b1c685b0Sdanielk1977 return SQLITE_ERROR; 3157b1c685b0Sdanielk1977 } 3158b1c685b0Sdanielk1977 pFrom->pIndex = pIdx; 3159b1c685b0Sdanielk1977 } 3160b1c685b0Sdanielk1977 return SQLITE_OK; 3161b1c685b0Sdanielk1977 } 3162b1c685b0Sdanielk1977 3163b1c685b0Sdanielk1977 /* 31647d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 31657d10d5a6Sdrh ** "Expanding" means to do the following: 31667d10d5a6Sdrh ** 31677d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 31687d10d5a6Sdrh ** element of the FROM clause. 31697d10d5a6Sdrh ** 31707d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 31717d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 31727d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 31737d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 31747d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 31757d10d5a6Sdrh ** without worrying about messing up the presistent representation 31767d10d5a6Sdrh ** of the view. 31777d10d5a6Sdrh ** 31787d10d5a6Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 31797d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 31807d10d5a6Sdrh ** 31817d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 31827d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 31837d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 31847d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 31857d10d5a6Sdrh ** 3186b3bce662Sdanielk1977 */ 31877d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 31887d10d5a6Sdrh Parse *pParse = pWalker->pParse; 31897d10d5a6Sdrh int i, j, k; 31907d10d5a6Sdrh SrcList *pTabList; 31917d10d5a6Sdrh ExprList *pEList; 31927d10d5a6Sdrh struct SrcList_item *pFrom; 31937d10d5a6Sdrh sqlite3 *db = pParse->db; 31947d10d5a6Sdrh 31957d10d5a6Sdrh if( db->mallocFailed ){ 31967d10d5a6Sdrh return WRC_Abort; 31977d10d5a6Sdrh } 319843152cf8Sdrh if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){ 31997d10d5a6Sdrh return WRC_Prune; 32007d10d5a6Sdrh } 32017d10d5a6Sdrh p->selFlags |= SF_Expanded; 32027d10d5a6Sdrh pTabList = p->pSrc; 32037d10d5a6Sdrh pEList = p->pEList; 32047d10d5a6Sdrh 32057d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 32067d10d5a6Sdrh ** the FROM clause of the SELECT statement. 32077d10d5a6Sdrh */ 32087d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 32097d10d5a6Sdrh 32107d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 32117d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 32127d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 32137d10d5a6Sdrh */ 32147d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 32157d10d5a6Sdrh Table *pTab; 32167d10d5a6Sdrh if( pFrom->pTab!=0 ){ 32177d10d5a6Sdrh /* This statement has already been prepared. There is no need 32187d10d5a6Sdrh ** to go further. */ 32197d10d5a6Sdrh assert( i==0 ); 32207d10d5a6Sdrh return WRC_Prune; 32217d10d5a6Sdrh } 32227d10d5a6Sdrh if( pFrom->zName==0 ){ 32237d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 32247d10d5a6Sdrh Select *pSel = pFrom->pSelect; 32257d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 32267d10d5a6Sdrh assert( pSel!=0 ); 32277d10d5a6Sdrh assert( pFrom->pTab==0 ); 32287d10d5a6Sdrh sqlite3WalkSelect(pWalker, pSel); 32297d10d5a6Sdrh pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 32307d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 32317d10d5a6Sdrh pTab->nRef = 1; 32327d10d5a6Sdrh pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab); 32337d10d5a6Sdrh while( pSel->pPrior ){ pSel = pSel->pPrior; } 32347d10d5a6Sdrh selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol); 32357d10d5a6Sdrh pTab->iPKey = -1; 32361ea87012Sdrh pTab->nRowEst = 1000000; 32377d10d5a6Sdrh pTab->tabFlags |= TF_Ephemeral; 32387d10d5a6Sdrh #endif 32397d10d5a6Sdrh }else{ 32407d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 32417d10d5a6Sdrh assert( pFrom->pTab==0 ); 32427d10d5a6Sdrh pFrom->pTab = pTab = 32437d10d5a6Sdrh sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase); 32447d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 32457d10d5a6Sdrh pTab->nRef++; 32467d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 32477d10d5a6Sdrh if( pTab->pSelect || IsVirtual(pTab) ){ 32487d10d5a6Sdrh /* We reach here if the named table is a really a view */ 32497d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 325043152cf8Sdrh assert( pFrom->pSelect==0 ); 32516ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 32527d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 32537d10d5a6Sdrh } 32547d10d5a6Sdrh #endif 32557d10d5a6Sdrh } 325685574e31Sdanielk1977 325785574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 3258b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 325985574e31Sdanielk1977 return WRC_Abort; 326085574e31Sdanielk1977 } 32617d10d5a6Sdrh } 32627d10d5a6Sdrh 32637d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 32647d10d5a6Sdrh */ 32657d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 32667d10d5a6Sdrh return WRC_Abort; 32677d10d5a6Sdrh } 32687d10d5a6Sdrh 32697d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 32707d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 32717d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 32727d10d5a6Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 32737d10d5a6Sdrh ** The following code just has to locate the TK_ALL expressions and expand 32747d10d5a6Sdrh ** each one to the list of all columns in all tables. 32757d10d5a6Sdrh ** 32767d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 32777d10d5a6Sdrh ** that need expanding. 32787d10d5a6Sdrh */ 32797d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 32807d10d5a6Sdrh Expr *pE = pEList->a[k].pExpr; 32817d10d5a6Sdrh if( pE->op==TK_ALL ) break; 328243152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 328343152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 328443152cf8Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; 32857d10d5a6Sdrh } 32867d10d5a6Sdrh if( k<pEList->nExpr ){ 32877d10d5a6Sdrh /* 32887d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 32897d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 32907d10d5a6Sdrh ** in the result set and expand them one by one. 32917d10d5a6Sdrh */ 32927d10d5a6Sdrh struct ExprList_item *a = pEList->a; 32937d10d5a6Sdrh ExprList *pNew = 0; 32947d10d5a6Sdrh int flags = pParse->db->flags; 32957d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 32967d10d5a6Sdrh && (flags & SQLITE_ShortColNames)==0; 32977d10d5a6Sdrh 32987d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 32997d10d5a6Sdrh Expr *pE = a[k].pExpr; 330043152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 330143152cf8Sdrh if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){ 33027d10d5a6Sdrh /* This particular expression does not need to be expanded. 33037d10d5a6Sdrh */ 3304b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 33057d10d5a6Sdrh if( pNew ){ 33067d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 3307b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 3308b7916a78Sdrh a[k].zName = 0; 3309b7916a78Sdrh a[k].zSpan = 0; 33107d10d5a6Sdrh } 33117d10d5a6Sdrh a[k].pExpr = 0; 33127d10d5a6Sdrh }else{ 33137d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 33147d10d5a6Sdrh ** expanded. */ 33157d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 33167d10d5a6Sdrh char *zTName; /* text of name of TABLE */ 331743152cf8Sdrh if( pE->op==TK_DOT ){ 331843152cf8Sdrh assert( pE->pLeft!=0 ); 331933e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 332033e619fcSdrh zTName = pE->pLeft->u.zToken; 33217d10d5a6Sdrh }else{ 33227d10d5a6Sdrh zTName = 0; 33237d10d5a6Sdrh } 33247d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 33257d10d5a6Sdrh Table *pTab = pFrom->pTab; 33267d10d5a6Sdrh char *zTabName = pFrom->zAlias; 332743152cf8Sdrh if( zTabName==0 ){ 33287d10d5a6Sdrh zTabName = pTab->zName; 33297d10d5a6Sdrh } 33307d10d5a6Sdrh if( db->mallocFailed ) break; 33317d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 33327d10d5a6Sdrh continue; 33337d10d5a6Sdrh } 33347d10d5a6Sdrh tableSeen = 1; 33357d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 33367d10d5a6Sdrh Expr *pExpr, *pRight; 33377d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 3338b7916a78Sdrh char *zColname; /* The computed column name */ 3339b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 3340b7916a78Sdrh Token sColname; /* Computed column name as a token */ 33417d10d5a6Sdrh 33427d10d5a6Sdrh /* If a column is marked as 'hidden' (currently only possible 33437d10d5a6Sdrh ** for virtual tables), do not include it in the expanded 33447d10d5a6Sdrh ** result-set list. 33457d10d5a6Sdrh */ 33467d10d5a6Sdrh if( IsHiddenColumn(&pTab->aCol[j]) ){ 33477d10d5a6Sdrh assert(IsVirtual(pTab)); 33487d10d5a6Sdrh continue; 33497d10d5a6Sdrh } 33507d10d5a6Sdrh 3351da55c48aSdrh if( i>0 && zTName==0 ){ 33522179b434Sdrh if( (pFrom->jointype & JT_NATURAL)!=0 33532179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 33542179b434Sdrh ){ 33557d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 33562179b434Sdrh ** table to the right of the join */ 33577d10d5a6Sdrh continue; 33587d10d5a6Sdrh } 33592179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 33607d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 33617d10d5a6Sdrh ** using clause from the table on the right. */ 33627d10d5a6Sdrh continue; 33637d10d5a6Sdrh } 33647d10d5a6Sdrh } 3365b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 3366b7916a78Sdrh zColname = zName; 3367b7916a78Sdrh zToFree = 0; 33687d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 3369b7916a78Sdrh Expr *pLeft; 3370b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 33717d10d5a6Sdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 3372b7916a78Sdrh if( longNames ){ 3373b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 3374b7916a78Sdrh zToFree = zColname; 3375b7916a78Sdrh } 33767d10d5a6Sdrh }else{ 33777d10d5a6Sdrh pExpr = pRight; 33787d10d5a6Sdrh } 3379b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 3380b7916a78Sdrh sColname.z = zColname; 3381b7916a78Sdrh sColname.n = sqlite3Strlen30(zColname); 3382b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 3383b7916a78Sdrh sqlite3DbFree(db, zToFree); 33847d10d5a6Sdrh } 33857d10d5a6Sdrh } 33867d10d5a6Sdrh if( !tableSeen ){ 33877d10d5a6Sdrh if( zTName ){ 33887d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 33897d10d5a6Sdrh }else{ 33907d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 33917d10d5a6Sdrh } 33927d10d5a6Sdrh } 33937d10d5a6Sdrh } 33947d10d5a6Sdrh } 33957d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 33967d10d5a6Sdrh p->pEList = pNew; 33977d10d5a6Sdrh } 33987d10d5a6Sdrh #if SQLITE_MAX_COLUMN 33997d10d5a6Sdrh if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 34007d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 34017d10d5a6Sdrh } 34027d10d5a6Sdrh #endif 34037d10d5a6Sdrh return WRC_Continue; 34047d10d5a6Sdrh } 34057d10d5a6Sdrh 34067d10d5a6Sdrh /* 34077d10d5a6Sdrh ** No-op routine for the parse-tree walker. 34087d10d5a6Sdrh ** 34097d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 34107d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 34117d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 34127d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 34137d10d5a6Sdrh ** subquery in the parser tree. 34147d10d5a6Sdrh */ 341562c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 341662c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 34177d10d5a6Sdrh return WRC_Continue; 34187d10d5a6Sdrh } 34197d10d5a6Sdrh 34207d10d5a6Sdrh /* 34217d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 34227d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 34237d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 34247d10d5a6Sdrh ** 34257d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 34267d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 34277d10d5a6Sdrh ** name resolution is performed. 34287d10d5a6Sdrh ** 34297d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 34307d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 34317d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 34327d10d5a6Sdrh */ 34337d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 34347d10d5a6Sdrh Walker w; 34357d10d5a6Sdrh w.xSelectCallback = selectExpander; 34367d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 34377d10d5a6Sdrh w.pParse = pParse; 34387d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 34397d10d5a6Sdrh } 34407d10d5a6Sdrh 34417d10d5a6Sdrh 34427d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 34437d10d5a6Sdrh /* 34447d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 34457d10d5a6Sdrh ** interface. 34467d10d5a6Sdrh ** 34477d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 34487d10d5a6Sdrh ** information to the Table structure that represents the result set 34497d10d5a6Sdrh ** of that subquery. 34507d10d5a6Sdrh ** 34517d10d5a6Sdrh ** The Table structure that represents the result set was constructed 34527d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 34537d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 34547d10d5a6Sdrh ** routine is called after identifier resolution. 34557d10d5a6Sdrh */ 34567d10d5a6Sdrh static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 34577d10d5a6Sdrh Parse *pParse; 34587d10d5a6Sdrh int i; 34597d10d5a6Sdrh SrcList *pTabList; 34607d10d5a6Sdrh struct SrcList_item *pFrom; 34617d10d5a6Sdrh 34629d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 34635a29d9cbSdrh if( (p->selFlags & SF_HasTypeInfo)==0 ){ 34647d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 34657d10d5a6Sdrh pParse = pWalker->pParse; 34667d10d5a6Sdrh pTabList = p->pSrc; 34677d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 34687d10d5a6Sdrh Table *pTab = pFrom->pTab; 346943152cf8Sdrh if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){ 34707d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 34717d10d5a6Sdrh Select *pSel = pFrom->pSelect; 34727d10d5a6Sdrh assert( pSel ); 34737d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 34747d10d5a6Sdrh selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel); 34757d10d5a6Sdrh } 34767d10d5a6Sdrh } 34775a29d9cbSdrh } 34787d10d5a6Sdrh return WRC_Continue; 34797d10d5a6Sdrh } 34807d10d5a6Sdrh #endif 34817d10d5a6Sdrh 34827d10d5a6Sdrh 34837d10d5a6Sdrh /* 34847d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 34857d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 34867d10d5a6Sdrh ** SELECT statement. 34877d10d5a6Sdrh ** 34887d10d5a6Sdrh ** Use this routine after name resolution. 34897d10d5a6Sdrh */ 34907d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 34917d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 34927d10d5a6Sdrh Walker w; 34937d10d5a6Sdrh w.xSelectCallback = selectAddSubqueryTypeInfo; 34947d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 34957d10d5a6Sdrh w.pParse = pParse; 34967d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 34977d10d5a6Sdrh #endif 34987d10d5a6Sdrh } 34997d10d5a6Sdrh 35007d10d5a6Sdrh 35017d10d5a6Sdrh /* 35027d10d5a6Sdrh ** This routine sets of a SELECT statement for processing. The 35037d10d5a6Sdrh ** following is accomplished: 35047d10d5a6Sdrh ** 35057d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 35067d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 35077d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 35087d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 35097d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 35107d10d5a6Sdrh ** 35117d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 35127d10d5a6Sdrh */ 35137d10d5a6Sdrh void sqlite3SelectPrep( 3514b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 3515b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 35167d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 3517b3bce662Sdanielk1977 ){ 35187d10d5a6Sdrh sqlite3 *db; 351943152cf8Sdrh if( NEVER(p==0) ) return; 35207d10d5a6Sdrh db = pParse->db; 35217d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 35227d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 35237d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 35247d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 35257d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 35267d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 3527f6bbe022Sdrh } 3528b3bce662Sdanielk1977 3529b3bce662Sdanielk1977 /* 353013449892Sdrh ** Reset the aggregate accumulator. 353113449892Sdrh ** 353213449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 353313449892Sdrh ** intermediate results while calculating an aggregate. This 353413449892Sdrh ** routine simply stores NULLs in all of those memory cells. 3535b3bce662Sdanielk1977 */ 353613449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 353713449892Sdrh Vdbe *v = pParse->pVdbe; 353813449892Sdrh int i; 3539c99130fdSdrh struct AggInfo_func *pFunc; 354013449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 354113449892Sdrh return; 354213449892Sdrh } 354313449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 35444c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); 354513449892Sdrh } 3546c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 35474c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); 3548c99130fdSdrh if( pFunc->iDistinct>=0 ){ 3549c99130fdSdrh Expr *pE = pFunc->pExpr; 35506ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 35516ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 35520daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 35530daa002cSdrh "argument"); 3554c99130fdSdrh pFunc->iDistinct = -1; 3555c99130fdSdrh }else{ 35566ab3a2ecSdanielk1977 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList); 355766a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 355866a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3559c99130fdSdrh } 3560c99130fdSdrh } 356113449892Sdrh } 3562b3bce662Sdanielk1977 } 3563b3bce662Sdanielk1977 3564b3bce662Sdanielk1977 /* 356513449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 356613449892Sdrh ** in the AggInfo structure. 3567b3bce662Sdanielk1977 */ 356813449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 356913449892Sdrh Vdbe *v = pParse->pVdbe; 357013449892Sdrh int i; 357113449892Sdrh struct AggInfo_func *pF; 357213449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 35736ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 35746ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 357566a5167bSdrh sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 357666a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 3577b3bce662Sdanielk1977 } 357813449892Sdrh } 357913449892Sdrh 358013449892Sdrh /* 358113449892Sdrh ** Update the accumulator memory cells for an aggregate based on 358213449892Sdrh ** the current cursor position. 358313449892Sdrh */ 358413449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 358513449892Sdrh Vdbe *v = pParse->pVdbe; 358613449892Sdrh int i; 358713449892Sdrh struct AggInfo_func *pF; 358813449892Sdrh struct AggInfo_col *pC; 358913449892Sdrh 359013449892Sdrh pAggInfo->directMode = 1; 3591ceea3321Sdrh sqlite3ExprCacheClear(pParse); 359213449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 359313449892Sdrh int nArg; 3594c99130fdSdrh int addrNext = 0; 359598757157Sdrh int regAgg; 35966ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 35976ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 359813449892Sdrh if( pList ){ 359913449892Sdrh nArg = pList->nExpr; 3600892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 36017153d1fbSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 1); 360213449892Sdrh }else{ 360313449892Sdrh nArg = 0; 360498757157Sdrh regAgg = 0; 360513449892Sdrh } 3606c99130fdSdrh if( pF->iDistinct>=0 ){ 3607c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 3608c99130fdSdrh assert( nArg==1 ); 36092dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 3610c99130fdSdrh } 3611e82f5d04Sdrh if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){ 361213449892Sdrh CollSeq *pColl = 0; 361313449892Sdrh struct ExprList_item *pItem; 361413449892Sdrh int j; 3615e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 361643617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 361713449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 361813449892Sdrh } 361913449892Sdrh if( !pColl ){ 362013449892Sdrh pColl = pParse->db->pDfltColl; 362113449892Sdrh } 362266a5167bSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 362313449892Sdrh } 362498757157Sdrh sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 362566a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 3626ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 3627da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 3628f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 3629c99130fdSdrh if( addrNext ){ 3630c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 3631ceea3321Sdrh sqlite3ExprCacheClear(pParse); 3632c99130fdSdrh } 363313449892Sdrh } 363467a6a40cSdan 363567a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 363667a6a40cSdan ** Otherwise, if any of the required column values are already present 363767a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 363867a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 363967a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 364067a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 364167a6a40cSdan ** 364267a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 364367a6a40cSdan ** values to an OP_Copy. 364467a6a40cSdan */ 364567a6a40cSdan sqlite3ExprCacheClear(pParse); 364613449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 3647389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 364813449892Sdrh } 364913449892Sdrh pAggInfo->directMode = 0; 3650ceea3321Sdrh sqlite3ExprCacheClear(pParse); 365113449892Sdrh } 365213449892Sdrh 3653b3bce662Sdanielk1977 /* 3654ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 3655ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 3656ef7075deSdan */ 3657ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 3658ef7075deSdan static void explainSimpleCount( 3659ef7075deSdan Parse *pParse, /* Parse context */ 3660ef7075deSdan Table *pTab, /* Table being queried */ 3661ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 3662ef7075deSdan ){ 3663ef7075deSdan if( pParse->explain==2 ){ 3664ef7075deSdan char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)", 3665ef7075deSdan pTab->zName, 3666ef7075deSdan pIdx ? "USING COVERING INDEX " : "", 3667ef7075deSdan pIdx ? pIdx->zName : "", 3668ef7075deSdan pTab->nRowEst 3669ef7075deSdan ); 3670ef7075deSdan sqlite3VdbeAddOp4( 3671ef7075deSdan pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC 3672ef7075deSdan ); 3673ef7075deSdan } 3674ef7075deSdan } 3675ef7075deSdan #else 3676ef7075deSdan # define explainSimpleCount(a,b,c) 3677ef7075deSdan #endif 3678ef7075deSdan 3679ef7075deSdan /* 36807d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 36819bb61fe7Sdrh ** 3682fef5208cSdrh ** The results are distributed in various ways depending on the 36836c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest 36846c8c8ce0Sdanielk1977 ** as follows: 3685fef5208cSdrh ** 36866c8c8ce0Sdanielk1977 ** pDest->eDest Result 3687fef5208cSdrh ** ------------ ------------------------------------------- 36887d10d5a6Sdrh ** SRT_Output Generate a row of output (using the OP_ResultRow 36897d10d5a6Sdrh ** opcode) for each row in the result set. 3690fef5208cSdrh ** 36917d10d5a6Sdrh ** SRT_Mem Only valid if the result is a single column. 36927d10d5a6Sdrh ** Store the first column of the first result row 36937d10d5a6Sdrh ** in register pDest->iParm then abandon the rest 36947d10d5a6Sdrh ** of the query. This destination implies "LIMIT 1". 3695fef5208cSdrh ** 36967d10d5a6Sdrh ** SRT_Set The result must be a single column. Store each 36977d10d5a6Sdrh ** row of result as the key in table pDest->iParm. 36987d10d5a6Sdrh ** Apply the affinity pDest->affinity before storing 36997d10d5a6Sdrh ** results. Used to implement "IN (SELECT ...)". 3700fef5208cSdrh ** 37016c8c8ce0Sdanielk1977 ** SRT_Union Store results as a key in a temporary table pDest->iParm. 370282c3d636Sdrh ** 37036c8c8ce0Sdanielk1977 ** SRT_Except Remove results from the temporary table pDest->iParm. 3704c4a3c779Sdrh ** 37057d10d5a6Sdrh ** SRT_Table Store results in temporary table pDest->iParm. 37067d10d5a6Sdrh ** This is like SRT_EphemTab except that the table 37077d10d5a6Sdrh ** is assumed to already be open. 37089bb61fe7Sdrh ** 37096c8c8ce0Sdanielk1977 ** SRT_EphemTab Create an temporary table pDest->iParm and store 37106c8c8ce0Sdanielk1977 ** the result there. The cursor is left open after 37117d10d5a6Sdrh ** returning. This is like SRT_Table except that 37127d10d5a6Sdrh ** this destination uses OP_OpenEphemeral to create 37137d10d5a6Sdrh ** the table first. 37146c8c8ce0Sdanielk1977 ** 37157d10d5a6Sdrh ** SRT_Coroutine Generate a co-routine that returns a new row of 37167d10d5a6Sdrh ** results each time it is invoked. The entry point 37177d10d5a6Sdrh ** of the co-routine is stored in register pDest->iParm. 37186c8c8ce0Sdanielk1977 ** 37196c8c8ce0Sdanielk1977 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result 37206c8c8ce0Sdanielk1977 ** set is not empty. 37216c8c8ce0Sdanielk1977 ** 37227d10d5a6Sdrh ** SRT_Discard Throw the results away. This is used by SELECT 37237d10d5a6Sdrh ** statements within triggers whose only purpose is 37247d10d5a6Sdrh ** the side-effects of functions. 3725e78e8284Sdrh ** 37269bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 37279bb61fe7Sdrh ** encountered, then an appropriate error message is left in 37289bb61fe7Sdrh ** pParse->zErrMsg. 37299bb61fe7Sdrh ** 37309bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 37319bb61fe7Sdrh ** calling function needs to do that. 37329bb61fe7Sdrh */ 37334adee20fSdanielk1977 int sqlite3Select( 3734cce7d176Sdrh Parse *pParse, /* The parser context */ 37359bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 37367d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 3737cce7d176Sdrh ){ 373813449892Sdrh int i, j; /* Loop counters */ 373913449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 374013449892Sdrh Vdbe *v; /* The virtual machine under construction */ 3741b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 3742a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 3743ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 37449bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 37459bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 37462282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 37472282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 374819a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 374919a775c2Sdrh int distinct; /* Table to use for the distinct set */ 37501d83f052Sdrh int rc = 1; /* Value to return from this function */ 3751b9bb7c18Sdrh int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 375238cc40c2Sdan int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */ 375313449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 3754ec7429aeSdrh int iEnd; /* Address of the end of the query */ 375517435752Sdrh sqlite3 *db; /* The database connection */ 37569bb61fe7Sdrh 37572ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 37582ce22453Sdan int iRestoreSelectId = pParse->iSelectId; 37592ce22453Sdan pParse->iSelectId = pParse->iNextSelectId++; 37602ce22453Sdan #endif 37612ce22453Sdan 376217435752Sdrh db = pParse->db; 376317435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 37646f7adc8aSdrh return 1; 37656f7adc8aSdrh } 37664adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 376713449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 3768daffd0e5Sdrh 37696c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 37709ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 37719ed1dfa8Sdanielk1977 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); 3772ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 3773ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 3774ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 3775ccfcbceaSdrh p->pOrderBy = 0; 37767d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 37779a99334dSdrh } 37787d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 3779ccfcbceaSdrh pOrderBy = p->pOrderBy; 3780b27b7f5dSdrh pTabList = p->pSrc; 3781b27b7f5dSdrh pEList = p->pEList; 3782956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 37839a99334dSdrh goto select_end; 37849a99334dSdrh } 37857d10d5a6Sdrh isAgg = (p->selFlags & SF_Aggregate)!=0; 378643152cf8Sdrh assert( pEList!=0 ); 3787cce7d176Sdrh 3788d820cb1bSdrh /* Begin generating code. 3789d820cb1bSdrh */ 37904adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 3791d820cb1bSdrh if( v==0 ) goto select_end; 3792d820cb1bSdrh 379374b617b2Sdan /* If writing to memory or generating a set 379474b617b2Sdan ** only a single column may be output. 379574b617b2Sdan */ 379674b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY 379774b617b2Sdan if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 379874b617b2Sdan goto select_end; 379974b617b2Sdan } 380074b617b2Sdan #endif 380174b617b2Sdan 3802d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 3803d820cb1bSdrh */ 380451522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3805f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 380613449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 38071013c932Sdrh SelectDest dest; 3808daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 3809f23329a2Sdanielk1977 int isAggSub; 3810c31c2eb8Sdrh 38115b6a9ed4Sdrh if( pSub==0 ) continue; 38125b6a9ed4Sdrh if( pItem->addrFillSub ){ 38135b6a9ed4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 38145b6a9ed4Sdrh continue; 38155b6a9ed4Sdrh } 3816daf79acbSdanielk1977 3817fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 3818fc976065Sdanielk1977 ** tree refered to by this, the parent select. The child select 3819fc976065Sdanielk1977 ** may contain expression trees of at most 3820fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 3821fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 3822fc976065Sdanielk1977 ** an exact limit. 3823fc976065Sdanielk1977 */ 3824fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 3825daf79acbSdanielk1977 38267d10d5a6Sdrh isAggSub = (pSub->selFlags & SF_Aggregate)!=0; 3827524cc21eSdanielk1977 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ 38285b6a9ed4Sdrh /* This subquery can be absorbed into its parent. */ 3829f23329a2Sdanielk1977 if( isAggSub ){ 38307d10d5a6Sdrh isAgg = 1; 38317d10d5a6Sdrh p->selFlags |= SF_Aggregate; 3832daf79acbSdanielk1977 } 3833daf79acbSdanielk1977 i = -1; 3834daf79acbSdanielk1977 }else{ 38355b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 38365b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 38375b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 38385b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 38395b6a9ed4Sdrh */ 38407157e8eaSdrh int topAddr; 384148f2d3b1Sdrh int onceAddr = 0; 38427157e8eaSdrh int retAddr; 38435b6a9ed4Sdrh assert( pItem->addrFillSub==0 ); 38445b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 38457157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 38467157e8eaSdrh pItem->addrFillSub = topAddr+1; 38477157e8eaSdrh VdbeNoopComment((v, "materialize %s", pItem->pTab->zName)); 38485b6a9ed4Sdrh if( pItem->isCorrelated==0 && pParse->pTriggerTab==0 ){ 38495b6a9ed4Sdrh /* If the subquery is no correlated and if we are not inside of 38505b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 38515b6a9ed4Sdrh ** once. */ 385248f2d3b1Sdrh int regOnce = ++pParse->nMem; 385348f2d3b1Sdrh onceAddr = sqlite3VdbeAddOp1(v, OP_Once, regOnce); 38545b6a9ed4Sdrh } 38551013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 3856ce7e189dSdan explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 38577d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 385895aa47b1Sdrh pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow; 385948f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 38607157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 38617157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 38627157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 3863cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 3864daf79acbSdanielk1977 } 386543152cf8Sdrh if( /*pParse->nErr ||*/ db->mallocFailed ){ 3866cfa063b3Sdrh goto select_end; 3867cfa063b3Sdrh } 3868fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 3869832508b7Sdrh pTabList = p->pSrc; 38706c8c8ce0Sdanielk1977 if( !IgnorableOrderby(pDest) ){ 3871832508b7Sdrh pOrderBy = p->pOrderBy; 3872acd4c695Sdrh } 3873daf79acbSdanielk1977 } 3874daf79acbSdanielk1977 pEList = p->pEList; 3875daf79acbSdanielk1977 #endif 3876daf79acbSdanielk1977 pWhere = p->pWhere; 3877832508b7Sdrh pGroupBy = p->pGroupBy; 3878832508b7Sdrh pHaving = p->pHaving; 38797d10d5a6Sdrh isDistinct = (p->selFlags & SF_Distinct)!=0; 3880832508b7Sdrh 3881f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3882f23329a2Sdanielk1977 /* If there is are a sequence of queries, do the earlier ones first. 3883f23329a2Sdanielk1977 */ 3884f23329a2Sdanielk1977 if( p->pPrior ){ 3885f23329a2Sdanielk1977 if( p->pRightmost==0 ){ 3886f23329a2Sdanielk1977 Select *pLoop, *pRight = 0; 3887f23329a2Sdanielk1977 int cnt = 0; 3888f23329a2Sdanielk1977 int mxSelect; 3889f23329a2Sdanielk1977 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 3890f23329a2Sdanielk1977 pLoop->pRightmost = p; 3891f23329a2Sdanielk1977 pLoop->pNext = pRight; 3892f23329a2Sdanielk1977 pRight = pLoop; 3893f23329a2Sdanielk1977 } 3894f23329a2Sdanielk1977 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; 3895f23329a2Sdanielk1977 if( mxSelect && cnt>mxSelect ){ 3896f23329a2Sdanielk1977 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 38972ce22453Sdan goto select_end; 3898f23329a2Sdanielk1977 } 3899f23329a2Sdanielk1977 } 39007f61e92cSdan rc = multiSelect(pParse, p, pDest); 390117c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 39027f61e92cSdan return rc; 3903f23329a2Sdanielk1977 } 3904f23329a2Sdanielk1977 #endif 3905f23329a2Sdanielk1977 39068c6f666bSdrh /* If there is both a GROUP BY and an ORDER BY clause and they are 39078c6f666bSdrh ** identical, then disable the ORDER BY clause since the GROUP BY 39088c6f666bSdrh ** will cause elements to come out in the correct order. This is 39098c6f666bSdrh ** an optimization - the correct answer should result regardless. 39108c6f666bSdrh ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER 39118c6f666bSdrh ** to disable this optimization for testing purposes. 39128c6f666bSdrh */ 39138c6f666bSdrh if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0 39148c6f666bSdrh && (db->flags & SQLITE_GroupByOrder)==0 ){ 39158c6f666bSdrh pOrderBy = 0; 39168c6f666bSdrh } 39178c6f666bSdrh 391850118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 391950118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 392050118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 392150118cdfSdan ** 392250118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 392350118cdfSdan ** 392450118cdfSdan ** is transformed to: 392550118cdfSdan ** 392650118cdfSdan ** SELECT xyz FROM ... GROUP BY xyz 392750118cdfSdan ** 392850118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 392950118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 393050118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 393150118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 393250118cdfSdan */ 393350118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 393450118cdfSdan && sqlite3ExprListCompare(pOrderBy, p->pEList)==0 393550118cdfSdan ){ 393650118cdfSdan p->selFlags &= ~SF_Distinct; 393750118cdfSdan p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0); 393850118cdfSdan pGroupBy = p->pGroupBy; 393950118cdfSdan pOrderBy = 0; 394050118cdfSdan } 394150118cdfSdan 39428b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 39438b4c40d8Sdrh ** index might end up being unused if the data can be 39449d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 3945b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 39469d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 39479d2985c7Sdrh ** variable is used to facilitate that change. 39487cedc8d4Sdanielk1977 */ 39497cedc8d4Sdanielk1977 if( pOrderBy ){ 39500342b1f5Sdrh KeyInfo *pKeyInfo; 39510342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 39529d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 3953b9bb7c18Sdrh p->addrOpenEphm[2] = addrSortIndex = 395466a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 395566a5167bSdrh pOrderBy->iECursor, pOrderBy->nExpr+2, 0, 395666a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 39579d2985c7Sdrh }else{ 39589d2985c7Sdrh addrSortIndex = -1; 39597cedc8d4Sdanielk1977 } 39607cedc8d4Sdanielk1977 39612d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 39622d0794e3Sdrh */ 39636c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 396466a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr); 39652d0794e3Sdrh } 39662d0794e3Sdrh 3967f42bacc2Sdrh /* Set the limiter. 3968f42bacc2Sdrh */ 3969f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 397095aa47b1Sdrh p->nSelectRow = (double)LARGEST_INT64; 3971f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 3972c6aff30cSdrh if( p->iLimit==0 && addrSortIndex>=0 ){ 3973c6aff30cSdrh sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen; 3974c6aff30cSdrh p->selFlags |= SF_UseSorter; 3975c6aff30cSdrh } 3976f42bacc2Sdrh 3977dece1a84Sdrh /* Open a virtual index to use for the distinct set. 3978cce7d176Sdrh */ 39792ce22453Sdan if( p->selFlags & SF_Distinct ){ 39800342b1f5Sdrh KeyInfo *pKeyInfo; 3981832508b7Sdrh distinct = pParse->nTab++; 39820342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 398338cc40c2Sdan addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0, 398466a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3985d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 3986832508b7Sdrh }else{ 3987ec661058Sdrh distinct = addrDistinctIndex = -1; 3988efb7251dSdrh } 3989832508b7Sdrh 399013449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 399113449892Sdrh if( !isAgg && pGroupBy==0 ){ 399238cc40c2Sdan ExprList *pDist = (isDistinct ? p->pEList : 0); 399338cc40c2Sdan 399438cc40c2Sdan /* Begin the database scan. */ 399538cc40c2Sdan pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0); 39961d83f052Sdrh if( pWInfo==0 ) goto select_end; 399795aa47b1Sdrh if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut; 3998cce7d176Sdrh 3999b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 4000b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 40019d2985c7Sdrh ** into an OP_Noop. 40029d2985c7Sdrh */ 40039d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 400448f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortIndex); 4005b9bb7c18Sdrh p->addrOpenEphm[2] = -1; 40069d2985c7Sdrh } 40079d2985c7Sdrh 400838cc40c2Sdan if( pWInfo->eDistinct ){ 400950118cdfSdan VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 401050118cdfSdan 401154bbe7f1Sdan assert( addrDistinctIndex>=0 ); 401250118cdfSdan pOp = sqlite3VdbeGetOp(v, addrDistinctIndex); 401350118cdfSdan 401438cc40c2Sdan assert( isDistinct ); 401538cc40c2Sdan assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED 401638cc40c2Sdan || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE 401738cc40c2Sdan ); 401838cc40c2Sdan distinct = -1; 401938cc40c2Sdan if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){ 402038cc40c2Sdan int iJump; 402138cc40c2Sdan int iExpr; 402238cc40c2Sdan int iFlag = ++pParse->nMem; 402338cc40c2Sdan int iBase = pParse->nMem+1; 402438cc40c2Sdan int iBase2 = iBase + pEList->nExpr; 402538cc40c2Sdan pParse->nMem += (pEList->nExpr*2); 402638cc40c2Sdan 402738cc40c2Sdan /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The 402838cc40c2Sdan ** OP_Integer initializes the "first row" flag. */ 402938cc40c2Sdan pOp->opcode = OP_Integer; 403038cc40c2Sdan pOp->p1 = 1; 403138cc40c2Sdan pOp->p2 = iFlag; 403238cc40c2Sdan 403338cc40c2Sdan sqlite3ExprCodeExprList(pParse, pEList, iBase, 1); 403438cc40c2Sdan iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1; 403538cc40c2Sdan sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1); 403638cc40c2Sdan for(iExpr=0; iExpr<pEList->nExpr; iExpr++){ 403738cc40c2Sdan CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr); 403838cc40c2Sdan sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr); 403938cc40c2Sdan sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 404038cc40c2Sdan sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 404138cc40c2Sdan } 404238cc40c2Sdan sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue); 404338cc40c2Sdan 404438cc40c2Sdan sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag); 404538cc40c2Sdan assert( sqlite3VdbeCurrentAddr(v)==iJump ); 404638cc40c2Sdan sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr); 404750118cdfSdan }else{ 404850118cdfSdan pOp->opcode = OP_Noop; 404938cc40c2Sdan } 405038cc40c2Sdan } 405138cc40c2Sdan 405238cc40c2Sdan /* Use the standard inner loop. */ 405338cc40c2Sdan selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest, 4054a9671a22Sdrh pWInfo->iContinue, pWInfo->iBreak); 40552282792aSdrh 4056cce7d176Sdrh /* End the database scan loop. 4057cce7d176Sdrh */ 40584adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 405913449892Sdrh }else{ 406013449892Sdrh /* This is the processing for aggregate queries */ 406113449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 406213449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 406313449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 406413449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 406513449892Sdrh ** one row of the input to the aggregator has been 406613449892Sdrh ** processed */ 406713449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 406813449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 4069d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 40701c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 40711c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 4072d176611bSdrh 4073d176611bSdrh /* Remove any and all aliases between the result set and the 4074d176611bSdrh ** GROUP BY clause. 4075d176611bSdrh */ 4076d176611bSdrh if( pGroupBy ){ 4077dc5ea5c7Sdrh int k; /* Loop counter */ 4078d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 4079d176611bSdrh 4080dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 4081d176611bSdrh pItem->iAlias = 0; 4082d176611bSdrh } 4083dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 4084d176611bSdrh pItem->iAlias = 0; 4085d176611bSdrh } 408695aa47b1Sdrh if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100; 408795aa47b1Sdrh }else{ 408895aa47b1Sdrh p->nSelectRow = (double)1; 4089d176611bSdrh } 4090cce7d176Sdrh 409113449892Sdrh 4092d176611bSdrh /* Create a label to jump to when we want to abort the query */ 409313449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 409413449892Sdrh 409513449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 409613449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 409713449892Sdrh ** SELECT statement. 40982282792aSdrh */ 409913449892Sdrh memset(&sNC, 0, sizeof(sNC)); 410013449892Sdrh sNC.pParse = pParse; 410113449892Sdrh sNC.pSrcList = pTabList; 410213449892Sdrh sNC.pAggInfo = &sAggInfo; 410313449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 41049d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 4105d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 4106d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); 4107d2b3e23bSdrh if( pHaving ){ 4108d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 410913449892Sdrh } 411013449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 411113449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 41126ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 41136ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 411413449892Sdrh } 411517435752Sdrh if( db->mallocFailed ) goto select_end; 411613449892Sdrh 411713449892Sdrh /* Processing for aggregates with GROUP BY is very different and 41183c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 411913449892Sdrh */ 412013449892Sdrh if( pGroupBy ){ 412113449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 4122d176611bSdrh int j1; /* A-vs-B comparision jump */ 4123d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 4124d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 4125d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 4126d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 4127d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 4128d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 4129d176611bSdrh int regReset; /* Return address register for reset subroutine */ 413013449892Sdrh 413113449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 413213449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 41331c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 413413449892Sdrh ** will be converted into a Noop. 413513449892Sdrh */ 413613449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 413713449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 41381c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 4139cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 4140cd3e8f7cSdanielk1977 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 414113449892Sdrh 414213449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 414313449892Sdrh */ 41440a07c107Sdrh iUseFlag = ++pParse->nMem; 41450a07c107Sdrh iAbortFlag = ++pParse->nMem; 4146d176611bSdrh regOutputRow = ++pParse->nMem; 4147d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 4148d176611bSdrh regReset = ++pParse->nMem; 4149d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 41500a07c107Sdrh iAMem = pParse->nMem + 1; 415113449892Sdrh pParse->nMem += pGroupBy->nExpr; 41520a07c107Sdrh iBMem = pParse->nMem + 1; 415313449892Sdrh pParse->nMem += pGroupBy->nExpr; 41544c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 4155d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 41564c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 4157d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 4158e313382eSdrh 415913449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 416013449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 416113449892Sdrh ** it might be a single loop that uses an index to extract information 416213449892Sdrh ** in the right order to begin with. 416313449892Sdrh */ 41642eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 416538cc40c2Sdan pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0); 41665360ad34Sdrh if( pWInfo==0 ) goto select_end; 416713449892Sdrh if( pGroupBy==0 ){ 416813449892Sdrh /* The optimizer is able to deliver rows in group by order so 4169b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 417013449892Sdrh ** cancelled later because we still need to use the pKeyInfo 417113449892Sdrh */ 417213449892Sdrh pGroupBy = p->pGroupBy; 417313449892Sdrh groupBySort = 0; 417413449892Sdrh }else{ 417513449892Sdrh /* Rows are coming out in undetermined order. We have to push 417613449892Sdrh ** each row into a sorting index, terminate the first loop, 417713449892Sdrh ** then loop over the sorting index in order to get the output 417813449892Sdrh ** in sorted order 417913449892Sdrh */ 4180892d3179Sdrh int regBase; 4181892d3179Sdrh int regRecord; 4182892d3179Sdrh int nCol; 4183892d3179Sdrh int nGroupBy; 4184892d3179Sdrh 41852ce22453Sdan explainTempTable(pParse, 41862ce22453Sdan isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY"); 41872ce22453Sdan 418813449892Sdrh groupBySort = 1; 4189892d3179Sdrh nGroupBy = pGroupBy->nExpr; 4190892d3179Sdrh nCol = nGroupBy + 1; 4191892d3179Sdrh j = nGroupBy+1; 419213449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 4193892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 4194892d3179Sdrh nCol++; 419513449892Sdrh j++; 419613449892Sdrh } 4197892d3179Sdrh } 4198892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 4199ceea3321Sdrh sqlite3ExprCacheClear(pParse); 4200191b54cbSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); 4201892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); 4202892d3179Sdrh j = nGroupBy+1; 4203892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 4204892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 4205892d3179Sdrh if( pCol->iSorterColumn>=j ){ 4206e55cbd72Sdrh int r1 = j + regBase; 42076a012f04Sdrh int r2; 4208701bb3b4Sdrh 42096a012f04Sdrh r2 = sqlite3ExprCodeGetColumn(pParse, 4210b6da74ebSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1); 42116a012f04Sdrh if( r1!=r2 ){ 42126a012f04Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); 42136a012f04Sdrh } 42146a012f04Sdrh j++; 4215892d3179Sdrh } 4216892d3179Sdrh } 4217892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 42181db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 42191c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 4220892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 4221892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 422213449892Sdrh sqlite3WhereEnd(pWInfo); 42235134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 42241c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 42251c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 42261c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 4227d4e70ebdSdrh VdbeComment((v, "GROUP BY sort")); 422813449892Sdrh sAggInfo.useSortingIdx = 1; 4229ceea3321Sdrh sqlite3ExprCacheClear(pParse); 423013449892Sdrh } 423113449892Sdrh 423213449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 423313449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 423413449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 423513449892Sdrh ** from the previous row currently stored in a0, a1, a2... 423613449892Sdrh */ 423713449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 4238ceea3321Sdrh sqlite3ExprCacheClear(pParse); 42391c9d835dSdrh if( groupBySort ){ 42401c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut); 42411c9d835dSdrh } 424213449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 424313449892Sdrh if( groupBySort ){ 42441c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 42451c9d835dSdrh if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 424613449892Sdrh }else{ 424713449892Sdrh sAggInfo.directMode = 1; 42482dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 424913449892Sdrh } 425013449892Sdrh } 425116ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 4252b21e7c70Sdrh (char*)pKeyInfo, P4_KEYINFO); 425316ee60ffSdrh j1 = sqlite3VdbeCurrentAddr(v); 425416ee60ffSdrh sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); 425513449892Sdrh 425613449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 4257e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 425813449892Sdrh ** block. If there were no changes, this block is skipped. 425913449892Sdrh ** 426013449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 426113449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 426213449892Sdrh ** and resets the aggregate accumulator registers in preparation 426313449892Sdrh ** for the next GROUP BY batch. 426413449892Sdrh */ 4265b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 42662eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 4267d4e70ebdSdrh VdbeComment((v, "output one row")); 42683c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); 4269d4e70ebdSdrh VdbeComment((v, "check abort flag")); 42702eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 4271d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 427213449892Sdrh 427313449892Sdrh /* Update the aggregate accumulators based on the content of 427413449892Sdrh ** the current row 427513449892Sdrh */ 427616ee60ffSdrh sqlite3VdbeJumpHere(v, j1); 427713449892Sdrh updateAccumulator(pParse, &sAggInfo); 42784c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 4279d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 428013449892Sdrh 428113449892Sdrh /* End of the loop 428213449892Sdrh */ 428313449892Sdrh if( groupBySort ){ 42841c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 428513449892Sdrh }else{ 428613449892Sdrh sqlite3WhereEnd(pWInfo); 428748f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 428813449892Sdrh } 428913449892Sdrh 429013449892Sdrh /* Output the final row of result 429113449892Sdrh */ 42922eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 4293d4e70ebdSdrh VdbeComment((v, "output final row")); 429413449892Sdrh 4295d176611bSdrh /* Jump over the subroutines 4296d176611bSdrh */ 4297d176611bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd); 4298d176611bSdrh 4299d176611bSdrh /* Generate a subroutine that outputs a single row of the result 4300d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 4301d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 4302d176611bSdrh ** the processing calls for the query to abort, this subroutine 4303d176611bSdrh ** increments the iAbortFlag memory location before returning in 4304d176611bSdrh ** order to signal the caller to abort. 4305d176611bSdrh */ 4306d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 4307d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 4308d176611bSdrh VdbeComment((v, "set abort flag")); 4309d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4310d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 4311d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 4312d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 4313d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 4314d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4315d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 4316d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 4317d176611bSdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 4318d176611bSdrh distinct, pDest, 4319d176611bSdrh addrOutputRow+1, addrSetAbort); 4320d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4321d176611bSdrh VdbeComment((v, "end groupby result generator")); 4322d176611bSdrh 4323d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 4324d176611bSdrh */ 4325d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 4326d176611bSdrh resetAccumulator(pParse, &sAggInfo); 4327d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 4328d176611bSdrh 432943152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 433013449892Sdrh else { 4331dba0137eSdanielk1977 ExprList *pDel = 0; 4332a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 4333a5533162Sdanielk1977 Table *pTab; 4334a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 4335a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 4336a5533162Sdanielk1977 ** the SQL statement is of the form: 4337a5533162Sdanielk1977 ** 4338a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 4339a5533162Sdanielk1977 ** 4340a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 4341a5533162Sdanielk1977 ** 4342a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 4343a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 4344a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 4345a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 4346a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 4347a5533162Sdanielk1977 */ 4348a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 4349a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 4350a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 4351a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 4352a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 4353a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 4354a9d1ccb9Sdanielk1977 4355a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 4356a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 4357a5533162Sdanielk1977 4358a5533162Sdanielk1977 /* Search for the index that has the least amount of columns. If 4359a5533162Sdanielk1977 ** there is such an index, and it has less columns than the table 4360a5533162Sdanielk1977 ** does, then we can assume that it consumes less space on disk and 4361a5533162Sdanielk1977 ** will therefore be cheaper to scan to determine the query result. 4362a5533162Sdanielk1977 ** In this case set iRoot to the root page number of the index b-tree 4363a5533162Sdanielk1977 ** and pKeyInfo to the KeyInfo structure required to navigate the 4364a5533162Sdanielk1977 ** index. 4365a5533162Sdanielk1977 ** 43663e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 43673e9548b3Sdrh ** 4368a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 4369a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 4370a5533162Sdanielk1977 */ 4371a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 43723e9548b3Sdrh if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){ 4373a5533162Sdanielk1977 pBest = pIdx; 4374a5533162Sdanielk1977 } 4375a5533162Sdanielk1977 } 4376a5533162Sdanielk1977 if( pBest && pBest->nColumn<pTab->nCol ){ 4377a5533162Sdanielk1977 iRoot = pBest->tnum; 4378a5533162Sdanielk1977 pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest); 4379a5533162Sdanielk1977 } 4380a5533162Sdanielk1977 4381a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 4382a5533162Sdanielk1977 sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb); 4383a5533162Sdanielk1977 if( pKeyInfo ){ 4384a5533162Sdanielk1977 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF); 4385a5533162Sdanielk1977 } 4386a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 4387a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 4388ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 4389a5533162Sdanielk1977 }else 4390a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 4391a5533162Sdanielk1977 { 4392738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 4393738bdcfbSdanielk1977 ** 4394738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 4395738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 4396738bdcfbSdanielk1977 ** 4397738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 4398738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 4399738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 4400738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 4401738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 4402738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 4403738bdcfbSdanielk1977 ** value of x, the only row required). 4404738bdcfbSdanielk1977 ** 4405738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 4406738bdcfbSdanielk1977 ** modify behaviour as follows: 4407738bdcfbSdanielk1977 ** 4408738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 4409738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 4410738bdcfbSdanielk1977 ** for x. 4411738bdcfbSdanielk1977 ** 4412738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 4413738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 4414738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 4415738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 4416738bdcfbSdanielk1977 */ 4417a5533162Sdanielk1977 ExprList *pMinMax = 0; 4418a5533162Sdanielk1977 u8 flag = minMaxQuery(p); 4419a9d1ccb9Sdanielk1977 if( flag ){ 44206ab3a2ecSdanielk1977 assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) ); 44216ab3a2ecSdanielk1977 pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0); 44226ab3a2ecSdanielk1977 pDel = pMinMax; 44230e359b30Sdrh if( pMinMax && !db->mallocFailed ){ 4424ea678832Sdrh pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; 4425a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 4426a9d1ccb9Sdanielk1977 } 44271013c932Sdrh } 4428a9d1ccb9Sdanielk1977 442913449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 443013449892Sdrh ** processing is much simpler since there is only a single row 443113449892Sdrh ** of output. 443213449892Sdrh */ 443313449892Sdrh resetAccumulator(pParse, &sAggInfo); 443438cc40c2Sdan pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag); 4435dba0137eSdanielk1977 if( pWInfo==0 ){ 4436633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 4437dba0137eSdanielk1977 goto select_end; 4438dba0137eSdanielk1977 } 443913449892Sdrh updateAccumulator(pParse, &sAggInfo); 4440a9d1ccb9Sdanielk1977 if( !pMinMax && flag ){ 4441a9d1ccb9Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); 4442a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 4443a5533162Sdanielk1977 (flag==WHERE_ORDERBY_MIN?"min":"max"))); 4444a9d1ccb9Sdanielk1977 } 444513449892Sdrh sqlite3WhereEnd(pWInfo); 444613449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 44477a895a80Sdanielk1977 } 44487a895a80Sdanielk1977 444913449892Sdrh pOrderBy = 0; 445035573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 445113449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 4452a9671a22Sdrh pDest, addrEnd, addrEnd); 4453633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 445413449892Sdrh } 445513449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 445613449892Sdrh 445713449892Sdrh } /* endif aggregate query */ 44582282792aSdrh 44592ce22453Sdan if( distinct>=0 ){ 44602ce22453Sdan explainTempTable(pParse, "DISTINCT"); 44612ce22453Sdan } 44622ce22453Sdan 4463cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 4464cce7d176Sdrh ** and send them to the callback one by one. 4465cce7d176Sdrh */ 4466cce7d176Sdrh if( pOrderBy ){ 44672ce22453Sdan explainTempTable(pParse, "ORDER BY"); 44686c8c8ce0Sdanielk1977 generateSortTail(pParse, p, v, pEList->nExpr, pDest); 4469cce7d176Sdrh } 44706a535340Sdrh 4471ec7429aeSdrh /* Jump here to skip this query 4472ec7429aeSdrh */ 4473ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 4474ec7429aeSdrh 44751d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 44761d83f052Sdrh ** to indicate no errors. 44771d83f052Sdrh */ 44781d83f052Sdrh rc = 0; 44791d83f052Sdrh 44801d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 44811d83f052Sdrh ** successful coding of the SELECT. 44821d83f052Sdrh */ 44831d83f052Sdrh select_end: 448417c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 4485955de52cSdanielk1977 44867d10d5a6Sdrh /* Identify column names if results of the SELECT are to be output. 4487955de52cSdanielk1977 */ 44887d10d5a6Sdrh if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ 4489955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 4490955de52cSdanielk1977 } 4491955de52cSdanielk1977 4492633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 4493633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 44941d83f052Sdrh return rc; 4495cce7d176Sdrh } 4496485f0039Sdrh 449777a2a5e7Sdrh #if defined(SQLITE_DEBUG) 4498485f0039Sdrh /* 44997e02e5e6Sdrh ** Generate a human-readable description of a the Select object. 4500485f0039Sdrh */ 4501a84203a0Sdrh static void explainOneSelect(Vdbe *pVdbe, Select *p){ 45027e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "SELECT "); 4503*4e2a9c32Sdrh if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ 4504*4e2a9c32Sdrh if( p->selFlags & SF_Distinct ){ 4505*4e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, "DISTINCT "); 4506*4e2a9c32Sdrh } 4507*4e2a9c32Sdrh if( p->selFlags & SF_Aggregate ){ 4508*4e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, "agg_flag "); 4509*4e2a9c32Sdrh } 4510*4e2a9c32Sdrh sqlite3ExplainNL(pVdbe); 4511*4e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, " "); 4512*4e2a9c32Sdrh } 45137e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pEList); 45147e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 45157e02e5e6Sdrh if( p->pSrc && p->pSrc->nSrc ){ 4516485f0039Sdrh int i; 45177e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "FROM "); 45187e02e5e6Sdrh sqlite3ExplainPush(pVdbe); 4519485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 4520485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 452104b8342bSdrh sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor); 4522485f0039Sdrh if( pItem->pSelect ){ 45237e02e5e6Sdrh sqlite3ExplainSelect(pVdbe, pItem->pSelect); 452404b8342bSdrh if( pItem->pTab ){ 452504b8342bSdrh sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName); 452604b8342bSdrh } 4527485f0039Sdrh }else if( pItem->zName ){ 45287e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName); 4529485f0039Sdrh } 453004b8342bSdrh if( pItem->zAlias ){ 453104b8342bSdrh sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias); 4532a84203a0Sdrh } 4533a84203a0Sdrh if( pItem->jointype & JT_LEFT ){ 4534a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN"); 4535485f0039Sdrh } 45367e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4537485f0039Sdrh } 45387e02e5e6Sdrh sqlite3ExplainPop(pVdbe); 4539485f0039Sdrh } 4540485f0039Sdrh if( p->pWhere ){ 45417e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "WHERE "); 45427e02e5e6Sdrh sqlite3ExplainExpr(pVdbe, p->pWhere); 45437e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4544485f0039Sdrh } 4545485f0039Sdrh if( p->pGroupBy ){ 45467e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "GROUPBY "); 45477e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pGroupBy); 45487e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4549485f0039Sdrh } 4550485f0039Sdrh if( p->pHaving ){ 45517e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "HAVING "); 45527e02e5e6Sdrh sqlite3ExplainExpr(pVdbe, p->pHaving); 45537e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4554485f0039Sdrh } 4555485f0039Sdrh if( p->pOrderBy ){ 45567e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "ORDERBY "); 45577e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pOrderBy); 45587e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4559485f0039Sdrh } 4560a84203a0Sdrh if( p->pLimit ){ 4561a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "LIMIT "); 4562a84203a0Sdrh sqlite3ExplainExpr(pVdbe, p->pLimit); 4563a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4564a84203a0Sdrh } 4565a84203a0Sdrh if( p->pOffset ){ 4566a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "OFFSET "); 4567a84203a0Sdrh sqlite3ExplainExpr(pVdbe, p->pOffset); 4568a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4569a84203a0Sdrh } 4570a84203a0Sdrh } 4571a84203a0Sdrh void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){ 4572a84203a0Sdrh if( p==0 ){ 4573a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "(null-select)"); 4574a84203a0Sdrh return; 4575a84203a0Sdrh } 4576a84203a0Sdrh while( p->pPrior ) p = p->pPrior; 4577a84203a0Sdrh sqlite3ExplainPush(pVdbe); 4578a84203a0Sdrh while( p ){ 4579a84203a0Sdrh explainOneSelect(pVdbe, p); 4580a84203a0Sdrh p = p->pNext; 4581a84203a0Sdrh if( p==0 ) break; 4582a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4583a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op)); 4584a84203a0Sdrh } 45857e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "END"); 4586a84203a0Sdrh sqlite3ExplainPop(pVdbe); 4587485f0039Sdrh } 45887e02e5e6Sdrh 4589485f0039Sdrh /* End of the structure debug printing code 4590485f0039Sdrh *****************************************************************************/ 4591485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ 4592