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; 767b113babSdrh if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc)); 779bb61fe7Sdrh pNew->pSrc = pSrc; 789bb61fe7Sdrh pNew->pWhere = pWhere; 799bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 809bb61fe7Sdrh pNew->pHaving = pHaving; 819bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 827d10d5a6Sdrh pNew->selFlags = isDistinct ? SF_Distinct : 0; 8382c3d636Sdrh pNew->op = TK_SELECT; 84a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 85a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 86373cc2ddSdrh assert( pOffset==0 || pLimit!=0 ); 87b9bb7c18Sdrh pNew->addrOpenEphm[0] = -1; 88b9bb7c18Sdrh pNew->addrOpenEphm[1] = -1; 89b9bb7c18Sdrh pNew->addrOpenEphm[2] = -1; 900a846f96Sdrh if( db->mallocFailed ) { 91633e6d57Sdrh clearSelect(db, pNew); 920a846f96Sdrh if( pNew!=&standin ) sqlite3DbFree(db, pNew); 93eda639e1Sdrh pNew = 0; 94a464c234Sdrh }else{ 95a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 96daffd0e5Sdrh } 97338ec3e1Sdrh assert( pNew!=&standin ); 989bb61fe7Sdrh return pNew; 999bb61fe7Sdrh } 1009bb61fe7Sdrh 1019bb61fe7Sdrh /* 102eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 103eda639e1Sdrh */ 104633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 105eda639e1Sdrh if( p ){ 106633e6d57Sdrh clearSelect(db, p); 107633e6d57Sdrh sqlite3DbFree(db, p); 108eda639e1Sdrh } 109eda639e1Sdrh } 110eda639e1Sdrh 111eda639e1Sdrh /* 11201f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 11301f3f253Sdrh ** type of join. Return an integer constant that expresses that type 11401f3f253Sdrh ** in terms of the following bit values: 11501f3f253Sdrh ** 11601f3f253Sdrh ** JT_INNER 1173dec223cSdrh ** JT_CROSS 11801f3f253Sdrh ** JT_OUTER 11901f3f253Sdrh ** JT_NATURAL 12001f3f253Sdrh ** JT_LEFT 12101f3f253Sdrh ** JT_RIGHT 12201f3f253Sdrh ** 12301f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 12401f3f253Sdrh ** 12501f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 12601f3f253Sdrh ** a join type, but put an error in the pParse structure. 12701f3f253Sdrh */ 1284adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 12901f3f253Sdrh int jointype = 0; 13001f3f253Sdrh Token *apAll[3]; 13101f3f253Sdrh Token *p; 132373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 133373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 1345719628aSdrh static const struct { 135373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 136373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 137373cc2ddSdrh u8 code; /* Join type mask */ 138373cc2ddSdrh } aKeyword[] = { 139373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 140373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 141373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 142373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 143373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 144373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 145373cc2ddSdrh /* cross */ { 28, 5, JT_INNER|JT_CROSS }, 14601f3f253Sdrh }; 14701f3f253Sdrh int i, j; 14801f3f253Sdrh apAll[0] = pA; 14901f3f253Sdrh apAll[1] = pB; 15001f3f253Sdrh apAll[2] = pC; 151195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 15201f3f253Sdrh p = apAll[i]; 153373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 154373cc2ddSdrh if( p->n==aKeyword[j].nChar 155373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 156373cc2ddSdrh jointype |= aKeyword[j].code; 15701f3f253Sdrh break; 15801f3f253Sdrh } 15901f3f253Sdrh } 160373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 161373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 16201f3f253Sdrh jointype |= JT_ERROR; 16301f3f253Sdrh break; 16401f3f253Sdrh } 16501f3f253Sdrh } 166ad2d8307Sdrh if( 167ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 168195e6967Sdrh (jointype & JT_ERROR)!=0 169ad2d8307Sdrh ){ 170a9671a22Sdrh const char *zSp = " "; 171a9671a22Sdrh assert( pB!=0 ); 172a9671a22Sdrh if( pC==0 ){ zSp++; } 173ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 174a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 17501f3f253Sdrh jointype = JT_INNER; 176373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 177373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 1784adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 179da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 180195e6967Sdrh jointype = JT_INNER; 18101f3f253Sdrh } 18201f3f253Sdrh return jointype; 18301f3f253Sdrh } 18401f3f253Sdrh 18501f3f253Sdrh /* 186ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 187ad2d8307Sdrh ** is not contained in the table. 188ad2d8307Sdrh */ 189ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 190ad2d8307Sdrh int i; 191ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1924adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 193ad2d8307Sdrh } 194ad2d8307Sdrh return -1; 195ad2d8307Sdrh } 196ad2d8307Sdrh 197ad2d8307Sdrh /* 1982179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 1992179b434Sdrh ** table that has a column named zCol. 2002179b434Sdrh ** 2012179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 2022179b434Sdrh ** of the matching column and return TRUE. 2032179b434Sdrh ** 2042179b434Sdrh ** If not found, return FALSE. 2052179b434Sdrh */ 2062179b434Sdrh static int tableAndColumnIndex( 2072179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 2082179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 2092179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 2102179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 2112179b434Sdrh int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 2122179b434Sdrh ){ 2132179b434Sdrh int i; /* For looping over tables in pSrc */ 2142179b434Sdrh int iCol; /* Index of column matching zCol */ 2152179b434Sdrh 2162179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 2172179b434Sdrh for(i=0; i<N; i++){ 2182179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 2192179b434Sdrh if( iCol>=0 ){ 2202179b434Sdrh if( piTab ){ 2212179b434Sdrh *piTab = i; 2222179b434Sdrh *piCol = iCol; 2232179b434Sdrh } 2242179b434Sdrh return 1; 2252179b434Sdrh } 2262179b434Sdrh } 2272179b434Sdrh return 0; 2282179b434Sdrh } 2292179b434Sdrh 2302179b434Sdrh /* 231f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 232f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 233f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 234f7b0b0adSdan ** 235f7b0b0adSdan ** (tab1.col1 = tab2.col2) 236f7b0b0adSdan ** 237f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 238f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 239f7b0b0adSdan ** column iColRight of tab2. 240ad2d8307Sdrh */ 241ad2d8307Sdrh static void addWhereTerm( 24217435752Sdrh Parse *pParse, /* Parsing context */ 243f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 2442179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 245f7b0b0adSdan int iColLeft, /* Index of column in first table */ 2462179b434Sdrh int iRight, /* Index of second table in pSrc */ 247f7b0b0adSdan int iColRight, /* Index of column in second table */ 248f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 249f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 250ad2d8307Sdrh ){ 251f7b0b0adSdan sqlite3 *db = pParse->db; 252f7b0b0adSdan Expr *pE1; 253f7b0b0adSdan Expr *pE2; 254f7b0b0adSdan Expr *pEq; 255ad2d8307Sdrh 2562179b434Sdrh assert( iLeft<iRight ); 2572179b434Sdrh assert( pSrc->nSrc>iRight ); 2582179b434Sdrh assert( pSrc->a[iLeft].pTab ); 2592179b434Sdrh assert( pSrc->a[iRight].pTab ); 260f7b0b0adSdan 2612179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 2622179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 263f7b0b0adSdan 264f7b0b0adSdan pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0); 265f7b0b0adSdan if( pEq && isOuterJoin ){ 266f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 267f7b0b0adSdan assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) ); 268f7b0b0adSdan ExprSetIrreducible(pEq); 269f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 270030530deSdrh } 271f7b0b0adSdan *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); 272ad2d8307Sdrh } 273ad2d8307Sdrh 274ad2d8307Sdrh /* 2751f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 27622d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 27722d6a53aSdrh ** expression. 2781cc093c2Sdrh ** 279e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 2801cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 2811f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 2821f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 2831f16230bSdrh ** WHERE clause during join processing but we need to remember that they 2841f16230bSdrh ** originated in the ON or USING clause. 28522d6a53aSdrh ** 28622d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 28722d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 28822d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 28922d6a53aSdrh ** for cases like this: 29022d6a53aSdrh ** 29122d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 29222d6a53aSdrh ** 29322d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 29422d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 29522d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 29622d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 29722d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 29822d6a53aSdrh ** the output, which is incorrect. 2991cc093c2Sdrh */ 30022d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 3011cc093c2Sdrh while( p ){ 3021f16230bSdrh ExprSetProperty(p, EP_FromJoin); 30333e619fcSdrh assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) ); 30433e619fcSdrh ExprSetIrreducible(p); 305cf697396Sshane p->iRightJoinTable = (i16)iTable; 30622d6a53aSdrh setJoinExpr(p->pLeft, iTable); 3071cc093c2Sdrh p = p->pRight; 3081cc093c2Sdrh } 3091cc093c2Sdrh } 3101cc093c2Sdrh 3111cc093c2Sdrh /* 312ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 313ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 314ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 315ad2d8307Sdrh ** 31691bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 31791bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 31891bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 31991bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 32091bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 32191bb0eedSdrh ** also attached to the left entry. 32291bb0eedSdrh ** 323ad2d8307Sdrh ** This routine returns the number of errors encountered. 324ad2d8307Sdrh */ 325ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 32691bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 32791bb0eedSdrh int i, j; /* Loop counters */ 32891bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 32991bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 330ad2d8307Sdrh 33191bb0eedSdrh pSrc = p->pSrc; 33291bb0eedSdrh pLeft = &pSrc->a[0]; 33391bb0eedSdrh pRight = &pLeft[1]; 33491bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 33591bb0eedSdrh Table *pLeftTab = pLeft->pTab; 33691bb0eedSdrh Table *pRightTab = pRight->pTab; 337ad27e761Sdrh int isOuter; 33891bb0eedSdrh 3391c767f0dSdrh if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; 340ad27e761Sdrh isOuter = (pRight->jointype & JT_OUTER)!=0; 341ad2d8307Sdrh 342ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 343ad2d8307Sdrh ** every column that the two tables have in common. 344ad2d8307Sdrh */ 34561dfc31dSdrh if( pRight->jointype & JT_NATURAL ){ 34661dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 3474adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 348ad2d8307Sdrh "an ON or USING clause", 0); 349ad2d8307Sdrh return 1; 350ad2d8307Sdrh } 3512179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 3522179b434Sdrh char *zName; /* Name of column in the right table */ 3532179b434Sdrh int iLeft; /* Matching left table */ 3542179b434Sdrh int iLeftCol; /* Matching column in the left table */ 3552179b434Sdrh 3562179b434Sdrh zName = pRightTab->aCol[j].zName; 3572179b434Sdrh if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ 3582179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 3592179b434Sdrh isOuter, &p->pWhere); 360ad2d8307Sdrh } 361ad2d8307Sdrh } 362ad2d8307Sdrh } 363ad2d8307Sdrh 364ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 365ad2d8307Sdrh */ 36661dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 3674adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 368da93d238Sdrh "clauses in the same join"); 369ad2d8307Sdrh return 1; 370ad2d8307Sdrh } 371ad2d8307Sdrh 372ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 37391bb0eedSdrh ** an AND operator. 374ad2d8307Sdrh */ 37561dfc31dSdrh if( pRight->pOn ){ 376ad27e761Sdrh if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 37717435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 37861dfc31dSdrh pRight->pOn = 0; 379ad2d8307Sdrh } 380ad2d8307Sdrh 381ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 382ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 383ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 384ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 385ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 386ad2d8307Sdrh ** not contained in both tables to be joined. 387ad2d8307Sdrh */ 38861dfc31dSdrh if( pRight->pUsing ){ 38961dfc31dSdrh IdList *pList = pRight->pUsing; 390ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 3912179b434Sdrh char *zName; /* Name of the term in the USING clause */ 3922179b434Sdrh int iLeft; /* Table on the left with matching column name */ 3932179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 3942179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 3952179b434Sdrh 3962179b434Sdrh zName = pList->a[j].zName; 3972179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 3982179b434Sdrh if( iRightCol<0 3992179b434Sdrh || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) 4002179b434Sdrh ){ 4014adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 40291bb0eedSdrh "not present in both tables", zName); 403ad2d8307Sdrh return 1; 404ad2d8307Sdrh } 4052179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 4062179b434Sdrh isOuter, &p->pWhere); 407ad2d8307Sdrh } 408ad2d8307Sdrh } 409ad2d8307Sdrh } 410ad2d8307Sdrh return 0; 411ad2d8307Sdrh } 412ad2d8307Sdrh 413ad2d8307Sdrh /* 414c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 415c926afbcSdrh ** stack into the sorter. 416c926afbcSdrh */ 417d59ba6ceSdrh static void pushOntoSorter( 418d59ba6ceSdrh Parse *pParse, /* Parser context */ 419d59ba6ceSdrh ExprList *pOrderBy, /* The ORDER BY clause */ 420b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 421b7654111Sdrh int regData /* Register holding data to be sorted */ 422d59ba6ceSdrh ){ 423d59ba6ceSdrh Vdbe *v = pParse->pVdbe; 424892d3179Sdrh int nExpr = pOrderBy->nExpr; 425892d3179Sdrh int regBase = sqlite3GetTempRange(pParse, nExpr+2); 426892d3179Sdrh int regRecord = sqlite3GetTempReg(pParse); 427c6aff30cSdrh int op; 428ceea3321Sdrh sqlite3ExprCacheClear(pParse); 429191b54cbSdrh sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0); 430892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); 431b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1); 4321db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord); 433c6aff30cSdrh if( pSelect->selFlags & SF_UseSorter ){ 434c6aff30cSdrh op = OP_SorterInsert; 435c6aff30cSdrh }else{ 436c6aff30cSdrh op = OP_IdxInsert; 437c6aff30cSdrh } 438c6aff30cSdrh sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord); 439892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 440892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nExpr+2); 44192b01d53Sdrh if( pSelect->iLimit ){ 44215007a99Sdrh int addr1, addr2; 443b7654111Sdrh int iLimit; 4440acb7e48Sdrh if( pSelect->iOffset ){ 445b7654111Sdrh iLimit = pSelect->iOffset+1; 446b7654111Sdrh }else{ 447b7654111Sdrh iLimit = pSelect->iLimit; 448b7654111Sdrh } 449b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); 450b7654111Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); 4513c84ddffSdrh addr2 = sqlite3VdbeAddOp0(v, OP_Goto); 452d59ba6ceSdrh sqlite3VdbeJumpHere(v, addr1); 4533c84ddffSdrh sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); 4543c84ddffSdrh sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); 45515007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 456d59ba6ceSdrh } 457c926afbcSdrh } 458c926afbcSdrh 459c926afbcSdrh /* 460ec7429aeSdrh ** Add code to implement the OFFSET 461ea48eb2eSdrh */ 462ec7429aeSdrh static void codeOffset( 463bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 464ea48eb2eSdrh Select *p, /* The SELECT statement being coded */ 465b7654111Sdrh int iContinue /* Jump here to skip the current record */ 466ea48eb2eSdrh ){ 46792b01d53Sdrh if( p->iOffset && iContinue!=0 ){ 46815007a99Sdrh int addr; 4698558cde1Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1); 4703c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset); 47166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); 472d4e70ebdSdrh VdbeComment((v, "skip OFFSET records")); 47315007a99Sdrh sqlite3VdbeJumpHere(v, addr); 474ea48eb2eSdrh } 475ea48eb2eSdrh } 476ea48eb2eSdrh 477ea48eb2eSdrh /* 47898757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 47998757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 480a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 481a2a49dc9Sdrh ** if the current N values are new. 482a2a49dc9Sdrh ** 483a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 484a2a49dc9Sdrh ** stack if the top N elements are not distinct. 485a2a49dc9Sdrh */ 486a2a49dc9Sdrh static void codeDistinct( 4872dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 488a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 489a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 490477df4b3Sdrh int N, /* Number of elements */ 491a2a49dc9Sdrh int iMem /* First element */ 492a2a49dc9Sdrh ){ 4932dcef11bSdrh Vdbe *v; 4942dcef11bSdrh int r1; 4952dcef11bSdrh 4962dcef11bSdrh v = pParse->pVdbe; 4972dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 49891fc4a0cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); 4991db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 5002dcef11bSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); 5012dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 502a2a49dc9Sdrh } 503a2a49dc9Sdrh 504bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY 505a2a49dc9Sdrh /* 506e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression 507e305f43fSdrh ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 508bb7dd683Sdrh ** column. We do this in a subroutine because the error used to occur 509bb7dd683Sdrh ** in multiple places. (The error only occurs in one place now, but we 510bb7dd683Sdrh ** retain the subroutine to minimize code disruption.) 511e305f43fSdrh */ 5126c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError( 5136c8c8ce0Sdanielk1977 Parse *pParse, /* Parse context. */ 5146c8c8ce0Sdanielk1977 SelectDest *pDest, /* Destination of SELECT results */ 5156c8c8ce0Sdanielk1977 int nExpr /* Number of result columns returned by SELECT */ 5166c8c8ce0Sdanielk1977 ){ 5176c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 518e305f43fSdrh if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 519e305f43fSdrh sqlite3ErrorMsg(pParse, "only a single result allowed for " 520e305f43fSdrh "a SELECT that is part of an expression"); 521e305f43fSdrh return 1; 522e305f43fSdrh }else{ 523e305f43fSdrh return 0; 524e305f43fSdrh } 525e305f43fSdrh } 526bb7dd683Sdrh #endif 527c99130fdSdrh 528c99130fdSdrh /* 5292282792aSdrh ** This routine generates the code for the inside of the inner loop 5302282792aSdrh ** of a SELECT. 53182c3d636Sdrh ** 53238640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 53338640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 53438640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 53538640e15Sdrh ** datatypes for each column. 5362282792aSdrh */ 537d2b3e23bSdrh static void selectInnerLoop( 5382282792aSdrh Parse *pParse, /* The parser context */ 539df199a25Sdrh Select *p, /* The complete select statement being coded */ 5402282792aSdrh ExprList *pEList, /* List of values being extracted */ 54182c3d636Sdrh int srcTab, /* Pull data from this table */ 542967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 5432282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 5442282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 5456c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 5462282792aSdrh int iContinue, /* Jump here to continue with next row */ 547a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 5482282792aSdrh ){ 5492282792aSdrh Vdbe *v = pParse->pVdbe; 550d847eaadSdrh int i; 551ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 552d847eaadSdrh int regResult; /* Start of memory holding result set */ 553d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 554d847eaadSdrh int iParm = pDest->iParm; /* First argument to disposal method */ 555d847eaadSdrh int nResultCol; /* Number of result columns */ 55638640e15Sdrh 5571c767f0dSdrh assert( v ); 5581c767f0dSdrh if( NEVER(v==0) ) return; 55938640e15Sdrh assert( pEList!=0 ); 560e49b146fSdrh hasDistinct = distinct>=0; 561ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 562b7654111Sdrh codeOffset(v, p, iContinue); 563df199a25Sdrh } 564df199a25Sdrh 565967e8b73Sdrh /* Pull the requested columns. 5662282792aSdrh */ 56738640e15Sdrh if( nColumn>0 ){ 568d847eaadSdrh nResultCol = nColumn; 569a2a49dc9Sdrh }else{ 570d847eaadSdrh nResultCol = pEList->nExpr; 571a2a49dc9Sdrh } 5721ece7325Sdrh if( pDest->iMem==0 ){ 5730acb7e48Sdrh pDest->iMem = pParse->nMem+1; 574ad27e761Sdrh pDest->nMem = nResultCol; 5750acb7e48Sdrh pParse->nMem += nResultCol; 5761c767f0dSdrh }else{ 5771c767f0dSdrh assert( pDest->nMem==nResultCol ); 5781013c932Sdrh } 5791ece7325Sdrh regResult = pDest->iMem; 580a2a49dc9Sdrh if( nColumn>0 ){ 581967e8b73Sdrh for(i=0; i<nColumn; i++){ 582d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 58382c3d636Sdrh } 5849ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 5859ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 5869ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 5879ed1dfa8Sdanielk1977 */ 588ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5897d10d5a6Sdrh sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output); 590a2a49dc9Sdrh } 591d847eaadSdrh nColumn = nResultCol; 5922282792aSdrh 593daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 594daffd0e5Sdrh ** and this row has been seen before, then do not make this row 595daffd0e5Sdrh ** part of the result. 5962282792aSdrh */ 597ea48eb2eSdrh if( hasDistinct ){ 598f8875400Sdrh assert( pEList!=0 ); 599f8875400Sdrh assert( pEList->nExpr==nColumn ); 600d847eaadSdrh codeDistinct(pParse, distinct, iContinue, nColumn, regResult); 601ea48eb2eSdrh if( pOrderBy==0 ){ 602b7654111Sdrh codeOffset(v, p, iContinue); 603ea48eb2eSdrh } 6042282792aSdrh } 60582c3d636Sdrh 606c926afbcSdrh switch( eDest ){ 60782c3d636Sdrh /* In this mode, write each query result to the key of the temporary 60882c3d636Sdrh ** table iParm. 6092282792aSdrh */ 61013449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 611c926afbcSdrh case SRT_Union: { 6129cbf3425Sdrh int r1; 6139cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 614d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6159cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 6169cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 617c926afbcSdrh break; 618c926afbcSdrh } 61982c3d636Sdrh 62082c3d636Sdrh /* Construct a record from the query result, but instead of 62182c3d636Sdrh ** saving that record, use it as a key to delete elements from 62282c3d636Sdrh ** the temporary table iParm. 62382c3d636Sdrh */ 624c926afbcSdrh case SRT_Except: { 625e14006d0Sdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn); 626c926afbcSdrh break; 627c926afbcSdrh } 6285338a5f7Sdanielk1977 #endif 6295338a5f7Sdanielk1977 6305338a5f7Sdanielk1977 /* Store the result as data using a unique key. 6315338a5f7Sdanielk1977 */ 6325338a5f7Sdanielk1977 case SRT_Table: 633b9bb7c18Sdrh case SRT_EphemTab: { 634b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 635373cc2ddSdrh testcase( eDest==SRT_Table ); 636373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 637d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6385338a5f7Sdanielk1977 if( pOrderBy ){ 639b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 6405338a5f7Sdanielk1977 }else{ 641b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 642b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 643b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 644b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 645b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 6465338a5f7Sdanielk1977 } 647b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 6485338a5f7Sdanielk1977 break; 6495338a5f7Sdanielk1977 } 6502282792aSdrh 65193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 6522282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 6532282792aSdrh ** then there should be a single item on the stack. Write this 6542282792aSdrh ** item into the set table with bogus data. 6552282792aSdrh */ 656c926afbcSdrh case SRT_Set: { 657967e8b73Sdrh assert( nColumn==1 ); 6586c8c8ce0Sdanielk1977 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity); 659c926afbcSdrh if( pOrderBy ){ 660de941c60Sdrh /* At first glance you would think we could optimize out the 661de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 662de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 663de941c60Sdrh ** case the order does matter */ 664d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 665c926afbcSdrh }else{ 666b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 667d847eaadSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1); 668da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, 1); 669b7654111Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 670b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 671c926afbcSdrh } 672c926afbcSdrh break; 673c926afbcSdrh } 67482c3d636Sdrh 675504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 676ec7429aeSdrh */ 677ec7429aeSdrh case SRT_Exists: { 6784c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 679ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 680ec7429aeSdrh break; 681ec7429aeSdrh } 682ec7429aeSdrh 6832282792aSdrh /* If this is a scalar select that is part of an expression, then 6842282792aSdrh ** store the results in the appropriate memory cell and break out 6852282792aSdrh ** of the scan loop. 6862282792aSdrh */ 687c926afbcSdrh case SRT_Mem: { 688967e8b73Sdrh assert( nColumn==1 ); 689c926afbcSdrh if( pOrderBy ){ 690d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 691c926afbcSdrh }else{ 692b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regResult, iParm, 1); 693ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 694c926afbcSdrh } 695c926afbcSdrh break; 696c926afbcSdrh } 69793758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 6982282792aSdrh 699c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 700c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 701c182d163Sdrh ** popping the data from the stack. 702f46f905aSdrh */ 703e00ee6ebSdrh case SRT_Coroutine: 7047d10d5a6Sdrh case SRT_Output: { 705373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 706373cc2ddSdrh testcase( eDest==SRT_Output ); 707f46f905aSdrh if( pOrderBy ){ 708b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 709d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 710b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 711b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 712e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 71392b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 714c182d163Sdrh }else{ 715d847eaadSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); 716da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn); 717ac82fcf5Sdrh } 718142e30dfSdrh break; 719142e30dfSdrh } 720142e30dfSdrh 7216a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 722d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 723d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 724d7489c39Sdrh ** user-defined functions that have side effects. We do not care 725d7489c39Sdrh ** about the actual results of the select. 726d7489c39Sdrh */ 727c926afbcSdrh default: { 728f46f905aSdrh assert( eDest==SRT_Discard ); 729c926afbcSdrh break; 730c926afbcSdrh } 73193758c8dSdanielk1977 #endif 732c926afbcSdrh } 733ec7429aeSdrh 7345e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 7355e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 7365e87be87Sdrh ** the output for us. 737ec7429aeSdrh */ 7385e87be87Sdrh if( pOrderBy==0 && p->iLimit ){ 7399b918ed1Sdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); 740ec7429aeSdrh } 74182c3d636Sdrh } 74282c3d636Sdrh 74382c3d636Sdrh /* 744dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 745dece1a84Sdrh ** the collating sequence for each expression in that expression list. 746dece1a84Sdrh ** 7470342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 7480342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 7490342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 7500342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 7510342b1f5Sdrh ** index to implement a DISTINCT test. 7520342b1f5Sdrh ** 753dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 754dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 75566a5167bSdrh ** freed. Add the KeyInfo structure to the P4 field of an opcode using 75666a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. 757dece1a84Sdrh */ 758dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 759dece1a84Sdrh sqlite3 *db = pParse->db; 760dece1a84Sdrh int nExpr; 761dece1a84Sdrh KeyInfo *pInfo; 762dece1a84Sdrh struct ExprList_item *pItem; 763dece1a84Sdrh int i; 764dece1a84Sdrh 765dece1a84Sdrh nExpr = pList->nExpr; 76617435752Sdrh pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 767dece1a84Sdrh if( pInfo ){ 7682646da7eSdrh pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 769ea678832Sdrh pInfo->nField = (u16)nExpr; 77014db2665Sdanielk1977 pInfo->enc = ENC(db); 7712aca5846Sdrh pInfo->db = db; 772dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 773dece1a84Sdrh CollSeq *pColl; 774dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 775dece1a84Sdrh if( !pColl ){ 776dece1a84Sdrh pColl = db->pDfltColl; 777dece1a84Sdrh } 778dece1a84Sdrh pInfo->aColl[i] = pColl; 779dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 780dece1a84Sdrh } 781dece1a84Sdrh } 782dece1a84Sdrh return pInfo; 783dece1a84Sdrh } 784dece1a84Sdrh 7857f61e92cSdan #ifndef SQLITE_OMIT_COMPOUND_SELECT 7867f61e92cSdan /* 7877f61e92cSdan ** Name of the connection operator, used for error messages. 7887f61e92cSdan */ 7897f61e92cSdan static const char *selectOpName(int id){ 7907f61e92cSdan char *z; 7917f61e92cSdan switch( id ){ 7927f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 7937f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 7947f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 7957f61e92cSdan default: z = "UNION"; break; 7967f61e92cSdan } 7977f61e92cSdan return z; 7987f61e92cSdan } 7997f61e92cSdan #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 8007f61e92cSdan 8012ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 80217c0bc0cSdan /* 80317c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 80417c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 80517c0bc0cSdan ** where the caption is of the form: 80617c0bc0cSdan ** 80717c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 80817c0bc0cSdan ** 80917c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 81017c0bc0cSdan ** is determined by the zUsage argument. 81117c0bc0cSdan */ 8122ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 8132ce22453Sdan if( pParse->explain==2 ){ 8142ce22453Sdan Vdbe *v = pParse->pVdbe; 8152ce22453Sdan char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); 8162ce22453Sdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 8172ce22453Sdan } 8182ce22453Sdan } 81917c0bc0cSdan 82017c0bc0cSdan /* 821bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 822bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 823bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 824bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 825bb2b4418Sdan ** code with #ifndef directives. 826bb2b4418Sdan */ 827bb2b4418Sdan # define explainSetInteger(a, b) a = b 828bb2b4418Sdan 829bb2b4418Sdan #else 830bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 831bb2b4418Sdan # define explainTempTable(y,z) 832bb2b4418Sdan # define explainSetInteger(y,z) 833bb2b4418Sdan #endif 834bb2b4418Sdan 835bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) 836bb2b4418Sdan /* 8377f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 8387f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 8397f61e92cSdan ** where the caption is of one of the two forms: 8407f61e92cSdan ** 8417f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" 8427f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" 8437f61e92cSdan ** 8447f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding 8457f61e92cSdan ** function parameters, and op is the text representation of the parameter 8467f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, 8477f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 8487f61e92cSdan ** false, or the second form if it is true. 8497f61e92cSdan */ 8507f61e92cSdan static void explainComposite( 8517f61e92cSdan Parse *pParse, /* Parse context */ 8527f61e92cSdan int op, /* One of TK_UNION, TK_EXCEPT etc. */ 8537f61e92cSdan int iSub1, /* Subquery id 1 */ 8547f61e92cSdan int iSub2, /* Subquery id 2 */ 8557f61e92cSdan int bUseTmp /* True if a temp table was used */ 8567f61e92cSdan ){ 8577f61e92cSdan assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); 8587f61e92cSdan if( pParse->explain==2 ){ 8597f61e92cSdan Vdbe *v = pParse->pVdbe; 8607f61e92cSdan char *zMsg = sqlite3MPrintf( 86130969d3fSdan pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, 8627f61e92cSdan bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) 8637f61e92cSdan ); 8647f61e92cSdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 8657f61e92cSdan } 8667f61e92cSdan } 8672ce22453Sdan #else 86817c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */ 8697f61e92cSdan # define explainComposite(v,w,x,y,z) 8702ce22453Sdan #endif 871dece1a84Sdrh 872dece1a84Sdrh /* 873d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 874d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 875d8bc7086Sdrh ** we need to run the sorter and output the results. The following 876d8bc7086Sdrh ** routine generates the code needed to do that. 877d8bc7086Sdrh */ 878c926afbcSdrh static void generateSortTail( 879cdd536f0Sdrh Parse *pParse, /* Parsing context */ 880c926afbcSdrh Select *p, /* The SELECT statement */ 881c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 882c926afbcSdrh int nColumn, /* Number of columns of data */ 8836c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 884c926afbcSdrh ){ 885dc5ea5c7Sdrh int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ 886dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 887d8bc7086Sdrh int addr; 8880342b1f5Sdrh int iTab; 88961fc595fSdrh int pseudoTab = 0; 8900342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 891ffbc3088Sdrh 8926c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 8936c8c8ce0Sdanielk1977 int iParm = pDest->iParm; 8946c8c8ce0Sdanielk1977 8952d401ab8Sdrh int regRow; 8962d401ab8Sdrh int regRowid; 8972d401ab8Sdrh 8989d2985c7Sdrh iTab = pOrderBy->iECursor; 8993e9ca094Sdrh regRow = sqlite3GetTempReg(pParse); 9007d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 901cdd536f0Sdrh pseudoTab = pParse->nTab++; 9023e9ca094Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn); 9033e9ca094Sdrh regRowid = 0; 9043e9ca094Sdrh }else{ 9053e9ca094Sdrh regRowid = sqlite3GetTempReg(pParse); 906cdd536f0Sdrh } 907c6aff30cSdrh if( p->selFlags & SF_UseSorter ){ 908c2bb3282Sdrh int regSortOut = ++pParse->nMem; 909c6aff30cSdrh int ptab2 = pParse->nTab++; 910c6aff30cSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2); 911c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 912c6aff30cSdrh codeOffset(v, p, addrContinue); 913c6aff30cSdrh sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut); 914c6aff30cSdrh sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow); 915c6aff30cSdrh sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 916c6aff30cSdrh }else{ 917dc5ea5c7Sdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); 918dc5ea5c7Sdrh codeOffset(v, p, addrContinue); 9192d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow); 920c6aff30cSdrh } 921c926afbcSdrh switch( eDest ){ 922c926afbcSdrh case SRT_Table: 923b9bb7c18Sdrh case SRT_EphemTab: { 9241c767f0dSdrh testcase( eDest==SRT_Table ); 9251c767f0dSdrh testcase( eDest==SRT_EphemTab ); 9262d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 9272d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 9282d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 929c926afbcSdrh break; 930c926afbcSdrh } 93193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 932c926afbcSdrh case SRT_Set: { 933c926afbcSdrh assert( nColumn==1 ); 934a7a8e14bSdanielk1977 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1); 935da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regRow, 1); 936a7a8e14bSdanielk1977 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); 937c926afbcSdrh break; 938c926afbcSdrh } 939c926afbcSdrh case SRT_Mem: { 940c926afbcSdrh assert( nColumn==1 ); 941b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regRow, iParm, 1); 942ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 943c926afbcSdrh break; 944c926afbcSdrh } 94593758c8dSdanielk1977 #endif 946373cc2ddSdrh default: { 947ac82fcf5Sdrh int i; 948373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 9491c767f0dSdrh testcase( eDest==SRT_Output ); 9501c767f0dSdrh testcase( eDest==SRT_Coroutine ); 951ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 9529882d999Sdanielk1977 assert( regRow!=pDest->iMem+i ); 9531013c932Sdrh sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i); 9543e9ca094Sdrh if( i==0 ){ 9553e9ca094Sdrh sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 9563e9ca094Sdrh } 957ac82fcf5Sdrh } 9587d10d5a6Sdrh if( eDest==SRT_Output ){ 9591013c932Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn); 960da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn); 961a9671a22Sdrh }else{ 96292b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 963ce665cf6Sdrh } 964ac82fcf5Sdrh break; 965ac82fcf5Sdrh } 966c926afbcSdrh } 9672d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 9682d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 969ec7429aeSdrh 970ec7429aeSdrh /* The bottom of the loop 971ec7429aeSdrh */ 972dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 973c6aff30cSdrh if( p->selFlags & SF_UseSorter ){ 974c6aff30cSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); 975c6aff30cSdrh }else{ 97666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); 977c6aff30cSdrh } 978dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 9797d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 98066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); 981cdd536f0Sdrh } 982d8bc7086Sdrh } 983d8bc7086Sdrh 984d8bc7086Sdrh /* 985517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 986517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 987e78e8284Sdrh ** 988955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 989955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 990955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 991955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 992955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 993955de52cSdanielk1977 ** considered a column by this function. 994e78e8284Sdrh ** 995955de52cSdanielk1977 ** SELECT col FROM tbl; 996955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 997955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 998955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 999955de52cSdanielk1977 ** 1000955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 1001fcb78a49Sdrh */ 1002955de52cSdanielk1977 static const char *columnType( 1003955de52cSdanielk1977 NameContext *pNC, 1004955de52cSdanielk1977 Expr *pExpr, 1005955de52cSdanielk1977 const char **pzOriginDb, 1006955de52cSdanielk1977 const char **pzOriginTab, 1007955de52cSdanielk1977 const char **pzOriginCol 1008955de52cSdanielk1977 ){ 1009955de52cSdanielk1977 char const *zType = 0; 1010955de52cSdanielk1977 char const *zOriginDb = 0; 1011955de52cSdanielk1977 char const *zOriginTab = 0; 1012955de52cSdanielk1977 char const *zOriginCol = 0; 1013517eb646Sdanielk1977 int j; 1014373cc2ddSdrh if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; 10155338a5f7Sdanielk1977 101600e279d9Sdanielk1977 switch( pExpr->op ){ 101730bcf5dbSdrh case TK_AGG_COLUMN: 101800e279d9Sdanielk1977 case TK_COLUMN: { 1019955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1020955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1021955de52cSdanielk1977 ** database table or a subquery. 1022955de52cSdanielk1977 */ 1023955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1024955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1025955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 1026373cc2ddSdrh testcase( pExpr->op==TK_AGG_COLUMN ); 1027373cc2ddSdrh testcase( pExpr->op==TK_COLUMN ); 102843bc88bbSdan while( pNC && !pTab ){ 1029b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1030b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1031b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 10326a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1033955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1034b3bce662Sdanielk1977 }else{ 1035b3bce662Sdanielk1977 pNC = pNC->pNext; 1036b3bce662Sdanielk1977 } 1037b3bce662Sdanielk1977 } 1038955de52cSdanielk1977 103943bc88bbSdan if( pTab==0 ){ 1040417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1041417168adSdrh ** cause this condition to run. Since then, we have restructured how 1042417168adSdrh ** trigger code is generated and so this condition is no longer 104343bc88bbSdan ** possible. However, it can still be true for statements like 104443bc88bbSdan ** the following: 104543bc88bbSdan ** 104643bc88bbSdan ** CREATE TABLE t1(col INTEGER); 104743bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 104843bc88bbSdan ** 104943bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 105043bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 105143bc88bbSdan ** though it should really be "INTEGER". 105243bc88bbSdan ** 105343bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 105443bc88bbSdan ** used. When columnType() is called on the expression 105543bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 105643bc88bbSdan ** branch below. */ 10577e62779aSdrh break; 10587e62779aSdrh } 1059955de52cSdanielk1977 106043bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1061955de52cSdanielk1977 if( pS ){ 1062955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1063955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1064955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1065955de52cSdanielk1977 */ 10667b688edeSdrh if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ 1067955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1068955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1069955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1070955de52cSdanielk1977 */ 1071955de52cSdanielk1977 NameContext sNC; 1072955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1073955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 107443bc88bbSdan sNC.pNext = pNC; 1075955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1076955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 1077955de52cSdanielk1977 } 10781c767f0dSdrh }else if( ALWAYS(pTab->pSchema) ){ 1079955de52cSdanielk1977 /* A real table */ 1080955de52cSdanielk1977 assert( !pS ); 1081fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1082fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1083fcb78a49Sdrh if( iCol<0 ){ 1084fcb78a49Sdrh zType = "INTEGER"; 1085955de52cSdanielk1977 zOriginCol = "rowid"; 1086fcb78a49Sdrh }else{ 1087fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 1088955de52cSdanielk1977 zOriginCol = pTab->aCol[iCol].zName; 1089955de52cSdanielk1977 } 1090955de52cSdanielk1977 zOriginTab = pTab->zName; 1091955de52cSdanielk1977 if( pNC->pParse ){ 1092955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1093955de52cSdanielk1977 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 1094955de52cSdanielk1977 } 1095fcb78a49Sdrh } 109600e279d9Sdanielk1977 break; 1097736c22b8Sdrh } 109893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 109900e279d9Sdanielk1977 case TK_SELECT: { 1100955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1101955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1102955de52cSdanielk1977 ** statement. 1103955de52cSdanielk1977 */ 1104b3bce662Sdanielk1977 NameContext sNC; 11056ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1106955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 11076ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1108955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1109b3bce662Sdanielk1977 sNC.pNext = pNC; 1110955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1111955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 111200e279d9Sdanielk1977 break; 1113fcb78a49Sdrh } 111493758c8dSdanielk1977 #endif 111500e279d9Sdanielk1977 } 111600e279d9Sdanielk1977 1117955de52cSdanielk1977 if( pzOriginDb ){ 1118955de52cSdanielk1977 assert( pzOriginTab && pzOriginCol ); 1119955de52cSdanielk1977 *pzOriginDb = zOriginDb; 1120955de52cSdanielk1977 *pzOriginTab = zOriginTab; 1121955de52cSdanielk1977 *pzOriginCol = zOriginCol; 1122955de52cSdanielk1977 } 1123517eb646Sdanielk1977 return zType; 1124517eb646Sdanielk1977 } 1125517eb646Sdanielk1977 1126517eb646Sdanielk1977 /* 1127517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1128517eb646Sdanielk1977 ** in the result set. 1129517eb646Sdanielk1977 */ 1130517eb646Sdanielk1977 static void generateColumnTypes( 1131517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1132517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1133517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1134517eb646Sdanielk1977 ){ 11353f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1136517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1137517eb646Sdanielk1977 int i; 1138b3bce662Sdanielk1977 NameContext sNC; 1139b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1140955de52cSdanielk1977 sNC.pParse = pParse; 1141517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1142517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 11433f913576Sdrh const char *zType; 11443f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1145955de52cSdanielk1977 const char *zOrigDb = 0; 1146955de52cSdanielk1977 const char *zOrigTab = 0; 1147955de52cSdanielk1977 const char *zOrigCol = 0; 11483f913576Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1149955de52cSdanielk1977 115085b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 11514b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 11524b1ae99dSdanielk1977 ** virtual machine is deleted. 1153fbcd585fSdanielk1977 */ 115410fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 115510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 115610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 11573f913576Sdrh #else 11583f913576Sdrh zType = columnType(&sNC, p, 0, 0, 0); 11593f913576Sdrh #endif 116010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1161fcb78a49Sdrh } 11623f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */ 1163fcb78a49Sdrh } 1164fcb78a49Sdrh 1165fcb78a49Sdrh /* 1166fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1167fcb78a49Sdrh ** in the result set. This information is used to provide the 1168fcabd464Sdrh ** azCol[] values in the callback. 116982c3d636Sdrh */ 1170832508b7Sdrh static void generateColumnNames( 1171832508b7Sdrh Parse *pParse, /* Parser context */ 1172ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1173832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1174832508b7Sdrh ){ 1175d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 11766a3ea0e6Sdrh int i, j; 11779bb575fdSdrh sqlite3 *db = pParse->db; 1178fcabd464Sdrh int fullNames, shortNames; 1179fcabd464Sdrh 1180fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 11813cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 11823cf86063Sdanielk1977 if( pParse->explain ){ 118361de0d1bSdanielk1977 return; 11843cf86063Sdanielk1977 } 11855338a5f7Sdanielk1977 #endif 11863cf86063Sdanielk1977 1187e2f02bacSdrh if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; 1188d8bc7086Sdrh pParse->colNamesSet = 1; 1189fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1190fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 119122322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 119282c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 119382c3d636Sdrh Expr *p; 11945a38705eSdrh p = pEList->a[i].pExpr; 1195373cc2ddSdrh if( NEVER(p==0) ) continue; 119682c3d636Sdrh if( pEList->a[i].zName ){ 119782c3d636Sdrh char *zName = pEList->a[i].zName; 119810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1199f018cc2eSdrh }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ 12006a3ea0e6Sdrh Table *pTab; 120197665873Sdrh char *zCol; 12028aff1015Sdrh int iCol = p->iColumn; 1203e2f02bacSdrh for(j=0; ALWAYS(j<pTabList->nSrc); j++){ 1204e2f02bacSdrh if( pTabList->a[j].iCursor==p->iTable ) break; 1205e2f02bacSdrh } 12066a3ea0e6Sdrh assert( j<pTabList->nSrc ); 12076a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 12088aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 120997665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1210b1363206Sdrh if( iCol<0 ){ 121147a6db2bSdrh zCol = "rowid"; 1212b1363206Sdrh }else{ 1213b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1214b1363206Sdrh } 1215e49b146fSdrh if( !shortNames && !fullNames ){ 121610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1217b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 12181c767f0dSdrh }else if( fullNames ){ 121982c3d636Sdrh char *zName = 0; 12201c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 122110fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 122282c3d636Sdrh }else{ 122310fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 122482c3d636Sdrh } 12251bee3d7bSdrh }else{ 122610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1227b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 122882c3d636Sdrh } 122982c3d636Sdrh } 123076d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 12315080aaa7Sdrh } 123282c3d636Sdrh 1233d8bc7086Sdrh /* 12347d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions 12357d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 12367d10d5a6Sdrh ** column names for a table that would hold the expression list. 12377d10d5a6Sdrh ** 12387d10d5a6Sdrh ** All column names will be unique. 12397d10d5a6Sdrh ** 12407d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 12417d10d5a6Sdrh ** and other fields of Column are zeroed. 12427d10d5a6Sdrh ** 12437d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 12447d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1245315555caSdrh */ 12467d10d5a6Sdrh static int selectColumnsFromExprList( 12477d10d5a6Sdrh Parse *pParse, /* Parsing context */ 12487d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 12497d10d5a6Sdrh int *pnCol, /* Write the number of columns here */ 12507d10d5a6Sdrh Column **paCol /* Write the new column list here */ 12517d10d5a6Sdrh ){ 1252dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1253dc5ea5c7Sdrh int i, j; /* Loop counters */ 1254dc5ea5c7Sdrh int cnt; /* Index added to make the name unique */ 1255dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1256dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1257dc5ea5c7Sdrh Expr *p; /* Expression for a single result column */ 1258dc5ea5c7Sdrh char *zName; /* Column name */ 1259dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 126079d5f63fSdrh 126163296052Sdrh *pnCol = nCol = pEList ? pEList->nExpr : 0; 12627d10d5a6Sdrh aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 12637d10d5a6Sdrh if( aCol==0 ) return SQLITE_NOMEM; 12647d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 126579d5f63fSdrh /* Get an appropriate name for the column 126679d5f63fSdrh */ 126779d5f63fSdrh p = pEList->a[i].pExpr; 126833e619fcSdrh assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue) 126933e619fcSdrh || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 ); 127091bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 127179d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 127217435752Sdrh zName = sqlite3DbStrDup(db, zName); 12737d10d5a6Sdrh }else{ 1274dc5ea5c7Sdrh Expr *pColExpr = p; /* The expression that is the result column name */ 1275dc5ea5c7Sdrh Table *pTab; /* Table associated with this expression */ 1276b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1277b07028f7Sdrh pColExpr = pColExpr->pRight; 1278b07028f7Sdrh assert( pColExpr!=0 ); 1279b07028f7Sdrh } 1280373cc2ddSdrh if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ 128193a960a0Sdrh /* For columns use the column name name */ 1282dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1283373cc2ddSdrh pTab = pColExpr->pTab; 1284f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1285f0209f74Sdrh zName = sqlite3MPrintf(db, "%s", 1286f0209f74Sdrh iCol>=0 ? pTab->aCol[iCol].zName : "rowid"); 1287b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 128833e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 128933e619fcSdrh zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); 129093a960a0Sdrh }else{ 129179d5f63fSdrh /* Use the original text of the column expression as its name */ 1292b7916a78Sdrh zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); 12937d10d5a6Sdrh } 129422f70c32Sdrh } 12957ce72f69Sdrh if( db->mallocFailed ){ 1296633e6d57Sdrh sqlite3DbFree(db, zName); 12977ce72f69Sdrh break; 1298dd5b2fa5Sdrh } 129979d5f63fSdrh 130079d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 130179d5f63fSdrh ** append a integer to the name so that it becomes unique. 130279d5f63fSdrh */ 1303ea678832Sdrh nName = sqlite3Strlen30(zName); 130479d5f63fSdrh for(j=cnt=0; j<i; j++){ 130579d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 1306633e6d57Sdrh char *zNewName; 13072564ef97Sdrh zName[nName] = 0; 1308633e6d57Sdrh zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt); 1309633e6d57Sdrh sqlite3DbFree(db, zName); 1310633e6d57Sdrh zName = zNewName; 131179d5f63fSdrh j = -1; 1312dd5b2fa5Sdrh if( zName==0 ) break; 131379d5f63fSdrh } 131479d5f63fSdrh } 131591bb0eedSdrh pCol->zName = zName; 13167d10d5a6Sdrh } 13177d10d5a6Sdrh if( db->mallocFailed ){ 13187d10d5a6Sdrh for(j=0; j<i; j++){ 13197d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 13207d10d5a6Sdrh } 13217d10d5a6Sdrh sqlite3DbFree(db, aCol); 13227d10d5a6Sdrh *paCol = 0; 13237d10d5a6Sdrh *pnCol = 0; 13247d10d5a6Sdrh return SQLITE_NOMEM; 13257d10d5a6Sdrh } 13267d10d5a6Sdrh return SQLITE_OK; 13277d10d5a6Sdrh } 1328e014a838Sdanielk1977 13297d10d5a6Sdrh /* 13307d10d5a6Sdrh ** Add type and collation information to a column list based on 13317d10d5a6Sdrh ** a SELECT statement. 13327d10d5a6Sdrh ** 13337d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 13347d10d5a6Sdrh ** The column list has only names, not types or collations. This 13357d10d5a6Sdrh ** routine goes through and adds the types and collations. 13367d10d5a6Sdrh ** 1337b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 13387d10d5a6Sdrh ** statement be resolved. 133979d5f63fSdrh */ 13407d10d5a6Sdrh static void selectAddColumnTypeAndCollation( 13417d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 13427d10d5a6Sdrh int nCol, /* Number of columns */ 13437d10d5a6Sdrh Column *aCol, /* List of columns */ 13447d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 13457d10d5a6Sdrh ){ 13467d10d5a6Sdrh sqlite3 *db = pParse->db; 13477d10d5a6Sdrh NameContext sNC; 13487d10d5a6Sdrh Column *pCol; 13497d10d5a6Sdrh CollSeq *pColl; 13507d10d5a6Sdrh int i; 13517d10d5a6Sdrh Expr *p; 13527d10d5a6Sdrh struct ExprList_item *a; 13537d10d5a6Sdrh 13547d10d5a6Sdrh assert( pSelect!=0 ); 13557d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 13567d10d5a6Sdrh assert( nCol==pSelect->pEList->nExpr || db->mallocFailed ); 13577d10d5a6Sdrh if( db->mallocFailed ) return; 1358c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1359b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 13607d10d5a6Sdrh a = pSelect->pEList->a; 13617d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 13627d10d5a6Sdrh p = a[i].pExpr; 13637d10d5a6Sdrh pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); 1364c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1365c4a64facSdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE; 1366b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1367b3bf556eSdanielk1977 if( pColl ){ 136817435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 13690202b29eSdanielk1977 } 137022f70c32Sdrh } 13717d10d5a6Sdrh } 13727d10d5a6Sdrh 13737d10d5a6Sdrh /* 13747d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 13757d10d5a6Sdrh ** the result set of that SELECT. 13767d10d5a6Sdrh */ 13777d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 13787d10d5a6Sdrh Table *pTab; 13797d10d5a6Sdrh sqlite3 *db = pParse->db; 13807d10d5a6Sdrh int savedFlags; 13817d10d5a6Sdrh 13827d10d5a6Sdrh savedFlags = db->flags; 13837d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 13847d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 13857d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 13867d10d5a6Sdrh if( pParse->nErr ) return 0; 13877d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 13887d10d5a6Sdrh db->flags = savedFlags; 13897d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 13907d10d5a6Sdrh if( pTab==0 ){ 13917d10d5a6Sdrh return 0; 13927d10d5a6Sdrh } 1393373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 1394b2468954Sdrh ** is disabled */ 1395373cc2ddSdrh assert( db->lookaside.bEnabled==0 ); 13967d10d5a6Sdrh pTab->nRef = 1; 13977d10d5a6Sdrh pTab->zName = 0; 13981ea87012Sdrh pTab->nRowEst = 1000000; 13997d10d5a6Sdrh selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 14007d10d5a6Sdrh selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect); 140122f70c32Sdrh pTab->iPKey = -1; 14027ce72f69Sdrh if( db->mallocFailed ){ 14031feeaed2Sdan sqlite3DeleteTable(db, pTab); 14047ce72f69Sdrh return 0; 14057ce72f69Sdrh } 140622f70c32Sdrh return pTab; 140722f70c32Sdrh } 140822f70c32Sdrh 140922f70c32Sdrh /* 1410d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1411d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1412d8bc7086Sdrh */ 14134adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1414d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1415d8bc7086Sdrh if( v==0 ){ 14164adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1417949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE 1418949f9cd5Sdrh if( v ){ 1419949f9cd5Sdrh sqlite3VdbeAddOp0(v, OP_Trace); 1420949f9cd5Sdrh } 1421949f9cd5Sdrh #endif 1422d8bc7086Sdrh } 1423d8bc7086Sdrh return v; 1424d8bc7086Sdrh } 1425d8bc7086Sdrh 142615007a99Sdrh 1427d8bc7086Sdrh /* 14287b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1429ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 14307b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1431a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1432a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1433a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1434a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 14357b58daeaSdrh ** 1436d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1437ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 14387b58daeaSdrh ** iOffset should have been preset to appropriate default values 14397b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1440ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 14417b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 14427b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 14437b58daeaSdrh ** SELECT statements. 14447b58daeaSdrh */ 1445ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 144602afc861Sdrh Vdbe *v = 0; 144702afc861Sdrh int iLimit = 0; 144815007a99Sdrh int iOffset; 14499b918ed1Sdrh int addr1, n; 14500acb7e48Sdrh if( p->iLimit ) return; 145115007a99Sdrh 14527b58daeaSdrh /* 14537b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 14547b58daeaSdrh ** contraversy about what the correct behavior should be. 14557b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 14567b58daeaSdrh ** no rows. 14577b58daeaSdrh */ 1458ceea3321Sdrh sqlite3ExprCacheClear(pParse); 1459373cc2ddSdrh assert( p->pOffset==0 || p->pLimit!=0 ); 1460a2dc3b1aSdanielk1977 if( p->pLimit ){ 14610a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 146215007a99Sdrh v = sqlite3GetVdbe(pParse); 1463373cc2ddSdrh if( NEVER(v==0) ) return; /* VDBE should have already been allocated */ 14649b918ed1Sdrh if( sqlite3ExprIsInteger(p->pLimit, &n) ){ 14659b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 14669b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 1467456e4e4fSdrh if( n==0 ){ 1468456e4e4fSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 146995aa47b1Sdrh }else{ 147095aa47b1Sdrh if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n; 14719b918ed1Sdrh } 14729b918ed1Sdrh }else{ 1473b7654111Sdrh sqlite3ExprCode(pParse, p->pLimit, iLimit); 1474b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); 1475d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 14763c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); 14779b918ed1Sdrh } 1478a2dc3b1aSdanielk1977 if( p->pOffset ){ 14790a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 1480b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 1481b7654111Sdrh sqlite3ExprCode(pParse, p->pOffset, iOffset); 1482b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); 1483d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 14843c84ddffSdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); 1485b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); 148615007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 1487b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1488d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 1489b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); 1490b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); 1491b7654111Sdrh sqlite3VdbeJumpHere(v, addr1); 1492b7654111Sdrh } 1493d59ba6ceSdrh } 14947b58daeaSdrh } 14957b58daeaSdrh 1496b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1497fbc4ee7bSdrh /* 1498fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1499fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1500fbc4ee7bSdrh ** the column has no default collating sequence. 1501fbc4ee7bSdrh ** 1502fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1503fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1504fbc4ee7bSdrh */ 1505dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1506fbc4ee7bSdrh CollSeq *pRet; 1507dc1bdc4fSdanielk1977 if( p->pPrior ){ 1508dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1509fbc4ee7bSdrh }else{ 1510fbc4ee7bSdrh pRet = 0; 1511dc1bdc4fSdanielk1977 } 151210c081adSdrh assert( iCol>=0 ); 151310c081adSdrh if( pRet==0 && iCol<p->pEList->nExpr ){ 1514dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1515dc1bdc4fSdanielk1977 } 1516dc1bdc4fSdanielk1977 return pRet; 1517d3d39e93Sdrh } 1518b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1519d3d39e93Sdrh 1520b21e7c70Sdrh /* Forward reference */ 1521b21e7c70Sdrh static int multiSelectOrderBy( 1522b21e7c70Sdrh Parse *pParse, /* Parsing context */ 1523b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 1524a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 1525b21e7c70Sdrh ); 1526b21e7c70Sdrh 1527b21e7c70Sdrh 1528b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1529d3d39e93Sdrh /* 153016ee60ffSdrh ** This routine is called to process a compound query form from 153116ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 153216ee60ffSdrh ** INTERSECT 1533c926afbcSdrh ** 1534e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1535e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1536e78e8284Sdrh ** in which case this routine will be called recursively. 1537e78e8284Sdrh ** 1538e78e8284Sdrh ** The results of the total query are to be written into a destination 1539e78e8284Sdrh ** of type eDest with parameter iParm. 1540e78e8284Sdrh ** 1541e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1542e78e8284Sdrh ** 1543e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1544e78e8284Sdrh ** 1545e78e8284Sdrh ** This statement is parsed up as follows: 1546e78e8284Sdrh ** 1547e78e8284Sdrh ** SELECT c FROM t3 1548e78e8284Sdrh ** | 1549e78e8284Sdrh ** `-----> SELECT b FROM t2 1550e78e8284Sdrh ** | 15514b11c6d3Sjplyon ** `------> SELECT a FROM t1 1552e78e8284Sdrh ** 1553e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1554e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1555e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1556e78e8284Sdrh ** 1557e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1558e78e8284Sdrh ** individual selects always group from left to right. 155982c3d636Sdrh */ 156084ac9d02Sdanielk1977 static int multiSelect( 1561fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1562fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1563a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 156484ac9d02Sdanielk1977 ){ 156584ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 156610e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 156710e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 15681013c932Sdrh SelectDest dest; /* Alternative data destination */ 1569eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 1570633e6d57Sdrh sqlite3 *db; /* Database connection */ 15717f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 15727f61e92cSdan int iSub1; /* EQP id of left-hand query */ 15737f61e92cSdan int iSub2; /* EQP id of right-hand query */ 15747f61e92cSdan #endif 157582c3d636Sdrh 15767b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1577fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 157882c3d636Sdrh */ 1579701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 1580633e6d57Sdrh db = pParse->db; 1581d8bc7086Sdrh pPrior = p->pPrior; 15820342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 15830342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1584bc10377aSdrh dest = *pDest; 1585d8bc7086Sdrh if( pPrior->pOrderBy ){ 15864adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1587da93d238Sdrh selectOpName(p->op)); 158884ac9d02Sdanielk1977 rc = 1; 158984ac9d02Sdanielk1977 goto multi_select_end; 159082c3d636Sdrh } 1591a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 15924adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 15937b58daeaSdrh selectOpName(p->op)); 159484ac9d02Sdanielk1977 rc = 1; 159584ac9d02Sdanielk1977 goto multi_select_end; 15967b58daeaSdrh } 159782c3d636Sdrh 15984adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 1599701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 1600d8bc7086Sdrh 16011cc3d75fSdrh /* Create the destination temporary table if necessary 16021cc3d75fSdrh */ 16036c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 1604b4964b72Sdanielk1977 assert( p->pEList ); 1605f6e369a1Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr); 1606d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 16076c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 16081cc3d75fSdrh } 16091cc3d75fSdrh 1610f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 1611f6e369a1Sdrh ** in their result sets. 1612f6e369a1Sdrh */ 1613f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 1614f6e369a1Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 16157b113babSdrh if( p->selFlags & SF_Values ){ 16167b113babSdrh sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 16177b113babSdrh }else{ 1618f6e369a1Sdrh sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1619f6e369a1Sdrh " do not have the same number of result columns", selectOpName(p->op)); 16207b113babSdrh } 1621f6e369a1Sdrh rc = 1; 1622f6e369a1Sdrh goto multi_select_end; 1623f6e369a1Sdrh } 1624f6e369a1Sdrh 1625a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 1626a9671a22Sdrh */ 1627f6e369a1Sdrh if( p->pOrderBy ){ 1628a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 1629f6e369a1Sdrh } 1630f6e369a1Sdrh 1631f46f905aSdrh /* Generate code for the left and right SELECT statements. 1632d8bc7086Sdrh */ 163382c3d636Sdrh switch( p->op ){ 1634f46f905aSdrh case TK_ALL: { 1635ec7429aeSdrh int addr = 0; 163695aa47b1Sdrh int nLimit; 1637a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1638a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1639a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 16407f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 16417d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 1642ad68cb6bSdanielk1977 p->pLimit = 0; 1643ad68cb6bSdanielk1977 p->pOffset = 0; 164484ac9d02Sdanielk1977 if( rc ){ 164584ac9d02Sdanielk1977 goto multi_select_end; 164684ac9d02Sdanielk1977 } 1647f46f905aSdrh p->pPrior = 0; 16487b58daeaSdrh p->iLimit = pPrior->iLimit; 16497b58daeaSdrh p->iOffset = pPrior->iOffset; 165092b01d53Sdrh if( p->iLimit ){ 16513c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); 1652d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 1653ec7429aeSdrh } 16547f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 16557d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 1656373cc2ddSdrh testcase( rc!=SQLITE_OK ); 1657eca7e01aSdanielk1977 pDelete = p->pPrior; 1658f46f905aSdrh p->pPrior = pPrior; 165995aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 166095aa47b1Sdrh if( pPrior->pLimit 166195aa47b1Sdrh && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) 166295aa47b1Sdrh && p->nSelectRow > (double)nLimit 166395aa47b1Sdrh ){ 166495aa47b1Sdrh p->nSelectRow = (double)nLimit; 166595aa47b1Sdrh } 1666ec7429aeSdrh if( addr ){ 1667ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1668ec7429aeSdrh } 1669f46f905aSdrh break; 1670f46f905aSdrh } 167182c3d636Sdrh case TK_EXCEPT: 167282c3d636Sdrh case TK_UNION: { 1673d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1674ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 1675d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1676a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1677dc1bdc4fSdanielk1977 int addr; 16786c8c8ce0Sdanielk1977 SelectDest uniondest; 167982c3d636Sdrh 1680373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 1681373cc2ddSdrh testcase( p->op==TK_UNION ); 168293a960a0Sdrh priorOp = SRT_Union; 1683e2f02bacSdrh if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){ 1684d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1685c926afbcSdrh ** right. 1686d8bc7086Sdrh */ 1687e2f02bacSdrh assert( p->pRightmost!=p ); /* Can only happen for leftward elements 1688e2f02bacSdrh ** of a 3-way or more compound */ 1689e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 1690e2f02bacSdrh assert( p->pOffset==0 ); /* Not allowed on leftward elements */ 16916c8c8ce0Sdanielk1977 unionTab = dest.iParm; 169282c3d636Sdrh }else{ 1693d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1694d8bc7086Sdrh ** intermediate results. 1695d8bc7086Sdrh */ 169682c3d636Sdrh unionTab = pParse->nTab++; 169793a960a0Sdrh assert( p->pOrderBy==0 ); 169866a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 1699b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1700b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 17017d10d5a6Sdrh p->pRightmost->selFlags |= SF_UsesEphemeral; 170284ac9d02Sdanielk1977 assert( p->pEList ); 1703d8bc7086Sdrh } 1704d8bc7086Sdrh 1705d8bc7086Sdrh /* Code the SELECT statements to our left 1706d8bc7086Sdrh */ 1707b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 17081013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 17097f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 17107d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 171184ac9d02Sdanielk1977 if( rc ){ 171284ac9d02Sdanielk1977 goto multi_select_end; 171384ac9d02Sdanielk1977 } 1714d8bc7086Sdrh 1715d8bc7086Sdrh /* Code the current SELECT statement 1716d8bc7086Sdrh */ 17174cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 17184cfb22f7Sdrh op = SRT_Except; 17194cfb22f7Sdrh }else{ 17204cfb22f7Sdrh assert( p->op==TK_UNION ); 17214cfb22f7Sdrh op = SRT_Union; 1722d8bc7086Sdrh } 172382c3d636Sdrh p->pPrior = 0; 1724a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1725a2dc3b1aSdanielk1977 p->pLimit = 0; 1726a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1727a2dc3b1aSdanielk1977 p->pOffset = 0; 17286c8c8ce0Sdanielk1977 uniondest.eDest = op; 17297f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 17307d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 1731373cc2ddSdrh testcase( rc!=SQLITE_OK ); 17325bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 17335bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 1734633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 1735eca7e01aSdanielk1977 pDelete = p->pPrior; 173682c3d636Sdrh p->pPrior = pPrior; 1737a9671a22Sdrh p->pOrderBy = 0; 173895aa47b1Sdrh if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow; 1739633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 1740a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1741a2dc3b1aSdanielk1977 p->pOffset = pOffset; 174292b01d53Sdrh p->iLimit = 0; 174392b01d53Sdrh p->iOffset = 0; 1744d8bc7086Sdrh 1745d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1746d8bc7086Sdrh ** it is that we currently need. 1747d8bc7086Sdrh */ 1748373cc2ddSdrh assert( unionTab==dest.iParm || dest.eDest!=priorOp ); 1749373cc2ddSdrh if( dest.eDest!=priorOp ){ 17506b56344dSdrh int iCont, iBreak, iStart; 175182c3d636Sdrh assert( p->pEList ); 17527d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 175392378253Sdrh Select *pFirst = p; 175492378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 175592378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 175641202ccaSdrh } 17574adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 17584adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1759ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 176066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); 17614adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 1762d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 1763a9671a22Sdrh 0, -1, &dest, iCont, iBreak); 17644adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 176566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); 17664adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 176766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 176882c3d636Sdrh } 176982c3d636Sdrh break; 177082c3d636Sdrh } 1771373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 177282c3d636Sdrh int tab1, tab2; 17736b56344dSdrh int iCont, iBreak, iStart; 1774a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 1775dc1bdc4fSdanielk1977 int addr; 17761013c932Sdrh SelectDest intersectdest; 17779cbf3425Sdrh int r1; 177882c3d636Sdrh 1779d8bc7086Sdrh /* INTERSECT is different from the others since it requires 17806206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1781d8bc7086Sdrh ** by allocating the tables we will need. 1782d8bc7086Sdrh */ 178382c3d636Sdrh tab1 = pParse->nTab++; 178482c3d636Sdrh tab2 = pParse->nTab++; 178593a960a0Sdrh assert( p->pOrderBy==0 ); 1786dc1bdc4fSdanielk1977 178766a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 1788b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1789b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 17907d10d5a6Sdrh p->pRightmost->selFlags |= SF_UsesEphemeral; 179184ac9d02Sdanielk1977 assert( p->pEList ); 1792d8bc7086Sdrh 1793d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1794d8bc7086Sdrh */ 17951013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 17967f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 17977d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 179884ac9d02Sdanielk1977 if( rc ){ 179984ac9d02Sdanielk1977 goto multi_select_end; 180084ac9d02Sdanielk1977 } 1801d8bc7086Sdrh 1802d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1803d8bc7086Sdrh */ 180466a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 1805b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 1806b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 180782c3d636Sdrh p->pPrior = 0; 1808a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1809a2dc3b1aSdanielk1977 p->pLimit = 0; 1810a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1811a2dc3b1aSdanielk1977 p->pOffset = 0; 18126c8c8ce0Sdanielk1977 intersectdest.iParm = tab2; 18137f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 18147d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 1815373cc2ddSdrh testcase( rc!=SQLITE_OK ); 1816eca7e01aSdanielk1977 pDelete = p->pPrior; 181782c3d636Sdrh p->pPrior = pPrior; 181895aa47b1Sdrh if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 1819633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 1820a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1821a2dc3b1aSdanielk1977 p->pOffset = pOffset; 1822d8bc7086Sdrh 1823d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1824d8bc7086Sdrh ** tables. 1825d8bc7086Sdrh */ 182682c3d636Sdrh assert( p->pEList ); 18277d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 182892378253Sdrh Select *pFirst = p; 182992378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 183092378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 183141202ccaSdrh } 18324adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 18334adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1834ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 183566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); 18369cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 18379cbf3425Sdrh iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 18388cff69dfSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); 18399cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 1840d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 1841a9671a22Sdrh 0, -1, &dest, iCont, iBreak); 18424adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 184366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); 18444adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 184566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 184666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 184782c3d636Sdrh break; 184882c3d636Sdrh } 184982c3d636Sdrh } 18508cdbf836Sdrh 18517f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); 18527f61e92cSdan 1853a9671a22Sdrh /* Compute collating sequences used by 1854a9671a22Sdrh ** temporary tables needed to implement the compound select. 1855a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 18568cdbf836Sdrh ** 18578cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 18588cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 18598cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 18608cdbf836Sdrh ** no temp tables are required. 1861fbc4ee7bSdrh */ 18627d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 1863fbc4ee7bSdrh int i; /* Loop counter */ 1864fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 18650342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 1866f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 186793a960a0Sdrh int nCol; /* Number of columns in result set */ 1868fbc4ee7bSdrh 18690342b1f5Sdrh assert( p->pRightmost==p ); 187093a960a0Sdrh nCol = p->pEList->nExpr; 1871633e6d57Sdrh pKeyInfo = sqlite3DbMallocZero(db, 1872a9671a22Sdrh sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1)); 1873dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1874dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1875dc1bdc4fSdanielk1977 goto multi_select_end; 1876dc1bdc4fSdanielk1977 } 1877dc1bdc4fSdanielk1977 1878633e6d57Sdrh pKeyInfo->enc = ENC(db); 1879ea678832Sdrh pKeyInfo->nField = (u16)nCol; 1880dc1bdc4fSdanielk1977 18810342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 18820342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 18830342b1f5Sdrh if( 0==*apColl ){ 1884633e6d57Sdrh *apColl = db->pDfltColl; 1885dc1bdc4fSdanielk1977 } 1886dc1bdc4fSdanielk1977 } 1887dc1bdc4fSdanielk1977 18880342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 18890342b1f5Sdrh for(i=0; i<2; i++){ 1890b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 18910342b1f5Sdrh if( addr<0 ){ 18920342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 18930342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 1894b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 18950342b1f5Sdrh break; 18960342b1f5Sdrh } 18970342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 189866a5167bSdrh sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); 18990ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 19000342b1f5Sdrh } 1901dc1bdc4fSdanielk1977 } 1902633e6d57Sdrh sqlite3DbFree(db, pKeyInfo); 1903dc1bdc4fSdanielk1977 } 1904dc1bdc4fSdanielk1977 1905dc1bdc4fSdanielk1977 multi_select_end: 19061013c932Sdrh pDest->iMem = dest.iMem; 1907ad27e761Sdrh pDest->nMem = dest.nMem; 1908633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 190984ac9d02Sdanielk1977 return rc; 19102282792aSdrh } 1911b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 19122282792aSdrh 1913b21e7c70Sdrh /* 1914b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 1915b21e7c70Sdrh ** SELECT statment. 19160acb7e48Sdrh ** 19170acb7e48Sdrh ** The data to be output is contained in pIn->iMem. There are 19180acb7e48Sdrh ** pIn->nMem columns to be output. pDest is where the output should 19190acb7e48Sdrh ** be sent. 19200acb7e48Sdrh ** 19210acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 19220acb7e48Sdrh ** return address. 19230acb7e48Sdrh ** 1924f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 19250acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 19260acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 19270acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 19280acb7e48Sdrh ** keys. 19290acb7e48Sdrh ** 19300acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 19310acb7e48Sdrh ** iBreak. 1932b21e7c70Sdrh */ 19330acb7e48Sdrh static int generateOutputSubroutine( 193492b01d53Sdrh Parse *pParse, /* Parsing context */ 193592b01d53Sdrh Select *p, /* The SELECT statement */ 193692b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 193792b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 193892b01d53Sdrh int regReturn, /* The return address register */ 19390acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 19400acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 19410acb7e48Sdrh int p4type, /* The p4 type for pKeyInfo */ 194292b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 1943b21e7c70Sdrh ){ 1944b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 194592b01d53Sdrh int iContinue; 194692b01d53Sdrh int addr; 1947b21e7c70Sdrh 194892b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 194992b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 19500acb7e48Sdrh 19510acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 19520acb7e48Sdrh */ 19530acb7e48Sdrh if( regPrev ){ 19540acb7e48Sdrh int j1, j2; 1955ec86c724Sdrh j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); 19560acb7e48Sdrh j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem, 19570acb7e48Sdrh (char*)pKeyInfo, p4type); 19580acb7e48Sdrh sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); 19590acb7e48Sdrh sqlite3VdbeJumpHere(v, j1); 19600acb7e48Sdrh sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem); 1961ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 19620acb7e48Sdrh } 19631f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 19640acb7e48Sdrh 19650acb7e48Sdrh /* Suppress the the first OFFSET entries if there is an OFFSET clause 19660acb7e48Sdrh */ 196792b01d53Sdrh codeOffset(v, p, iContinue); 1968b21e7c70Sdrh 1969b21e7c70Sdrh switch( pDest->eDest ){ 1970b21e7c70Sdrh /* Store the result as data using a unique key. 1971b21e7c70Sdrh */ 1972b21e7c70Sdrh case SRT_Table: 1973b21e7c70Sdrh case SRT_EphemTab: { 1974b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 1975b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 1976373cc2ddSdrh testcase( pDest->eDest==SRT_Table ); 1977373cc2ddSdrh testcase( pDest->eDest==SRT_EphemTab ); 197892b01d53Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1); 197992b01d53Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2); 198092b01d53Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2); 1981b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1982b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 1983b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 1984b21e7c70Sdrh break; 1985b21e7c70Sdrh } 1986b21e7c70Sdrh 1987b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 1988b21e7c70Sdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 1989b21e7c70Sdrh ** then there should be a single item on the stack. Write this 1990b21e7c70Sdrh ** item into the set table with bogus data. 1991b21e7c70Sdrh */ 1992b21e7c70Sdrh case SRT_Set: { 19936fccc35aSdrh int r1; 199492b01d53Sdrh assert( pIn->nMem==1 ); 199592b01d53Sdrh p->affinity = 199692b01d53Sdrh sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity); 1997b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 199892b01d53Sdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1); 199992b01d53Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1); 200092b01d53Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1); 2001b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2002b21e7c70Sdrh break; 2003b21e7c70Sdrh } 2004b21e7c70Sdrh 200585e9e22bSdrh #if 0 /* Never occurs on an ORDER BY query */ 2006b21e7c70Sdrh /* If any row exist in the result set, record that fact and abort. 2007b21e7c70Sdrh */ 2008b21e7c70Sdrh case SRT_Exists: { 200992b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm); 2010b21e7c70Sdrh /* The LIMIT clause will terminate the loop for us */ 2011b21e7c70Sdrh break; 2012b21e7c70Sdrh } 201385e9e22bSdrh #endif 2014b21e7c70Sdrh 2015b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2016b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2017b21e7c70Sdrh ** of the scan loop. 2018b21e7c70Sdrh */ 2019b21e7c70Sdrh case SRT_Mem: { 202092b01d53Sdrh assert( pIn->nMem==1 ); 202192b01d53Sdrh sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1); 2022b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 2023b21e7c70Sdrh break; 2024b21e7c70Sdrh } 2025b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2026b21e7c70Sdrh 20277d10d5a6Sdrh /* The results are stored in a sequence of registers 20287d10d5a6Sdrh ** starting at pDest->iMem. Then the co-routine yields. 2029b21e7c70Sdrh */ 203092b01d53Sdrh case SRT_Coroutine: { 203192b01d53Sdrh if( pDest->iMem==0 ){ 203292b01d53Sdrh pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem); 203392b01d53Sdrh pDest->nMem = pIn->nMem; 2034b21e7c70Sdrh } 203592b01d53Sdrh sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem); 203692b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); 203792b01d53Sdrh break; 203892b01d53Sdrh } 203992b01d53Sdrh 2040ccfcbceaSdrh /* If none of the above, then the result destination must be 2041ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2042ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2043ccfcbceaSdrh ** 2044ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2045ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2046ccfcbceaSdrh ** return the next row of result. 20477d10d5a6Sdrh */ 2048ccfcbceaSdrh default: { 2049ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 205092b01d53Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem); 205192b01d53Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem); 2052b21e7c70Sdrh break; 2053b21e7c70Sdrh } 2054b21e7c70Sdrh } 205592b01d53Sdrh 205692b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 205792b01d53Sdrh */ 205892b01d53Sdrh if( p->iLimit ){ 20599b918ed1Sdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); 206092b01d53Sdrh } 206192b01d53Sdrh 206292b01d53Sdrh /* Generate the subroutine return 206392b01d53Sdrh */ 20640acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 206592b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 206692b01d53Sdrh 206792b01d53Sdrh return addr; 2068b21e7c70Sdrh } 2069b21e7c70Sdrh 2070b21e7c70Sdrh /* 2071b21e7c70Sdrh ** Alternative compound select code generator for cases when there 2072b21e7c70Sdrh ** is an ORDER BY clause. 2073b21e7c70Sdrh ** 2074b21e7c70Sdrh ** We assume a query of the following form: 2075b21e7c70Sdrh ** 2076b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 2077b21e7c70Sdrh ** 2078b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 2079b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 2080b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 2081b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 2082b21e7c70Sdrh ** selectB) there are 7 subroutines: 2083b21e7c70Sdrh ** 2084b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 2085b21e7c70Sdrh ** of the compound query. 2086b21e7c70Sdrh ** 2087b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 2088b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 2089b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 2090b21e7c70Sdrh ** appears only in B.) 2091b21e7c70Sdrh ** 2092b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 2093b21e7c70Sdrh ** 2094b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 2095b21e7c70Sdrh ** 2096b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 2097b21e7c70Sdrh ** 2098b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 2099b21e7c70Sdrh ** 2100b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 2101b21e7c70Sdrh ** 2102b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 2103b21e7c70Sdrh ** <operator> is used: 2104b21e7c70Sdrh ** 2105b21e7c70Sdrh ** 2106b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 2107b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 2108b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 2109b21e7c70Sdrh ** 21100acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 2111b21e7c70Sdrh ** 2112b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 2113b21e7c70Sdrh ** 21140acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 2115b21e7c70Sdrh ** 21160acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 21170acb7e48Sdrh ** 21180acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 21190acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 21200acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 21210acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 21220acb7e48Sdrh ** 21230acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 21240acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 21250acb7e48Sdrh ** output value. A comparison is made against this value and the output 21260acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 2127b21e7c70Sdrh ** 2128b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 2129b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 2130b21e7c70Sdrh ** 2131b21e7c70Sdrh ** goto Init 2132b21e7c70Sdrh ** coA: coroutine for left query (A) 2133b21e7c70Sdrh ** coB: coroutine for right query (B) 2134b21e7c70Sdrh ** outA: output one row of A 2135b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 2136b21e7c70Sdrh ** EofA: ... 2137b21e7c70Sdrh ** EofB: ... 2138b21e7c70Sdrh ** AltB: ... 2139b21e7c70Sdrh ** AeqB: ... 2140b21e7c70Sdrh ** AgtB: ... 2141b21e7c70Sdrh ** Init: initialize coroutine registers 2142b21e7c70Sdrh ** yield coA 2143b21e7c70Sdrh ** if eof(A) goto EofA 2144b21e7c70Sdrh ** yield coB 2145b21e7c70Sdrh ** if eof(B) goto EofB 2146b21e7c70Sdrh ** Cmpr: Compare A, B 2147b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 2148b21e7c70Sdrh ** End: ... 2149b21e7c70Sdrh ** 2150b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 2151b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 2152b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 2153b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 2154b21e7c70Sdrh */ 2155de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 2156b21e7c70Sdrh static int multiSelectOrderBy( 2157b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2158b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2159a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2160b21e7c70Sdrh ){ 21610acb7e48Sdrh int i, j; /* Loop counters */ 2162b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 2163b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 2164b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 2165b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 216692b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 216792b01d53Sdrh int regEofA; /* Flag to indicate when select-A is complete */ 216892b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 216992b01d53Sdrh int regEofB; /* Flag to indicate when select-B is complete */ 217092b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 217192b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 217292b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 217392b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 217492b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 2175b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 217692b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 217792b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 217892b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 217992b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 218092b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 218192b01d53Sdrh int regLimitA; /* Limit register for select-A */ 218292b01d53Sdrh int regLimitB; /* Limit register for select-A */ 21830acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 218492b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 218592b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 218692b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 218792b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 21880acb7e48Sdrh int j1; /* Jump instructions that get retargetted */ 218992b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 219096067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 21910acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 21920acb7e48Sdrh sqlite3 *db; /* Database connection */ 21930acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 21940acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 21950acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 21967f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 21977f61e92cSdan int iSub1; /* EQP id of left-hand query */ 21987f61e92cSdan int iSub2; /* EQP id of right-hand query */ 21997f61e92cSdan #endif 2200b21e7c70Sdrh 220192b01d53Sdrh assert( p->pOrderBy!=0 ); 220296067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 22030acb7e48Sdrh db = pParse->db; 220492b01d53Sdrh v = pParse->pVdbe; 2205ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 220692b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 220792b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 22080acb7e48Sdrh 2209b21e7c70Sdrh 221092b01d53Sdrh /* Patch up the ORDER BY clause 221192b01d53Sdrh */ 221292b01d53Sdrh op = p->op; 2213b21e7c70Sdrh pPrior = p->pPrior; 221492b01d53Sdrh assert( pPrior->pOrderBy==0 ); 22150acb7e48Sdrh pOrderBy = p->pOrderBy; 221693a960a0Sdrh assert( pOrderBy ); 22170acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 221893a960a0Sdrh 22190acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 22200acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 22210acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 22220acb7e48Sdrh */ 22230acb7e48Sdrh if( op!=TK_ALL ){ 22240acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 22257d10d5a6Sdrh struct ExprList_item *pItem; 22267d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 22274b3ac73cSdrh assert( pItem->iOrderByCol>0 ); 22284b3ac73cSdrh if( pItem->iOrderByCol==i ) break; 22290acb7e48Sdrh } 22300acb7e48Sdrh if( j==nOrderBy ){ 2231b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 22320acb7e48Sdrh if( pNew==0 ) return SQLITE_NOMEM; 22330acb7e48Sdrh pNew->flags |= EP_IntValue; 223433e619fcSdrh pNew->u.iValue = i; 2235b7916a78Sdrh pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 2236a3cc3c96Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i; 22370acb7e48Sdrh } 22380acb7e48Sdrh } 22390acb7e48Sdrh } 22400acb7e48Sdrh 22410acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 224210c081adSdrh ** the permutation used to determine if the next 22430acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 22440acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 22450acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 22460acb7e48Sdrh ** collation. 22470acb7e48Sdrh */ 22480acb7e48Sdrh aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); 22490acb7e48Sdrh if( aPermute ){ 22507d10d5a6Sdrh struct ExprList_item *pItem; 22517d10d5a6Sdrh for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){ 22524b3ac73cSdrh assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr ); 22534b3ac73cSdrh aPermute[i] = pItem->iOrderByCol - 1; 22540acb7e48Sdrh } 22550acb7e48Sdrh pKeyMerge = 22560acb7e48Sdrh sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1)); 22570acb7e48Sdrh if( pKeyMerge ){ 22580acb7e48Sdrh pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy]; 2259ea678832Sdrh pKeyMerge->nField = (u16)nOrderBy; 22600acb7e48Sdrh pKeyMerge->enc = ENC(db); 22610acb7e48Sdrh for(i=0; i<nOrderBy; i++){ 22620acb7e48Sdrh CollSeq *pColl; 22630acb7e48Sdrh Expr *pTerm = pOrderBy->a[i].pExpr; 22640acb7e48Sdrh if( pTerm->flags & EP_ExpCollate ){ 22650acb7e48Sdrh pColl = pTerm->pColl; 22660acb7e48Sdrh }else{ 22670acb7e48Sdrh pColl = multiSelectCollSeq(pParse, p, aPermute[i]); 22680acb7e48Sdrh pTerm->flags |= EP_ExpCollate; 22690acb7e48Sdrh pTerm->pColl = pColl; 22700acb7e48Sdrh } 22710acb7e48Sdrh pKeyMerge->aColl[i] = pColl; 22720acb7e48Sdrh pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder; 22730acb7e48Sdrh } 22740acb7e48Sdrh } 22750acb7e48Sdrh }else{ 22760acb7e48Sdrh pKeyMerge = 0; 22770acb7e48Sdrh } 22780acb7e48Sdrh 22790acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 22800acb7e48Sdrh */ 22810acb7e48Sdrh p->pOrderBy = pOrderBy; 22826ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 22830acb7e48Sdrh 22840acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 22850acb7e48Sdrh ** for the logic that removes duplicate result rows when the 22860acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 22870acb7e48Sdrh */ 22880acb7e48Sdrh if( op==TK_ALL ){ 22890acb7e48Sdrh regPrev = 0; 22900acb7e48Sdrh }else{ 22910acb7e48Sdrh int nExpr = p->pEList->nExpr; 22921c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 22930acb7e48Sdrh regPrev = sqlite3GetTempRange(pParse, nExpr+1); 22940acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 22950acb7e48Sdrh pKeyDup = sqlite3DbMallocZero(db, 22960acb7e48Sdrh sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) ); 22970acb7e48Sdrh if( pKeyDup ){ 22980acb7e48Sdrh pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr]; 2299ea678832Sdrh pKeyDup->nField = (u16)nExpr; 23000acb7e48Sdrh pKeyDup->enc = ENC(db); 23010acb7e48Sdrh for(i=0; i<nExpr; i++){ 23020acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 23030acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 23040acb7e48Sdrh } 23050acb7e48Sdrh } 23060acb7e48Sdrh } 230792b01d53Sdrh 230892b01d53Sdrh /* Separate the left and the right query from one another 230992b01d53Sdrh */ 231092b01d53Sdrh p->pPrior = 0; 23117d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 23120acb7e48Sdrh if( pPrior->pPrior==0 ){ 23137d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 23140acb7e48Sdrh } 231592b01d53Sdrh 231692b01d53Sdrh /* Compute the limit registers */ 231792b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 23180acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 231992b01d53Sdrh regLimitA = ++pParse->nMem; 232092b01d53Sdrh regLimitB = ++pParse->nMem; 232192b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 232292b01d53Sdrh regLimitA); 232392b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 232492b01d53Sdrh }else{ 232592b01d53Sdrh regLimitA = regLimitB = 0; 232692b01d53Sdrh } 2327633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 23280acb7e48Sdrh p->pLimit = 0; 2329633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 23300acb7e48Sdrh p->pOffset = 0; 233192b01d53Sdrh 2332b21e7c70Sdrh regAddrA = ++pParse->nMem; 2333b21e7c70Sdrh regEofA = ++pParse->nMem; 2334b21e7c70Sdrh regAddrB = ++pParse->nMem; 2335b21e7c70Sdrh regEofB = ++pParse->nMem; 2336b21e7c70Sdrh regOutA = ++pParse->nMem; 2337b21e7c70Sdrh regOutB = ++pParse->nMem; 2338b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 2339b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 2340b21e7c70Sdrh 234192b01d53Sdrh /* Jump past the various subroutines and coroutines to the main 234292b01d53Sdrh ** merge loop 234392b01d53Sdrh */ 2344b21e7c70Sdrh j1 = sqlite3VdbeAddOp0(v, OP_Goto); 2345b21e7c70Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v); 234692b01d53Sdrh 23470acb7e48Sdrh 234892b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 23490acb7e48Sdrh ** left of the compound operator - the "A" select. 23500acb7e48Sdrh */ 2351b21e7c70Sdrh VdbeNoopComment((v, "Begin coroutine for left SELECT")); 235292b01d53Sdrh pPrior->iLimit = regLimitA; 23537f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 23547d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 2355b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA); 235692b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 2357b21e7c70Sdrh VdbeNoopComment((v, "End coroutine for left SELECT")); 2358b21e7c70Sdrh 235992b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 236092b01d53Sdrh ** the right - the "B" select 236192b01d53Sdrh */ 2362b21e7c70Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v); 2363b21e7c70Sdrh VdbeNoopComment((v, "Begin coroutine for right SELECT")); 236492b01d53Sdrh savedLimit = p->iLimit; 236592b01d53Sdrh savedOffset = p->iOffset; 236692b01d53Sdrh p->iLimit = regLimitB; 236792b01d53Sdrh p->iOffset = 0; 23687f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 23697d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 237092b01d53Sdrh p->iLimit = savedLimit; 237192b01d53Sdrh p->iOffset = savedOffset; 2372b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB); 237392b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 2374b21e7c70Sdrh VdbeNoopComment((v, "End coroutine for right SELECT")); 2375b21e7c70Sdrh 237692b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 23770acb7e48Sdrh ** select as the next output row of the compound select. 237892b01d53Sdrh */ 2379b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 23800acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 23810acb7e48Sdrh p, &destA, pDest, regOutA, 23820acb7e48Sdrh regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd); 2383b21e7c70Sdrh 238492b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 23850acb7e48Sdrh ** select as the next output row of the compound select. 238692b01d53Sdrh */ 23870acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 2388b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 23890acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 23900acb7e48Sdrh p, &destB, pDest, regOutB, 23910acb7e48Sdrh regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd); 23920acb7e48Sdrh } 2393b21e7c70Sdrh 239492b01d53Sdrh /* Generate a subroutine to run when the results from select A 239592b01d53Sdrh ** are exhausted and only data in select B remains. 239692b01d53Sdrh */ 239792b01d53Sdrh VdbeNoopComment((v, "eof-A subroutine")); 239892b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 23990acb7e48Sdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd); 240092b01d53Sdrh }else{ 24010acb7e48Sdrh addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd); 2402b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 240392b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 24040acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); 240595aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 2406b21e7c70Sdrh } 2407b21e7c70Sdrh 240892b01d53Sdrh /* Generate a subroutine to run when the results from select B 240992b01d53Sdrh ** are exhausted and only data in select A remains. 241092b01d53Sdrh */ 2411b21e7c70Sdrh if( op==TK_INTERSECT ){ 241292b01d53Sdrh addrEofB = addrEofA; 241395aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 2414b21e7c70Sdrh }else{ 241592b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 24160acb7e48Sdrh addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd); 2417b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 241892b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 24190acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); 2420b21e7c70Sdrh } 2421b21e7c70Sdrh 242292b01d53Sdrh /* Generate code to handle the case of A<B 242392b01d53Sdrh */ 2424b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 24250acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 242692b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 2427b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 242892b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 2429b21e7c70Sdrh 243092b01d53Sdrh /* Generate code to handle the case of A==B 243192b01d53Sdrh */ 2432b21e7c70Sdrh if( op==TK_ALL ){ 2433b21e7c70Sdrh addrAeqB = addrAltB; 24340acb7e48Sdrh }else if( op==TK_INTERSECT ){ 24350acb7e48Sdrh addrAeqB = addrAltB; 24360acb7e48Sdrh addrAltB++; 243792b01d53Sdrh }else{ 2438b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 24390acb7e48Sdrh addrAeqB = 244092b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 244192b01d53Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 244292b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 244392b01d53Sdrh } 2444b21e7c70Sdrh 244592b01d53Sdrh /* Generate code to handle the case of A>B 244692b01d53Sdrh */ 2447b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 2448b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 2449b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 2450b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 245192b01d53Sdrh } 24520acb7e48Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 2453b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); 245492b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 2455b21e7c70Sdrh 245692b01d53Sdrh /* This code runs once to initialize everything. 245792b01d53Sdrh */ 2458b21e7c70Sdrh sqlite3VdbeJumpHere(v, j1); 2459b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA); 2460b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB); 246192b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA); 24620acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB); 2463b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 2464b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); 246592b01d53Sdrh 246692b01d53Sdrh /* Implement the main merge loop 246792b01d53Sdrh */ 246892b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 24690acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 24700acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy, 24710acb7e48Sdrh (char*)pKeyMerge, P4_KEYINFO_HANDOFF); 2472b21e7c70Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); 247392b01d53Sdrh 24740acb7e48Sdrh /* Release temporary registers 24750acb7e48Sdrh */ 24760acb7e48Sdrh if( regPrev ){ 24770acb7e48Sdrh sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1); 24780acb7e48Sdrh } 24790acb7e48Sdrh 248092b01d53Sdrh /* Jump to the this point in order to terminate the query. 248192b01d53Sdrh */ 2482b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 2483b21e7c70Sdrh 248492b01d53Sdrh /* Set the number of output columns 248592b01d53Sdrh */ 24867d10d5a6Sdrh if( pDest->eDest==SRT_Output ){ 24870acb7e48Sdrh Select *pFirst = pPrior; 248892b01d53Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 248992b01d53Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 2490b21e7c70Sdrh } 249192b01d53Sdrh 24920acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 24930acb7e48Sdrh ** by the calling function */ 24945e7ad508Sdanielk1977 if( p->pPrior ){ 2495633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 24965e7ad508Sdanielk1977 } 24970acb7e48Sdrh p->pPrior = pPrior; 249892b01d53Sdrh 249992b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 250092b01d53Sdrh **** subqueries ****/ 25017f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, 0); 250292b01d53Sdrh return SQLITE_OK; 250392b01d53Sdrh } 2504de3e41e3Sdanielk1977 #endif 2505b21e7c70Sdrh 25063514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 250717435752Sdrh /* Forward Declarations */ 250817435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*); 250917435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *); 251017435752Sdrh 25112282792aSdrh /* 2512832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 25136a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 251484e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 25156a3ea0e6Sdrh ** unchanged.) 2516832508b7Sdrh ** 2517832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 2518832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 2519832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 2520832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 2521832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 2522832508b7Sdrh ** of the subquery rather the result set of the subquery. 2523832508b7Sdrh */ 2524b7916a78Sdrh static Expr *substExpr( 252517435752Sdrh sqlite3 *db, /* Report malloc errors to this connection */ 252617435752Sdrh Expr *pExpr, /* Expr in which substitution occurs */ 252717435752Sdrh int iTable, /* Table to be substituted */ 252817435752Sdrh ExprList *pEList /* Substitute expressions */ 252917435752Sdrh ){ 2530b7916a78Sdrh if( pExpr==0 ) return 0; 253150350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 253250350a15Sdrh if( pExpr->iColumn<0 ){ 253350350a15Sdrh pExpr->op = TK_NULL; 253450350a15Sdrh }else{ 2535832508b7Sdrh Expr *pNew; 253684e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 25376ab3a2ecSdanielk1977 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 2538b7916a78Sdrh pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); 253938210ac5Sdrh if( pNew && pExpr->pColl ){ 25400a458e5eSdanielk1977 pNew->pColl = pExpr->pColl; 25410a458e5eSdanielk1977 } 2542b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 2543b7916a78Sdrh pExpr = pNew; 254450350a15Sdrh } 2545832508b7Sdrh }else{ 2546b7916a78Sdrh pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); 2547b7916a78Sdrh pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); 25486ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 25496ab3a2ecSdanielk1977 substSelect(db, pExpr->x.pSelect, iTable, pEList); 25506ab3a2ecSdanielk1977 }else{ 25516ab3a2ecSdanielk1977 substExprList(db, pExpr->x.pList, iTable, pEList); 25526ab3a2ecSdanielk1977 } 2553832508b7Sdrh } 2554b7916a78Sdrh return pExpr; 2555832508b7Sdrh } 255617435752Sdrh static void substExprList( 255717435752Sdrh sqlite3 *db, /* Report malloc errors here */ 255817435752Sdrh ExprList *pList, /* List to scan and in which to make substitutes */ 255917435752Sdrh int iTable, /* Table to be substituted */ 256017435752Sdrh ExprList *pEList /* Substitute values */ 256117435752Sdrh ){ 2562832508b7Sdrh int i; 2563832508b7Sdrh if( pList==0 ) return; 2564832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 2565b7916a78Sdrh pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); 2566832508b7Sdrh } 2567832508b7Sdrh } 256817435752Sdrh static void substSelect( 256917435752Sdrh sqlite3 *db, /* Report malloc errors here */ 257017435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 257117435752Sdrh int iTable, /* Table to be replaced */ 257217435752Sdrh ExprList *pEList /* Substitute values */ 257317435752Sdrh ){ 2574588a9a1aSdrh SrcList *pSrc; 2575588a9a1aSdrh struct SrcList_item *pItem; 2576588a9a1aSdrh int i; 2577b3bce662Sdanielk1977 if( !p ) return; 257817435752Sdrh substExprList(db, p->pEList, iTable, pEList); 257917435752Sdrh substExprList(db, p->pGroupBy, iTable, pEList); 258017435752Sdrh substExprList(db, p->pOrderBy, iTable, pEList); 2581b7916a78Sdrh p->pHaving = substExpr(db, p->pHaving, iTable, pEList); 2582b7916a78Sdrh p->pWhere = substExpr(db, p->pWhere, iTable, pEList); 258317435752Sdrh substSelect(db, p->pPrior, iTable, pEList); 2584588a9a1aSdrh pSrc = p->pSrc; 2585e2f02bacSdrh assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ 2586e2f02bacSdrh if( ALWAYS(pSrc) ){ 2587588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 2588588a9a1aSdrh substSelect(db, pItem->pSelect, iTable, pEList); 2589588a9a1aSdrh } 2590588a9a1aSdrh } 2591b3bce662Sdanielk1977 } 25923514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 2593832508b7Sdrh 25943514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 2595832508b7Sdrh /* 2596630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 2597630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 25981350b030Sdrh ** 25991350b030Sdrh ** To understand the concept of flattening, consider the following 26001350b030Sdrh ** query: 26011350b030Sdrh ** 26021350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 26031350b030Sdrh ** 26041350b030Sdrh ** The default way of implementing this query is to execute the 26051350b030Sdrh ** subquery first and store the results in a temporary table, then 26061350b030Sdrh ** run the outer query on that temporary table. This requires two 26071350b030Sdrh ** passes over the data. Furthermore, because the temporary table 26081350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 2609832508b7Sdrh ** optimized. 26101350b030Sdrh ** 2611832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 26121350b030Sdrh ** a single flat select, like this: 26131350b030Sdrh ** 26141350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 26151350b030Sdrh ** 26161350b030Sdrh ** The code generated for this simpification gives the same result 2617832508b7Sdrh ** but only has to scan the data once. And because indices might 2618832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 2619832508b7Sdrh ** avoided. 26201350b030Sdrh ** 2621832508b7Sdrh ** Flattening is only attempted if all of the following are true: 26221350b030Sdrh ** 2623832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 26241350b030Sdrh ** 2625832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 2626832508b7Sdrh ** 26272b300d5dSdrh ** (3) The subquery is not the right operand of a left outer join 262849ad330dSdan ** (Originally ticket #306. Strengthened by ticket #3300) 2629832508b7Sdrh ** 263049ad330dSdan ** (4) The subquery is not DISTINCT. 2631832508b7Sdrh ** 263249ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 263349ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 263449ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 2635832508b7Sdrh ** 2636832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 2637832508b7Sdrh ** DISTINCT. 2638832508b7Sdrh ** 2639630d296cSdrh ** (7) The subquery has a FROM clause. TODO: For subqueries without 2640630d296cSdrh ** A FROM clause, consider adding a FROM close with the special 2641630d296cSdrh ** table sqlite_once that consists of a single row containing a 2642630d296cSdrh ** single NULL. 264308192d5fSdrh ** 2644df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 2645df199a25Sdrh ** 2646df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 2647df199a25Sdrh ** aggregates. 2648df199a25Sdrh ** 2649df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 2650df199a25Sdrh ** use LIMIT. 2651df199a25Sdrh ** 2652174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 2653174b6195Sdrh ** 26547b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 26552b300d5dSdrh ** a separate restriction deriving from ticket #350. 26563fc673e6Sdrh ** 265749ad330dSdan ** (13) The subquery and outer query do not both use LIMIT. 2658ac83963aSdrh ** 265949ad330dSdan ** (14) The subquery does not use OFFSET. 2660ac83963aSdrh ** 2661ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 2662f3913278Sdrh ** subquery does not have a LIMIT clause. 2663f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 2664ad91c6cdSdrh ** 2665c52e355dSdrh ** (16) The outer query is not an aggregate or the subquery does 2666c52e355dSdrh ** not contain ORDER BY. (Ticket #2942) This used to not matter 2667c52e355dSdrh ** until we introduced the group_concat() function. 2668c52e355dSdrh ** 2669f23329a2Sdanielk1977 ** (17) The sub-query is not a compound select, or it is a UNION ALL 26704914cf92Sdanielk1977 ** compound clause made up entirely of non-aggregate queries, and 2671f23329a2Sdanielk1977 ** the parent query: 2672f23329a2Sdanielk1977 ** 2673f23329a2Sdanielk1977 ** * is not itself part of a compound select, 2674f23329a2Sdanielk1977 ** * is not an aggregate or DISTINCT query, and 2675630d296cSdrh ** * is not a join 2676f23329a2Sdanielk1977 ** 26774914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 26784914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 2679630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 2680630d296cSdrh ** operator other than UNION ALL because all the other compound 2681630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 2682630d296cSdrh ** restriction (4). 2683f23329a2Sdanielk1977 ** 268449fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 268549fc1f60Sdanielk1977 ** ORDER by clause of the parent must be simple references to 268649fc1f60Sdanielk1977 ** columns of the sub-query. 268749fc1f60Sdanielk1977 ** 2688229cf702Sdrh ** (19) The subquery does not use LIMIT or the outer query does not 2689229cf702Sdrh ** have a WHERE clause. 2690229cf702Sdrh ** 2691e8902a70Sdrh ** (20) If the sub-query is a compound select, then it must not use 2692e8902a70Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 2693e8902a70Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 2694630d296cSdrh ** appear as unmodified result columns in the outer query. But we 2695e8902a70Sdrh ** have other optimizations in mind to deal with that case. 2696e8902a70Sdrh ** 2697a91491e5Sshaneh ** (21) The subquery does not use LIMIT or the outer query is not 2698a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 2699a91491e5Sshaneh ** 2700832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 2701832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2702832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2703832508b7Sdrh ** 2704665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 2705832508b7Sdrh ** If flattening is attempted this routine returns 1. 2706832508b7Sdrh ** 2707832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 2708832508b7Sdrh ** the subquery before this routine runs. 27091350b030Sdrh */ 27108c74a8caSdrh static int flattenSubquery( 2711524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 27128c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 27138c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 27148c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 27158c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 27168c74a8caSdrh ){ 2717524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 2718f23329a2Sdanielk1977 Select *pParent; 27190bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2720f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 2721ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2722ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 27230bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 27246a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 272591bb0eedSdrh int i; /* Loop counter */ 272691bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 272791bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 2728524cc21eSdanielk1977 sqlite3 *db = pParse->db; 27291350b030Sdrh 2730832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2731832508b7Sdrh */ 2732a78c22c4Sdrh assert( p!=0 ); 2733a78c22c4Sdrh assert( p->pPrior==0 ); /* Unable to flatten compound queries */ 273407096f68Sdrh if( db->flags & SQLITE_QueryFlattener ) return 0; 2735832508b7Sdrh pSrc = p->pSrc; 2736ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 273791bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 273849fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 273991bb0eedSdrh pSub = pSubitem->pSelect; 2740832508b7Sdrh assert( pSub!=0 ); 2741ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2742ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2743832508b7Sdrh pSubSrc = pSub->pSrc; 2744832508b7Sdrh assert( pSubSrc ); 2745ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2746ac83963aSdrh ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2747ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 2748ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 2749ac83963aSdrh ** and (14). */ 2750ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2751ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 2752f3913278Sdrh if( p->pRightmost && pSub->pLimit ){ 2753ad91c6cdSdrh return 0; /* Restriction (15) */ 2754ad91c6cdSdrh } 2755ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 275649ad330dSdan if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ 275749ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 275849ad330dSdan return 0; /* Restrictions (8)(9) */ 2759df199a25Sdrh } 27607d10d5a6Sdrh if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ 27617d10d5a6Sdrh return 0; /* Restriction (6) */ 27627d10d5a6Sdrh } 27637d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 2764ac83963aSdrh return 0; /* Restriction (11) */ 2765ac83963aSdrh } 2766c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 2767229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 2768a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 2769a91491e5Sshaneh return 0; /* Restriction (21) */ 2770a91491e5Sshaneh } 2771832508b7Sdrh 27722b300d5dSdrh /* OBSOLETE COMMENT 1: 27732b300d5dSdrh ** Restriction 3: If the subquery is a join, make sure the subquery is 27748af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 27758af4d3acSdrh ** is not allowed: 27768af4d3acSdrh ** 27778af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 27788af4d3acSdrh ** 27798af4d3acSdrh ** If we flatten the above, we would get 27808af4d3acSdrh ** 27818af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 27828af4d3acSdrh ** 27838af4d3acSdrh ** which is not at all the same thing. 27842b300d5dSdrh ** 27852b300d5dSdrh ** OBSOLETE COMMENT 2: 27862b300d5dSdrh ** Restriction 12: If the subquery is the right operand of a left outer 27873fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 27883fc673e6Sdrh ** An examples of why this is not allowed: 27893fc673e6Sdrh ** 27903fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 27913fc673e6Sdrh ** 27923fc673e6Sdrh ** If we flatten the above, we would get 27933fc673e6Sdrh ** 27943fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 27953fc673e6Sdrh ** 27963fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 27973fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 27982b300d5dSdrh ** 27992b300d5dSdrh ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: 28002b300d5dSdrh ** Ticket #3300 shows that flattening the right term of a LEFT JOIN 28012b300d5dSdrh ** is fraught with danger. Best to avoid the whole thing. If the 28022b300d5dSdrh ** subquery is the right term of a LEFT JOIN, then do not flatten. 28033fc673e6Sdrh */ 28042b300d5dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 ){ 28053fc673e6Sdrh return 0; 28063fc673e6Sdrh } 28073fc673e6Sdrh 2808f23329a2Sdanielk1977 /* Restriction 17: If the sub-query is a compound SELECT, then it must 2809f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 2810f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 2811f23329a2Sdanielk1977 ** queries. 2812f23329a2Sdanielk1977 */ 2813f23329a2Sdanielk1977 if( pSub->pPrior ){ 2814e8902a70Sdrh if( pSub->pOrderBy ){ 2815e8902a70Sdrh return 0; /* Restriction 20 */ 2816e8902a70Sdrh } 2817e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 2818f23329a2Sdanielk1977 return 0; 2819f23329a2Sdanielk1977 } 2820f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 2821ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 2822ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 28234b3ac73cSdrh assert( pSub->pSrc!=0 ); 28247d10d5a6Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 282580b3c548Sdanielk1977 || (pSub1->pPrior && pSub1->op!=TK_ALL) 28264b3ac73cSdrh || pSub1->pSrc->nSrc<1 282780b3c548Sdanielk1977 ){ 2828f23329a2Sdanielk1977 return 0; 2829f23329a2Sdanielk1977 } 28304b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 2831f23329a2Sdanielk1977 } 283249fc1f60Sdanielk1977 283349fc1f60Sdanielk1977 /* Restriction 18. */ 283449fc1f60Sdanielk1977 if( p->pOrderBy ){ 283549fc1f60Sdanielk1977 int ii; 283649fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 28374b3ac73cSdrh if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0; 283849fc1f60Sdanielk1977 } 283949fc1f60Sdanielk1977 } 2840f23329a2Sdanielk1977 } 2841f23329a2Sdanielk1977 28427d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 28437d10d5a6Sdrh 28447d10d5a6Sdrh /* Authorize the subquery */ 2845524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 2846524cc21eSdanielk1977 sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 2847524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 2848524cc21eSdanielk1977 28497d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 28507d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 28517d10d5a6Sdrh ** be of the form: 2852f23329a2Sdanielk1977 ** 2853f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 2854f23329a2Sdanielk1977 ** 2855f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 2856a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 2857f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 2858f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 2859f23329a2Sdanielk1977 ** select statements in the compound sub-query. 2860a78c22c4Sdrh ** 2861a78c22c4Sdrh ** Example: 2862a78c22c4Sdrh ** 2863a78c22c4Sdrh ** SELECT a+1 FROM ( 2864a78c22c4Sdrh ** SELECT x FROM tab 2865a78c22c4Sdrh ** UNION ALL 2866a78c22c4Sdrh ** SELECT y FROM tab 2867a78c22c4Sdrh ** UNION ALL 2868a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 2869a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 2870a78c22c4Sdrh ** 2871a78c22c4Sdrh ** Transformed into: 2872a78c22c4Sdrh ** 2873a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 2874a78c22c4Sdrh ** UNION ALL 2875a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 2876a78c22c4Sdrh ** UNION ALL 2877a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 2878a78c22c4Sdrh ** ORDER BY 1 2879a78c22c4Sdrh ** 2880a78c22c4Sdrh ** We call this the "compound-subquery flattening". 2881f23329a2Sdanielk1977 */ 2882f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 2883f23329a2Sdanielk1977 Select *pNew; 2884f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 28854b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 2886f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 2887f23329a2Sdanielk1977 p->pOrderBy = 0; 2888f23329a2Sdanielk1977 p->pSrc = 0; 2889f23329a2Sdanielk1977 p->pPrior = 0; 28904b86ef1dSdanielk1977 p->pLimit = 0; 28916ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 28924b86ef1dSdanielk1977 p->pLimit = pLimit; 2893a78c22c4Sdrh p->pOrderBy = pOrderBy; 2894a78c22c4Sdrh p->pSrc = pSrc; 2895a78c22c4Sdrh p->op = TK_ALL; 2896f23329a2Sdanielk1977 p->pRightmost = 0; 2897a78c22c4Sdrh if( pNew==0 ){ 2898a78c22c4Sdrh pNew = pPrior; 2899a78c22c4Sdrh }else{ 2900a78c22c4Sdrh pNew->pPrior = pPrior; 2901f23329a2Sdanielk1977 pNew->pRightmost = 0; 2902f23329a2Sdanielk1977 } 2903a78c22c4Sdrh p->pPrior = pNew; 2904a78c22c4Sdrh if( db->mallocFailed ) return 1; 2905a78c22c4Sdrh } 2906f23329a2Sdanielk1977 29077d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 29087d10d5a6Sdrh ** in the outer query. 2909832508b7Sdrh */ 2910f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 2911c31c2eb8Sdrh 2912a78c22c4Sdrh /* Delete the transient table structure associated with the 2913a78c22c4Sdrh ** subquery 2914a78c22c4Sdrh */ 2915a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 2916a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 2917a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 2918a78c22c4Sdrh pSubitem->zDatabase = 0; 2919a78c22c4Sdrh pSubitem->zName = 0; 2920a78c22c4Sdrh pSubitem->zAlias = 0; 2921a78c22c4Sdrh pSubitem->pSelect = 0; 2922a78c22c4Sdrh 2923a78c22c4Sdrh /* Defer deleting the Table object associated with the 2924a78c22c4Sdrh ** subquery until code generation is 2925a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 2926a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 2927ccfcbceaSdrh ** 2928ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 2929a78c22c4Sdrh */ 2930ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 2931a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 2932a78c22c4Sdrh if( pTabToDel->nRef==1 ){ 293365a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 293465a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 293565a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 2936a78c22c4Sdrh }else{ 2937a78c22c4Sdrh pTabToDel->nRef--; 2938a78c22c4Sdrh } 2939a78c22c4Sdrh pSubitem->pTab = 0; 2940a78c22c4Sdrh } 2941a78c22c4Sdrh 2942a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 2943a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 2944a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 2945a78c22c4Sdrh ** then this loop only runs once. 2946a78c22c4Sdrh ** 2947a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 2948c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2949c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2950c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2951c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2952c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2953c31c2eb8Sdrh ** elements we are now copying in. 2954c31c2eb8Sdrh */ 2955a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 2956a78c22c4Sdrh int nSubSrc; 2957ea678832Sdrh u8 jointype = 0; 2958a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 2959a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 2960a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 2961588a9a1aSdrh 2962a78c22c4Sdrh if( pSrc ){ 2963a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 2964a78c22c4Sdrh jointype = pSubitem->jointype; 2965588a9a1aSdrh }else{ 2966a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 2967a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 2968cfa063b3Sdrh if( pSrc==0 ){ 2969a78c22c4Sdrh assert( db->mallocFailed ); 2970a78c22c4Sdrh break; 2971cfa063b3Sdrh } 2972c31c2eb8Sdrh } 2973a78c22c4Sdrh 2974a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 2975a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 2976a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 2977a78c22c4Sdrh ** of the subquery. 2978a78c22c4Sdrh ** 2979a78c22c4Sdrh ** Example: 2980a78c22c4Sdrh ** 2981a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 2982a78c22c4Sdrh ** 2983a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 2984a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 2985a78c22c4Sdrh ** block of code will expand the out query to 4 slots. The middle 2986a78c22c4Sdrh ** slot is expanded to two slots in order to make space for the 2987a78c22c4Sdrh ** two elements in the FROM clause of the subquery. 2988a78c22c4Sdrh */ 2989a78c22c4Sdrh if( nSubSrc>1 ){ 2990a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 2991a78c22c4Sdrh if( db->mallocFailed ){ 2992a78c22c4Sdrh break; 2993c31c2eb8Sdrh } 2994c31c2eb8Sdrh } 2995a78c22c4Sdrh 2996a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 2997a78c22c4Sdrh ** outer query. 2998a78c22c4Sdrh */ 2999c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 3000c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 3001c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 3002c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 3003c31c2eb8Sdrh } 300461dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 3005c31c2eb8Sdrh 3006c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 3007c31c2eb8Sdrh ** references to the iParent in the outer query. 3008c31c2eb8Sdrh ** 3009c31c2eb8Sdrh ** Example: 3010c31c2eb8Sdrh ** 3011c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 3012c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 3013c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 3014c31c2eb8Sdrh ** 3015c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 3016c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 3017c31c2eb8Sdrh */ 3018f23329a2Sdanielk1977 pList = pParent->pEList; 3019832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 3020ccfcbceaSdrh if( pList->a[i].zName==0 ){ 3021b7916a78Sdrh const char *zSpan = pList->a[i].zSpan; 3022d6b8c434Sdrh if( ALWAYS(zSpan) ){ 3023b7916a78Sdrh pList->a[i].zName = sqlite3DbStrDup(db, zSpan); 3024832508b7Sdrh } 3025832508b7Sdrh } 3026ccfcbceaSdrh } 3027f23329a2Sdanielk1977 substExprList(db, pParent->pEList, iParent, pSub->pEList); 30281b2e0329Sdrh if( isAgg ){ 3029f23329a2Sdanielk1977 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList); 3030b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 30311b2e0329Sdrh } 3032174b6195Sdrh if( pSub->pOrderBy ){ 3033f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 3034f23329a2Sdanielk1977 pParent->pOrderBy = pSub->pOrderBy; 3035174b6195Sdrh pSub->pOrderBy = 0; 3036f23329a2Sdanielk1977 }else if( pParent->pOrderBy ){ 3037f23329a2Sdanielk1977 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList); 3038174b6195Sdrh } 3039832508b7Sdrh if( pSub->pWhere ){ 30406ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 3041832508b7Sdrh }else{ 3042832508b7Sdrh pWhere = 0; 3043832508b7Sdrh } 3044832508b7Sdrh if( subqueryIsAgg ){ 3045f23329a2Sdanielk1977 assert( pParent->pHaving==0 ); 3046f23329a2Sdanielk1977 pParent->pHaving = pParent->pWhere; 3047f23329a2Sdanielk1977 pParent->pWhere = pWhere; 3048b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 3049f23329a2Sdanielk1977 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 30506ab3a2ecSdanielk1977 sqlite3ExprDup(db, pSub->pHaving, 0)); 3051f23329a2Sdanielk1977 assert( pParent->pGroupBy==0 ); 30526ab3a2ecSdanielk1977 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); 3053832508b7Sdrh }else{ 3054b7916a78Sdrh pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList); 3055f23329a2Sdanielk1977 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); 3056832508b7Sdrh } 3057c31c2eb8Sdrh 3058c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 3059c31c2eb8Sdrh ** outer query is distinct. 3060c31c2eb8Sdrh */ 30617d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 30628c74a8caSdrh 3063a58fdfb1Sdanielk1977 /* 3064a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3065ac83963aSdrh ** 3066ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 3067ac83963aSdrh ** does not work if either limit is negative. 3068a58fdfb1Sdanielk1977 */ 3069a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 3070f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 3071a2dc3b1aSdanielk1977 pSub->pLimit = 0; 3072df199a25Sdrh } 3073f23329a2Sdanielk1977 } 30748c74a8caSdrh 3075c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 3076c31c2eb8Sdrh ** success. 3077c31c2eb8Sdrh */ 3078633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 3079f23329a2Sdanielk1977 3080832508b7Sdrh return 1; 30811350b030Sdrh } 30823514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 30831350b030Sdrh 30841350b030Sdrh /* 3085a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it 308608c88eb0Sdrh ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 3087a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be 3088a9d1ccb9Sdanielk1977 ** a min()/max() query if: 3089a9d1ccb9Sdanielk1977 ** 3090738bdcfbSdanielk1977 ** 1. There is a single object in the FROM clause. 3091738bdcfbSdanielk1977 ** 3092738bdcfbSdanielk1977 ** 2. There is a single expression in the result set, and it is 3093738bdcfbSdanielk1977 ** either min(x) or max(x), where x is a column reference. 3094a9d1ccb9Sdanielk1977 */ 30954f21c4afSdrh static u8 minMaxQuery(Select *p){ 3096a9d1ccb9Sdanielk1977 Expr *pExpr; 3097a9d1ccb9Sdanielk1977 ExprList *pEList = p->pEList; 3098a9d1ccb9Sdanielk1977 309908c88eb0Sdrh if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL; 3100a9d1ccb9Sdanielk1977 pExpr = pEList->a[0].pExpr; 310143152cf8Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 310243152cf8Sdrh if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0; 31036ab3a2ecSdanielk1977 pEList = pExpr->x.pList; 310443152cf8Sdrh if( pEList==0 || pEList->nExpr!=1 ) return 0; 310508c88eb0Sdrh if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL; 310633e619fcSdrh assert( !ExprHasProperty(pExpr, EP_IntValue) ); 310733e619fcSdrh if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){ 310808c88eb0Sdrh return WHERE_ORDERBY_MIN; 310933e619fcSdrh }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){ 311008c88eb0Sdrh return WHERE_ORDERBY_MAX; 3111a9d1ccb9Sdanielk1977 } 311208c88eb0Sdrh return WHERE_ORDERBY_NORMAL; 3113a9d1ccb9Sdanielk1977 } 3114a9d1ccb9Sdanielk1977 3115a9d1ccb9Sdanielk1977 /* 3116a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 3117a5533162Sdanielk1977 ** The second argment is the associated aggregate-info object. This 3118a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 3119a5533162Sdanielk1977 ** 3120a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 3121a5533162Sdanielk1977 ** 3122a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 3123a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 3124a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 3125a5533162Sdanielk1977 */ 3126a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 3127a5533162Sdanielk1977 Table *pTab; 3128a5533162Sdanielk1977 Expr *pExpr; 3129a5533162Sdanielk1977 3130a5533162Sdanielk1977 assert( !p->pGroupBy ); 3131a5533162Sdanielk1977 31327a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 3133a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 3134a5533162Sdanielk1977 ){ 3135a5533162Sdanielk1977 return 0; 3136a5533162Sdanielk1977 } 3137a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 3138a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 313902f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 314002f33725Sdanielk1977 314102f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 3142a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 3143a5533162Sdanielk1977 if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0; 3144a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 3145a5533162Sdanielk1977 3146a5533162Sdanielk1977 return pTab; 3147a5533162Sdanielk1977 } 3148a5533162Sdanielk1977 3149a5533162Sdanielk1977 /* 3150b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 3151b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 3152b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 3153b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 3154b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 3155b1c685b0Sdanielk1977 */ 3156b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 3157b1c685b0Sdanielk1977 if( pFrom->pTab && pFrom->zIndex ){ 3158b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 3159b1c685b0Sdanielk1977 char *zIndex = pFrom->zIndex; 3160b1c685b0Sdanielk1977 Index *pIdx; 3161b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 3162b1c685b0Sdanielk1977 pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 3163b1c685b0Sdanielk1977 pIdx=pIdx->pNext 3164b1c685b0Sdanielk1977 ); 3165b1c685b0Sdanielk1977 if( !pIdx ){ 3166b1c685b0Sdanielk1977 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0); 31671db95106Sdan pParse->checkSchema = 1; 3168b1c685b0Sdanielk1977 return SQLITE_ERROR; 3169b1c685b0Sdanielk1977 } 3170b1c685b0Sdanielk1977 pFrom->pIndex = pIdx; 3171b1c685b0Sdanielk1977 } 3172b1c685b0Sdanielk1977 return SQLITE_OK; 3173b1c685b0Sdanielk1977 } 3174b1c685b0Sdanielk1977 3175b1c685b0Sdanielk1977 /* 31767d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 31777d10d5a6Sdrh ** "Expanding" means to do the following: 31787d10d5a6Sdrh ** 31797d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 31807d10d5a6Sdrh ** element of the FROM clause. 31817d10d5a6Sdrh ** 31827d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 31837d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 31847d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 31857d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 31867d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 31877d10d5a6Sdrh ** without worrying about messing up the presistent representation 31887d10d5a6Sdrh ** of the view. 31897d10d5a6Sdrh ** 31907d10d5a6Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 31917d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 31927d10d5a6Sdrh ** 31937d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 31947d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 31957d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 31967d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 31977d10d5a6Sdrh ** 3198b3bce662Sdanielk1977 */ 31997d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 32007d10d5a6Sdrh Parse *pParse = pWalker->pParse; 32017d10d5a6Sdrh int i, j, k; 32027d10d5a6Sdrh SrcList *pTabList; 32037d10d5a6Sdrh ExprList *pEList; 32047d10d5a6Sdrh struct SrcList_item *pFrom; 32057d10d5a6Sdrh sqlite3 *db = pParse->db; 32067d10d5a6Sdrh 32077d10d5a6Sdrh if( db->mallocFailed ){ 32087d10d5a6Sdrh return WRC_Abort; 32097d10d5a6Sdrh } 321043152cf8Sdrh if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){ 32117d10d5a6Sdrh return WRC_Prune; 32127d10d5a6Sdrh } 32137d10d5a6Sdrh p->selFlags |= SF_Expanded; 32147d10d5a6Sdrh pTabList = p->pSrc; 32157d10d5a6Sdrh pEList = p->pEList; 32167d10d5a6Sdrh 32177d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 32187d10d5a6Sdrh ** the FROM clause of the SELECT statement. 32197d10d5a6Sdrh */ 32207d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 32217d10d5a6Sdrh 32227d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 32237d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 32247d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 32257d10d5a6Sdrh */ 32267d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 32277d10d5a6Sdrh Table *pTab; 32287d10d5a6Sdrh if( pFrom->pTab!=0 ){ 32297d10d5a6Sdrh /* This statement has already been prepared. There is no need 32307d10d5a6Sdrh ** to go further. */ 32317d10d5a6Sdrh assert( i==0 ); 32327d10d5a6Sdrh return WRC_Prune; 32337d10d5a6Sdrh } 32347d10d5a6Sdrh if( pFrom->zName==0 ){ 32357d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 32367d10d5a6Sdrh Select *pSel = pFrom->pSelect; 32377d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 32387d10d5a6Sdrh assert( pSel!=0 ); 32397d10d5a6Sdrh assert( pFrom->pTab==0 ); 32407d10d5a6Sdrh sqlite3WalkSelect(pWalker, pSel); 32417d10d5a6Sdrh pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 32427d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 32437d10d5a6Sdrh pTab->nRef = 1; 32447d10d5a6Sdrh pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab); 32457d10d5a6Sdrh while( pSel->pPrior ){ pSel = pSel->pPrior; } 32467d10d5a6Sdrh selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol); 32477d10d5a6Sdrh pTab->iPKey = -1; 32481ea87012Sdrh pTab->nRowEst = 1000000; 32497d10d5a6Sdrh pTab->tabFlags |= TF_Ephemeral; 32507d10d5a6Sdrh #endif 32517d10d5a6Sdrh }else{ 32527d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 32537d10d5a6Sdrh assert( pFrom->pTab==0 ); 32547d10d5a6Sdrh pFrom->pTab = pTab = 32557d10d5a6Sdrh sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase); 32567d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 32577d10d5a6Sdrh pTab->nRef++; 32587d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 32597d10d5a6Sdrh if( pTab->pSelect || IsVirtual(pTab) ){ 32607d10d5a6Sdrh /* We reach here if the named table is a really a view */ 32617d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 326243152cf8Sdrh assert( pFrom->pSelect==0 ); 32636ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 32647d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 32657d10d5a6Sdrh } 32667d10d5a6Sdrh #endif 32677d10d5a6Sdrh } 326885574e31Sdanielk1977 326985574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 3270b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 327185574e31Sdanielk1977 return WRC_Abort; 327285574e31Sdanielk1977 } 32737d10d5a6Sdrh } 32747d10d5a6Sdrh 32757d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 32767d10d5a6Sdrh */ 32777d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 32787d10d5a6Sdrh return WRC_Abort; 32797d10d5a6Sdrh } 32807d10d5a6Sdrh 32817d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 32827d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 32837d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 32847d10d5a6Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 32857d10d5a6Sdrh ** The following code just has to locate the TK_ALL expressions and expand 32867d10d5a6Sdrh ** each one to the list of all columns in all tables. 32877d10d5a6Sdrh ** 32887d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 32897d10d5a6Sdrh ** that need expanding. 32907d10d5a6Sdrh */ 32917d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 32927d10d5a6Sdrh Expr *pE = pEList->a[k].pExpr; 32937d10d5a6Sdrh if( pE->op==TK_ALL ) break; 329443152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 329543152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 329643152cf8Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; 32977d10d5a6Sdrh } 32987d10d5a6Sdrh if( k<pEList->nExpr ){ 32997d10d5a6Sdrh /* 33007d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 33017d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 33027d10d5a6Sdrh ** in the result set and expand them one by one. 33037d10d5a6Sdrh */ 33047d10d5a6Sdrh struct ExprList_item *a = pEList->a; 33057d10d5a6Sdrh ExprList *pNew = 0; 33067d10d5a6Sdrh int flags = pParse->db->flags; 33077d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 33087d10d5a6Sdrh && (flags & SQLITE_ShortColNames)==0; 33097d10d5a6Sdrh 33107d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 33117d10d5a6Sdrh Expr *pE = a[k].pExpr; 331243152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 331343152cf8Sdrh if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){ 33147d10d5a6Sdrh /* This particular expression does not need to be expanded. 33157d10d5a6Sdrh */ 3316b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 33177d10d5a6Sdrh if( pNew ){ 33187d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 3319b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 3320b7916a78Sdrh a[k].zName = 0; 3321b7916a78Sdrh a[k].zSpan = 0; 33227d10d5a6Sdrh } 33237d10d5a6Sdrh a[k].pExpr = 0; 33247d10d5a6Sdrh }else{ 33257d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 33267d10d5a6Sdrh ** expanded. */ 33277d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 33287d10d5a6Sdrh char *zTName; /* text of name of TABLE */ 332943152cf8Sdrh if( pE->op==TK_DOT ){ 333043152cf8Sdrh assert( pE->pLeft!=0 ); 333133e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 333233e619fcSdrh zTName = pE->pLeft->u.zToken; 33337d10d5a6Sdrh }else{ 33347d10d5a6Sdrh zTName = 0; 33357d10d5a6Sdrh } 33367d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 33377d10d5a6Sdrh Table *pTab = pFrom->pTab; 33387d10d5a6Sdrh char *zTabName = pFrom->zAlias; 333943152cf8Sdrh if( zTabName==0 ){ 33407d10d5a6Sdrh zTabName = pTab->zName; 33417d10d5a6Sdrh } 33427d10d5a6Sdrh if( db->mallocFailed ) break; 33437d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 33447d10d5a6Sdrh continue; 33457d10d5a6Sdrh } 33467d10d5a6Sdrh tableSeen = 1; 33477d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 33487d10d5a6Sdrh Expr *pExpr, *pRight; 33497d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 3350b7916a78Sdrh char *zColname; /* The computed column name */ 3351b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 3352b7916a78Sdrh Token sColname; /* Computed column name as a token */ 33537d10d5a6Sdrh 33547d10d5a6Sdrh /* If a column is marked as 'hidden' (currently only possible 33557d10d5a6Sdrh ** for virtual tables), do not include it in the expanded 33567d10d5a6Sdrh ** result-set list. 33577d10d5a6Sdrh */ 33587d10d5a6Sdrh if( IsHiddenColumn(&pTab->aCol[j]) ){ 33597d10d5a6Sdrh assert(IsVirtual(pTab)); 33607d10d5a6Sdrh continue; 33617d10d5a6Sdrh } 33627d10d5a6Sdrh 3363da55c48aSdrh if( i>0 && zTName==0 ){ 33642179b434Sdrh if( (pFrom->jointype & JT_NATURAL)!=0 33652179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 33662179b434Sdrh ){ 33677d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 33682179b434Sdrh ** table to the right of the join */ 33697d10d5a6Sdrh continue; 33707d10d5a6Sdrh } 33712179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 33727d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 33737d10d5a6Sdrh ** using clause from the table on the right. */ 33747d10d5a6Sdrh continue; 33757d10d5a6Sdrh } 33767d10d5a6Sdrh } 3377b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 3378b7916a78Sdrh zColname = zName; 3379b7916a78Sdrh zToFree = 0; 33807d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 3381b7916a78Sdrh Expr *pLeft; 3382b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 33837d10d5a6Sdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 3384b7916a78Sdrh if( longNames ){ 3385b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 3386b7916a78Sdrh zToFree = zColname; 3387b7916a78Sdrh } 33887d10d5a6Sdrh }else{ 33897d10d5a6Sdrh pExpr = pRight; 33907d10d5a6Sdrh } 3391b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 3392b7916a78Sdrh sColname.z = zColname; 3393b7916a78Sdrh sColname.n = sqlite3Strlen30(zColname); 3394b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 3395b7916a78Sdrh sqlite3DbFree(db, zToFree); 33967d10d5a6Sdrh } 33977d10d5a6Sdrh } 33987d10d5a6Sdrh if( !tableSeen ){ 33997d10d5a6Sdrh if( zTName ){ 34007d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 34017d10d5a6Sdrh }else{ 34027d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 34037d10d5a6Sdrh } 34047d10d5a6Sdrh } 34057d10d5a6Sdrh } 34067d10d5a6Sdrh } 34077d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 34087d10d5a6Sdrh p->pEList = pNew; 34097d10d5a6Sdrh } 34107d10d5a6Sdrh #if SQLITE_MAX_COLUMN 34117d10d5a6Sdrh if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 34127d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 34137d10d5a6Sdrh } 34147d10d5a6Sdrh #endif 34157d10d5a6Sdrh return WRC_Continue; 34167d10d5a6Sdrh } 34177d10d5a6Sdrh 34187d10d5a6Sdrh /* 34197d10d5a6Sdrh ** No-op routine for the parse-tree walker. 34207d10d5a6Sdrh ** 34217d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 34227d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 34237d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 34247d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 34257d10d5a6Sdrh ** subquery in the parser tree. 34267d10d5a6Sdrh */ 342762c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 342862c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 34297d10d5a6Sdrh return WRC_Continue; 34307d10d5a6Sdrh } 34317d10d5a6Sdrh 34327d10d5a6Sdrh /* 34337d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 34347d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 34357d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 34367d10d5a6Sdrh ** 34377d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 34387d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 34397d10d5a6Sdrh ** name resolution is performed. 34407d10d5a6Sdrh ** 34417d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 34427d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 34437d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 34447d10d5a6Sdrh */ 34457d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 34467d10d5a6Sdrh Walker w; 34477d10d5a6Sdrh w.xSelectCallback = selectExpander; 34487d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 34497d10d5a6Sdrh w.pParse = pParse; 34507d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 34517d10d5a6Sdrh } 34527d10d5a6Sdrh 34537d10d5a6Sdrh 34547d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 34557d10d5a6Sdrh /* 34567d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 34577d10d5a6Sdrh ** interface. 34587d10d5a6Sdrh ** 34597d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 34607d10d5a6Sdrh ** information to the Table structure that represents the result set 34617d10d5a6Sdrh ** of that subquery. 34627d10d5a6Sdrh ** 34637d10d5a6Sdrh ** The Table structure that represents the result set was constructed 34647d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 34657d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 34667d10d5a6Sdrh ** routine is called after identifier resolution. 34677d10d5a6Sdrh */ 34687d10d5a6Sdrh static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 34697d10d5a6Sdrh Parse *pParse; 34707d10d5a6Sdrh int i; 34717d10d5a6Sdrh SrcList *pTabList; 34727d10d5a6Sdrh struct SrcList_item *pFrom; 34737d10d5a6Sdrh 34749d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 34755a29d9cbSdrh if( (p->selFlags & SF_HasTypeInfo)==0 ){ 34767d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 34777d10d5a6Sdrh pParse = pWalker->pParse; 34787d10d5a6Sdrh pTabList = p->pSrc; 34797d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 34807d10d5a6Sdrh Table *pTab = pFrom->pTab; 348143152cf8Sdrh if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){ 34827d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 34837d10d5a6Sdrh Select *pSel = pFrom->pSelect; 34847d10d5a6Sdrh assert( pSel ); 34857d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 34867d10d5a6Sdrh selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel); 34877d10d5a6Sdrh } 34887d10d5a6Sdrh } 34895a29d9cbSdrh } 34907d10d5a6Sdrh return WRC_Continue; 34917d10d5a6Sdrh } 34927d10d5a6Sdrh #endif 34937d10d5a6Sdrh 34947d10d5a6Sdrh 34957d10d5a6Sdrh /* 34967d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 34977d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 34987d10d5a6Sdrh ** SELECT statement. 34997d10d5a6Sdrh ** 35007d10d5a6Sdrh ** Use this routine after name resolution. 35017d10d5a6Sdrh */ 35027d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 35037d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 35047d10d5a6Sdrh Walker w; 35057d10d5a6Sdrh w.xSelectCallback = selectAddSubqueryTypeInfo; 35067d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 35077d10d5a6Sdrh w.pParse = pParse; 35087d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 35097d10d5a6Sdrh #endif 35107d10d5a6Sdrh } 35117d10d5a6Sdrh 35127d10d5a6Sdrh 35137d10d5a6Sdrh /* 35147d10d5a6Sdrh ** This routine sets of a SELECT statement for processing. The 35157d10d5a6Sdrh ** following is accomplished: 35167d10d5a6Sdrh ** 35177d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 35187d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 35197d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 35207d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 35217d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 35227d10d5a6Sdrh ** 35237d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 35247d10d5a6Sdrh */ 35257d10d5a6Sdrh void sqlite3SelectPrep( 3526b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 3527b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 35287d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 3529b3bce662Sdanielk1977 ){ 35307d10d5a6Sdrh sqlite3 *db; 353143152cf8Sdrh if( NEVER(p==0) ) return; 35327d10d5a6Sdrh db = pParse->db; 35337d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 35347d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 35357d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 35367d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 35377d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 35387d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 3539f6bbe022Sdrh } 3540b3bce662Sdanielk1977 3541b3bce662Sdanielk1977 /* 354213449892Sdrh ** Reset the aggregate accumulator. 354313449892Sdrh ** 354413449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 354513449892Sdrh ** intermediate results while calculating an aggregate. This 354613449892Sdrh ** routine simply stores NULLs in all of those memory cells. 3547b3bce662Sdanielk1977 */ 354813449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 354913449892Sdrh Vdbe *v = pParse->pVdbe; 355013449892Sdrh int i; 3551c99130fdSdrh struct AggInfo_func *pFunc; 355213449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 355313449892Sdrh return; 355413449892Sdrh } 355513449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 35564c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); 355713449892Sdrh } 3558c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 35594c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); 3560c99130fdSdrh if( pFunc->iDistinct>=0 ){ 3561c99130fdSdrh Expr *pE = pFunc->pExpr; 35626ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 35636ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 35640daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 35650daa002cSdrh "argument"); 3566c99130fdSdrh pFunc->iDistinct = -1; 3567c99130fdSdrh }else{ 35686ab3a2ecSdanielk1977 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList); 356966a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 357066a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3571c99130fdSdrh } 3572c99130fdSdrh } 357313449892Sdrh } 3574b3bce662Sdanielk1977 } 3575b3bce662Sdanielk1977 3576b3bce662Sdanielk1977 /* 357713449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 357813449892Sdrh ** in the AggInfo structure. 3579b3bce662Sdanielk1977 */ 358013449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 358113449892Sdrh Vdbe *v = pParse->pVdbe; 358213449892Sdrh int i; 358313449892Sdrh struct AggInfo_func *pF; 358413449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 35856ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 35866ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 358766a5167bSdrh sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 358866a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 3589b3bce662Sdanielk1977 } 359013449892Sdrh } 359113449892Sdrh 359213449892Sdrh /* 359313449892Sdrh ** Update the accumulator memory cells for an aggregate based on 359413449892Sdrh ** the current cursor position. 359513449892Sdrh */ 359613449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 359713449892Sdrh Vdbe *v = pParse->pVdbe; 359813449892Sdrh int i; 35997a95789cSdrh int regHit = 0; 36007a95789cSdrh int addrHitTest = 0; 360113449892Sdrh struct AggInfo_func *pF; 360213449892Sdrh struct AggInfo_col *pC; 360313449892Sdrh 360413449892Sdrh pAggInfo->directMode = 1; 3605ceea3321Sdrh sqlite3ExprCacheClear(pParse); 360613449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 360713449892Sdrh int nArg; 3608c99130fdSdrh int addrNext = 0; 360998757157Sdrh int regAgg; 36106ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 36116ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 361213449892Sdrh if( pList ){ 361313449892Sdrh nArg = pList->nExpr; 3614892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 36157153d1fbSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 1); 361613449892Sdrh }else{ 361713449892Sdrh nArg = 0; 361898757157Sdrh regAgg = 0; 361913449892Sdrh } 3620c99130fdSdrh if( pF->iDistinct>=0 ){ 3621c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 3622c99130fdSdrh assert( nArg==1 ); 36232dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 3624c99130fdSdrh } 3625e82f5d04Sdrh if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){ 362613449892Sdrh CollSeq *pColl = 0; 362713449892Sdrh struct ExprList_item *pItem; 362813449892Sdrh int j; 3629e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 363043617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 363113449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 363213449892Sdrh } 363313449892Sdrh if( !pColl ){ 363413449892Sdrh pColl = pParse->db->pDfltColl; 363513449892Sdrh } 36367a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 36377a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 363813449892Sdrh } 363998757157Sdrh sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 364066a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 3641ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 3642da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 3643f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 3644c99130fdSdrh if( addrNext ){ 3645c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 3646ceea3321Sdrh sqlite3ExprCacheClear(pParse); 3647c99130fdSdrh } 364813449892Sdrh } 364967a6a40cSdan 365067a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 365167a6a40cSdan ** Otherwise, if any of the required column values are already present 365267a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 365367a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 365467a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 365567a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 365667a6a40cSdan ** 365767a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 365867a6a40cSdan ** values to an OP_Copy. 365967a6a40cSdan */ 36607a95789cSdrh if( regHit ){ 36617a95789cSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); 36627a95789cSdrh } 366367a6a40cSdan sqlite3ExprCacheClear(pParse); 366413449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 3665389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 366613449892Sdrh } 366713449892Sdrh pAggInfo->directMode = 0; 3668ceea3321Sdrh sqlite3ExprCacheClear(pParse); 36697a95789cSdrh if( addrHitTest ){ 36707a95789cSdrh sqlite3VdbeJumpHere(v, addrHitTest); 36717a95789cSdrh } 367213449892Sdrh } 367313449892Sdrh 3674b3bce662Sdanielk1977 /* 3675ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 3676ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 3677ef7075deSdan */ 3678ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 3679ef7075deSdan static void explainSimpleCount( 3680ef7075deSdan Parse *pParse, /* Parse context */ 3681ef7075deSdan Table *pTab, /* Table being queried */ 3682ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 3683ef7075deSdan ){ 3684ef7075deSdan if( pParse->explain==2 ){ 3685ef7075deSdan char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)", 3686ef7075deSdan pTab->zName, 3687ef7075deSdan pIdx ? "USING COVERING INDEX " : "", 3688ef7075deSdan pIdx ? pIdx->zName : "", 3689ef7075deSdan pTab->nRowEst 3690ef7075deSdan ); 3691ef7075deSdan sqlite3VdbeAddOp4( 3692ef7075deSdan pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC 3693ef7075deSdan ); 3694ef7075deSdan } 3695ef7075deSdan } 3696ef7075deSdan #else 3697ef7075deSdan # define explainSimpleCount(a,b,c) 3698ef7075deSdan #endif 3699ef7075deSdan 3700ef7075deSdan /* 37017d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 37029bb61fe7Sdrh ** 3703fef5208cSdrh ** The results are distributed in various ways depending on the 37046c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest 37056c8c8ce0Sdanielk1977 ** as follows: 3706fef5208cSdrh ** 37076c8c8ce0Sdanielk1977 ** pDest->eDest Result 3708fef5208cSdrh ** ------------ ------------------------------------------- 37097d10d5a6Sdrh ** SRT_Output Generate a row of output (using the OP_ResultRow 37107d10d5a6Sdrh ** opcode) for each row in the result set. 3711fef5208cSdrh ** 37127d10d5a6Sdrh ** SRT_Mem Only valid if the result is a single column. 37137d10d5a6Sdrh ** Store the first column of the first result row 37147d10d5a6Sdrh ** in register pDest->iParm then abandon the rest 37157d10d5a6Sdrh ** of the query. This destination implies "LIMIT 1". 3716fef5208cSdrh ** 37177d10d5a6Sdrh ** SRT_Set The result must be a single column. Store each 37187d10d5a6Sdrh ** row of result as the key in table pDest->iParm. 37197d10d5a6Sdrh ** Apply the affinity pDest->affinity before storing 37207d10d5a6Sdrh ** results. Used to implement "IN (SELECT ...)". 3721fef5208cSdrh ** 37226c8c8ce0Sdanielk1977 ** SRT_Union Store results as a key in a temporary table pDest->iParm. 372382c3d636Sdrh ** 37246c8c8ce0Sdanielk1977 ** SRT_Except Remove results from the temporary table pDest->iParm. 3725c4a3c779Sdrh ** 37267d10d5a6Sdrh ** SRT_Table Store results in temporary table pDest->iParm. 37277d10d5a6Sdrh ** This is like SRT_EphemTab except that the table 37287d10d5a6Sdrh ** is assumed to already be open. 37299bb61fe7Sdrh ** 37306c8c8ce0Sdanielk1977 ** SRT_EphemTab Create an temporary table pDest->iParm and store 37316c8c8ce0Sdanielk1977 ** the result there. The cursor is left open after 37327d10d5a6Sdrh ** returning. This is like SRT_Table except that 37337d10d5a6Sdrh ** this destination uses OP_OpenEphemeral to create 37347d10d5a6Sdrh ** the table first. 37356c8c8ce0Sdanielk1977 ** 37367d10d5a6Sdrh ** SRT_Coroutine Generate a co-routine that returns a new row of 37377d10d5a6Sdrh ** results each time it is invoked. The entry point 37387d10d5a6Sdrh ** of the co-routine is stored in register pDest->iParm. 37396c8c8ce0Sdanielk1977 ** 37406c8c8ce0Sdanielk1977 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result 37416c8c8ce0Sdanielk1977 ** set is not empty. 37426c8c8ce0Sdanielk1977 ** 37437d10d5a6Sdrh ** SRT_Discard Throw the results away. This is used by SELECT 37447d10d5a6Sdrh ** statements within triggers whose only purpose is 37457d10d5a6Sdrh ** the side-effects of functions. 3746e78e8284Sdrh ** 37479bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 37489bb61fe7Sdrh ** encountered, then an appropriate error message is left in 37499bb61fe7Sdrh ** pParse->zErrMsg. 37509bb61fe7Sdrh ** 37519bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 37529bb61fe7Sdrh ** calling function needs to do that. 37539bb61fe7Sdrh */ 37544adee20fSdanielk1977 int sqlite3Select( 3755cce7d176Sdrh Parse *pParse, /* The parser context */ 37569bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 37577d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 3758cce7d176Sdrh ){ 375913449892Sdrh int i, j; /* Loop counters */ 376013449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 376113449892Sdrh Vdbe *v; /* The virtual machine under construction */ 3762b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 3763a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 3764ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 37659bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 37669bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 37672282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 37682282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 376919a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 377019a775c2Sdrh int distinct; /* Table to use for the distinct set */ 37711d83f052Sdrh int rc = 1; /* Value to return from this function */ 3772b9bb7c18Sdrh int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 377338cc40c2Sdan int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */ 377413449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 3775ec7429aeSdrh int iEnd; /* Address of the end of the query */ 377617435752Sdrh sqlite3 *db; /* The database connection */ 37779bb61fe7Sdrh 37782ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 37792ce22453Sdan int iRestoreSelectId = pParse->iSelectId; 37802ce22453Sdan pParse->iSelectId = pParse->iNextSelectId++; 37812ce22453Sdan #endif 37822ce22453Sdan 378317435752Sdrh db = pParse->db; 378417435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 37856f7adc8aSdrh return 1; 37866f7adc8aSdrh } 37874adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 378813449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 3789daffd0e5Sdrh 37906c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 37919ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 37929ed1dfa8Sdanielk1977 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); 3793ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 3794ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 3795ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 3796ccfcbceaSdrh p->pOrderBy = 0; 37977d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 37989a99334dSdrh } 37997d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 3800ccfcbceaSdrh pOrderBy = p->pOrderBy; 3801b27b7f5dSdrh pTabList = p->pSrc; 3802b27b7f5dSdrh pEList = p->pEList; 3803956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 38049a99334dSdrh goto select_end; 38059a99334dSdrh } 38067d10d5a6Sdrh isAgg = (p->selFlags & SF_Aggregate)!=0; 380743152cf8Sdrh assert( pEList!=0 ); 3808cce7d176Sdrh 3809d820cb1bSdrh /* Begin generating code. 3810d820cb1bSdrh */ 38114adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 3812d820cb1bSdrh if( v==0 ) goto select_end; 3813d820cb1bSdrh 381474b617b2Sdan /* If writing to memory or generating a set 381574b617b2Sdan ** only a single column may be output. 381674b617b2Sdan */ 381774b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY 381874b617b2Sdan if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 381974b617b2Sdan goto select_end; 382074b617b2Sdan } 382174b617b2Sdan #endif 382274b617b2Sdan 3823d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 3824d820cb1bSdrh */ 382551522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3826f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 382713449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 38281013c932Sdrh SelectDest dest; 3829daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 3830f23329a2Sdanielk1977 int isAggSub; 3831c31c2eb8Sdrh 38325b6a9ed4Sdrh if( pSub==0 ) continue; 38335b6a9ed4Sdrh if( pItem->addrFillSub ){ 38345b6a9ed4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 38355b6a9ed4Sdrh continue; 38365b6a9ed4Sdrh } 3837daf79acbSdanielk1977 3838fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 3839fc976065Sdanielk1977 ** tree refered to by this, the parent select. The child select 3840fc976065Sdanielk1977 ** may contain expression trees of at most 3841fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 3842fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 3843fc976065Sdanielk1977 ** an exact limit. 3844fc976065Sdanielk1977 */ 3845fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 3846daf79acbSdanielk1977 38477d10d5a6Sdrh isAggSub = (pSub->selFlags & SF_Aggregate)!=0; 3848524cc21eSdanielk1977 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ 38495b6a9ed4Sdrh /* This subquery can be absorbed into its parent. */ 3850f23329a2Sdanielk1977 if( isAggSub ){ 38517d10d5a6Sdrh isAgg = 1; 38527d10d5a6Sdrh p->selFlags |= SF_Aggregate; 3853daf79acbSdanielk1977 } 3854daf79acbSdanielk1977 i = -1; 3855daf79acbSdanielk1977 }else{ 38565b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 38575b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 38585b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 38595b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 38605b6a9ed4Sdrh */ 38617157e8eaSdrh int topAddr; 386248f2d3b1Sdrh int onceAddr = 0; 38637157e8eaSdrh int retAddr; 38645b6a9ed4Sdrh assert( pItem->addrFillSub==0 ); 38655b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 38667157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 38677157e8eaSdrh pItem->addrFillSub = topAddr+1; 38687157e8eaSdrh VdbeNoopComment((v, "materialize %s", pItem->pTab->zName)); 38691d8cb21fSdan if( pItem->isCorrelated==0 ){ 38705b6a9ed4Sdrh /* If the subquery is no correlated and if we are not inside of 38715b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 38725b6a9ed4Sdrh ** once. */ 38731d8cb21fSdan onceAddr = sqlite3CodeOnce(pParse); 38745b6a9ed4Sdrh } 38751013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 3876ce7e189dSdan explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 38777d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 387895aa47b1Sdrh pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow; 387948f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 38807157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 38817157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 38827157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 3883cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 3884daf79acbSdanielk1977 } 388543152cf8Sdrh if( /*pParse->nErr ||*/ db->mallocFailed ){ 3886cfa063b3Sdrh goto select_end; 3887cfa063b3Sdrh } 3888fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 3889832508b7Sdrh pTabList = p->pSrc; 38906c8c8ce0Sdanielk1977 if( !IgnorableOrderby(pDest) ){ 3891832508b7Sdrh pOrderBy = p->pOrderBy; 3892acd4c695Sdrh } 3893daf79acbSdanielk1977 } 3894daf79acbSdanielk1977 pEList = p->pEList; 3895daf79acbSdanielk1977 #endif 3896daf79acbSdanielk1977 pWhere = p->pWhere; 3897832508b7Sdrh pGroupBy = p->pGroupBy; 3898832508b7Sdrh pHaving = p->pHaving; 38997d10d5a6Sdrh isDistinct = (p->selFlags & SF_Distinct)!=0; 3900832508b7Sdrh 3901f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3902f23329a2Sdanielk1977 /* If there is are a sequence of queries, do the earlier ones first. 3903f23329a2Sdanielk1977 */ 3904f23329a2Sdanielk1977 if( p->pPrior ){ 3905f23329a2Sdanielk1977 if( p->pRightmost==0 ){ 3906f23329a2Sdanielk1977 Select *pLoop, *pRight = 0; 3907f23329a2Sdanielk1977 int cnt = 0; 3908f23329a2Sdanielk1977 int mxSelect; 3909f23329a2Sdanielk1977 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 3910f23329a2Sdanielk1977 pLoop->pRightmost = p; 3911f23329a2Sdanielk1977 pLoop->pNext = pRight; 3912f23329a2Sdanielk1977 pRight = pLoop; 3913f23329a2Sdanielk1977 } 3914f23329a2Sdanielk1977 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; 3915f23329a2Sdanielk1977 if( mxSelect && cnt>mxSelect ){ 3916f23329a2Sdanielk1977 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 39172ce22453Sdan goto select_end; 3918f23329a2Sdanielk1977 } 3919f23329a2Sdanielk1977 } 39207f61e92cSdan rc = multiSelect(pParse, p, pDest); 392117c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 39227f61e92cSdan return rc; 3923f23329a2Sdanielk1977 } 3924f23329a2Sdanielk1977 #endif 3925f23329a2Sdanielk1977 39268c6f666bSdrh /* If there is both a GROUP BY and an ORDER BY clause and they are 39278c6f666bSdrh ** identical, then disable the ORDER BY clause since the GROUP BY 39288c6f666bSdrh ** will cause elements to come out in the correct order. This is 39298c6f666bSdrh ** an optimization - the correct answer should result regardless. 39308c6f666bSdrh ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER 39318c6f666bSdrh ** to disable this optimization for testing purposes. 39328c6f666bSdrh */ 39338c6f666bSdrh if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0 39348c6f666bSdrh && (db->flags & SQLITE_GroupByOrder)==0 ){ 39358c6f666bSdrh pOrderBy = 0; 39368c6f666bSdrh } 39378c6f666bSdrh 393850118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 393950118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 394050118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 394150118cdfSdan ** 394250118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 394350118cdfSdan ** 394450118cdfSdan ** is transformed to: 394550118cdfSdan ** 394650118cdfSdan ** SELECT xyz FROM ... GROUP BY xyz 394750118cdfSdan ** 394850118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 394950118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 395050118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 395150118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 395250118cdfSdan */ 395350118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 395450118cdfSdan && sqlite3ExprListCompare(pOrderBy, p->pEList)==0 395550118cdfSdan ){ 395650118cdfSdan p->selFlags &= ~SF_Distinct; 395750118cdfSdan p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0); 395850118cdfSdan pGroupBy = p->pGroupBy; 395950118cdfSdan pOrderBy = 0; 396050118cdfSdan } 396150118cdfSdan 39628b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 39638b4c40d8Sdrh ** index might end up being unused if the data can be 39649d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 3965b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 39669d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 39679d2985c7Sdrh ** variable is used to facilitate that change. 39687cedc8d4Sdanielk1977 */ 39697cedc8d4Sdanielk1977 if( pOrderBy ){ 39700342b1f5Sdrh KeyInfo *pKeyInfo; 39710342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 39729d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 3973b9bb7c18Sdrh p->addrOpenEphm[2] = addrSortIndex = 397466a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 397566a5167bSdrh pOrderBy->iECursor, pOrderBy->nExpr+2, 0, 397666a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 39779d2985c7Sdrh }else{ 39789d2985c7Sdrh addrSortIndex = -1; 39797cedc8d4Sdanielk1977 } 39807cedc8d4Sdanielk1977 39812d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 39822d0794e3Sdrh */ 39836c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 398466a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr); 39852d0794e3Sdrh } 39862d0794e3Sdrh 3987f42bacc2Sdrh /* Set the limiter. 3988f42bacc2Sdrh */ 3989f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 399095aa47b1Sdrh p->nSelectRow = (double)LARGEST_INT64; 3991f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 3992c6aff30cSdrh if( p->iLimit==0 && addrSortIndex>=0 ){ 3993c6aff30cSdrh sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen; 3994c6aff30cSdrh p->selFlags |= SF_UseSorter; 3995c6aff30cSdrh } 3996f42bacc2Sdrh 3997dece1a84Sdrh /* Open a virtual index to use for the distinct set. 3998cce7d176Sdrh */ 39992ce22453Sdan if( p->selFlags & SF_Distinct ){ 40000342b1f5Sdrh KeyInfo *pKeyInfo; 4001832508b7Sdrh distinct = pParse->nTab++; 40020342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 400338cc40c2Sdan addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0, 400466a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 4005d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 4006832508b7Sdrh }else{ 4007ec661058Sdrh distinct = addrDistinctIndex = -1; 4008efb7251dSdrh } 4009832508b7Sdrh 401013449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 401113449892Sdrh if( !isAgg && pGroupBy==0 ){ 401238cc40c2Sdan ExprList *pDist = (isDistinct ? p->pEList : 0); 401338cc40c2Sdan 401438cc40c2Sdan /* Begin the database scan. */ 401538cc40c2Sdan pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0); 40161d83f052Sdrh if( pWInfo==0 ) goto select_end; 401795aa47b1Sdrh if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut; 4018cce7d176Sdrh 4019b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 4020b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 40219d2985c7Sdrh ** into an OP_Noop. 40229d2985c7Sdrh */ 40239d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 402448f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortIndex); 4025b9bb7c18Sdrh p->addrOpenEphm[2] = -1; 40269d2985c7Sdrh } 40279d2985c7Sdrh 402838cc40c2Sdan if( pWInfo->eDistinct ){ 402950118cdfSdan VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 403050118cdfSdan 403154bbe7f1Sdan assert( addrDistinctIndex>=0 ); 403250118cdfSdan pOp = sqlite3VdbeGetOp(v, addrDistinctIndex); 403350118cdfSdan 403438cc40c2Sdan assert( isDistinct ); 403538cc40c2Sdan assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED 403638cc40c2Sdan || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE 403738cc40c2Sdan ); 403838cc40c2Sdan distinct = -1; 403938cc40c2Sdan if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){ 404038cc40c2Sdan int iJump; 404138cc40c2Sdan int iExpr; 404238cc40c2Sdan int iFlag = ++pParse->nMem; 404338cc40c2Sdan int iBase = pParse->nMem+1; 404438cc40c2Sdan int iBase2 = iBase + pEList->nExpr; 404538cc40c2Sdan pParse->nMem += (pEList->nExpr*2); 404638cc40c2Sdan 404738cc40c2Sdan /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The 404838cc40c2Sdan ** OP_Integer initializes the "first row" flag. */ 404938cc40c2Sdan pOp->opcode = OP_Integer; 405038cc40c2Sdan pOp->p1 = 1; 405138cc40c2Sdan pOp->p2 = iFlag; 405238cc40c2Sdan 405338cc40c2Sdan sqlite3ExprCodeExprList(pParse, pEList, iBase, 1); 405438cc40c2Sdan iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1; 405538cc40c2Sdan sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1); 405638cc40c2Sdan for(iExpr=0; iExpr<pEList->nExpr; iExpr++){ 405738cc40c2Sdan CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr); 405838cc40c2Sdan sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr); 405938cc40c2Sdan sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 406038cc40c2Sdan sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 406138cc40c2Sdan } 406238cc40c2Sdan sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue); 406338cc40c2Sdan 406438cc40c2Sdan sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag); 406538cc40c2Sdan assert( sqlite3VdbeCurrentAddr(v)==iJump ); 406638cc40c2Sdan sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr); 406750118cdfSdan }else{ 406850118cdfSdan pOp->opcode = OP_Noop; 406938cc40c2Sdan } 407038cc40c2Sdan } 407138cc40c2Sdan 407238cc40c2Sdan /* Use the standard inner loop. */ 407338cc40c2Sdan selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest, 4074a9671a22Sdrh pWInfo->iContinue, pWInfo->iBreak); 40752282792aSdrh 4076cce7d176Sdrh /* End the database scan loop. 4077cce7d176Sdrh */ 40784adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 407913449892Sdrh }else{ 408013449892Sdrh /* This is the processing for aggregate queries */ 408113449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 408213449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 408313449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 408413449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 408513449892Sdrh ** one row of the input to the aggregator has been 408613449892Sdrh ** processed */ 408713449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 408813449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 4089d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 40901c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 40911c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 4092d176611bSdrh 4093d176611bSdrh /* Remove any and all aliases between the result set and the 4094d176611bSdrh ** GROUP BY clause. 4095d176611bSdrh */ 4096d176611bSdrh if( pGroupBy ){ 4097dc5ea5c7Sdrh int k; /* Loop counter */ 4098d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 4099d176611bSdrh 4100dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 4101d176611bSdrh pItem->iAlias = 0; 4102d176611bSdrh } 4103dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 4104d176611bSdrh pItem->iAlias = 0; 4105d176611bSdrh } 410695aa47b1Sdrh if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100; 410795aa47b1Sdrh }else{ 410895aa47b1Sdrh p->nSelectRow = (double)1; 4109d176611bSdrh } 4110cce7d176Sdrh 411113449892Sdrh 4112d176611bSdrh /* Create a label to jump to when we want to abort the query */ 411313449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 411413449892Sdrh 411513449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 411613449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 411713449892Sdrh ** SELECT statement. 41182282792aSdrh */ 411913449892Sdrh memset(&sNC, 0, sizeof(sNC)); 412013449892Sdrh sNC.pParse = pParse; 412113449892Sdrh sNC.pSrcList = pTabList; 412213449892Sdrh sNC.pAggInfo = &sAggInfo; 412313449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 41249d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 4125d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 4126d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); 4127d2b3e23bSdrh if( pHaving ){ 4128d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 412913449892Sdrh } 413013449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 413113449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 41326ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 41336ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 413413449892Sdrh } 413517435752Sdrh if( db->mallocFailed ) goto select_end; 413613449892Sdrh 413713449892Sdrh /* Processing for aggregates with GROUP BY is very different and 41383c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 413913449892Sdrh */ 414013449892Sdrh if( pGroupBy ){ 414113449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 4142d176611bSdrh int j1; /* A-vs-B comparision jump */ 4143d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 4144d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 4145d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 4146d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 4147d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 4148d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 4149d176611bSdrh int regReset; /* Return address register for reset subroutine */ 415013449892Sdrh 415113449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 415213449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 41531c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 415413449892Sdrh ** will be converted into a Noop. 415513449892Sdrh */ 415613449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 415713449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 41581c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 4159cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 4160cd3e8f7cSdanielk1977 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 416113449892Sdrh 416213449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 416313449892Sdrh */ 41640a07c107Sdrh iUseFlag = ++pParse->nMem; 41650a07c107Sdrh iAbortFlag = ++pParse->nMem; 4166d176611bSdrh regOutputRow = ++pParse->nMem; 4167d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 4168d176611bSdrh regReset = ++pParse->nMem; 4169d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 41700a07c107Sdrh iAMem = pParse->nMem + 1; 417113449892Sdrh pParse->nMem += pGroupBy->nExpr; 41720a07c107Sdrh iBMem = pParse->nMem + 1; 417313449892Sdrh pParse->nMem += pGroupBy->nExpr; 41744c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 4175d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 41764c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 4177d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 4178b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 4179e313382eSdrh 418013449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 418113449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 418213449892Sdrh ** it might be a single loop that uses an index to extract information 418313449892Sdrh ** in the right order to begin with. 418413449892Sdrh */ 41852eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 418638cc40c2Sdan pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0); 41875360ad34Sdrh if( pWInfo==0 ) goto select_end; 418813449892Sdrh if( pGroupBy==0 ){ 418913449892Sdrh /* The optimizer is able to deliver rows in group by order so 4190b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 419113449892Sdrh ** cancelled later because we still need to use the pKeyInfo 419213449892Sdrh */ 419313449892Sdrh pGroupBy = p->pGroupBy; 419413449892Sdrh groupBySort = 0; 419513449892Sdrh }else{ 419613449892Sdrh /* Rows are coming out in undetermined order. We have to push 419713449892Sdrh ** each row into a sorting index, terminate the first loop, 419813449892Sdrh ** then loop over the sorting index in order to get the output 419913449892Sdrh ** in sorted order 420013449892Sdrh */ 4201892d3179Sdrh int regBase; 4202892d3179Sdrh int regRecord; 4203892d3179Sdrh int nCol; 4204892d3179Sdrh int nGroupBy; 4205892d3179Sdrh 42062ce22453Sdan explainTempTable(pParse, 42072ce22453Sdan isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY"); 42082ce22453Sdan 420913449892Sdrh groupBySort = 1; 4210892d3179Sdrh nGroupBy = pGroupBy->nExpr; 4211892d3179Sdrh nCol = nGroupBy + 1; 4212892d3179Sdrh j = nGroupBy+1; 421313449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 4214892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 4215892d3179Sdrh nCol++; 421613449892Sdrh j++; 421713449892Sdrh } 4218892d3179Sdrh } 4219892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 4220ceea3321Sdrh sqlite3ExprCacheClear(pParse); 4221191b54cbSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); 4222892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); 4223892d3179Sdrh j = nGroupBy+1; 4224892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 4225892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 4226892d3179Sdrh if( pCol->iSorterColumn>=j ){ 4227e55cbd72Sdrh int r1 = j + regBase; 42286a012f04Sdrh int r2; 4229701bb3b4Sdrh 42306a012f04Sdrh r2 = sqlite3ExprCodeGetColumn(pParse, 4231*a748fdccSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0); 42326a012f04Sdrh if( r1!=r2 ){ 42336a012f04Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); 42346a012f04Sdrh } 42356a012f04Sdrh j++; 4236892d3179Sdrh } 4237892d3179Sdrh } 4238892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 42391db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 42401c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 4241892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 4242892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 424313449892Sdrh sqlite3WhereEnd(pWInfo); 42445134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 42451c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 42461c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 42471c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 4248d4e70ebdSdrh VdbeComment((v, "GROUP BY sort")); 424913449892Sdrh sAggInfo.useSortingIdx = 1; 4250ceea3321Sdrh sqlite3ExprCacheClear(pParse); 425113449892Sdrh } 425213449892Sdrh 425313449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 425413449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 425513449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 425613449892Sdrh ** from the previous row currently stored in a0, a1, a2... 425713449892Sdrh */ 425813449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 4259ceea3321Sdrh sqlite3ExprCacheClear(pParse); 42601c9d835dSdrh if( groupBySort ){ 42611c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut); 42621c9d835dSdrh } 426313449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 426413449892Sdrh if( groupBySort ){ 42651c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 42661c9d835dSdrh if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 426713449892Sdrh }else{ 426813449892Sdrh sAggInfo.directMode = 1; 42692dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 427013449892Sdrh } 427113449892Sdrh } 427216ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 4273b21e7c70Sdrh (char*)pKeyInfo, P4_KEYINFO); 427416ee60ffSdrh j1 = sqlite3VdbeCurrentAddr(v); 427516ee60ffSdrh sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); 427613449892Sdrh 427713449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 4278e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 427913449892Sdrh ** block. If there were no changes, this block is skipped. 428013449892Sdrh ** 428113449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 428213449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 428313449892Sdrh ** and resets the aggregate accumulator registers in preparation 428413449892Sdrh ** for the next GROUP BY batch. 428513449892Sdrh */ 4286b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 42872eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 4288d4e70ebdSdrh VdbeComment((v, "output one row")); 42893c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); 4290d4e70ebdSdrh VdbeComment((v, "check abort flag")); 42912eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 4292d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 429313449892Sdrh 429413449892Sdrh /* Update the aggregate accumulators based on the content of 429513449892Sdrh ** the current row 429613449892Sdrh */ 429716ee60ffSdrh sqlite3VdbeJumpHere(v, j1); 429813449892Sdrh updateAccumulator(pParse, &sAggInfo); 42994c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 4300d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 430113449892Sdrh 430213449892Sdrh /* End of the loop 430313449892Sdrh */ 430413449892Sdrh if( groupBySort ){ 43051c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 430613449892Sdrh }else{ 430713449892Sdrh sqlite3WhereEnd(pWInfo); 430848f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 430913449892Sdrh } 431013449892Sdrh 431113449892Sdrh /* Output the final row of result 431213449892Sdrh */ 43132eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 4314d4e70ebdSdrh VdbeComment((v, "output final row")); 431513449892Sdrh 4316d176611bSdrh /* Jump over the subroutines 4317d176611bSdrh */ 4318d176611bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd); 4319d176611bSdrh 4320d176611bSdrh /* Generate a subroutine that outputs a single row of the result 4321d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 4322d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 4323d176611bSdrh ** the processing calls for the query to abort, this subroutine 4324d176611bSdrh ** increments the iAbortFlag memory location before returning in 4325d176611bSdrh ** order to signal the caller to abort. 4326d176611bSdrh */ 4327d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 4328d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 4329d176611bSdrh VdbeComment((v, "set abort flag")); 4330d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4331d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 4332d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 4333d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 4334d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 4335d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4336d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 4337d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 4338d176611bSdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 4339d176611bSdrh distinct, pDest, 4340d176611bSdrh addrOutputRow+1, addrSetAbort); 4341d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4342d176611bSdrh VdbeComment((v, "end groupby result generator")); 4343d176611bSdrh 4344d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 4345d176611bSdrh */ 4346d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 4347d176611bSdrh resetAccumulator(pParse, &sAggInfo); 4348d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 4349d176611bSdrh 435043152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 435113449892Sdrh else { 4352dba0137eSdanielk1977 ExprList *pDel = 0; 4353a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 4354a5533162Sdanielk1977 Table *pTab; 4355a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 4356a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 4357a5533162Sdanielk1977 ** the SQL statement is of the form: 4358a5533162Sdanielk1977 ** 4359a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 4360a5533162Sdanielk1977 ** 4361a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 4362a5533162Sdanielk1977 ** 4363a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 4364a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 4365a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 4366a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 4367a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 4368a5533162Sdanielk1977 */ 4369a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 4370a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 4371a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 4372a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 4373a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 4374a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 4375a9d1ccb9Sdanielk1977 4376a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 4377a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 4378a5533162Sdanielk1977 4379a5533162Sdanielk1977 /* Search for the index that has the least amount of columns. If 4380a5533162Sdanielk1977 ** there is such an index, and it has less columns than the table 4381a5533162Sdanielk1977 ** does, then we can assume that it consumes less space on disk and 4382a5533162Sdanielk1977 ** will therefore be cheaper to scan to determine the query result. 4383a5533162Sdanielk1977 ** In this case set iRoot to the root page number of the index b-tree 4384a5533162Sdanielk1977 ** and pKeyInfo to the KeyInfo structure required to navigate the 4385a5533162Sdanielk1977 ** index. 4386a5533162Sdanielk1977 ** 43873e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 43883e9548b3Sdrh ** 4389a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 4390a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 4391a5533162Sdanielk1977 */ 4392a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 43933e9548b3Sdrh if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){ 4394a5533162Sdanielk1977 pBest = pIdx; 4395a5533162Sdanielk1977 } 4396a5533162Sdanielk1977 } 4397a5533162Sdanielk1977 if( pBest && pBest->nColumn<pTab->nCol ){ 4398a5533162Sdanielk1977 iRoot = pBest->tnum; 4399a5533162Sdanielk1977 pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest); 4400a5533162Sdanielk1977 } 4401a5533162Sdanielk1977 4402a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 4403a5533162Sdanielk1977 sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb); 4404a5533162Sdanielk1977 if( pKeyInfo ){ 4405a5533162Sdanielk1977 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF); 4406a5533162Sdanielk1977 } 4407a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 4408a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 4409ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 4410a5533162Sdanielk1977 }else 4411a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 4412a5533162Sdanielk1977 { 4413738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 4414738bdcfbSdanielk1977 ** 4415738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 4416738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 4417738bdcfbSdanielk1977 ** 4418738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 4419738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 4420738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 4421738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 4422738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 4423738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 4424738bdcfbSdanielk1977 ** value of x, the only row required). 4425738bdcfbSdanielk1977 ** 4426738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 4427738bdcfbSdanielk1977 ** modify behaviour as follows: 4428738bdcfbSdanielk1977 ** 4429738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 4430738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 4431738bdcfbSdanielk1977 ** for x. 4432738bdcfbSdanielk1977 ** 4433738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 4434738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 4435738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 4436738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 4437738bdcfbSdanielk1977 */ 4438a5533162Sdanielk1977 ExprList *pMinMax = 0; 4439a5533162Sdanielk1977 u8 flag = minMaxQuery(p); 4440a9d1ccb9Sdanielk1977 if( flag ){ 44416ab3a2ecSdanielk1977 assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) ); 44426ab3a2ecSdanielk1977 pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0); 44436ab3a2ecSdanielk1977 pDel = pMinMax; 44440e359b30Sdrh if( pMinMax && !db->mallocFailed ){ 4445ea678832Sdrh pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; 4446a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 4447a9d1ccb9Sdanielk1977 } 44481013c932Sdrh } 4449a9d1ccb9Sdanielk1977 445013449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 445113449892Sdrh ** processing is much simpler since there is only a single row 445213449892Sdrh ** of output. 445313449892Sdrh */ 445413449892Sdrh resetAccumulator(pParse, &sAggInfo); 445538cc40c2Sdan pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag); 4456dba0137eSdanielk1977 if( pWInfo==0 ){ 4457633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 4458dba0137eSdanielk1977 goto select_end; 4459dba0137eSdanielk1977 } 446013449892Sdrh updateAccumulator(pParse, &sAggInfo); 4461a9d1ccb9Sdanielk1977 if( !pMinMax && flag ){ 4462a9d1ccb9Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); 4463a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 4464a5533162Sdanielk1977 (flag==WHERE_ORDERBY_MIN?"min":"max"))); 4465a9d1ccb9Sdanielk1977 } 446613449892Sdrh sqlite3WhereEnd(pWInfo); 446713449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 44687a895a80Sdanielk1977 } 44697a895a80Sdanielk1977 447013449892Sdrh pOrderBy = 0; 447135573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 447213449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 4473a9671a22Sdrh pDest, addrEnd, addrEnd); 4474633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 447513449892Sdrh } 447613449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 447713449892Sdrh 447813449892Sdrh } /* endif aggregate query */ 44792282792aSdrh 44802ce22453Sdan if( distinct>=0 ){ 44812ce22453Sdan explainTempTable(pParse, "DISTINCT"); 44822ce22453Sdan } 44832ce22453Sdan 4484cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 4485cce7d176Sdrh ** and send them to the callback one by one. 4486cce7d176Sdrh */ 4487cce7d176Sdrh if( pOrderBy ){ 44882ce22453Sdan explainTempTable(pParse, "ORDER BY"); 44896c8c8ce0Sdanielk1977 generateSortTail(pParse, p, v, pEList->nExpr, pDest); 4490cce7d176Sdrh } 44916a535340Sdrh 4492ec7429aeSdrh /* Jump here to skip this query 4493ec7429aeSdrh */ 4494ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 4495ec7429aeSdrh 44961d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 44971d83f052Sdrh ** to indicate no errors. 44981d83f052Sdrh */ 44991d83f052Sdrh rc = 0; 45001d83f052Sdrh 45011d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 45021d83f052Sdrh ** successful coding of the SELECT. 45031d83f052Sdrh */ 45041d83f052Sdrh select_end: 450517c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 4506955de52cSdanielk1977 45077d10d5a6Sdrh /* Identify column names if results of the SELECT are to be output. 4508955de52cSdanielk1977 */ 45097d10d5a6Sdrh if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ 4510955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 4511955de52cSdanielk1977 } 4512955de52cSdanielk1977 4513633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 4514633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 45151d83f052Sdrh return rc; 4516cce7d176Sdrh } 4517485f0039Sdrh 4518678a9aa7Sdrh #if defined(SQLITE_ENABLE_TREE_EXPLAIN) 4519485f0039Sdrh /* 45207e02e5e6Sdrh ** Generate a human-readable description of a the Select object. 4521485f0039Sdrh */ 4522a84203a0Sdrh static void explainOneSelect(Vdbe *pVdbe, Select *p){ 45237e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "SELECT "); 45244e2a9c32Sdrh if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ 45254e2a9c32Sdrh if( p->selFlags & SF_Distinct ){ 45264e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, "DISTINCT "); 4527485f0039Sdrh } 45284e2a9c32Sdrh if( p->selFlags & SF_Aggregate ){ 45294e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, "agg_flag "); 4530485f0039Sdrh } 45314e2a9c32Sdrh sqlite3ExplainNL(pVdbe); 45324e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, " "); 4533485f0039Sdrh } 45347e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pEList); 45357e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 45367e02e5e6Sdrh if( p->pSrc && p->pSrc->nSrc ){ 4537485f0039Sdrh int i; 45387e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "FROM "); 45397e02e5e6Sdrh sqlite3ExplainPush(pVdbe); 4540485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 4541485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 454204b8342bSdrh sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor); 4543485f0039Sdrh if( pItem->pSelect ){ 45447e02e5e6Sdrh sqlite3ExplainSelect(pVdbe, pItem->pSelect); 4545485f0039Sdrh if( pItem->pTab ){ 454604b8342bSdrh sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName); 454704b8342bSdrh } 4548485f0039Sdrh }else if( pItem->zName ){ 45497e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName); 4550485f0039Sdrh } 4551485f0039Sdrh if( pItem->zAlias ){ 455204b8342bSdrh sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias); 4553485f0039Sdrh } 4554a84203a0Sdrh if( pItem->jointype & JT_LEFT ){ 4555a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN"); 4556485f0039Sdrh } 45577e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4558485f0039Sdrh } 45597e02e5e6Sdrh sqlite3ExplainPop(pVdbe); 4560485f0039Sdrh } 4561485f0039Sdrh if( p->pWhere ){ 45627e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "WHERE "); 45637e02e5e6Sdrh sqlite3ExplainExpr(pVdbe, p->pWhere); 45647e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4565485f0039Sdrh } 4566485f0039Sdrh if( p->pGroupBy ){ 45677e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "GROUPBY "); 45687e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pGroupBy); 45697e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4570485f0039Sdrh } 4571485f0039Sdrh if( p->pHaving ){ 45727e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "HAVING "); 45737e02e5e6Sdrh sqlite3ExplainExpr(pVdbe, p->pHaving); 45747e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4575485f0039Sdrh } 4576485f0039Sdrh if( p->pOrderBy ){ 45777e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "ORDERBY "); 45787e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pOrderBy); 45797e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4580485f0039Sdrh } 4581a84203a0Sdrh if( p->pLimit ){ 4582a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "LIMIT "); 4583a84203a0Sdrh sqlite3ExplainExpr(pVdbe, p->pLimit); 4584a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4585a84203a0Sdrh } 4586a84203a0Sdrh if( p->pOffset ){ 4587a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "OFFSET "); 4588a84203a0Sdrh sqlite3ExplainExpr(pVdbe, p->pOffset); 4589a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4590485f0039Sdrh } 4591485f0039Sdrh } 4592a84203a0Sdrh void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){ 4593a84203a0Sdrh if( p==0 ){ 4594a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "(null-select)"); 4595a84203a0Sdrh return; 4596a84203a0Sdrh } 4597a84203a0Sdrh while( p->pPrior ) p = p->pPrior; 4598a84203a0Sdrh sqlite3ExplainPush(pVdbe); 4599a84203a0Sdrh while( p ){ 4600a84203a0Sdrh explainOneSelect(pVdbe, p); 4601a84203a0Sdrh p = p->pNext; 4602a84203a0Sdrh if( p==0 ) break; 4603a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4604a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op)); 4605a84203a0Sdrh } 46067e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "END"); 4607a84203a0Sdrh sqlite3ExplainPop(pVdbe); 4608485f0039Sdrh } 46097e02e5e6Sdrh 4610485f0039Sdrh /* End of the structure debug printing code 4611485f0039Sdrh *****************************************************************************/ 461214a55b71Smistachkin #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */ 4613