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; 392b596da8Sdrh pDest->iSDParm = iParm; 402b596da8Sdrh pDest->affSdst = 0; 412b596da8Sdrh pDest->iSdst = 0; 422b596da8Sdrh pDest->nSdst = 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 /* 529e8e4af76Sdrh ** An instance of the following object is used to record information about 530e8e4af76Sdrh ** how to process the DISTINCT keyword, to simplify passing that information 531e8e4af76Sdrh ** into the selectInnerLoop() routine. 532e8e4af76Sdrh */ 533e8e4af76Sdrh typedef struct DistinctCtx DistinctCtx; 534e8e4af76Sdrh struct DistinctCtx { 535e8e4af76Sdrh u8 isTnct; /* True if the DISTINCT keyword is present */ 536e8e4af76Sdrh u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ 537e8e4af76Sdrh int tabTnct; /* Ephemeral table used for DISTINCT processing */ 538e8e4af76Sdrh int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ 539e8e4af76Sdrh }; 540e8e4af76Sdrh 541e8e4af76Sdrh /* 5422282792aSdrh ** This routine generates the code for the inside of the inner loop 5432282792aSdrh ** of a SELECT. 54482c3d636Sdrh ** 54538640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 54638640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 54738640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 54838640e15Sdrh ** datatypes for each column. 5492282792aSdrh */ 550d2b3e23bSdrh static void selectInnerLoop( 5512282792aSdrh Parse *pParse, /* The parser context */ 552df199a25Sdrh Select *p, /* The complete select statement being coded */ 5532282792aSdrh ExprList *pEList, /* List of values being extracted */ 55482c3d636Sdrh int srcTab, /* Pull data from this table */ 555967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 5562282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 557e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 5586c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 5592282792aSdrh int iContinue, /* Jump here to continue with next row */ 560a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 5612282792aSdrh ){ 5622282792aSdrh Vdbe *v = pParse->pVdbe; 563d847eaadSdrh int i; 564ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 565d847eaadSdrh int regResult; /* Start of memory holding result set */ 566d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 5672b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 568d847eaadSdrh int nResultCol; /* Number of result columns */ 56938640e15Sdrh 5701c767f0dSdrh assert( v ); 5711c767f0dSdrh if( NEVER(v==0) ) return; 57238640e15Sdrh assert( pEList!=0 ); 573e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 574ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 575b7654111Sdrh codeOffset(v, p, iContinue); 576df199a25Sdrh } 577df199a25Sdrh 578967e8b73Sdrh /* Pull the requested columns. 5792282792aSdrh */ 58038640e15Sdrh if( nColumn>0 ){ 581d847eaadSdrh nResultCol = nColumn; 582a2a49dc9Sdrh }else{ 583d847eaadSdrh nResultCol = pEList->nExpr; 584a2a49dc9Sdrh } 5852b596da8Sdrh if( pDest->iSdst==0 ){ 5862b596da8Sdrh pDest->iSdst = pParse->nMem+1; 5872b596da8Sdrh pDest->nSdst = nResultCol; 5880acb7e48Sdrh pParse->nMem += nResultCol; 5891c767f0dSdrh }else{ 5902b596da8Sdrh assert( pDest->nSdst==nResultCol ); 5911013c932Sdrh } 5922b596da8Sdrh regResult = pDest->iSdst; 593a2a49dc9Sdrh if( nColumn>0 ){ 594967e8b73Sdrh for(i=0; i<nColumn; i++){ 595d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 59682c3d636Sdrh } 5979ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 5989ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 5999ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 6009ed1dfa8Sdanielk1977 */ 601ceea3321Sdrh sqlite3ExprCacheClear(pParse); 6027d10d5a6Sdrh sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output); 603a2a49dc9Sdrh } 604d847eaadSdrh nColumn = nResultCol; 6052282792aSdrh 606daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 607daffd0e5Sdrh ** and this row has been seen before, then do not make this row 608daffd0e5Sdrh ** part of the result. 6092282792aSdrh */ 610ea48eb2eSdrh if( hasDistinct ){ 611f8875400Sdrh assert( pEList!=0 ); 612f8875400Sdrh assert( pEList->nExpr==nColumn ); 613e8e4af76Sdrh switch( pDistinct->eTnctType ){ 614e8e4af76Sdrh case WHERE_DISTINCT_ORDERED: { 615e8e4af76Sdrh VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 616e8e4af76Sdrh int iJump; /* Jump destination */ 617e8e4af76Sdrh int regPrev; /* Previous row content */ 618e8e4af76Sdrh 619e8e4af76Sdrh /* Allocate space for the previous row */ 620e8e4af76Sdrh regPrev = pParse->nMem+1; 621e8e4af76Sdrh pParse->nMem += nColumn; 622e8e4af76Sdrh 623e8e4af76Sdrh /* Change the OP_OpenEphemeral coded earlier to an OP_Null 624e8e4af76Sdrh ** sets the MEM_Cleared bit on the first register of the 625e8e4af76Sdrh ** previous value. This will cause the OP_Ne below to always 626e8e4af76Sdrh ** fail on the first iteration of the loop even if the first 627e8e4af76Sdrh ** row is all NULLs. 628e8e4af76Sdrh */ 629e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 630e8e4af76Sdrh pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); 631e8e4af76Sdrh pOp->opcode = OP_Null; 632e8e4af76Sdrh pOp->p1 = 1; 633e8e4af76Sdrh pOp->p2 = regPrev; 634e8e4af76Sdrh 635e8e4af76Sdrh iJump = sqlite3VdbeCurrentAddr(v) + nColumn; 636e8e4af76Sdrh for(i=0; i<nColumn; i++){ 637e8e4af76Sdrh CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr); 638e8e4af76Sdrh if( i<nColumn-1 ){ 639e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); 640e8e4af76Sdrh }else{ 641e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); 642e8e4af76Sdrh } 643e8e4af76Sdrh sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 644e8e4af76Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 645e8e4af76Sdrh } 646e8e4af76Sdrh assert( sqlite3VdbeCurrentAddr(v)==iJump ); 647e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1); 648e8e4af76Sdrh break; 649e8e4af76Sdrh } 650e8e4af76Sdrh 651e8e4af76Sdrh case WHERE_DISTINCT_UNIQUE: { 652e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 653e8e4af76Sdrh break; 654e8e4af76Sdrh } 655e8e4af76Sdrh 656e8e4af76Sdrh default: { 657e8e4af76Sdrh assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 658e8e4af76Sdrh codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult); 659e8e4af76Sdrh break; 660e8e4af76Sdrh } 661e8e4af76Sdrh } 662ea48eb2eSdrh if( pOrderBy==0 ){ 663b7654111Sdrh codeOffset(v, p, iContinue); 664ea48eb2eSdrh } 6652282792aSdrh } 66682c3d636Sdrh 667c926afbcSdrh switch( eDest ){ 66882c3d636Sdrh /* In this mode, write each query result to the key of the temporary 66982c3d636Sdrh ** table iParm. 6702282792aSdrh */ 67113449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 672c926afbcSdrh case SRT_Union: { 6739cbf3425Sdrh int r1; 6749cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 675d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6769cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 6779cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 678c926afbcSdrh break; 679c926afbcSdrh } 68082c3d636Sdrh 68182c3d636Sdrh /* Construct a record from the query result, but instead of 68282c3d636Sdrh ** saving that record, use it as a key to delete elements from 68382c3d636Sdrh ** the temporary table iParm. 68482c3d636Sdrh */ 685c926afbcSdrh case SRT_Except: { 686e14006d0Sdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn); 687c926afbcSdrh break; 688c926afbcSdrh } 6895338a5f7Sdanielk1977 #endif 6905338a5f7Sdanielk1977 6915338a5f7Sdanielk1977 /* Store the result as data using a unique key. 6925338a5f7Sdanielk1977 */ 6935338a5f7Sdanielk1977 case SRT_Table: 694b9bb7c18Sdrh case SRT_EphemTab: { 695b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 696373cc2ddSdrh testcase( eDest==SRT_Table ); 697373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 698d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 6995338a5f7Sdanielk1977 if( pOrderBy ){ 700b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 7015338a5f7Sdanielk1977 }else{ 702b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 703b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 704b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 705b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 706b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 7075338a5f7Sdanielk1977 } 708b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 7095338a5f7Sdanielk1977 break; 7105338a5f7Sdanielk1977 } 7112282792aSdrh 71293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 7132282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 7142282792aSdrh ** then there should be a single item on the stack. Write this 7152282792aSdrh ** item into the set table with bogus data. 7162282792aSdrh */ 717c926afbcSdrh case SRT_Set: { 718967e8b73Sdrh assert( nColumn==1 ); 719634d81deSdrh pDest->affSdst = 720634d81deSdrh sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst); 721c926afbcSdrh if( pOrderBy ){ 722de941c60Sdrh /* At first glance you would think we could optimize out the 723de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 724de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 725de941c60Sdrh ** case the order does matter */ 726d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 727c926afbcSdrh }else{ 728b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 729634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1); 730da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, 1); 731b7654111Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 732b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 733c926afbcSdrh } 734c926afbcSdrh break; 735c926afbcSdrh } 73682c3d636Sdrh 737504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 738ec7429aeSdrh */ 739ec7429aeSdrh case SRT_Exists: { 7404c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 741ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 742ec7429aeSdrh break; 743ec7429aeSdrh } 744ec7429aeSdrh 7452282792aSdrh /* If this is a scalar select that is part of an expression, then 7462282792aSdrh ** store the results in the appropriate memory cell and break out 7472282792aSdrh ** of the scan loop. 7482282792aSdrh */ 749c926afbcSdrh case SRT_Mem: { 750967e8b73Sdrh assert( nColumn==1 ); 751c926afbcSdrh if( pOrderBy ){ 752d847eaadSdrh pushOntoSorter(pParse, pOrderBy, p, regResult); 753c926afbcSdrh }else{ 754b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regResult, iParm, 1); 755ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 756c926afbcSdrh } 757c926afbcSdrh break; 758c926afbcSdrh } 75993758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 7602282792aSdrh 761c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 762c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 763c182d163Sdrh ** popping the data from the stack. 764f46f905aSdrh */ 765e00ee6ebSdrh case SRT_Coroutine: 7667d10d5a6Sdrh case SRT_Output: { 767373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 768373cc2ddSdrh testcase( eDest==SRT_Output ); 769f46f905aSdrh if( pOrderBy ){ 770b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 771d847eaadSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); 772b7654111Sdrh pushOntoSorter(pParse, pOrderBy, p, r1); 773b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 774e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 7752b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 776c182d163Sdrh }else{ 777d847eaadSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); 778da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn); 779ac82fcf5Sdrh } 780142e30dfSdrh break; 781142e30dfSdrh } 782142e30dfSdrh 7836a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 784d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 785d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 786d7489c39Sdrh ** user-defined functions that have side effects. We do not care 787d7489c39Sdrh ** about the actual results of the select. 788d7489c39Sdrh */ 789c926afbcSdrh default: { 790f46f905aSdrh assert( eDest==SRT_Discard ); 791c926afbcSdrh break; 792c926afbcSdrh } 79393758c8dSdanielk1977 #endif 794c926afbcSdrh } 795ec7429aeSdrh 7965e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 7975e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 7985e87be87Sdrh ** the output for us. 799ec7429aeSdrh */ 8005e87be87Sdrh if( pOrderBy==0 && p->iLimit ){ 8019b918ed1Sdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); 802ec7429aeSdrh } 80382c3d636Sdrh } 80482c3d636Sdrh 80582c3d636Sdrh /* 806dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 807dece1a84Sdrh ** the collating sequence for each expression in that expression list. 808dece1a84Sdrh ** 8090342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 8100342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 8110342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 8120342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 8130342b1f5Sdrh ** index to implement a DISTINCT test. 8140342b1f5Sdrh ** 815dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 816dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 81766a5167bSdrh ** freed. Add the KeyInfo structure to the P4 field of an opcode using 81866a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. 819dece1a84Sdrh */ 820dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 821dece1a84Sdrh sqlite3 *db = pParse->db; 822dece1a84Sdrh int nExpr; 823dece1a84Sdrh KeyInfo *pInfo; 824dece1a84Sdrh struct ExprList_item *pItem; 825dece1a84Sdrh int i; 826dece1a84Sdrh 827dece1a84Sdrh nExpr = pList->nExpr; 82817435752Sdrh pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 829dece1a84Sdrh if( pInfo ){ 8302646da7eSdrh pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 831ea678832Sdrh pInfo->nField = (u16)nExpr; 83214db2665Sdanielk1977 pInfo->enc = ENC(db); 8332aca5846Sdrh pInfo->db = db; 834dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 835dece1a84Sdrh CollSeq *pColl; 836dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 837dece1a84Sdrh if( !pColl ){ 838dece1a84Sdrh pColl = db->pDfltColl; 839dece1a84Sdrh } 840dece1a84Sdrh pInfo->aColl[i] = pColl; 841dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 842dece1a84Sdrh } 843dece1a84Sdrh } 844dece1a84Sdrh return pInfo; 845dece1a84Sdrh } 846dece1a84Sdrh 8477f61e92cSdan #ifndef SQLITE_OMIT_COMPOUND_SELECT 8487f61e92cSdan /* 8497f61e92cSdan ** Name of the connection operator, used for error messages. 8507f61e92cSdan */ 8517f61e92cSdan static const char *selectOpName(int id){ 8527f61e92cSdan char *z; 8537f61e92cSdan switch( id ){ 8547f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 8557f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 8567f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 8577f61e92cSdan default: z = "UNION"; break; 8587f61e92cSdan } 8597f61e92cSdan return z; 8607f61e92cSdan } 8617f61e92cSdan #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 8627f61e92cSdan 8632ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 86417c0bc0cSdan /* 86517c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 86617c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 86717c0bc0cSdan ** where the caption is of the form: 86817c0bc0cSdan ** 86917c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 87017c0bc0cSdan ** 87117c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 87217c0bc0cSdan ** is determined by the zUsage argument. 87317c0bc0cSdan */ 8742ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 8752ce22453Sdan if( pParse->explain==2 ){ 8762ce22453Sdan Vdbe *v = pParse->pVdbe; 8772ce22453Sdan char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); 8782ce22453Sdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 8792ce22453Sdan } 8802ce22453Sdan } 88117c0bc0cSdan 88217c0bc0cSdan /* 883bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 884bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 885bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 886bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 887bb2b4418Sdan ** code with #ifndef directives. 888bb2b4418Sdan */ 889bb2b4418Sdan # define explainSetInteger(a, b) a = b 890bb2b4418Sdan 891bb2b4418Sdan #else 892bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 893bb2b4418Sdan # define explainTempTable(y,z) 894bb2b4418Sdan # define explainSetInteger(y,z) 895bb2b4418Sdan #endif 896bb2b4418Sdan 897bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) 898bb2b4418Sdan /* 8997f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 9007f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 9017f61e92cSdan ** where the caption is of one of the two forms: 9027f61e92cSdan ** 9037f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" 9047f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" 9057f61e92cSdan ** 9067f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding 9077f61e92cSdan ** function parameters, and op is the text representation of the parameter 9087f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, 9097f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 9107f61e92cSdan ** false, or the second form if it is true. 9117f61e92cSdan */ 9127f61e92cSdan static void explainComposite( 9137f61e92cSdan Parse *pParse, /* Parse context */ 9147f61e92cSdan int op, /* One of TK_UNION, TK_EXCEPT etc. */ 9157f61e92cSdan int iSub1, /* Subquery id 1 */ 9167f61e92cSdan int iSub2, /* Subquery id 2 */ 9177f61e92cSdan int bUseTmp /* True if a temp table was used */ 9187f61e92cSdan ){ 9197f61e92cSdan assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); 9207f61e92cSdan if( pParse->explain==2 ){ 9217f61e92cSdan Vdbe *v = pParse->pVdbe; 9227f61e92cSdan char *zMsg = sqlite3MPrintf( 92330969d3fSdan pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, 9247f61e92cSdan bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) 9257f61e92cSdan ); 9267f61e92cSdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 9277f61e92cSdan } 9287f61e92cSdan } 9292ce22453Sdan #else 93017c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */ 9317f61e92cSdan # define explainComposite(v,w,x,y,z) 9322ce22453Sdan #endif 933dece1a84Sdrh 934dece1a84Sdrh /* 935d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 936d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 937d8bc7086Sdrh ** we need to run the sorter and output the results. The following 938d8bc7086Sdrh ** routine generates the code needed to do that. 939d8bc7086Sdrh */ 940c926afbcSdrh static void generateSortTail( 941cdd536f0Sdrh Parse *pParse, /* Parsing context */ 942c926afbcSdrh Select *p, /* The SELECT statement */ 943c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 944c926afbcSdrh int nColumn, /* Number of columns of data */ 9456c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 946c926afbcSdrh ){ 947dc5ea5c7Sdrh int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ 948dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 949d8bc7086Sdrh int addr; 9500342b1f5Sdrh int iTab; 95161fc595fSdrh int pseudoTab = 0; 9520342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 953ffbc3088Sdrh 9546c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 9552b596da8Sdrh int iParm = pDest->iSDParm; 9566c8c8ce0Sdanielk1977 9572d401ab8Sdrh int regRow; 9582d401ab8Sdrh int regRowid; 9592d401ab8Sdrh 9609d2985c7Sdrh iTab = pOrderBy->iECursor; 9613e9ca094Sdrh regRow = sqlite3GetTempReg(pParse); 9627d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 963cdd536f0Sdrh pseudoTab = pParse->nTab++; 9643e9ca094Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn); 9653e9ca094Sdrh regRowid = 0; 9663e9ca094Sdrh }else{ 9673e9ca094Sdrh regRowid = sqlite3GetTempReg(pParse); 968cdd536f0Sdrh } 969c6aff30cSdrh if( p->selFlags & SF_UseSorter ){ 970c2bb3282Sdrh int regSortOut = ++pParse->nMem; 971c6aff30cSdrh int ptab2 = pParse->nTab++; 972c6aff30cSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2); 973c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 974c6aff30cSdrh codeOffset(v, p, addrContinue); 975c6aff30cSdrh sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut); 976c6aff30cSdrh sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow); 977c6aff30cSdrh sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 978c6aff30cSdrh }else{ 979dc5ea5c7Sdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); 980dc5ea5c7Sdrh codeOffset(v, p, addrContinue); 9812d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow); 982c6aff30cSdrh } 983c926afbcSdrh switch( eDest ){ 984c926afbcSdrh case SRT_Table: 985b9bb7c18Sdrh case SRT_EphemTab: { 9861c767f0dSdrh testcase( eDest==SRT_Table ); 9871c767f0dSdrh testcase( eDest==SRT_EphemTab ); 9882d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 9892d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 9902d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 991c926afbcSdrh break; 992c926afbcSdrh } 99393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 994c926afbcSdrh case SRT_Set: { 995c926afbcSdrh assert( nColumn==1 ); 996634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, 997634d81deSdrh &pDest->affSdst, 1); 998da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regRow, 1); 999a7a8e14bSdanielk1977 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); 1000c926afbcSdrh break; 1001c926afbcSdrh } 1002c926afbcSdrh case SRT_Mem: { 1003c926afbcSdrh assert( nColumn==1 ); 1004b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regRow, iParm, 1); 1005ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1006c926afbcSdrh break; 1007c926afbcSdrh } 100893758c8dSdanielk1977 #endif 1009373cc2ddSdrh default: { 1010ac82fcf5Sdrh int i; 1011373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 10121c767f0dSdrh testcase( eDest==SRT_Output ); 10131c767f0dSdrh testcase( eDest==SRT_Coroutine ); 1014ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 10152b596da8Sdrh assert( regRow!=pDest->iSdst+i ); 10162b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i); 10173e9ca094Sdrh if( i==0 ){ 10183e9ca094Sdrh sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 10193e9ca094Sdrh } 1020ac82fcf5Sdrh } 10217d10d5a6Sdrh if( eDest==SRT_Output ){ 10222b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 10232b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); 1024a9671a22Sdrh }else{ 10252b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1026ce665cf6Sdrh } 1027ac82fcf5Sdrh break; 1028ac82fcf5Sdrh } 1029c926afbcSdrh } 10302d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 10312d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1032ec7429aeSdrh 1033ec7429aeSdrh /* The bottom of the loop 1034ec7429aeSdrh */ 1035dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1036c6aff30cSdrh if( p->selFlags & SF_UseSorter ){ 1037c6aff30cSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); 1038c6aff30cSdrh }else{ 103966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); 1040c6aff30cSdrh } 1041dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 10427d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 104366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); 1044cdd536f0Sdrh } 1045d8bc7086Sdrh } 1046d8bc7086Sdrh 1047d8bc7086Sdrh /* 1048517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1049517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1050e78e8284Sdrh ** 1051955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1052955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1053955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1054955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1055955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1056955de52cSdanielk1977 ** considered a column by this function. 1057e78e8284Sdrh ** 1058955de52cSdanielk1977 ** SELECT col FROM tbl; 1059955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1060955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1061955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1062955de52cSdanielk1977 ** 1063955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 1064fcb78a49Sdrh */ 1065955de52cSdanielk1977 static const char *columnType( 1066955de52cSdanielk1977 NameContext *pNC, 1067955de52cSdanielk1977 Expr *pExpr, 1068955de52cSdanielk1977 const char **pzOriginDb, 1069955de52cSdanielk1977 const char **pzOriginTab, 1070955de52cSdanielk1977 const char **pzOriginCol 1071955de52cSdanielk1977 ){ 1072955de52cSdanielk1977 char const *zType = 0; 1073955de52cSdanielk1977 char const *zOriginDb = 0; 1074955de52cSdanielk1977 char const *zOriginTab = 0; 1075955de52cSdanielk1977 char const *zOriginCol = 0; 1076517eb646Sdanielk1977 int j; 1077373cc2ddSdrh if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; 10785338a5f7Sdanielk1977 107900e279d9Sdanielk1977 switch( pExpr->op ){ 108030bcf5dbSdrh case TK_AGG_COLUMN: 108100e279d9Sdanielk1977 case TK_COLUMN: { 1082955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1083955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1084955de52cSdanielk1977 ** database table or a subquery. 1085955de52cSdanielk1977 */ 1086955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1087955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1088955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 1089373cc2ddSdrh testcase( pExpr->op==TK_AGG_COLUMN ); 1090373cc2ddSdrh testcase( pExpr->op==TK_COLUMN ); 109143bc88bbSdan while( pNC && !pTab ){ 1092b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1093b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1094b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 10956a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1096955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1097b3bce662Sdanielk1977 }else{ 1098b3bce662Sdanielk1977 pNC = pNC->pNext; 1099b3bce662Sdanielk1977 } 1100b3bce662Sdanielk1977 } 1101955de52cSdanielk1977 110243bc88bbSdan if( pTab==0 ){ 1103417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1104417168adSdrh ** cause this condition to run. Since then, we have restructured how 1105417168adSdrh ** trigger code is generated and so this condition is no longer 110643bc88bbSdan ** possible. However, it can still be true for statements like 110743bc88bbSdan ** the following: 110843bc88bbSdan ** 110943bc88bbSdan ** CREATE TABLE t1(col INTEGER); 111043bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 111143bc88bbSdan ** 111243bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 111343bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 111443bc88bbSdan ** though it should really be "INTEGER". 111543bc88bbSdan ** 111643bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 111743bc88bbSdan ** used. When columnType() is called on the expression 111843bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 111943bc88bbSdan ** branch below. */ 11207e62779aSdrh break; 11217e62779aSdrh } 1122955de52cSdanielk1977 112343bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1124955de52cSdanielk1977 if( pS ){ 1125955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1126955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1127955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1128955de52cSdanielk1977 */ 11297b688edeSdrh if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ 1130955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1131955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1132955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1133955de52cSdanielk1977 */ 1134955de52cSdanielk1977 NameContext sNC; 1135955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1136955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 113743bc88bbSdan sNC.pNext = pNC; 1138955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1139955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 1140955de52cSdanielk1977 } 11411c767f0dSdrh }else if( ALWAYS(pTab->pSchema) ){ 1142955de52cSdanielk1977 /* A real table */ 1143955de52cSdanielk1977 assert( !pS ); 1144fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1145fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1146fcb78a49Sdrh if( iCol<0 ){ 1147fcb78a49Sdrh zType = "INTEGER"; 1148955de52cSdanielk1977 zOriginCol = "rowid"; 1149fcb78a49Sdrh }else{ 1150fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 1151955de52cSdanielk1977 zOriginCol = pTab->aCol[iCol].zName; 1152955de52cSdanielk1977 } 1153955de52cSdanielk1977 zOriginTab = pTab->zName; 1154955de52cSdanielk1977 if( pNC->pParse ){ 1155955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1156955de52cSdanielk1977 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 1157955de52cSdanielk1977 } 1158fcb78a49Sdrh } 115900e279d9Sdanielk1977 break; 1160736c22b8Sdrh } 116193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 116200e279d9Sdanielk1977 case TK_SELECT: { 1163955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1164955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1165955de52cSdanielk1977 ** statement. 1166955de52cSdanielk1977 */ 1167b3bce662Sdanielk1977 NameContext sNC; 11686ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1169955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 11706ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1171955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1172b3bce662Sdanielk1977 sNC.pNext = pNC; 1173955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1174955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 117500e279d9Sdanielk1977 break; 1176fcb78a49Sdrh } 117793758c8dSdanielk1977 #endif 117800e279d9Sdanielk1977 } 117900e279d9Sdanielk1977 1180955de52cSdanielk1977 if( pzOriginDb ){ 1181955de52cSdanielk1977 assert( pzOriginTab && pzOriginCol ); 1182955de52cSdanielk1977 *pzOriginDb = zOriginDb; 1183955de52cSdanielk1977 *pzOriginTab = zOriginTab; 1184955de52cSdanielk1977 *pzOriginCol = zOriginCol; 1185955de52cSdanielk1977 } 1186517eb646Sdanielk1977 return zType; 1187517eb646Sdanielk1977 } 1188517eb646Sdanielk1977 1189517eb646Sdanielk1977 /* 1190517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1191517eb646Sdanielk1977 ** in the result set. 1192517eb646Sdanielk1977 */ 1193517eb646Sdanielk1977 static void generateColumnTypes( 1194517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1195517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1196517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1197517eb646Sdanielk1977 ){ 11983f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1199517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1200517eb646Sdanielk1977 int i; 1201b3bce662Sdanielk1977 NameContext sNC; 1202b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1203955de52cSdanielk1977 sNC.pParse = pParse; 1204517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1205517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 12063f913576Sdrh const char *zType; 12073f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1208955de52cSdanielk1977 const char *zOrigDb = 0; 1209955de52cSdanielk1977 const char *zOrigTab = 0; 1210955de52cSdanielk1977 const char *zOrigCol = 0; 12113f913576Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1212955de52cSdanielk1977 121385b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 12144b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 12154b1ae99dSdanielk1977 ** virtual machine is deleted. 1216fbcd585fSdanielk1977 */ 121710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 121810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 121910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 12203f913576Sdrh #else 12213f913576Sdrh zType = columnType(&sNC, p, 0, 0, 0); 12223f913576Sdrh #endif 122310fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1224fcb78a49Sdrh } 12253f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */ 1226fcb78a49Sdrh } 1227fcb78a49Sdrh 1228fcb78a49Sdrh /* 1229fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1230fcb78a49Sdrh ** in the result set. This information is used to provide the 1231fcabd464Sdrh ** azCol[] values in the callback. 123282c3d636Sdrh */ 1233832508b7Sdrh static void generateColumnNames( 1234832508b7Sdrh Parse *pParse, /* Parser context */ 1235ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1236832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1237832508b7Sdrh ){ 1238d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 12396a3ea0e6Sdrh int i, j; 12409bb575fdSdrh sqlite3 *db = pParse->db; 1241fcabd464Sdrh int fullNames, shortNames; 1242fcabd464Sdrh 1243fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 12443cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 12453cf86063Sdanielk1977 if( pParse->explain ){ 124661de0d1bSdanielk1977 return; 12473cf86063Sdanielk1977 } 12485338a5f7Sdanielk1977 #endif 12493cf86063Sdanielk1977 1250e2f02bacSdrh if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; 1251d8bc7086Sdrh pParse->colNamesSet = 1; 1252fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1253fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 125422322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 125582c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 125682c3d636Sdrh Expr *p; 12575a38705eSdrh p = pEList->a[i].pExpr; 1258373cc2ddSdrh if( NEVER(p==0) ) continue; 125982c3d636Sdrh if( pEList->a[i].zName ){ 126082c3d636Sdrh char *zName = pEList->a[i].zName; 126110fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1262f018cc2eSdrh }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ 12636a3ea0e6Sdrh Table *pTab; 126497665873Sdrh char *zCol; 12658aff1015Sdrh int iCol = p->iColumn; 1266e2f02bacSdrh for(j=0; ALWAYS(j<pTabList->nSrc); j++){ 1267e2f02bacSdrh if( pTabList->a[j].iCursor==p->iTable ) break; 1268e2f02bacSdrh } 12696a3ea0e6Sdrh assert( j<pTabList->nSrc ); 12706a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 12718aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 127297665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1273b1363206Sdrh if( iCol<0 ){ 127447a6db2bSdrh zCol = "rowid"; 1275b1363206Sdrh }else{ 1276b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1277b1363206Sdrh } 1278e49b146fSdrh if( !shortNames && !fullNames ){ 127910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1280b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 12811c767f0dSdrh }else if( fullNames ){ 128282c3d636Sdrh char *zName = 0; 12831c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 128410fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 128582c3d636Sdrh }else{ 128610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 128782c3d636Sdrh } 12881bee3d7bSdrh }else{ 128910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1290b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 129182c3d636Sdrh } 129282c3d636Sdrh } 129376d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 12945080aaa7Sdrh } 129582c3d636Sdrh 1296d8bc7086Sdrh /* 12977d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions 12987d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 12997d10d5a6Sdrh ** column names for a table that would hold the expression list. 13007d10d5a6Sdrh ** 13017d10d5a6Sdrh ** All column names will be unique. 13027d10d5a6Sdrh ** 13037d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 13047d10d5a6Sdrh ** and other fields of Column are zeroed. 13057d10d5a6Sdrh ** 13067d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 13077d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1308315555caSdrh */ 13097d10d5a6Sdrh static int selectColumnsFromExprList( 13107d10d5a6Sdrh Parse *pParse, /* Parsing context */ 13117d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 1312d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 13137d10d5a6Sdrh Column **paCol /* Write the new column list here */ 13147d10d5a6Sdrh ){ 1315dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1316dc5ea5c7Sdrh int i, j; /* Loop counters */ 1317dc5ea5c7Sdrh int cnt; /* Index added to make the name unique */ 1318dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1319dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1320dc5ea5c7Sdrh Expr *p; /* Expression for a single result column */ 1321dc5ea5c7Sdrh char *zName; /* Column name */ 1322dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 132379d5f63fSdrh 13248c2e0f02Sdan if( pEList ){ 13258c2e0f02Sdan nCol = pEList->nExpr; 13268c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 13278c2e0f02Sdan testcase( aCol==0 ); 13288c2e0f02Sdan }else{ 13298c2e0f02Sdan nCol = 0; 13308c2e0f02Sdan aCol = 0; 13318c2e0f02Sdan } 13328c2e0f02Sdan *pnCol = nCol; 13338c2e0f02Sdan *paCol = aCol; 13348c2e0f02Sdan 13357d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 133679d5f63fSdrh /* Get an appropriate name for the column 133779d5f63fSdrh */ 133879d5f63fSdrh p = pEList->a[i].pExpr; 133933e619fcSdrh assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue) 134033e619fcSdrh || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 ); 134191bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 134279d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 134317435752Sdrh zName = sqlite3DbStrDup(db, zName); 13447d10d5a6Sdrh }else{ 1345dc5ea5c7Sdrh Expr *pColExpr = p; /* The expression that is the result column name */ 1346dc5ea5c7Sdrh Table *pTab; /* Table associated with this expression */ 1347b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1348b07028f7Sdrh pColExpr = pColExpr->pRight; 1349b07028f7Sdrh assert( pColExpr!=0 ); 1350b07028f7Sdrh } 1351373cc2ddSdrh if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ 135293a960a0Sdrh /* For columns use the column name name */ 1353dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1354373cc2ddSdrh pTab = pColExpr->pTab; 1355f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1356f0209f74Sdrh zName = sqlite3MPrintf(db, "%s", 1357f0209f74Sdrh iCol>=0 ? pTab->aCol[iCol].zName : "rowid"); 1358b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 135933e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 136033e619fcSdrh zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); 136193a960a0Sdrh }else{ 136279d5f63fSdrh /* Use the original text of the column expression as its name */ 1363b7916a78Sdrh zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); 13647d10d5a6Sdrh } 136522f70c32Sdrh } 13667ce72f69Sdrh if( db->mallocFailed ){ 1367633e6d57Sdrh sqlite3DbFree(db, zName); 13687ce72f69Sdrh break; 1369dd5b2fa5Sdrh } 137079d5f63fSdrh 137179d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 137279d5f63fSdrh ** append a integer to the name so that it becomes unique. 137379d5f63fSdrh */ 1374ea678832Sdrh nName = sqlite3Strlen30(zName); 137579d5f63fSdrh for(j=cnt=0; j<i; j++){ 137679d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 1377633e6d57Sdrh char *zNewName; 13782564ef97Sdrh zName[nName] = 0; 1379633e6d57Sdrh zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt); 1380633e6d57Sdrh sqlite3DbFree(db, zName); 1381633e6d57Sdrh zName = zNewName; 138279d5f63fSdrh j = -1; 1383dd5b2fa5Sdrh if( zName==0 ) break; 138479d5f63fSdrh } 138579d5f63fSdrh } 138691bb0eedSdrh pCol->zName = zName; 13877d10d5a6Sdrh } 13887d10d5a6Sdrh if( db->mallocFailed ){ 13897d10d5a6Sdrh for(j=0; j<i; j++){ 13907d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 13917d10d5a6Sdrh } 13927d10d5a6Sdrh sqlite3DbFree(db, aCol); 13937d10d5a6Sdrh *paCol = 0; 13947d10d5a6Sdrh *pnCol = 0; 13957d10d5a6Sdrh return SQLITE_NOMEM; 13967d10d5a6Sdrh } 13977d10d5a6Sdrh return SQLITE_OK; 13987d10d5a6Sdrh } 1399e014a838Sdanielk1977 14007d10d5a6Sdrh /* 14017d10d5a6Sdrh ** Add type and collation information to a column list based on 14027d10d5a6Sdrh ** a SELECT statement. 14037d10d5a6Sdrh ** 14047d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 14057d10d5a6Sdrh ** The column list has only names, not types or collations. This 14067d10d5a6Sdrh ** routine goes through and adds the types and collations. 14077d10d5a6Sdrh ** 1408b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 14097d10d5a6Sdrh ** statement be resolved. 141079d5f63fSdrh */ 14117d10d5a6Sdrh static void selectAddColumnTypeAndCollation( 14127d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 14137d10d5a6Sdrh int nCol, /* Number of columns */ 14147d10d5a6Sdrh Column *aCol, /* List of columns */ 14157d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 14167d10d5a6Sdrh ){ 14177d10d5a6Sdrh sqlite3 *db = pParse->db; 14187d10d5a6Sdrh NameContext sNC; 14197d10d5a6Sdrh Column *pCol; 14207d10d5a6Sdrh CollSeq *pColl; 14217d10d5a6Sdrh int i; 14227d10d5a6Sdrh Expr *p; 14237d10d5a6Sdrh struct ExprList_item *a; 14247d10d5a6Sdrh 14257d10d5a6Sdrh assert( pSelect!=0 ); 14267d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 14277d10d5a6Sdrh assert( nCol==pSelect->pEList->nExpr || db->mallocFailed ); 14287d10d5a6Sdrh if( db->mallocFailed ) return; 1429c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1430b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 14317d10d5a6Sdrh a = pSelect->pEList->a; 14327d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 14337d10d5a6Sdrh p = a[i].pExpr; 14347d10d5a6Sdrh pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0)); 1435c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1436c4a64facSdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE; 1437b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1438b3bf556eSdanielk1977 if( pColl ){ 143917435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 14400202b29eSdanielk1977 } 144122f70c32Sdrh } 14427d10d5a6Sdrh } 14437d10d5a6Sdrh 14447d10d5a6Sdrh /* 14457d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 14467d10d5a6Sdrh ** the result set of that SELECT. 14477d10d5a6Sdrh */ 14487d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 14497d10d5a6Sdrh Table *pTab; 14507d10d5a6Sdrh sqlite3 *db = pParse->db; 14517d10d5a6Sdrh int savedFlags; 14527d10d5a6Sdrh 14537d10d5a6Sdrh savedFlags = db->flags; 14547d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 14557d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 14567d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 14577d10d5a6Sdrh if( pParse->nErr ) return 0; 14587d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 14597d10d5a6Sdrh db->flags = savedFlags; 14607d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 14617d10d5a6Sdrh if( pTab==0 ){ 14627d10d5a6Sdrh return 0; 14637d10d5a6Sdrh } 1464373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 1465b2468954Sdrh ** is disabled */ 1466373cc2ddSdrh assert( db->lookaside.bEnabled==0 ); 14677d10d5a6Sdrh pTab->nRef = 1; 14687d10d5a6Sdrh pTab->zName = 0; 14691ea87012Sdrh pTab->nRowEst = 1000000; 14707d10d5a6Sdrh selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 14717d10d5a6Sdrh selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect); 147222f70c32Sdrh pTab->iPKey = -1; 14737ce72f69Sdrh if( db->mallocFailed ){ 14741feeaed2Sdan sqlite3DeleteTable(db, pTab); 14757ce72f69Sdrh return 0; 14767ce72f69Sdrh } 147722f70c32Sdrh return pTab; 147822f70c32Sdrh } 147922f70c32Sdrh 148022f70c32Sdrh /* 1481d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1482d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1483d8bc7086Sdrh */ 14844adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1485d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1486d8bc7086Sdrh if( v==0 ){ 14874adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1488949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE 1489949f9cd5Sdrh if( v ){ 1490949f9cd5Sdrh sqlite3VdbeAddOp0(v, OP_Trace); 1491949f9cd5Sdrh } 1492949f9cd5Sdrh #endif 1493d8bc7086Sdrh } 1494d8bc7086Sdrh return v; 1495d8bc7086Sdrh } 1496d8bc7086Sdrh 149715007a99Sdrh 1498d8bc7086Sdrh /* 14997b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1500ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 15017b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1502a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1503a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1504a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1505a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 15067b58daeaSdrh ** 1507d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1508ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 15097b58daeaSdrh ** iOffset should have been preset to appropriate default values 15107b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1511ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 15127b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 15137b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 15147b58daeaSdrh ** SELECT statements. 15157b58daeaSdrh */ 1516ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 151702afc861Sdrh Vdbe *v = 0; 151802afc861Sdrh int iLimit = 0; 151915007a99Sdrh int iOffset; 15209b918ed1Sdrh int addr1, n; 15210acb7e48Sdrh if( p->iLimit ) return; 152215007a99Sdrh 15237b58daeaSdrh /* 15247b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 15257b58daeaSdrh ** contraversy about what the correct behavior should be. 15267b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 15277b58daeaSdrh ** no rows. 15287b58daeaSdrh */ 1529ceea3321Sdrh sqlite3ExprCacheClear(pParse); 1530373cc2ddSdrh assert( p->pOffset==0 || p->pLimit!=0 ); 1531a2dc3b1aSdanielk1977 if( p->pLimit ){ 15320a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 153315007a99Sdrh v = sqlite3GetVdbe(pParse); 1534373cc2ddSdrh if( NEVER(v==0) ) return; /* VDBE should have already been allocated */ 15359b918ed1Sdrh if( sqlite3ExprIsInteger(p->pLimit, &n) ){ 15369b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 15379b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 1538456e4e4fSdrh if( n==0 ){ 1539456e4e4fSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 154095aa47b1Sdrh }else{ 154195aa47b1Sdrh if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n; 15429b918ed1Sdrh } 15439b918ed1Sdrh }else{ 1544b7654111Sdrh sqlite3ExprCode(pParse, p->pLimit, iLimit); 1545b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); 1546d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 15473c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); 15489b918ed1Sdrh } 1549a2dc3b1aSdanielk1977 if( p->pOffset ){ 15500a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 1551b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 1552b7654111Sdrh sqlite3ExprCode(pParse, p->pOffset, iOffset); 1553b7654111Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); 1554d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 15553c84ddffSdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); 1556b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); 155715007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 1558b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1559d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 1560b7654111Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); 1561b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); 1562b7654111Sdrh sqlite3VdbeJumpHere(v, addr1); 1563b7654111Sdrh } 1564d59ba6ceSdrh } 15657b58daeaSdrh } 15667b58daeaSdrh 1567b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1568fbc4ee7bSdrh /* 1569fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1570fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1571fbc4ee7bSdrh ** the column has no default collating sequence. 1572fbc4ee7bSdrh ** 1573fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1574fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1575fbc4ee7bSdrh */ 1576dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1577fbc4ee7bSdrh CollSeq *pRet; 1578dc1bdc4fSdanielk1977 if( p->pPrior ){ 1579dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1580fbc4ee7bSdrh }else{ 1581fbc4ee7bSdrh pRet = 0; 1582dc1bdc4fSdanielk1977 } 158310c081adSdrh assert( iCol>=0 ); 158410c081adSdrh if( pRet==0 && iCol<p->pEList->nExpr ){ 1585dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1586dc1bdc4fSdanielk1977 } 1587dc1bdc4fSdanielk1977 return pRet; 1588d3d39e93Sdrh } 1589b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1590d3d39e93Sdrh 1591b21e7c70Sdrh /* Forward reference */ 1592b21e7c70Sdrh static int multiSelectOrderBy( 1593b21e7c70Sdrh Parse *pParse, /* Parsing context */ 1594b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 1595a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 1596b21e7c70Sdrh ); 1597b21e7c70Sdrh 1598b21e7c70Sdrh 1599b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1600d3d39e93Sdrh /* 160116ee60ffSdrh ** This routine is called to process a compound query form from 160216ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 160316ee60ffSdrh ** INTERSECT 1604c926afbcSdrh ** 1605e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1606e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1607e78e8284Sdrh ** in which case this routine will be called recursively. 1608e78e8284Sdrh ** 1609e78e8284Sdrh ** The results of the total query are to be written into a destination 1610e78e8284Sdrh ** of type eDest with parameter iParm. 1611e78e8284Sdrh ** 1612e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1613e78e8284Sdrh ** 1614e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1615e78e8284Sdrh ** 1616e78e8284Sdrh ** This statement is parsed up as follows: 1617e78e8284Sdrh ** 1618e78e8284Sdrh ** SELECT c FROM t3 1619e78e8284Sdrh ** | 1620e78e8284Sdrh ** `-----> SELECT b FROM t2 1621e78e8284Sdrh ** | 16224b11c6d3Sjplyon ** `------> SELECT a FROM t1 1623e78e8284Sdrh ** 1624e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1625e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1626e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1627e78e8284Sdrh ** 1628e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1629e78e8284Sdrh ** individual selects always group from left to right. 163082c3d636Sdrh */ 163184ac9d02Sdanielk1977 static int multiSelect( 1632fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1633fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1634a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 163584ac9d02Sdanielk1977 ){ 163684ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 163710e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 163810e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 16391013c932Sdrh SelectDest dest; /* Alternative data destination */ 1640eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 1641633e6d57Sdrh sqlite3 *db; /* Database connection */ 16427f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 16437f61e92cSdan int iSub1; /* EQP id of left-hand query */ 16447f61e92cSdan int iSub2; /* EQP id of right-hand query */ 16457f61e92cSdan #endif 164682c3d636Sdrh 16477b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1648fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 164982c3d636Sdrh */ 1650701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 1651633e6d57Sdrh db = pParse->db; 1652d8bc7086Sdrh pPrior = p->pPrior; 16530342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 16540342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1655bc10377aSdrh dest = *pDest; 1656d8bc7086Sdrh if( pPrior->pOrderBy ){ 16574adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1658da93d238Sdrh selectOpName(p->op)); 165984ac9d02Sdanielk1977 rc = 1; 166084ac9d02Sdanielk1977 goto multi_select_end; 166182c3d636Sdrh } 1662a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 16634adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 16647b58daeaSdrh selectOpName(p->op)); 166584ac9d02Sdanielk1977 rc = 1; 166684ac9d02Sdanielk1977 goto multi_select_end; 16677b58daeaSdrh } 166882c3d636Sdrh 16694adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 1670701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 1671d8bc7086Sdrh 16721cc3d75fSdrh /* Create the destination temporary table if necessary 16731cc3d75fSdrh */ 16746c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 1675b4964b72Sdanielk1977 assert( p->pEList ); 16762b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 1677d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 16786c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 16791cc3d75fSdrh } 16801cc3d75fSdrh 1681f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 1682f6e369a1Sdrh ** in their result sets. 1683f6e369a1Sdrh */ 1684f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 1685f6e369a1Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 16867b113babSdrh if( p->selFlags & SF_Values ){ 16877b113babSdrh sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 16887b113babSdrh }else{ 1689f6e369a1Sdrh sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1690f6e369a1Sdrh " do not have the same number of result columns", selectOpName(p->op)); 16917b113babSdrh } 1692f6e369a1Sdrh rc = 1; 1693f6e369a1Sdrh goto multi_select_end; 1694f6e369a1Sdrh } 1695f6e369a1Sdrh 1696a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 1697a9671a22Sdrh */ 1698f6e369a1Sdrh if( p->pOrderBy ){ 1699a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 1700f6e369a1Sdrh } 1701f6e369a1Sdrh 1702f46f905aSdrh /* Generate code for the left and right SELECT statements. 1703d8bc7086Sdrh */ 170482c3d636Sdrh switch( p->op ){ 1705f46f905aSdrh case TK_ALL: { 1706ec7429aeSdrh int addr = 0; 170795aa47b1Sdrh int nLimit; 1708a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1709a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1710a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 17117f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 17127d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 1713ad68cb6bSdanielk1977 p->pLimit = 0; 1714ad68cb6bSdanielk1977 p->pOffset = 0; 171584ac9d02Sdanielk1977 if( rc ){ 171684ac9d02Sdanielk1977 goto multi_select_end; 171784ac9d02Sdanielk1977 } 1718f46f905aSdrh p->pPrior = 0; 17197b58daeaSdrh p->iLimit = pPrior->iLimit; 17207b58daeaSdrh p->iOffset = pPrior->iOffset; 172192b01d53Sdrh if( p->iLimit ){ 17223c84ddffSdrh addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); 1723d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 1724ec7429aeSdrh } 17257f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 17267d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 1727373cc2ddSdrh testcase( rc!=SQLITE_OK ); 1728eca7e01aSdanielk1977 pDelete = p->pPrior; 1729f46f905aSdrh p->pPrior = pPrior; 173095aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 173195aa47b1Sdrh if( pPrior->pLimit 173295aa47b1Sdrh && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) 173395aa47b1Sdrh && p->nSelectRow > (double)nLimit 173495aa47b1Sdrh ){ 173595aa47b1Sdrh p->nSelectRow = (double)nLimit; 173695aa47b1Sdrh } 1737ec7429aeSdrh if( addr ){ 1738ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1739ec7429aeSdrh } 1740f46f905aSdrh break; 1741f46f905aSdrh } 174282c3d636Sdrh case TK_EXCEPT: 174382c3d636Sdrh case TK_UNION: { 1744d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1745ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 1746d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1747a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1748dc1bdc4fSdanielk1977 int addr; 17496c8c8ce0Sdanielk1977 SelectDest uniondest; 175082c3d636Sdrh 1751373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 1752373cc2ddSdrh testcase( p->op==TK_UNION ); 175393a960a0Sdrh priorOp = SRT_Union; 1754e2f02bacSdrh if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){ 1755d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1756c926afbcSdrh ** right. 1757d8bc7086Sdrh */ 1758e2f02bacSdrh assert( p->pRightmost!=p ); /* Can only happen for leftward elements 1759e2f02bacSdrh ** of a 3-way or more compound */ 1760e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 1761e2f02bacSdrh assert( p->pOffset==0 ); /* Not allowed on leftward elements */ 17622b596da8Sdrh unionTab = dest.iSDParm; 176382c3d636Sdrh }else{ 1764d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1765d8bc7086Sdrh ** intermediate results. 1766d8bc7086Sdrh */ 176782c3d636Sdrh unionTab = pParse->nTab++; 176893a960a0Sdrh assert( p->pOrderBy==0 ); 176966a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 1770b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1771b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 17727d10d5a6Sdrh p->pRightmost->selFlags |= SF_UsesEphemeral; 177384ac9d02Sdanielk1977 assert( p->pEList ); 1774d8bc7086Sdrh } 1775d8bc7086Sdrh 1776d8bc7086Sdrh /* Code the SELECT statements to our left 1777d8bc7086Sdrh */ 1778b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 17791013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 17807f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 17817d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 178284ac9d02Sdanielk1977 if( rc ){ 178384ac9d02Sdanielk1977 goto multi_select_end; 178484ac9d02Sdanielk1977 } 1785d8bc7086Sdrh 1786d8bc7086Sdrh /* Code the current SELECT statement 1787d8bc7086Sdrh */ 17884cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 17894cfb22f7Sdrh op = SRT_Except; 17904cfb22f7Sdrh }else{ 17914cfb22f7Sdrh assert( p->op==TK_UNION ); 17924cfb22f7Sdrh op = SRT_Union; 1793d8bc7086Sdrh } 179482c3d636Sdrh p->pPrior = 0; 1795a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1796a2dc3b1aSdanielk1977 p->pLimit = 0; 1797a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1798a2dc3b1aSdanielk1977 p->pOffset = 0; 17996c8c8ce0Sdanielk1977 uniondest.eDest = op; 18007f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 18017d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 1802373cc2ddSdrh testcase( rc!=SQLITE_OK ); 18035bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 18045bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 1805633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 1806eca7e01aSdanielk1977 pDelete = p->pPrior; 180782c3d636Sdrh p->pPrior = pPrior; 1808a9671a22Sdrh p->pOrderBy = 0; 180995aa47b1Sdrh if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow; 1810633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 1811a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1812a2dc3b1aSdanielk1977 p->pOffset = pOffset; 181392b01d53Sdrh p->iLimit = 0; 181492b01d53Sdrh p->iOffset = 0; 1815d8bc7086Sdrh 1816d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1817d8bc7086Sdrh ** it is that we currently need. 1818d8bc7086Sdrh */ 18192b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 1820373cc2ddSdrh if( dest.eDest!=priorOp ){ 18216b56344dSdrh int iCont, iBreak, iStart; 182282c3d636Sdrh assert( p->pEList ); 18237d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 182492378253Sdrh Select *pFirst = p; 182592378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 182692378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 182741202ccaSdrh } 18284adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 18294adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1830ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 183166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); 18324adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 1833d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 1834e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 18354adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 183666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); 18374adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 183866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 183982c3d636Sdrh } 184082c3d636Sdrh break; 184182c3d636Sdrh } 1842373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 184382c3d636Sdrh int tab1, tab2; 18446b56344dSdrh int iCont, iBreak, iStart; 1845a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 1846dc1bdc4fSdanielk1977 int addr; 18471013c932Sdrh SelectDest intersectdest; 18489cbf3425Sdrh int r1; 184982c3d636Sdrh 1850d8bc7086Sdrh /* INTERSECT is different from the others since it requires 18516206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1852d8bc7086Sdrh ** by allocating the tables we will need. 1853d8bc7086Sdrh */ 185482c3d636Sdrh tab1 = pParse->nTab++; 185582c3d636Sdrh tab2 = pParse->nTab++; 185693a960a0Sdrh assert( p->pOrderBy==0 ); 1857dc1bdc4fSdanielk1977 185866a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 1859b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1860b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 18617d10d5a6Sdrh p->pRightmost->selFlags |= SF_UsesEphemeral; 186284ac9d02Sdanielk1977 assert( p->pEList ); 1863d8bc7086Sdrh 1864d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1865d8bc7086Sdrh */ 18661013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 18677f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 18687d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 186984ac9d02Sdanielk1977 if( rc ){ 187084ac9d02Sdanielk1977 goto multi_select_end; 187184ac9d02Sdanielk1977 } 1872d8bc7086Sdrh 1873d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1874d8bc7086Sdrh */ 187566a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 1876b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 1877b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 187882c3d636Sdrh p->pPrior = 0; 1879a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1880a2dc3b1aSdanielk1977 p->pLimit = 0; 1881a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1882a2dc3b1aSdanielk1977 p->pOffset = 0; 18832b596da8Sdrh intersectdest.iSDParm = tab2; 18847f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 18857d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 1886373cc2ddSdrh testcase( rc!=SQLITE_OK ); 1887eca7e01aSdanielk1977 pDelete = p->pPrior; 188882c3d636Sdrh p->pPrior = pPrior; 188995aa47b1Sdrh if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 1890633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 1891a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1892a2dc3b1aSdanielk1977 p->pOffset = pOffset; 1893d8bc7086Sdrh 1894d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1895d8bc7086Sdrh ** tables. 1896d8bc7086Sdrh */ 189782c3d636Sdrh assert( p->pEList ); 18987d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 189992378253Sdrh Select *pFirst = p; 190092378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 190192378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 190241202ccaSdrh } 19034adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 19044adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1905ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 190666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); 19079cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 19089cbf3425Sdrh iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 19098cff69dfSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); 19109cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 1911d2b3e23bSdrh selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 1912e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 19134adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 191466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); 19154adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 191666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 191766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 191882c3d636Sdrh break; 191982c3d636Sdrh } 192082c3d636Sdrh } 19218cdbf836Sdrh 19227f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); 19237f61e92cSdan 1924a9671a22Sdrh /* Compute collating sequences used by 1925a9671a22Sdrh ** temporary tables needed to implement the compound select. 1926a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 19278cdbf836Sdrh ** 19288cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 19298cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 19308cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 19318cdbf836Sdrh ** no temp tables are required. 1932fbc4ee7bSdrh */ 19337d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 1934fbc4ee7bSdrh int i; /* Loop counter */ 1935fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 19360342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 1937f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 193893a960a0Sdrh int nCol; /* Number of columns in result set */ 1939fbc4ee7bSdrh 19400342b1f5Sdrh assert( p->pRightmost==p ); 194193a960a0Sdrh nCol = p->pEList->nExpr; 1942633e6d57Sdrh pKeyInfo = sqlite3DbMallocZero(db, 1943a9671a22Sdrh sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1)); 1944dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1945dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1946dc1bdc4fSdanielk1977 goto multi_select_end; 1947dc1bdc4fSdanielk1977 } 1948dc1bdc4fSdanielk1977 1949633e6d57Sdrh pKeyInfo->enc = ENC(db); 1950ea678832Sdrh pKeyInfo->nField = (u16)nCol; 1951dc1bdc4fSdanielk1977 19520342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 19530342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 19540342b1f5Sdrh if( 0==*apColl ){ 1955633e6d57Sdrh *apColl = db->pDfltColl; 1956dc1bdc4fSdanielk1977 } 1957dc1bdc4fSdanielk1977 } 1958e1a022e4Sdrh pKeyInfo->aSortOrder = (u8*)apColl; 1959dc1bdc4fSdanielk1977 19600342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 19610342b1f5Sdrh for(i=0; i<2; i++){ 1962b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 19630342b1f5Sdrh if( addr<0 ){ 19640342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 19650342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 1966b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 19670342b1f5Sdrh break; 19680342b1f5Sdrh } 19690342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 197066a5167bSdrh sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); 19710ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 19720342b1f5Sdrh } 1973dc1bdc4fSdanielk1977 } 1974633e6d57Sdrh sqlite3DbFree(db, pKeyInfo); 1975dc1bdc4fSdanielk1977 } 1976dc1bdc4fSdanielk1977 1977dc1bdc4fSdanielk1977 multi_select_end: 19782b596da8Sdrh pDest->iSdst = dest.iSdst; 19792b596da8Sdrh pDest->nSdst = dest.nSdst; 1980633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 198184ac9d02Sdanielk1977 return rc; 19822282792aSdrh } 1983b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 19842282792aSdrh 1985b21e7c70Sdrh /* 1986b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 1987b21e7c70Sdrh ** SELECT statment. 19880acb7e48Sdrh ** 19892b596da8Sdrh ** The data to be output is contained in pIn->iSdst. There are 19902b596da8Sdrh ** pIn->nSdst columns to be output. pDest is where the output should 19910acb7e48Sdrh ** be sent. 19920acb7e48Sdrh ** 19930acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 19940acb7e48Sdrh ** return address. 19950acb7e48Sdrh ** 1996f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 19970acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 19980acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 19990acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 20000acb7e48Sdrh ** keys. 20010acb7e48Sdrh ** 20020acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 20030acb7e48Sdrh ** iBreak. 2004b21e7c70Sdrh */ 20050acb7e48Sdrh static int generateOutputSubroutine( 200692b01d53Sdrh Parse *pParse, /* Parsing context */ 200792b01d53Sdrh Select *p, /* The SELECT statement */ 200892b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 200992b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 201092b01d53Sdrh int regReturn, /* The return address register */ 20110acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 20120acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 20130acb7e48Sdrh int p4type, /* The p4 type for pKeyInfo */ 201492b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 2015b21e7c70Sdrh ){ 2016b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 201792b01d53Sdrh int iContinue; 201892b01d53Sdrh int addr; 2019b21e7c70Sdrh 202092b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 202192b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 20220acb7e48Sdrh 20230acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 20240acb7e48Sdrh */ 20250acb7e48Sdrh if( regPrev ){ 20260acb7e48Sdrh int j1, j2; 2027ec86c724Sdrh j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); 20282b596da8Sdrh j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 20290acb7e48Sdrh (char*)pKeyInfo, p4type); 20300acb7e48Sdrh sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); 20310acb7e48Sdrh sqlite3VdbeJumpHere(v, j1); 2032e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 2033ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 20340acb7e48Sdrh } 20351f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 20360acb7e48Sdrh 2037d5578433Smistachkin /* Suppress the first OFFSET entries if there is an OFFSET clause 20380acb7e48Sdrh */ 203992b01d53Sdrh codeOffset(v, p, iContinue); 2040b21e7c70Sdrh 2041b21e7c70Sdrh switch( pDest->eDest ){ 2042b21e7c70Sdrh /* Store the result as data using a unique key. 2043b21e7c70Sdrh */ 2044b21e7c70Sdrh case SRT_Table: 2045b21e7c70Sdrh case SRT_EphemTab: { 2046b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 2047b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 2048373cc2ddSdrh testcase( pDest->eDest==SRT_Table ); 2049373cc2ddSdrh testcase( pDest->eDest==SRT_EphemTab ); 20502b596da8Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 20512b596da8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 20522b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 2053b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2054b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 2055b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2056b21e7c70Sdrh break; 2057b21e7c70Sdrh } 2058b21e7c70Sdrh 2059b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 2060b21e7c70Sdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 2061b21e7c70Sdrh ** then there should be a single item on the stack. Write this 2062b21e7c70Sdrh ** item into the set table with bogus data. 2063b21e7c70Sdrh */ 2064b21e7c70Sdrh case SRT_Set: { 20656fccc35aSdrh int r1; 20662b596da8Sdrh assert( pIn->nSdst==1 ); 2067634d81deSdrh pDest->affSdst = 20682b596da8Sdrh sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst); 2069b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 2070634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1); 20712b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1); 20722b596da8Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1); 2073b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2074b21e7c70Sdrh break; 2075b21e7c70Sdrh } 2076b21e7c70Sdrh 207785e9e22bSdrh #if 0 /* Never occurs on an ORDER BY query */ 2078b21e7c70Sdrh /* If any row exist in the result set, record that fact and abort. 2079b21e7c70Sdrh */ 2080b21e7c70Sdrh case SRT_Exists: { 20812b596da8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm); 2082b21e7c70Sdrh /* The LIMIT clause will terminate the loop for us */ 2083b21e7c70Sdrh break; 2084b21e7c70Sdrh } 208585e9e22bSdrh #endif 2086b21e7c70Sdrh 2087b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2088b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2089b21e7c70Sdrh ** of the scan loop. 2090b21e7c70Sdrh */ 2091b21e7c70Sdrh case SRT_Mem: { 20922b596da8Sdrh assert( pIn->nSdst==1 ); 20932b596da8Sdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); 2094b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 2095b21e7c70Sdrh break; 2096b21e7c70Sdrh } 2097b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2098b21e7c70Sdrh 20997d10d5a6Sdrh /* The results are stored in a sequence of registers 21002b596da8Sdrh ** starting at pDest->iSdst. Then the co-routine yields. 2101b21e7c70Sdrh */ 210292b01d53Sdrh case SRT_Coroutine: { 21032b596da8Sdrh if( pDest->iSdst==0 ){ 21042b596da8Sdrh pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 21052b596da8Sdrh pDest->nSdst = pIn->nSdst; 2106b21e7c70Sdrh } 21072b596da8Sdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst); 21082b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 210992b01d53Sdrh break; 211092b01d53Sdrh } 211192b01d53Sdrh 2112ccfcbceaSdrh /* If none of the above, then the result destination must be 2113ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2114ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2115ccfcbceaSdrh ** 2116ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2117ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2118ccfcbceaSdrh ** return the next row of result. 21197d10d5a6Sdrh */ 2120ccfcbceaSdrh default: { 2121ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 21222b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 21232b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 2124b21e7c70Sdrh break; 2125b21e7c70Sdrh } 2126b21e7c70Sdrh } 212792b01d53Sdrh 212892b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 212992b01d53Sdrh */ 213092b01d53Sdrh if( p->iLimit ){ 21319b918ed1Sdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); 213292b01d53Sdrh } 213392b01d53Sdrh 213492b01d53Sdrh /* Generate the subroutine return 213592b01d53Sdrh */ 21360acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 213792b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 213892b01d53Sdrh 213992b01d53Sdrh return addr; 2140b21e7c70Sdrh } 2141b21e7c70Sdrh 2142b21e7c70Sdrh /* 2143b21e7c70Sdrh ** Alternative compound select code generator for cases when there 2144b21e7c70Sdrh ** is an ORDER BY clause. 2145b21e7c70Sdrh ** 2146b21e7c70Sdrh ** We assume a query of the following form: 2147b21e7c70Sdrh ** 2148b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 2149b21e7c70Sdrh ** 2150b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 2151b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 2152b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 2153b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 2154b21e7c70Sdrh ** selectB) there are 7 subroutines: 2155b21e7c70Sdrh ** 2156b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 2157b21e7c70Sdrh ** of the compound query. 2158b21e7c70Sdrh ** 2159b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 2160b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 2161b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 2162b21e7c70Sdrh ** appears only in B.) 2163b21e7c70Sdrh ** 2164b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 2165b21e7c70Sdrh ** 2166b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 2167b21e7c70Sdrh ** 2168b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 2169b21e7c70Sdrh ** 2170b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 2171b21e7c70Sdrh ** 2172b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 2173b21e7c70Sdrh ** 2174b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 2175b21e7c70Sdrh ** <operator> is used: 2176b21e7c70Sdrh ** 2177b21e7c70Sdrh ** 2178b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 2179b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 2180b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 2181b21e7c70Sdrh ** 21820acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 2183b21e7c70Sdrh ** 2184b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 2185b21e7c70Sdrh ** 21860acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 2187b21e7c70Sdrh ** 21880acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 21890acb7e48Sdrh ** 21900acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 21910acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 21920acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 21930acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 21940acb7e48Sdrh ** 21950acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 21960acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 21970acb7e48Sdrh ** output value. A comparison is made against this value and the output 21980acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 2199b21e7c70Sdrh ** 2200b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 2201b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 2202b21e7c70Sdrh ** 2203b21e7c70Sdrh ** goto Init 2204b21e7c70Sdrh ** coA: coroutine for left query (A) 2205b21e7c70Sdrh ** coB: coroutine for right query (B) 2206b21e7c70Sdrh ** outA: output one row of A 2207b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 2208b21e7c70Sdrh ** EofA: ... 2209b21e7c70Sdrh ** EofB: ... 2210b21e7c70Sdrh ** AltB: ... 2211b21e7c70Sdrh ** AeqB: ... 2212b21e7c70Sdrh ** AgtB: ... 2213b21e7c70Sdrh ** Init: initialize coroutine registers 2214b21e7c70Sdrh ** yield coA 2215b21e7c70Sdrh ** if eof(A) goto EofA 2216b21e7c70Sdrh ** yield coB 2217b21e7c70Sdrh ** if eof(B) goto EofB 2218b21e7c70Sdrh ** Cmpr: Compare A, B 2219b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 2220b21e7c70Sdrh ** End: ... 2221b21e7c70Sdrh ** 2222b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 2223b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 2224b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 2225b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 2226b21e7c70Sdrh */ 2227de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 2228b21e7c70Sdrh static int multiSelectOrderBy( 2229b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2230b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2231a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2232b21e7c70Sdrh ){ 22330acb7e48Sdrh int i, j; /* Loop counters */ 2234b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 2235b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 2236b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 2237b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 223892b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 223992b01d53Sdrh int regEofA; /* Flag to indicate when select-A is complete */ 224092b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 224192b01d53Sdrh int regEofB; /* Flag to indicate when select-B is complete */ 224292b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 224392b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 224492b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 224592b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 224692b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 2247b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 224892b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 224992b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 225092b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 225192b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 225292b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 225392b01d53Sdrh int regLimitA; /* Limit register for select-A */ 225492b01d53Sdrh int regLimitB; /* Limit register for select-A */ 22550acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 225692b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 225792b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 225892b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 225992b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 22600acb7e48Sdrh int j1; /* Jump instructions that get retargetted */ 226192b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 226296067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 22630acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 22640acb7e48Sdrh sqlite3 *db; /* Database connection */ 22650acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 22660acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 22670acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 22687f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 22697f61e92cSdan int iSub1; /* EQP id of left-hand query */ 22707f61e92cSdan int iSub2; /* EQP id of right-hand query */ 22717f61e92cSdan #endif 2272b21e7c70Sdrh 227392b01d53Sdrh assert( p->pOrderBy!=0 ); 227496067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 22750acb7e48Sdrh db = pParse->db; 227692b01d53Sdrh v = pParse->pVdbe; 2277ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 227892b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 227992b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 22800acb7e48Sdrh 2281b21e7c70Sdrh 228292b01d53Sdrh /* Patch up the ORDER BY clause 228392b01d53Sdrh */ 228492b01d53Sdrh op = p->op; 2285b21e7c70Sdrh pPrior = p->pPrior; 228692b01d53Sdrh assert( pPrior->pOrderBy==0 ); 22870acb7e48Sdrh pOrderBy = p->pOrderBy; 228893a960a0Sdrh assert( pOrderBy ); 22890acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 229093a960a0Sdrh 22910acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 22920acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 22930acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 22940acb7e48Sdrh */ 22950acb7e48Sdrh if( op!=TK_ALL ){ 22960acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 22977d10d5a6Sdrh struct ExprList_item *pItem; 22987d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 22994b3ac73cSdrh assert( pItem->iOrderByCol>0 ); 23004b3ac73cSdrh if( pItem->iOrderByCol==i ) break; 23010acb7e48Sdrh } 23020acb7e48Sdrh if( j==nOrderBy ){ 2303b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 23040acb7e48Sdrh if( pNew==0 ) return SQLITE_NOMEM; 23050acb7e48Sdrh pNew->flags |= EP_IntValue; 230633e619fcSdrh pNew->u.iValue = i; 2307b7916a78Sdrh pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 2308a3cc3c96Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i; 23090acb7e48Sdrh } 23100acb7e48Sdrh } 23110acb7e48Sdrh } 23120acb7e48Sdrh 23130acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 231410c081adSdrh ** the permutation used to determine if the next 23150acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 23160acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 23170acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 23180acb7e48Sdrh ** collation. 23190acb7e48Sdrh */ 23200acb7e48Sdrh aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); 23210acb7e48Sdrh if( aPermute ){ 23227d10d5a6Sdrh struct ExprList_item *pItem; 23237d10d5a6Sdrh for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){ 23244b3ac73cSdrh assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr ); 23254b3ac73cSdrh aPermute[i] = pItem->iOrderByCol - 1; 23260acb7e48Sdrh } 23270acb7e48Sdrh pKeyMerge = 23280acb7e48Sdrh sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1)); 23290acb7e48Sdrh if( pKeyMerge ){ 23300acb7e48Sdrh pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy]; 2331ea678832Sdrh pKeyMerge->nField = (u16)nOrderBy; 23320acb7e48Sdrh pKeyMerge->enc = ENC(db); 23330acb7e48Sdrh for(i=0; i<nOrderBy; i++){ 23340acb7e48Sdrh CollSeq *pColl; 23350acb7e48Sdrh Expr *pTerm = pOrderBy->a[i].pExpr; 23360acb7e48Sdrh if( pTerm->flags & EP_ExpCollate ){ 23370acb7e48Sdrh pColl = pTerm->pColl; 23380acb7e48Sdrh }else{ 23390acb7e48Sdrh pColl = multiSelectCollSeq(pParse, p, aPermute[i]); 23400acb7e48Sdrh pTerm->flags |= EP_ExpCollate; 23410acb7e48Sdrh pTerm->pColl = pColl; 23420acb7e48Sdrh } 23430acb7e48Sdrh pKeyMerge->aColl[i] = pColl; 23440acb7e48Sdrh pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder; 23450acb7e48Sdrh } 23460acb7e48Sdrh } 23470acb7e48Sdrh }else{ 23480acb7e48Sdrh pKeyMerge = 0; 23490acb7e48Sdrh } 23500acb7e48Sdrh 23510acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 23520acb7e48Sdrh */ 23530acb7e48Sdrh p->pOrderBy = pOrderBy; 23546ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 23550acb7e48Sdrh 23560acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 23570acb7e48Sdrh ** for the logic that removes duplicate result rows when the 23580acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 23590acb7e48Sdrh */ 23600acb7e48Sdrh if( op==TK_ALL ){ 23610acb7e48Sdrh regPrev = 0; 23620acb7e48Sdrh }else{ 23630acb7e48Sdrh int nExpr = p->pEList->nExpr; 23641c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 23650acb7e48Sdrh regPrev = sqlite3GetTempRange(pParse, nExpr+1); 23660acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 23670acb7e48Sdrh pKeyDup = sqlite3DbMallocZero(db, 23680acb7e48Sdrh sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) ); 23690acb7e48Sdrh if( pKeyDup ){ 23700acb7e48Sdrh pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr]; 2371ea678832Sdrh pKeyDup->nField = (u16)nExpr; 23720acb7e48Sdrh pKeyDup->enc = ENC(db); 23730acb7e48Sdrh for(i=0; i<nExpr; i++){ 23740acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 23750acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 23760acb7e48Sdrh } 23770acb7e48Sdrh } 23780acb7e48Sdrh } 237992b01d53Sdrh 238092b01d53Sdrh /* Separate the left and the right query from one another 238192b01d53Sdrh */ 238292b01d53Sdrh p->pPrior = 0; 23837d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 23840acb7e48Sdrh if( pPrior->pPrior==0 ){ 23857d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 23860acb7e48Sdrh } 238792b01d53Sdrh 238892b01d53Sdrh /* Compute the limit registers */ 238992b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 23900acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 239192b01d53Sdrh regLimitA = ++pParse->nMem; 239292b01d53Sdrh regLimitB = ++pParse->nMem; 239392b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 239492b01d53Sdrh regLimitA); 239592b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 239692b01d53Sdrh }else{ 239792b01d53Sdrh regLimitA = regLimitB = 0; 239892b01d53Sdrh } 2399633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 24000acb7e48Sdrh p->pLimit = 0; 2401633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 24020acb7e48Sdrh p->pOffset = 0; 240392b01d53Sdrh 2404b21e7c70Sdrh regAddrA = ++pParse->nMem; 2405b21e7c70Sdrh regEofA = ++pParse->nMem; 2406b21e7c70Sdrh regAddrB = ++pParse->nMem; 2407b21e7c70Sdrh regEofB = ++pParse->nMem; 2408b21e7c70Sdrh regOutA = ++pParse->nMem; 2409b21e7c70Sdrh regOutB = ++pParse->nMem; 2410b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 2411b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 2412b21e7c70Sdrh 241392b01d53Sdrh /* Jump past the various subroutines and coroutines to the main 241492b01d53Sdrh ** merge loop 241592b01d53Sdrh */ 2416b21e7c70Sdrh j1 = sqlite3VdbeAddOp0(v, OP_Goto); 2417b21e7c70Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v); 241892b01d53Sdrh 24190acb7e48Sdrh 242092b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 24210acb7e48Sdrh ** left of the compound operator - the "A" select. 24220acb7e48Sdrh */ 2423b21e7c70Sdrh VdbeNoopComment((v, "Begin coroutine for left SELECT")); 242492b01d53Sdrh pPrior->iLimit = regLimitA; 24257f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 24267d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 2427b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA); 242892b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 2429b21e7c70Sdrh VdbeNoopComment((v, "End coroutine for left SELECT")); 2430b21e7c70Sdrh 243192b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 243292b01d53Sdrh ** the right - the "B" select 243392b01d53Sdrh */ 2434b21e7c70Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v); 2435b21e7c70Sdrh VdbeNoopComment((v, "Begin coroutine for right SELECT")); 243692b01d53Sdrh savedLimit = p->iLimit; 243792b01d53Sdrh savedOffset = p->iOffset; 243892b01d53Sdrh p->iLimit = regLimitB; 243992b01d53Sdrh p->iOffset = 0; 24407f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 24417d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 244292b01d53Sdrh p->iLimit = savedLimit; 244392b01d53Sdrh p->iOffset = savedOffset; 2444b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB); 244592b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 2446b21e7c70Sdrh VdbeNoopComment((v, "End coroutine for right SELECT")); 2447b21e7c70Sdrh 244892b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 24490acb7e48Sdrh ** select as the next output row of the compound select. 245092b01d53Sdrh */ 2451b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 24520acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 24530acb7e48Sdrh p, &destA, pDest, regOutA, 24540acb7e48Sdrh regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd); 2455b21e7c70Sdrh 245692b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 24570acb7e48Sdrh ** select as the next output row of the compound select. 245892b01d53Sdrh */ 24590acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 2460b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 24610acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 24620acb7e48Sdrh p, &destB, pDest, regOutB, 24630acb7e48Sdrh regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd); 24640acb7e48Sdrh } 2465b21e7c70Sdrh 246692b01d53Sdrh /* Generate a subroutine to run when the results from select A 246792b01d53Sdrh ** are exhausted and only data in select B remains. 246892b01d53Sdrh */ 246992b01d53Sdrh VdbeNoopComment((v, "eof-A subroutine")); 247092b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 24710acb7e48Sdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd); 247292b01d53Sdrh }else{ 24730acb7e48Sdrh addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd); 2474b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 247592b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 24760acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); 247795aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 2478b21e7c70Sdrh } 2479b21e7c70Sdrh 248092b01d53Sdrh /* Generate a subroutine to run when the results from select B 248192b01d53Sdrh ** are exhausted and only data in select A remains. 248292b01d53Sdrh */ 2483b21e7c70Sdrh if( op==TK_INTERSECT ){ 248492b01d53Sdrh addrEofB = addrEofA; 248595aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 2486b21e7c70Sdrh }else{ 248792b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 24880acb7e48Sdrh addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd); 2489b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 249092b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 24910acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); 2492b21e7c70Sdrh } 2493b21e7c70Sdrh 249492b01d53Sdrh /* Generate code to handle the case of A<B 249592b01d53Sdrh */ 2496b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 24970acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 249892b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 2499b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 250092b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 2501b21e7c70Sdrh 250292b01d53Sdrh /* Generate code to handle the case of A==B 250392b01d53Sdrh */ 2504b21e7c70Sdrh if( op==TK_ALL ){ 2505b21e7c70Sdrh addrAeqB = addrAltB; 25060acb7e48Sdrh }else if( op==TK_INTERSECT ){ 25070acb7e48Sdrh addrAeqB = addrAltB; 25080acb7e48Sdrh addrAltB++; 250992b01d53Sdrh }else{ 2510b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 25110acb7e48Sdrh addrAeqB = 251292b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); 251392b01d53Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 251492b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 251592b01d53Sdrh } 2516b21e7c70Sdrh 251792b01d53Sdrh /* Generate code to handle the case of A>B 251892b01d53Sdrh */ 2519b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 2520b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 2521b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 2522b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 252392b01d53Sdrh } 25240acb7e48Sdrh sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); 2525b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); 252692b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 2527b21e7c70Sdrh 252892b01d53Sdrh /* This code runs once to initialize everything. 252992b01d53Sdrh */ 2530b21e7c70Sdrh sqlite3VdbeJumpHere(v, j1); 2531b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA); 2532b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB); 253392b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA); 25340acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB); 2535b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); 2536b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); 253792b01d53Sdrh 253892b01d53Sdrh /* Implement the main merge loop 253992b01d53Sdrh */ 254092b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 25410acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 25422b596da8Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 25430acb7e48Sdrh (char*)pKeyMerge, P4_KEYINFO_HANDOFF); 2544b21e7c70Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); 254592b01d53Sdrh 25460acb7e48Sdrh /* Release temporary registers 25470acb7e48Sdrh */ 25480acb7e48Sdrh if( regPrev ){ 25490acb7e48Sdrh sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1); 25500acb7e48Sdrh } 25510acb7e48Sdrh 255292b01d53Sdrh /* Jump to the this point in order to terminate the query. 255392b01d53Sdrh */ 2554b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 2555b21e7c70Sdrh 255692b01d53Sdrh /* Set the number of output columns 255792b01d53Sdrh */ 25587d10d5a6Sdrh if( pDest->eDest==SRT_Output ){ 25590acb7e48Sdrh Select *pFirst = pPrior; 256092b01d53Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 256192b01d53Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 2562b21e7c70Sdrh } 256392b01d53Sdrh 25640acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 25650acb7e48Sdrh ** by the calling function */ 25665e7ad508Sdanielk1977 if( p->pPrior ){ 2567633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 25685e7ad508Sdanielk1977 } 25690acb7e48Sdrh p->pPrior = pPrior; 257092b01d53Sdrh 257192b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 257292b01d53Sdrh **** subqueries ****/ 25737f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, 0); 257492b01d53Sdrh return SQLITE_OK; 257592b01d53Sdrh } 2576de3e41e3Sdanielk1977 #endif 2577b21e7c70Sdrh 25783514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 257917435752Sdrh /* Forward Declarations */ 258017435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*); 258117435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *); 258217435752Sdrh 25832282792aSdrh /* 2584832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 25856a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 258684e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 25876a3ea0e6Sdrh ** unchanged.) 2588832508b7Sdrh ** 2589832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 2590832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 2591832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 2592832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 2593832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 2594832508b7Sdrh ** of the subquery rather the result set of the subquery. 2595832508b7Sdrh */ 2596b7916a78Sdrh static Expr *substExpr( 259717435752Sdrh sqlite3 *db, /* Report malloc errors to this connection */ 259817435752Sdrh Expr *pExpr, /* Expr in which substitution occurs */ 259917435752Sdrh int iTable, /* Table to be substituted */ 260017435752Sdrh ExprList *pEList /* Substitute expressions */ 260117435752Sdrh ){ 2602b7916a78Sdrh if( pExpr==0 ) return 0; 260350350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 260450350a15Sdrh if( pExpr->iColumn<0 ){ 260550350a15Sdrh pExpr->op = TK_NULL; 260650350a15Sdrh }else{ 2607832508b7Sdrh Expr *pNew; 260884e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 26096ab3a2ecSdanielk1977 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 2610b7916a78Sdrh pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); 261138210ac5Sdrh if( pNew && pExpr->pColl ){ 26120a458e5eSdanielk1977 pNew->pColl = pExpr->pColl; 26130a458e5eSdanielk1977 } 2614b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 2615b7916a78Sdrh pExpr = pNew; 261650350a15Sdrh } 2617832508b7Sdrh }else{ 2618b7916a78Sdrh pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); 2619b7916a78Sdrh pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); 26206ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 26216ab3a2ecSdanielk1977 substSelect(db, pExpr->x.pSelect, iTable, pEList); 26226ab3a2ecSdanielk1977 }else{ 26236ab3a2ecSdanielk1977 substExprList(db, pExpr->x.pList, iTable, pEList); 26246ab3a2ecSdanielk1977 } 2625832508b7Sdrh } 2626b7916a78Sdrh return pExpr; 2627832508b7Sdrh } 262817435752Sdrh static void substExprList( 262917435752Sdrh sqlite3 *db, /* Report malloc errors here */ 263017435752Sdrh ExprList *pList, /* List to scan and in which to make substitutes */ 263117435752Sdrh int iTable, /* Table to be substituted */ 263217435752Sdrh ExprList *pEList /* Substitute values */ 263317435752Sdrh ){ 2634832508b7Sdrh int i; 2635832508b7Sdrh if( pList==0 ) return; 2636832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 2637b7916a78Sdrh pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); 2638832508b7Sdrh } 2639832508b7Sdrh } 264017435752Sdrh static void substSelect( 264117435752Sdrh sqlite3 *db, /* Report malloc errors here */ 264217435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 264317435752Sdrh int iTable, /* Table to be replaced */ 264417435752Sdrh ExprList *pEList /* Substitute values */ 264517435752Sdrh ){ 2646588a9a1aSdrh SrcList *pSrc; 2647588a9a1aSdrh struct SrcList_item *pItem; 2648588a9a1aSdrh int i; 2649b3bce662Sdanielk1977 if( !p ) return; 265017435752Sdrh substExprList(db, p->pEList, iTable, pEList); 265117435752Sdrh substExprList(db, p->pGroupBy, iTable, pEList); 265217435752Sdrh substExprList(db, p->pOrderBy, iTable, pEList); 2653b7916a78Sdrh p->pHaving = substExpr(db, p->pHaving, iTable, pEList); 2654b7916a78Sdrh p->pWhere = substExpr(db, p->pWhere, iTable, pEList); 265517435752Sdrh substSelect(db, p->pPrior, iTable, pEList); 2656588a9a1aSdrh pSrc = p->pSrc; 2657e2f02bacSdrh assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ 2658e2f02bacSdrh if( ALWAYS(pSrc) ){ 2659588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 2660588a9a1aSdrh substSelect(db, pItem->pSelect, iTable, pEList); 2661588a9a1aSdrh } 2662588a9a1aSdrh } 2663b3bce662Sdanielk1977 } 26643514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 2665832508b7Sdrh 26663514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 2667832508b7Sdrh /* 2668630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 2669630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 26701350b030Sdrh ** 26711350b030Sdrh ** To understand the concept of flattening, consider the following 26721350b030Sdrh ** query: 26731350b030Sdrh ** 26741350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 26751350b030Sdrh ** 26761350b030Sdrh ** The default way of implementing this query is to execute the 26771350b030Sdrh ** subquery first and store the results in a temporary table, then 26781350b030Sdrh ** run the outer query on that temporary table. This requires two 26791350b030Sdrh ** passes over the data. Furthermore, because the temporary table 26801350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 2681832508b7Sdrh ** optimized. 26821350b030Sdrh ** 2683832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 26841350b030Sdrh ** a single flat select, like this: 26851350b030Sdrh ** 26861350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 26871350b030Sdrh ** 26881350b030Sdrh ** The code generated for this simpification gives the same result 2689832508b7Sdrh ** but only has to scan the data once. And because indices might 2690832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 2691832508b7Sdrh ** avoided. 26921350b030Sdrh ** 2693832508b7Sdrh ** Flattening is only attempted if all of the following are true: 26941350b030Sdrh ** 2695832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 26961350b030Sdrh ** 2697832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 2698832508b7Sdrh ** 26992b300d5dSdrh ** (3) The subquery is not the right operand of a left outer join 270049ad330dSdan ** (Originally ticket #306. Strengthened by ticket #3300) 2701832508b7Sdrh ** 270249ad330dSdan ** (4) The subquery is not DISTINCT. 2703832508b7Sdrh ** 270449ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 270549ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 270649ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 2707832508b7Sdrh ** 2708832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 2709832508b7Sdrh ** DISTINCT. 2710832508b7Sdrh ** 2711630d296cSdrh ** (7) The subquery has a FROM clause. TODO: For subqueries without 2712630d296cSdrh ** A FROM clause, consider adding a FROM close with the special 2713630d296cSdrh ** table sqlite_once that consists of a single row containing a 2714630d296cSdrh ** single NULL. 271508192d5fSdrh ** 2716df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 2717df199a25Sdrh ** 2718df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 2719df199a25Sdrh ** aggregates. 2720df199a25Sdrh ** 2721df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 2722df199a25Sdrh ** use LIMIT. 2723df199a25Sdrh ** 2724174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 2725174b6195Sdrh ** 27267b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 27272b300d5dSdrh ** a separate restriction deriving from ticket #350. 27283fc673e6Sdrh ** 272949ad330dSdan ** (13) The subquery and outer query do not both use LIMIT. 2730ac83963aSdrh ** 273149ad330dSdan ** (14) The subquery does not use OFFSET. 2732ac83963aSdrh ** 2733ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 2734f3913278Sdrh ** subquery does not have a LIMIT clause. 2735f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 2736ad91c6cdSdrh ** 2737c52e355dSdrh ** (16) The outer query is not an aggregate or the subquery does 2738c52e355dSdrh ** not contain ORDER BY. (Ticket #2942) This used to not matter 2739c52e355dSdrh ** until we introduced the group_concat() function. 2740c52e355dSdrh ** 2741f23329a2Sdanielk1977 ** (17) The sub-query is not a compound select, or it is a UNION ALL 27424914cf92Sdanielk1977 ** compound clause made up entirely of non-aggregate queries, and 2743f23329a2Sdanielk1977 ** the parent query: 2744f23329a2Sdanielk1977 ** 2745f23329a2Sdanielk1977 ** * is not itself part of a compound select, 2746f23329a2Sdanielk1977 ** * is not an aggregate or DISTINCT query, and 2747630d296cSdrh ** * is not a join 2748f23329a2Sdanielk1977 ** 27494914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 27504914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 2751630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 2752630d296cSdrh ** operator other than UNION ALL because all the other compound 2753630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 2754630d296cSdrh ** restriction (4). 2755f23329a2Sdanielk1977 ** 275667c70142Sdan ** Also, each component of the sub-query must return the same number 275767c70142Sdan ** of result columns. This is actually a requirement for any compound 275867c70142Sdan ** SELECT statement, but all the code here does is make sure that no 275967c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 276067c70142Sdan ** syntax error and return a detailed message. 276167c70142Sdan ** 276249fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 276349fc1f60Sdanielk1977 ** ORDER by clause of the parent must be simple references to 276449fc1f60Sdanielk1977 ** columns of the sub-query. 276549fc1f60Sdanielk1977 ** 2766229cf702Sdrh ** (19) The subquery does not use LIMIT or the outer query does not 2767229cf702Sdrh ** have a WHERE clause. 2768229cf702Sdrh ** 2769e8902a70Sdrh ** (20) If the sub-query is a compound select, then it must not use 2770e8902a70Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 2771e8902a70Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 2772630d296cSdrh ** appear as unmodified result columns in the outer query. But we 2773e8902a70Sdrh ** have other optimizations in mind to deal with that case. 2774e8902a70Sdrh ** 2775a91491e5Sshaneh ** (21) The subquery does not use LIMIT or the outer query is not 2776a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 2777a91491e5Sshaneh ** 2778832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 2779832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2780832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2781832508b7Sdrh ** 2782665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 2783832508b7Sdrh ** If flattening is attempted this routine returns 1. 2784832508b7Sdrh ** 2785832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 2786832508b7Sdrh ** the subquery before this routine runs. 27871350b030Sdrh */ 27888c74a8caSdrh static int flattenSubquery( 2789524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 27908c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 27918c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 27928c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 27938c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 27948c74a8caSdrh ){ 2795524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 2796f23329a2Sdanielk1977 Select *pParent; 27970bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2798f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 2799ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2800ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 28010bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 28026a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 280391bb0eedSdrh int i; /* Loop counter */ 280491bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 280591bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 2806524cc21eSdanielk1977 sqlite3 *db = pParse->db; 28071350b030Sdrh 2808832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2809832508b7Sdrh */ 2810a78c22c4Sdrh assert( p!=0 ); 2811a78c22c4Sdrh assert( p->pPrior==0 ); /* Unable to flatten compound queries */ 28127e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 2813832508b7Sdrh pSrc = p->pSrc; 2814ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 281591bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 281649fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 281791bb0eedSdrh pSub = pSubitem->pSelect; 2818832508b7Sdrh assert( pSub!=0 ); 2819ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2820ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2821832508b7Sdrh pSubSrc = pSub->pSrc; 2822832508b7Sdrh assert( pSubSrc ); 2823ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2824ac83963aSdrh ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2825ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 2826ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 2827ac83963aSdrh ** and (14). */ 2828ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2829ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 2830f3913278Sdrh if( p->pRightmost && pSub->pLimit ){ 2831ad91c6cdSdrh return 0; /* Restriction (15) */ 2832ad91c6cdSdrh } 2833ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 283449ad330dSdan if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ 283549ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 283649ad330dSdan return 0; /* Restrictions (8)(9) */ 2837df199a25Sdrh } 28387d10d5a6Sdrh if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ 28397d10d5a6Sdrh return 0; /* Restriction (6) */ 28407d10d5a6Sdrh } 28417d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 2842ac83963aSdrh return 0; /* Restriction (11) */ 2843ac83963aSdrh } 2844c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 2845229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 2846a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 2847a91491e5Sshaneh return 0; /* Restriction (21) */ 2848a91491e5Sshaneh } 2849832508b7Sdrh 28502b300d5dSdrh /* OBSOLETE COMMENT 1: 28512b300d5dSdrh ** Restriction 3: If the subquery is a join, make sure the subquery is 28528af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 28538af4d3acSdrh ** is not allowed: 28548af4d3acSdrh ** 28558af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 28568af4d3acSdrh ** 28578af4d3acSdrh ** If we flatten the above, we would get 28588af4d3acSdrh ** 28598af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 28608af4d3acSdrh ** 28618af4d3acSdrh ** which is not at all the same thing. 28622b300d5dSdrh ** 28632b300d5dSdrh ** OBSOLETE COMMENT 2: 28642b300d5dSdrh ** Restriction 12: If the subquery is the right operand of a left outer 28653fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 28663fc673e6Sdrh ** An examples of why this is not allowed: 28673fc673e6Sdrh ** 28683fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 28693fc673e6Sdrh ** 28703fc673e6Sdrh ** If we flatten the above, we would get 28713fc673e6Sdrh ** 28723fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 28733fc673e6Sdrh ** 28743fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 28753fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 28762b300d5dSdrh ** 28772b300d5dSdrh ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: 28782b300d5dSdrh ** Ticket #3300 shows that flattening the right term of a LEFT JOIN 28792b300d5dSdrh ** is fraught with danger. Best to avoid the whole thing. If the 28802b300d5dSdrh ** subquery is the right term of a LEFT JOIN, then do not flatten. 28813fc673e6Sdrh */ 28822b300d5dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 ){ 28833fc673e6Sdrh return 0; 28843fc673e6Sdrh } 28853fc673e6Sdrh 2886f23329a2Sdanielk1977 /* Restriction 17: If the sub-query is a compound SELECT, then it must 2887f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 2888f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 2889f23329a2Sdanielk1977 ** queries. 2890f23329a2Sdanielk1977 */ 2891f23329a2Sdanielk1977 if( pSub->pPrior ){ 2892e8902a70Sdrh if( pSub->pOrderBy ){ 2893e8902a70Sdrh return 0; /* Restriction 20 */ 2894e8902a70Sdrh } 2895e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 2896f23329a2Sdanielk1977 return 0; 2897f23329a2Sdanielk1977 } 2898f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 2899ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 2900ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 29014b3ac73cSdrh assert( pSub->pSrc!=0 ); 29027d10d5a6Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 290380b3c548Sdanielk1977 || (pSub1->pPrior && pSub1->op!=TK_ALL) 29044b3ac73cSdrh || pSub1->pSrc->nSrc<1 290567c70142Sdan || pSub->pEList->nExpr!=pSub1->pEList->nExpr 290680b3c548Sdanielk1977 ){ 2907f23329a2Sdanielk1977 return 0; 2908f23329a2Sdanielk1977 } 29094b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 2910f23329a2Sdanielk1977 } 291149fc1f60Sdanielk1977 291249fc1f60Sdanielk1977 /* Restriction 18. */ 291349fc1f60Sdanielk1977 if( p->pOrderBy ){ 291449fc1f60Sdanielk1977 int ii; 291549fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 29164b3ac73cSdrh if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0; 291749fc1f60Sdanielk1977 } 291849fc1f60Sdanielk1977 } 2919f23329a2Sdanielk1977 } 2920f23329a2Sdanielk1977 29217d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 29227d10d5a6Sdrh 29237d10d5a6Sdrh /* Authorize the subquery */ 2924524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 2925a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 2926a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 2927524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 2928524cc21eSdanielk1977 29297d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 29307d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 29317d10d5a6Sdrh ** be of the form: 2932f23329a2Sdanielk1977 ** 2933f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 2934f23329a2Sdanielk1977 ** 2935f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 2936a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 2937f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 2938f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 2939f23329a2Sdanielk1977 ** select statements in the compound sub-query. 2940a78c22c4Sdrh ** 2941a78c22c4Sdrh ** Example: 2942a78c22c4Sdrh ** 2943a78c22c4Sdrh ** SELECT a+1 FROM ( 2944a78c22c4Sdrh ** SELECT x FROM tab 2945a78c22c4Sdrh ** UNION ALL 2946a78c22c4Sdrh ** SELECT y FROM tab 2947a78c22c4Sdrh ** UNION ALL 2948a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 2949a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 2950a78c22c4Sdrh ** 2951a78c22c4Sdrh ** Transformed into: 2952a78c22c4Sdrh ** 2953a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 2954a78c22c4Sdrh ** UNION ALL 2955a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 2956a78c22c4Sdrh ** UNION ALL 2957a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 2958a78c22c4Sdrh ** ORDER BY 1 2959a78c22c4Sdrh ** 2960a78c22c4Sdrh ** We call this the "compound-subquery flattening". 2961f23329a2Sdanielk1977 */ 2962f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 2963f23329a2Sdanielk1977 Select *pNew; 2964f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 29654b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 2966f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 2967f23329a2Sdanielk1977 p->pOrderBy = 0; 2968f23329a2Sdanielk1977 p->pSrc = 0; 2969f23329a2Sdanielk1977 p->pPrior = 0; 29704b86ef1dSdanielk1977 p->pLimit = 0; 29716ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 29724b86ef1dSdanielk1977 p->pLimit = pLimit; 2973a78c22c4Sdrh p->pOrderBy = pOrderBy; 2974a78c22c4Sdrh p->pSrc = pSrc; 2975a78c22c4Sdrh p->op = TK_ALL; 2976f23329a2Sdanielk1977 p->pRightmost = 0; 2977a78c22c4Sdrh if( pNew==0 ){ 2978a78c22c4Sdrh pNew = pPrior; 2979a78c22c4Sdrh }else{ 2980a78c22c4Sdrh pNew->pPrior = pPrior; 2981f23329a2Sdanielk1977 pNew->pRightmost = 0; 2982f23329a2Sdanielk1977 } 2983a78c22c4Sdrh p->pPrior = pNew; 2984a78c22c4Sdrh if( db->mallocFailed ) return 1; 2985a78c22c4Sdrh } 2986f23329a2Sdanielk1977 29877d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 29887d10d5a6Sdrh ** in the outer query. 2989832508b7Sdrh */ 2990f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 2991c31c2eb8Sdrh 2992a78c22c4Sdrh /* Delete the transient table structure associated with the 2993a78c22c4Sdrh ** subquery 2994a78c22c4Sdrh */ 2995a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 2996a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 2997a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 2998a78c22c4Sdrh pSubitem->zDatabase = 0; 2999a78c22c4Sdrh pSubitem->zName = 0; 3000a78c22c4Sdrh pSubitem->zAlias = 0; 3001a78c22c4Sdrh pSubitem->pSelect = 0; 3002a78c22c4Sdrh 3003a78c22c4Sdrh /* Defer deleting the Table object associated with the 3004a78c22c4Sdrh ** subquery until code generation is 3005a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 3006a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 3007ccfcbceaSdrh ** 3008ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 3009a78c22c4Sdrh */ 3010ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 3011a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 3012a78c22c4Sdrh if( pTabToDel->nRef==1 ){ 301365a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 301465a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 301565a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 3016a78c22c4Sdrh }else{ 3017a78c22c4Sdrh pTabToDel->nRef--; 3018a78c22c4Sdrh } 3019a78c22c4Sdrh pSubitem->pTab = 0; 3020a78c22c4Sdrh } 3021a78c22c4Sdrh 3022a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 3023a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 3024a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 3025a78c22c4Sdrh ** then this loop only runs once. 3026a78c22c4Sdrh ** 3027a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 3028c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 3029c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 3030c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 3031c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 3032c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 3033c31c2eb8Sdrh ** elements we are now copying in. 3034c31c2eb8Sdrh */ 3035a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 3036a78c22c4Sdrh int nSubSrc; 3037ea678832Sdrh u8 jointype = 0; 3038a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 3039a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 3040a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 3041588a9a1aSdrh 3042a78c22c4Sdrh if( pSrc ){ 3043a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 3044a78c22c4Sdrh jointype = pSubitem->jointype; 3045588a9a1aSdrh }else{ 3046a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 3047a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 3048cfa063b3Sdrh if( pSrc==0 ){ 3049a78c22c4Sdrh assert( db->mallocFailed ); 3050a78c22c4Sdrh break; 3051cfa063b3Sdrh } 3052c31c2eb8Sdrh } 3053a78c22c4Sdrh 3054a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 3055a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 3056a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 3057a78c22c4Sdrh ** of the subquery. 3058a78c22c4Sdrh ** 3059a78c22c4Sdrh ** Example: 3060a78c22c4Sdrh ** 3061a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 3062a78c22c4Sdrh ** 3063a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 3064a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 3065a78c22c4Sdrh ** block of code will expand the out query to 4 slots. The middle 3066a78c22c4Sdrh ** slot is expanded to two slots in order to make space for the 3067a78c22c4Sdrh ** two elements in the FROM clause of the subquery. 3068a78c22c4Sdrh */ 3069a78c22c4Sdrh if( nSubSrc>1 ){ 3070a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 3071a78c22c4Sdrh if( db->mallocFailed ){ 3072a78c22c4Sdrh break; 3073c31c2eb8Sdrh } 3074c31c2eb8Sdrh } 3075a78c22c4Sdrh 3076a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 3077a78c22c4Sdrh ** outer query. 3078a78c22c4Sdrh */ 3079c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 3080c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 3081c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 3082c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 3083c31c2eb8Sdrh } 308461dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 3085c31c2eb8Sdrh 3086c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 3087c31c2eb8Sdrh ** references to the iParent in the outer query. 3088c31c2eb8Sdrh ** 3089c31c2eb8Sdrh ** Example: 3090c31c2eb8Sdrh ** 3091c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 3092c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 3093c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 3094c31c2eb8Sdrh ** 3095c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 3096c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 3097c31c2eb8Sdrh */ 3098f23329a2Sdanielk1977 pList = pParent->pEList; 3099832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 3100ccfcbceaSdrh if( pList->a[i].zName==0 ){ 3101*42fbf321Sdrh char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); 3102*42fbf321Sdrh sqlite3Dequote(zName); 3103*42fbf321Sdrh pList->a[i].zName = zName; 3104832508b7Sdrh } 3105ccfcbceaSdrh } 3106f23329a2Sdanielk1977 substExprList(db, pParent->pEList, iParent, pSub->pEList); 31071b2e0329Sdrh if( isAgg ){ 3108f23329a2Sdanielk1977 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList); 3109b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 31101b2e0329Sdrh } 3111174b6195Sdrh if( pSub->pOrderBy ){ 3112f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 3113f23329a2Sdanielk1977 pParent->pOrderBy = pSub->pOrderBy; 3114174b6195Sdrh pSub->pOrderBy = 0; 3115f23329a2Sdanielk1977 }else if( pParent->pOrderBy ){ 3116f23329a2Sdanielk1977 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList); 3117174b6195Sdrh } 3118832508b7Sdrh if( pSub->pWhere ){ 31196ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 3120832508b7Sdrh }else{ 3121832508b7Sdrh pWhere = 0; 3122832508b7Sdrh } 3123832508b7Sdrh if( subqueryIsAgg ){ 3124f23329a2Sdanielk1977 assert( pParent->pHaving==0 ); 3125f23329a2Sdanielk1977 pParent->pHaving = pParent->pWhere; 3126f23329a2Sdanielk1977 pParent->pWhere = pWhere; 3127b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 3128f23329a2Sdanielk1977 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 31296ab3a2ecSdanielk1977 sqlite3ExprDup(db, pSub->pHaving, 0)); 3130f23329a2Sdanielk1977 assert( pParent->pGroupBy==0 ); 31316ab3a2ecSdanielk1977 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); 3132832508b7Sdrh }else{ 3133b7916a78Sdrh pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList); 3134f23329a2Sdanielk1977 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); 3135832508b7Sdrh } 3136c31c2eb8Sdrh 3137c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 3138c31c2eb8Sdrh ** outer query is distinct. 3139c31c2eb8Sdrh */ 31407d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 31418c74a8caSdrh 3142a58fdfb1Sdanielk1977 /* 3143a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3144ac83963aSdrh ** 3145ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 3146ac83963aSdrh ** does not work if either limit is negative. 3147a58fdfb1Sdanielk1977 */ 3148a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 3149f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 3150a2dc3b1aSdanielk1977 pSub->pLimit = 0; 3151df199a25Sdrh } 3152f23329a2Sdanielk1977 } 31538c74a8caSdrh 3154c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 3155c31c2eb8Sdrh ** success. 3156c31c2eb8Sdrh */ 3157633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 3158f23329a2Sdanielk1977 3159832508b7Sdrh return 1; 31601350b030Sdrh } 31613514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 31621350b030Sdrh 31631350b030Sdrh /* 3164a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it 316508c88eb0Sdrh ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 3166a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be 3167a9d1ccb9Sdanielk1977 ** a min()/max() query if: 3168a9d1ccb9Sdanielk1977 ** 3169738bdcfbSdanielk1977 ** 1. There is a single object in the FROM clause. 3170738bdcfbSdanielk1977 ** 3171738bdcfbSdanielk1977 ** 2. There is a single expression in the result set, and it is 3172738bdcfbSdanielk1977 ** either min(x) or max(x), where x is a column reference. 3173a9d1ccb9Sdanielk1977 */ 31744f21c4afSdrh static u8 minMaxQuery(Select *p){ 3175a9d1ccb9Sdanielk1977 Expr *pExpr; 3176a9d1ccb9Sdanielk1977 ExprList *pEList = p->pEList; 3177a9d1ccb9Sdanielk1977 317808c88eb0Sdrh if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL; 3179a9d1ccb9Sdanielk1977 pExpr = pEList->a[0].pExpr; 318043152cf8Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 318143152cf8Sdrh if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0; 31826ab3a2ecSdanielk1977 pEList = pExpr->x.pList; 318343152cf8Sdrh if( pEList==0 || pEList->nExpr!=1 ) return 0; 318408c88eb0Sdrh if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL; 318533e619fcSdrh assert( !ExprHasProperty(pExpr, EP_IntValue) ); 318633e619fcSdrh if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){ 318708c88eb0Sdrh return WHERE_ORDERBY_MIN; 318833e619fcSdrh }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){ 318908c88eb0Sdrh return WHERE_ORDERBY_MAX; 3190a9d1ccb9Sdanielk1977 } 319108c88eb0Sdrh return WHERE_ORDERBY_NORMAL; 3192a9d1ccb9Sdanielk1977 } 3193a9d1ccb9Sdanielk1977 3194a9d1ccb9Sdanielk1977 /* 3195a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 3196a5533162Sdanielk1977 ** The second argment is the associated aggregate-info object. This 3197a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 3198a5533162Sdanielk1977 ** 3199a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 3200a5533162Sdanielk1977 ** 3201a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 3202a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 3203a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 3204a5533162Sdanielk1977 */ 3205a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 3206a5533162Sdanielk1977 Table *pTab; 3207a5533162Sdanielk1977 Expr *pExpr; 3208a5533162Sdanielk1977 3209a5533162Sdanielk1977 assert( !p->pGroupBy ); 3210a5533162Sdanielk1977 32117a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 3212a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 3213a5533162Sdanielk1977 ){ 3214a5533162Sdanielk1977 return 0; 3215a5533162Sdanielk1977 } 3216a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 3217a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 321802f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 321902f33725Sdanielk1977 322002f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 3221a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 3222fb0a6081Sdrh if( NEVER(pAggInfo->nFunc==0) ) return 0; 3223a5533162Sdanielk1977 if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0; 3224a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 3225a5533162Sdanielk1977 3226a5533162Sdanielk1977 return pTab; 3227a5533162Sdanielk1977 } 3228a5533162Sdanielk1977 3229a5533162Sdanielk1977 /* 3230b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 3231b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 3232b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 3233b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 3234b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 3235b1c685b0Sdanielk1977 */ 3236b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 3237b1c685b0Sdanielk1977 if( pFrom->pTab && pFrom->zIndex ){ 3238b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 3239b1c685b0Sdanielk1977 char *zIndex = pFrom->zIndex; 3240b1c685b0Sdanielk1977 Index *pIdx; 3241b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 3242b1c685b0Sdanielk1977 pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 3243b1c685b0Sdanielk1977 pIdx=pIdx->pNext 3244b1c685b0Sdanielk1977 ); 3245b1c685b0Sdanielk1977 if( !pIdx ){ 3246b1c685b0Sdanielk1977 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0); 32471db95106Sdan pParse->checkSchema = 1; 3248b1c685b0Sdanielk1977 return SQLITE_ERROR; 3249b1c685b0Sdanielk1977 } 3250b1c685b0Sdanielk1977 pFrom->pIndex = pIdx; 3251b1c685b0Sdanielk1977 } 3252b1c685b0Sdanielk1977 return SQLITE_OK; 3253b1c685b0Sdanielk1977 } 3254b1c685b0Sdanielk1977 3255b1c685b0Sdanielk1977 /* 32567d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 32577d10d5a6Sdrh ** "Expanding" means to do the following: 32587d10d5a6Sdrh ** 32597d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 32607d10d5a6Sdrh ** element of the FROM clause. 32617d10d5a6Sdrh ** 32627d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 32637d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 32647d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 32657d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 32667d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 32677d10d5a6Sdrh ** without worrying about messing up the presistent representation 32687d10d5a6Sdrh ** of the view. 32697d10d5a6Sdrh ** 32707d10d5a6Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 32717d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 32727d10d5a6Sdrh ** 32737d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 32747d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 32757d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 32767d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 32777d10d5a6Sdrh ** 3278b3bce662Sdanielk1977 */ 32797d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 32807d10d5a6Sdrh Parse *pParse = pWalker->pParse; 32817d10d5a6Sdrh int i, j, k; 32827d10d5a6Sdrh SrcList *pTabList; 32837d10d5a6Sdrh ExprList *pEList; 32847d10d5a6Sdrh struct SrcList_item *pFrom; 32857d10d5a6Sdrh sqlite3 *db = pParse->db; 32867d10d5a6Sdrh 32877d10d5a6Sdrh if( db->mallocFailed ){ 32887d10d5a6Sdrh return WRC_Abort; 32897d10d5a6Sdrh } 329043152cf8Sdrh if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){ 32917d10d5a6Sdrh return WRC_Prune; 32927d10d5a6Sdrh } 32937d10d5a6Sdrh p->selFlags |= SF_Expanded; 32947d10d5a6Sdrh pTabList = p->pSrc; 32957d10d5a6Sdrh pEList = p->pEList; 32967d10d5a6Sdrh 32977d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 32987d10d5a6Sdrh ** the FROM clause of the SELECT statement. 32997d10d5a6Sdrh */ 33007d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 33017d10d5a6Sdrh 33027d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 33037d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 33047d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 33057d10d5a6Sdrh */ 33067d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 33077d10d5a6Sdrh Table *pTab; 33087d10d5a6Sdrh if( pFrom->pTab!=0 ){ 33097d10d5a6Sdrh /* This statement has already been prepared. There is no need 33107d10d5a6Sdrh ** to go further. */ 33117d10d5a6Sdrh assert( i==0 ); 33127d10d5a6Sdrh return WRC_Prune; 33137d10d5a6Sdrh } 33147d10d5a6Sdrh if( pFrom->zName==0 ){ 33157d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 33167d10d5a6Sdrh Select *pSel = pFrom->pSelect; 33177d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 33187d10d5a6Sdrh assert( pSel!=0 ); 33197d10d5a6Sdrh assert( pFrom->pTab==0 ); 33207d10d5a6Sdrh sqlite3WalkSelect(pWalker, pSel); 33217d10d5a6Sdrh pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 33227d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 33237d10d5a6Sdrh pTab->nRef = 1; 33247d10d5a6Sdrh pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab); 33257d10d5a6Sdrh while( pSel->pPrior ){ pSel = pSel->pPrior; } 33267d10d5a6Sdrh selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol); 33277d10d5a6Sdrh pTab->iPKey = -1; 33281ea87012Sdrh pTab->nRowEst = 1000000; 33297d10d5a6Sdrh pTab->tabFlags |= TF_Ephemeral; 33307d10d5a6Sdrh #endif 33317d10d5a6Sdrh }else{ 33327d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 33337d10d5a6Sdrh assert( pFrom->pTab==0 ); 333441fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 33357d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 33367d10d5a6Sdrh pTab->nRef++; 33377d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 33387d10d5a6Sdrh if( pTab->pSelect || IsVirtual(pTab) ){ 33397d10d5a6Sdrh /* We reach here if the named table is a really a view */ 33407d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 334143152cf8Sdrh assert( pFrom->pSelect==0 ); 33426ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 33437d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 33447d10d5a6Sdrh } 33457d10d5a6Sdrh #endif 33467d10d5a6Sdrh } 334785574e31Sdanielk1977 334885574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 3349b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 335085574e31Sdanielk1977 return WRC_Abort; 335185574e31Sdanielk1977 } 33527d10d5a6Sdrh } 33537d10d5a6Sdrh 33547d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 33557d10d5a6Sdrh */ 33567d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 33577d10d5a6Sdrh return WRC_Abort; 33587d10d5a6Sdrh } 33597d10d5a6Sdrh 33607d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 33617d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 33627d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 33637d10d5a6Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 33647d10d5a6Sdrh ** The following code just has to locate the TK_ALL expressions and expand 33657d10d5a6Sdrh ** each one to the list of all columns in all tables. 33667d10d5a6Sdrh ** 33677d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 33687d10d5a6Sdrh ** that need expanding. 33697d10d5a6Sdrh */ 33707d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 33717d10d5a6Sdrh Expr *pE = pEList->a[k].pExpr; 33727d10d5a6Sdrh if( pE->op==TK_ALL ) break; 337343152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 337443152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 337543152cf8Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; 33767d10d5a6Sdrh } 33777d10d5a6Sdrh if( k<pEList->nExpr ){ 33787d10d5a6Sdrh /* 33797d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 33807d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 33817d10d5a6Sdrh ** in the result set and expand them one by one. 33827d10d5a6Sdrh */ 33837d10d5a6Sdrh struct ExprList_item *a = pEList->a; 33847d10d5a6Sdrh ExprList *pNew = 0; 33857d10d5a6Sdrh int flags = pParse->db->flags; 33867d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 33877d10d5a6Sdrh && (flags & SQLITE_ShortColNames)==0; 33887d10d5a6Sdrh 33897d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 33907d10d5a6Sdrh Expr *pE = a[k].pExpr; 339143152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 339243152cf8Sdrh if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){ 33937d10d5a6Sdrh /* This particular expression does not need to be expanded. 33947d10d5a6Sdrh */ 3395b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 33967d10d5a6Sdrh if( pNew ){ 33977d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 3398b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 3399b7916a78Sdrh a[k].zName = 0; 3400b7916a78Sdrh a[k].zSpan = 0; 34017d10d5a6Sdrh } 34027d10d5a6Sdrh a[k].pExpr = 0; 34037d10d5a6Sdrh }else{ 34047d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 34057d10d5a6Sdrh ** expanded. */ 34067d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 34077d10d5a6Sdrh char *zTName; /* text of name of TABLE */ 340843152cf8Sdrh if( pE->op==TK_DOT ){ 340943152cf8Sdrh assert( pE->pLeft!=0 ); 341033e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 341133e619fcSdrh zTName = pE->pLeft->u.zToken; 34127d10d5a6Sdrh }else{ 34137d10d5a6Sdrh zTName = 0; 34147d10d5a6Sdrh } 34157d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 34167d10d5a6Sdrh Table *pTab = pFrom->pTab; 34177d10d5a6Sdrh char *zTabName = pFrom->zAlias; 341843152cf8Sdrh if( zTabName==0 ){ 34197d10d5a6Sdrh zTabName = pTab->zName; 34207d10d5a6Sdrh } 34217d10d5a6Sdrh if( db->mallocFailed ) break; 34227d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 34237d10d5a6Sdrh continue; 34247d10d5a6Sdrh } 34257d10d5a6Sdrh tableSeen = 1; 34267d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 34277d10d5a6Sdrh Expr *pExpr, *pRight; 34287d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 3429b7916a78Sdrh char *zColname; /* The computed column name */ 3430b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 3431b7916a78Sdrh Token sColname; /* Computed column name as a token */ 34327d10d5a6Sdrh 34337d10d5a6Sdrh /* If a column is marked as 'hidden' (currently only possible 34347d10d5a6Sdrh ** for virtual tables), do not include it in the expanded 34357d10d5a6Sdrh ** result-set list. 34367d10d5a6Sdrh */ 34377d10d5a6Sdrh if( IsHiddenColumn(&pTab->aCol[j]) ){ 34387d10d5a6Sdrh assert(IsVirtual(pTab)); 34397d10d5a6Sdrh continue; 34407d10d5a6Sdrh } 34417d10d5a6Sdrh 3442da55c48aSdrh if( i>0 && zTName==0 ){ 34432179b434Sdrh if( (pFrom->jointype & JT_NATURAL)!=0 34442179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 34452179b434Sdrh ){ 34467d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 34472179b434Sdrh ** table to the right of the join */ 34487d10d5a6Sdrh continue; 34497d10d5a6Sdrh } 34502179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 34517d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 34527d10d5a6Sdrh ** using clause from the table on the right. */ 34537d10d5a6Sdrh continue; 34547d10d5a6Sdrh } 34557d10d5a6Sdrh } 3456b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 3457b7916a78Sdrh zColname = zName; 3458b7916a78Sdrh zToFree = 0; 34597d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 3460b7916a78Sdrh Expr *pLeft; 3461b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 34627d10d5a6Sdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 3463b7916a78Sdrh if( longNames ){ 3464b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 3465b7916a78Sdrh zToFree = zColname; 3466b7916a78Sdrh } 34677d10d5a6Sdrh }else{ 34687d10d5a6Sdrh pExpr = pRight; 34697d10d5a6Sdrh } 3470b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 3471b7916a78Sdrh sColname.z = zColname; 3472b7916a78Sdrh sColname.n = sqlite3Strlen30(zColname); 3473b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 3474b7916a78Sdrh sqlite3DbFree(db, zToFree); 34757d10d5a6Sdrh } 34767d10d5a6Sdrh } 34777d10d5a6Sdrh if( !tableSeen ){ 34787d10d5a6Sdrh if( zTName ){ 34797d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 34807d10d5a6Sdrh }else{ 34817d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 34827d10d5a6Sdrh } 34837d10d5a6Sdrh } 34847d10d5a6Sdrh } 34857d10d5a6Sdrh } 34867d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 34877d10d5a6Sdrh p->pEList = pNew; 34887d10d5a6Sdrh } 34897d10d5a6Sdrh #if SQLITE_MAX_COLUMN 34907d10d5a6Sdrh if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 34917d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 34927d10d5a6Sdrh } 34937d10d5a6Sdrh #endif 34947d10d5a6Sdrh return WRC_Continue; 34957d10d5a6Sdrh } 34967d10d5a6Sdrh 34977d10d5a6Sdrh /* 34987d10d5a6Sdrh ** No-op routine for the parse-tree walker. 34997d10d5a6Sdrh ** 35007d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 35017d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 35027d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 35037d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 35047d10d5a6Sdrh ** subquery in the parser tree. 35057d10d5a6Sdrh */ 350662c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 350762c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 35087d10d5a6Sdrh return WRC_Continue; 35097d10d5a6Sdrh } 35107d10d5a6Sdrh 35117d10d5a6Sdrh /* 35127d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 35137d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 35147d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 35157d10d5a6Sdrh ** 35167d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 35177d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 35187d10d5a6Sdrh ** name resolution is performed. 35197d10d5a6Sdrh ** 35207d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 35217d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 35227d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 35237d10d5a6Sdrh */ 35247d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 35257d10d5a6Sdrh Walker w; 35267d10d5a6Sdrh w.xSelectCallback = selectExpander; 35277d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 35287d10d5a6Sdrh w.pParse = pParse; 35297d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 35307d10d5a6Sdrh } 35317d10d5a6Sdrh 35327d10d5a6Sdrh 35337d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 35347d10d5a6Sdrh /* 35357d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 35367d10d5a6Sdrh ** interface. 35377d10d5a6Sdrh ** 35387d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 35397d10d5a6Sdrh ** information to the Table structure that represents the result set 35407d10d5a6Sdrh ** of that subquery. 35417d10d5a6Sdrh ** 35427d10d5a6Sdrh ** The Table structure that represents the result set was constructed 35437d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 35447d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 35457d10d5a6Sdrh ** routine is called after identifier resolution. 35467d10d5a6Sdrh */ 35477d10d5a6Sdrh static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 35487d10d5a6Sdrh Parse *pParse; 35497d10d5a6Sdrh int i; 35507d10d5a6Sdrh SrcList *pTabList; 35517d10d5a6Sdrh struct SrcList_item *pFrom; 35527d10d5a6Sdrh 35539d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 35545a29d9cbSdrh if( (p->selFlags & SF_HasTypeInfo)==0 ){ 35557d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 35567d10d5a6Sdrh pParse = pWalker->pParse; 35577d10d5a6Sdrh pTabList = p->pSrc; 35587d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 35597d10d5a6Sdrh Table *pTab = pFrom->pTab; 356043152cf8Sdrh if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){ 35617d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 35627d10d5a6Sdrh Select *pSel = pFrom->pSelect; 35637d10d5a6Sdrh assert( pSel ); 35647d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 35657d10d5a6Sdrh selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel); 35667d10d5a6Sdrh } 35677d10d5a6Sdrh } 35685a29d9cbSdrh } 35697d10d5a6Sdrh return WRC_Continue; 35707d10d5a6Sdrh } 35717d10d5a6Sdrh #endif 35727d10d5a6Sdrh 35737d10d5a6Sdrh 35747d10d5a6Sdrh /* 35757d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 35767d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 35777d10d5a6Sdrh ** SELECT statement. 35787d10d5a6Sdrh ** 35797d10d5a6Sdrh ** Use this routine after name resolution. 35807d10d5a6Sdrh */ 35817d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 35827d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 35837d10d5a6Sdrh Walker w; 35847d10d5a6Sdrh w.xSelectCallback = selectAddSubqueryTypeInfo; 35857d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 35867d10d5a6Sdrh w.pParse = pParse; 35877d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 35887d10d5a6Sdrh #endif 35897d10d5a6Sdrh } 35907d10d5a6Sdrh 35917d10d5a6Sdrh 35927d10d5a6Sdrh /* 3593030796dfSdrh ** This routine sets up a SELECT statement for processing. The 35947d10d5a6Sdrh ** following is accomplished: 35957d10d5a6Sdrh ** 35967d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 35977d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 35987d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 35997d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 36007d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 36017d10d5a6Sdrh ** 36027d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 36037d10d5a6Sdrh */ 36047d10d5a6Sdrh void sqlite3SelectPrep( 3605b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 3606b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 36077d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 3608b3bce662Sdanielk1977 ){ 36097d10d5a6Sdrh sqlite3 *db; 361043152cf8Sdrh if( NEVER(p==0) ) return; 36117d10d5a6Sdrh db = pParse->db; 36127d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 36137d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 36147d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 36157d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 36167d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 36177d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 3618f6bbe022Sdrh } 3619b3bce662Sdanielk1977 3620b3bce662Sdanielk1977 /* 362113449892Sdrh ** Reset the aggregate accumulator. 362213449892Sdrh ** 362313449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 362413449892Sdrh ** intermediate results while calculating an aggregate. This 3625030796dfSdrh ** routine generates code that stores NULLs in all of those memory 3626030796dfSdrh ** cells. 3627b3bce662Sdanielk1977 */ 362813449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 362913449892Sdrh Vdbe *v = pParse->pVdbe; 363013449892Sdrh int i; 3631c99130fdSdrh struct AggInfo_func *pFunc; 363213449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 363313449892Sdrh return; 363413449892Sdrh } 363513449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 36364c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); 363713449892Sdrh } 3638c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 36394c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); 3640c99130fdSdrh if( pFunc->iDistinct>=0 ){ 3641c99130fdSdrh Expr *pE = pFunc->pExpr; 36426ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 36436ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 36440daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 36450daa002cSdrh "argument"); 3646c99130fdSdrh pFunc->iDistinct = -1; 3647c99130fdSdrh }else{ 36486ab3a2ecSdanielk1977 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList); 364966a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 365066a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 3651c99130fdSdrh } 3652c99130fdSdrh } 365313449892Sdrh } 3654b3bce662Sdanielk1977 } 3655b3bce662Sdanielk1977 3656b3bce662Sdanielk1977 /* 365713449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 365813449892Sdrh ** in the AggInfo structure. 3659b3bce662Sdanielk1977 */ 366013449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 366113449892Sdrh Vdbe *v = pParse->pVdbe; 366213449892Sdrh int i; 366313449892Sdrh struct AggInfo_func *pF; 366413449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 36656ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 36666ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 366766a5167bSdrh sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 366866a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 3669b3bce662Sdanielk1977 } 367013449892Sdrh } 367113449892Sdrh 367213449892Sdrh /* 367313449892Sdrh ** Update the accumulator memory cells for an aggregate based on 367413449892Sdrh ** the current cursor position. 367513449892Sdrh */ 367613449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 367713449892Sdrh Vdbe *v = pParse->pVdbe; 367813449892Sdrh int i; 36797a95789cSdrh int regHit = 0; 36807a95789cSdrh int addrHitTest = 0; 368113449892Sdrh struct AggInfo_func *pF; 368213449892Sdrh struct AggInfo_col *pC; 368313449892Sdrh 368413449892Sdrh pAggInfo->directMode = 1; 3685ceea3321Sdrh sqlite3ExprCacheClear(pParse); 368613449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 368713449892Sdrh int nArg; 3688c99130fdSdrh int addrNext = 0; 368998757157Sdrh int regAgg; 36906ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 36916ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 369213449892Sdrh if( pList ){ 369313449892Sdrh nArg = pList->nExpr; 3694892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 36957153d1fbSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 1); 369613449892Sdrh }else{ 369713449892Sdrh nArg = 0; 369898757157Sdrh regAgg = 0; 369913449892Sdrh } 3700c99130fdSdrh if( pF->iDistinct>=0 ){ 3701c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 3702c99130fdSdrh assert( nArg==1 ); 37032dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 3704c99130fdSdrh } 3705e82f5d04Sdrh if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){ 370613449892Sdrh CollSeq *pColl = 0; 370713449892Sdrh struct ExprList_item *pItem; 370813449892Sdrh int j; 3709e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 371043617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 371113449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 371213449892Sdrh } 371313449892Sdrh if( !pColl ){ 371413449892Sdrh pColl = pParse->db->pDfltColl; 371513449892Sdrh } 37167a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 37177a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 371813449892Sdrh } 371998757157Sdrh sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 372066a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 3721ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 3722da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 3723f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 3724c99130fdSdrh if( addrNext ){ 3725c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 3726ceea3321Sdrh sqlite3ExprCacheClear(pParse); 3727c99130fdSdrh } 372813449892Sdrh } 372967a6a40cSdan 373067a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 373167a6a40cSdan ** Otherwise, if any of the required column values are already present 373267a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 373367a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 373467a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 373567a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 373667a6a40cSdan ** 373767a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 373867a6a40cSdan ** values to an OP_Copy. 373967a6a40cSdan */ 37407a95789cSdrh if( regHit ){ 37417a95789cSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); 37427a95789cSdrh } 374367a6a40cSdan sqlite3ExprCacheClear(pParse); 374413449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 3745389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 374613449892Sdrh } 374713449892Sdrh pAggInfo->directMode = 0; 3748ceea3321Sdrh sqlite3ExprCacheClear(pParse); 37497a95789cSdrh if( addrHitTest ){ 37507a95789cSdrh sqlite3VdbeJumpHere(v, addrHitTest); 37517a95789cSdrh } 375213449892Sdrh } 375313449892Sdrh 3754b3bce662Sdanielk1977 /* 3755ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 3756ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 3757ef7075deSdan */ 3758ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 3759ef7075deSdan static void explainSimpleCount( 3760ef7075deSdan Parse *pParse, /* Parse context */ 3761ef7075deSdan Table *pTab, /* Table being queried */ 3762ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 3763ef7075deSdan ){ 3764ef7075deSdan if( pParse->explain==2 ){ 3765ef7075deSdan char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)", 3766ef7075deSdan pTab->zName, 3767ef7075deSdan pIdx ? "USING COVERING INDEX " : "", 3768ef7075deSdan pIdx ? pIdx->zName : "", 3769ef7075deSdan pTab->nRowEst 3770ef7075deSdan ); 3771ef7075deSdan sqlite3VdbeAddOp4( 3772ef7075deSdan pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC 3773ef7075deSdan ); 3774ef7075deSdan } 3775ef7075deSdan } 3776ef7075deSdan #else 3777ef7075deSdan # define explainSimpleCount(a,b,c) 3778ef7075deSdan #endif 3779ef7075deSdan 3780ef7075deSdan /* 37817d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 37829bb61fe7Sdrh ** 3783fef5208cSdrh ** The results are distributed in various ways depending on the 37846c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest 37856c8c8ce0Sdanielk1977 ** as follows: 3786fef5208cSdrh ** 37876c8c8ce0Sdanielk1977 ** pDest->eDest Result 3788fef5208cSdrh ** ------------ ------------------------------------------- 37897d10d5a6Sdrh ** SRT_Output Generate a row of output (using the OP_ResultRow 37907d10d5a6Sdrh ** opcode) for each row in the result set. 3791fef5208cSdrh ** 37927d10d5a6Sdrh ** SRT_Mem Only valid if the result is a single column. 37937d10d5a6Sdrh ** Store the first column of the first result row 37942b596da8Sdrh ** in register pDest->iSDParm then abandon the rest 37957d10d5a6Sdrh ** of the query. This destination implies "LIMIT 1". 3796fef5208cSdrh ** 37977d10d5a6Sdrh ** SRT_Set The result must be a single column. Store each 37982b596da8Sdrh ** row of result as the key in table pDest->iSDParm. 3799c041c16cSdrh ** Apply the affinity pDest->affSdst before storing 38007d10d5a6Sdrh ** results. Used to implement "IN (SELECT ...)". 3801fef5208cSdrh ** 38022b596da8Sdrh ** SRT_Union Store results as a key in a temporary table 38032b596da8Sdrh ** identified by pDest->iSDParm. 380482c3d636Sdrh ** 38052b596da8Sdrh ** SRT_Except Remove results from the temporary table pDest->iSDParm. 3806c4a3c779Sdrh ** 38072b596da8Sdrh ** SRT_Table Store results in temporary table pDest->iSDParm. 38087d10d5a6Sdrh ** This is like SRT_EphemTab except that the table 38097d10d5a6Sdrh ** is assumed to already be open. 38109bb61fe7Sdrh ** 38112b596da8Sdrh ** SRT_EphemTab Create an temporary table pDest->iSDParm and store 38126c8c8ce0Sdanielk1977 ** the result there. The cursor is left open after 38137d10d5a6Sdrh ** returning. This is like SRT_Table except that 38147d10d5a6Sdrh ** this destination uses OP_OpenEphemeral to create 38157d10d5a6Sdrh ** the table first. 38166c8c8ce0Sdanielk1977 ** 38177d10d5a6Sdrh ** SRT_Coroutine Generate a co-routine that returns a new row of 38187d10d5a6Sdrh ** results each time it is invoked. The entry point 38192b596da8Sdrh ** of the co-routine is stored in register pDest->iSDParm. 38206c8c8ce0Sdanielk1977 ** 38212b596da8Sdrh ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result 38226c8c8ce0Sdanielk1977 ** set is not empty. 38236c8c8ce0Sdanielk1977 ** 38247d10d5a6Sdrh ** SRT_Discard Throw the results away. This is used by SELECT 38257d10d5a6Sdrh ** statements within triggers whose only purpose is 38267d10d5a6Sdrh ** the side-effects of functions. 3827e78e8284Sdrh ** 38289bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 38299bb61fe7Sdrh ** encountered, then an appropriate error message is left in 38309bb61fe7Sdrh ** pParse->zErrMsg. 38319bb61fe7Sdrh ** 38329bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 38339bb61fe7Sdrh ** calling function needs to do that. 38349bb61fe7Sdrh */ 38354adee20fSdanielk1977 int sqlite3Select( 3836cce7d176Sdrh Parse *pParse, /* The parser context */ 38379bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 38387d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 3839cce7d176Sdrh ){ 384013449892Sdrh int i, j; /* Loop counters */ 384113449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 384213449892Sdrh Vdbe *v; /* The virtual machine under construction */ 3843b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 3844a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 3845ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 38469bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 38479bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 38482282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 38492282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 38501d83f052Sdrh int rc = 1; /* Value to return from this function */ 3851b9bb7c18Sdrh int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 3852e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 385313449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 3854ec7429aeSdrh int iEnd; /* Address of the end of the query */ 385517435752Sdrh sqlite3 *db; /* The database connection */ 38569bb61fe7Sdrh 38572ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 38582ce22453Sdan int iRestoreSelectId = pParse->iSelectId; 38592ce22453Sdan pParse->iSelectId = pParse->iNextSelectId++; 38602ce22453Sdan #endif 38612ce22453Sdan 386217435752Sdrh db = pParse->db; 386317435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 38646f7adc8aSdrh return 1; 38656f7adc8aSdrh } 38664adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 386713449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 3868daffd0e5Sdrh 38696c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 38709ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 38719ed1dfa8Sdanielk1977 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); 3872ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 3873ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 3874ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 3875ccfcbceaSdrh p->pOrderBy = 0; 38767d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 38779a99334dSdrh } 38787d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 3879ccfcbceaSdrh pOrderBy = p->pOrderBy; 3880b27b7f5dSdrh pTabList = p->pSrc; 3881b27b7f5dSdrh pEList = p->pEList; 3882956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 38839a99334dSdrh goto select_end; 38849a99334dSdrh } 38857d10d5a6Sdrh isAgg = (p->selFlags & SF_Aggregate)!=0; 388643152cf8Sdrh assert( pEList!=0 ); 3887cce7d176Sdrh 3888d820cb1bSdrh /* Begin generating code. 3889d820cb1bSdrh */ 38904adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 3891d820cb1bSdrh if( v==0 ) goto select_end; 3892d820cb1bSdrh 389374b617b2Sdan /* If writing to memory or generating a set 389474b617b2Sdan ** only a single column may be output. 389574b617b2Sdan */ 389674b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY 389774b617b2Sdan if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 389874b617b2Sdan goto select_end; 389974b617b2Sdan } 390074b617b2Sdan #endif 390174b617b2Sdan 3902d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 3903d820cb1bSdrh */ 390451522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3905f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 390613449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 39071013c932Sdrh SelectDest dest; 3908daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 3909f23329a2Sdanielk1977 int isAggSub; 3910c31c2eb8Sdrh 39115b6a9ed4Sdrh if( pSub==0 ) continue; 39125b6a9ed4Sdrh if( pItem->addrFillSub ){ 39135b6a9ed4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 39145b6a9ed4Sdrh continue; 39155b6a9ed4Sdrh } 3916daf79acbSdanielk1977 3917fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 3918fc976065Sdanielk1977 ** tree refered to by this, the parent select. The child select 3919fc976065Sdanielk1977 ** may contain expression trees of at most 3920fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 3921fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 3922fc976065Sdanielk1977 ** an exact limit. 3923fc976065Sdanielk1977 */ 3924fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 3925daf79acbSdanielk1977 39267d10d5a6Sdrh isAggSub = (pSub->selFlags & SF_Aggregate)!=0; 3927524cc21eSdanielk1977 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ 39285b6a9ed4Sdrh /* This subquery can be absorbed into its parent. */ 3929f23329a2Sdanielk1977 if( isAggSub ){ 39307d10d5a6Sdrh isAgg = 1; 39317d10d5a6Sdrh p->selFlags |= SF_Aggregate; 3932daf79acbSdanielk1977 } 3933daf79acbSdanielk1977 i = -1; 3934daf79acbSdanielk1977 }else{ 39355b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 39365b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 39375b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 39385b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 39395b6a9ed4Sdrh */ 39407157e8eaSdrh int topAddr; 394148f2d3b1Sdrh int onceAddr = 0; 39427157e8eaSdrh int retAddr; 39435b6a9ed4Sdrh assert( pItem->addrFillSub==0 ); 39445b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 39457157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 39467157e8eaSdrh pItem->addrFillSub = topAddr+1; 39477157e8eaSdrh VdbeNoopComment((v, "materialize %s", pItem->pTab->zName)); 39481d8cb21fSdan if( pItem->isCorrelated==0 ){ 39495b6a9ed4Sdrh /* If the subquery is no correlated and if we are not inside of 39505b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 39515b6a9ed4Sdrh ** once. */ 39521d8cb21fSdan onceAddr = sqlite3CodeOnce(pParse); 39535b6a9ed4Sdrh } 39541013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 3955ce7e189dSdan explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 39567d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 395795aa47b1Sdrh pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow; 395848f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 39597157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 39607157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 39617157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 3962cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 3963daf79acbSdanielk1977 } 396443152cf8Sdrh if( /*pParse->nErr ||*/ db->mallocFailed ){ 3965cfa063b3Sdrh goto select_end; 3966cfa063b3Sdrh } 3967fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 3968832508b7Sdrh pTabList = p->pSrc; 39696c8c8ce0Sdanielk1977 if( !IgnorableOrderby(pDest) ){ 3970832508b7Sdrh pOrderBy = p->pOrderBy; 3971acd4c695Sdrh } 3972daf79acbSdanielk1977 } 3973daf79acbSdanielk1977 pEList = p->pEList; 3974daf79acbSdanielk1977 #endif 3975daf79acbSdanielk1977 pWhere = p->pWhere; 3976832508b7Sdrh pGroupBy = p->pGroupBy; 3977832508b7Sdrh pHaving = p->pHaving; 3978e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 3979832508b7Sdrh 3980f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3981f23329a2Sdanielk1977 /* If there is are a sequence of queries, do the earlier ones first. 3982f23329a2Sdanielk1977 */ 3983f23329a2Sdanielk1977 if( p->pPrior ){ 3984f23329a2Sdanielk1977 if( p->pRightmost==0 ){ 3985f23329a2Sdanielk1977 Select *pLoop, *pRight = 0; 3986f23329a2Sdanielk1977 int cnt = 0; 3987f23329a2Sdanielk1977 int mxSelect; 3988f23329a2Sdanielk1977 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 3989f23329a2Sdanielk1977 pLoop->pRightmost = p; 3990f23329a2Sdanielk1977 pLoop->pNext = pRight; 3991f23329a2Sdanielk1977 pRight = pLoop; 3992f23329a2Sdanielk1977 } 3993f23329a2Sdanielk1977 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; 3994f23329a2Sdanielk1977 if( mxSelect && cnt>mxSelect ){ 3995f23329a2Sdanielk1977 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 39962ce22453Sdan goto select_end; 3997f23329a2Sdanielk1977 } 3998f23329a2Sdanielk1977 } 39997f61e92cSdan rc = multiSelect(pParse, p, pDest); 400017c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 40017f61e92cSdan return rc; 4002f23329a2Sdanielk1977 } 4003f23329a2Sdanielk1977 #endif 4004f23329a2Sdanielk1977 40058c6f666bSdrh /* If there is both a GROUP BY and an ORDER BY clause and they are 40068c6f666bSdrh ** identical, then disable the ORDER BY clause since the GROUP BY 40078c6f666bSdrh ** will cause elements to come out in the correct order. This is 40088c6f666bSdrh ** an optimization - the correct answer should result regardless. 40098c6f666bSdrh ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER 40108c6f666bSdrh ** to disable this optimization for testing purposes. 40118c6f666bSdrh */ 40128c6f666bSdrh if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0 40137e5418e4Sdrh && OptimizationEnabled(db, SQLITE_GroupByOrder) ){ 40148c6f666bSdrh pOrderBy = 0; 40158c6f666bSdrh } 40168c6f666bSdrh 401750118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 401850118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 401950118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 402050118cdfSdan ** 402150118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 402250118cdfSdan ** 402350118cdfSdan ** is transformed to: 402450118cdfSdan ** 402550118cdfSdan ** SELECT xyz FROM ... GROUP BY xyz 402650118cdfSdan ** 402750118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 402850118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 402950118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 403050118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 403150118cdfSdan */ 403250118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 403350118cdfSdan && sqlite3ExprListCompare(pOrderBy, p->pEList)==0 403450118cdfSdan ){ 403550118cdfSdan p->selFlags &= ~SF_Distinct; 403650118cdfSdan p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0); 403750118cdfSdan pGroupBy = p->pGroupBy; 403850118cdfSdan pOrderBy = 0; 4039e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 4040e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 4041e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 4042e8e4af76Sdrh assert( sDistinct.isTnct ); 404350118cdfSdan } 404450118cdfSdan 40458b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 40468b4c40d8Sdrh ** index might end up being unused if the data can be 40479d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 4048b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 40499d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 40509d2985c7Sdrh ** variable is used to facilitate that change. 40517cedc8d4Sdanielk1977 */ 40527cedc8d4Sdanielk1977 if( pOrderBy ){ 40530342b1f5Sdrh KeyInfo *pKeyInfo; 40540342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 40559d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 4056b9bb7c18Sdrh p->addrOpenEphm[2] = addrSortIndex = 405766a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 405866a5167bSdrh pOrderBy->iECursor, pOrderBy->nExpr+2, 0, 405966a5167bSdrh (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 40609d2985c7Sdrh }else{ 40619d2985c7Sdrh addrSortIndex = -1; 40627cedc8d4Sdanielk1977 } 40637cedc8d4Sdanielk1977 40642d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 40652d0794e3Sdrh */ 40666c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 40672b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 40682d0794e3Sdrh } 40692d0794e3Sdrh 4070f42bacc2Sdrh /* Set the limiter. 4071f42bacc2Sdrh */ 4072f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 407395aa47b1Sdrh p->nSelectRow = (double)LARGEST_INT64; 4074f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 4075c6aff30cSdrh if( p->iLimit==0 && addrSortIndex>=0 ){ 4076c6aff30cSdrh sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen; 4077c6aff30cSdrh p->selFlags |= SF_UseSorter; 4078c6aff30cSdrh } 4079f42bacc2Sdrh 4080dece1a84Sdrh /* Open a virtual index to use for the distinct set. 4081cce7d176Sdrh */ 40822ce22453Sdan if( p->selFlags & SF_Distinct ){ 4083e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 4084e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 4085e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 4086e8e4af76Sdrh (char*)keyInfoFromExprList(pParse, p->pEList), 4087e8e4af76Sdrh P4_KEYINFO_HANDOFF); 4088d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 4089e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 4090832508b7Sdrh }else{ 4091e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 4092efb7251dSdrh } 4093832508b7Sdrh 409413449892Sdrh if( !isAgg && pGroupBy==0 ){ 4095e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 4096e8e4af76Sdrh ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0); 409738cc40c2Sdan 409838cc40c2Sdan /* Begin the database scan. */ 409946ec5b63Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0); 41001d83f052Sdrh if( pWInfo==0 ) goto select_end; 410195aa47b1Sdrh if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut; 4102e8e4af76Sdrh if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct; 410346ec5b63Sdrh if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0; 4104cce7d176Sdrh 4105b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 4106b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 41079d2985c7Sdrh ** into an OP_Noop. 41089d2985c7Sdrh */ 41099d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 411048f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortIndex); 4111b9bb7c18Sdrh p->addrOpenEphm[2] = -1; 41129d2985c7Sdrh } 41139d2985c7Sdrh 411438cc40c2Sdan /* Use the standard inner loop. */ 4115e8e4af76Sdrh selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest, 4116a9671a22Sdrh pWInfo->iContinue, pWInfo->iBreak); 41172282792aSdrh 4118cce7d176Sdrh /* End the database scan loop. 4119cce7d176Sdrh */ 41204adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 412113449892Sdrh }else{ 4122e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 4123e8e4af76Sdrh ** or both */ 412413449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 412513449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 412613449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 412713449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 412813449892Sdrh ** one row of the input to the aggregator has been 412913449892Sdrh ** processed */ 413013449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 413113449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 4132d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 41331c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 41341c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 4135d176611bSdrh 4136d176611bSdrh /* Remove any and all aliases between the result set and the 4137d176611bSdrh ** GROUP BY clause. 4138d176611bSdrh */ 4139d176611bSdrh if( pGroupBy ){ 4140dc5ea5c7Sdrh int k; /* Loop counter */ 4141d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 4142d176611bSdrh 4143dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 4144d176611bSdrh pItem->iAlias = 0; 4145d176611bSdrh } 4146dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 4147d176611bSdrh pItem->iAlias = 0; 4148d176611bSdrh } 414995aa47b1Sdrh if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100; 415095aa47b1Sdrh }else{ 415195aa47b1Sdrh p->nSelectRow = (double)1; 4152d176611bSdrh } 4153cce7d176Sdrh 415413449892Sdrh 4155d176611bSdrh /* Create a label to jump to when we want to abort the query */ 415613449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 415713449892Sdrh 415813449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 415913449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 416013449892Sdrh ** SELECT statement. 41612282792aSdrh */ 416213449892Sdrh memset(&sNC, 0, sizeof(sNC)); 416313449892Sdrh sNC.pParse = pParse; 416413449892Sdrh sNC.pSrcList = pTabList; 416513449892Sdrh sNC.pAggInfo = &sAggInfo; 416613449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 41679d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 4168d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 4169d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); 4170d2b3e23bSdrh if( pHaving ){ 4171d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 417213449892Sdrh } 417313449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 417413449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 41756ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 41763a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 41776ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 41783a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 417913449892Sdrh } 418017435752Sdrh if( db->mallocFailed ) goto select_end; 418113449892Sdrh 418213449892Sdrh /* Processing for aggregates with GROUP BY is very different and 41833c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 418413449892Sdrh */ 418513449892Sdrh if( pGroupBy ){ 418613449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 4187d176611bSdrh int j1; /* A-vs-B comparision jump */ 4188d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 4189d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 4190d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 4191d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 4192d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 4193d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 4194d176611bSdrh int regReset; /* Return address register for reset subroutine */ 419513449892Sdrh 419613449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 419713449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 41981c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 419913449892Sdrh ** will be converted into a Noop. 420013449892Sdrh */ 420113449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 420213449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 42031c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 4204cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 4205cd3e8f7cSdanielk1977 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); 420613449892Sdrh 420713449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 420813449892Sdrh */ 42090a07c107Sdrh iUseFlag = ++pParse->nMem; 42100a07c107Sdrh iAbortFlag = ++pParse->nMem; 4211d176611bSdrh regOutputRow = ++pParse->nMem; 4212d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 4213d176611bSdrh regReset = ++pParse->nMem; 4214d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 42150a07c107Sdrh iAMem = pParse->nMem + 1; 421613449892Sdrh pParse->nMem += pGroupBy->nExpr; 42170a07c107Sdrh iBMem = pParse->nMem + 1; 421813449892Sdrh pParse->nMem += pGroupBy->nExpr; 42194c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 4220d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 42214c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 4222d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 4223b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 4224e313382eSdrh 422513449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 422613449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 422713449892Sdrh ** it might be a single loop that uses an index to extract information 422813449892Sdrh ** in the right order to begin with. 422913449892Sdrh */ 42302eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 423146ec5b63Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0); 42325360ad34Sdrh if( pWInfo==0 ) goto select_end; 423346ec5b63Sdrh if( pWInfo->nOBSat==pGroupBy->nExpr ){ 423413449892Sdrh /* The optimizer is able to deliver rows in group by order so 4235b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 423613449892Sdrh ** cancelled later because we still need to use the pKeyInfo 423713449892Sdrh */ 423813449892Sdrh groupBySort = 0; 423913449892Sdrh }else{ 424013449892Sdrh /* Rows are coming out in undetermined order. We have to push 424113449892Sdrh ** each row into a sorting index, terminate the first loop, 424213449892Sdrh ** then loop over the sorting index in order to get the output 424313449892Sdrh ** in sorted order 424413449892Sdrh */ 4245892d3179Sdrh int regBase; 4246892d3179Sdrh int regRecord; 4247892d3179Sdrh int nCol; 4248892d3179Sdrh int nGroupBy; 4249892d3179Sdrh 42502ce22453Sdan explainTempTable(pParse, 4251e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 4252e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 42532ce22453Sdan 425413449892Sdrh groupBySort = 1; 4255892d3179Sdrh nGroupBy = pGroupBy->nExpr; 4256892d3179Sdrh nCol = nGroupBy + 1; 4257892d3179Sdrh j = nGroupBy+1; 425813449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 4259892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 4260892d3179Sdrh nCol++; 426113449892Sdrh j++; 426213449892Sdrh } 4263892d3179Sdrh } 4264892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 4265ceea3321Sdrh sqlite3ExprCacheClear(pParse); 4266191b54cbSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); 4267892d3179Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); 4268892d3179Sdrh j = nGroupBy+1; 4269892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 4270892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 4271892d3179Sdrh if( pCol->iSorterColumn>=j ){ 4272e55cbd72Sdrh int r1 = j + regBase; 42736a012f04Sdrh int r2; 4274701bb3b4Sdrh 42756a012f04Sdrh r2 = sqlite3ExprCodeGetColumn(pParse, 4276a748fdccSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0); 42776a012f04Sdrh if( r1!=r2 ){ 42786a012f04Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); 42796a012f04Sdrh } 42806a012f04Sdrh j++; 4281892d3179Sdrh } 4282892d3179Sdrh } 4283892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 42841db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 42851c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 4286892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 4287892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 428813449892Sdrh sqlite3WhereEnd(pWInfo); 42895134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 42901c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 42911c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 42921c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 4293d4e70ebdSdrh VdbeComment((v, "GROUP BY sort")); 429413449892Sdrh sAggInfo.useSortingIdx = 1; 4295ceea3321Sdrh sqlite3ExprCacheClear(pParse); 429613449892Sdrh } 429713449892Sdrh 429813449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 429913449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 430013449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 430113449892Sdrh ** from the previous row currently stored in a0, a1, a2... 430213449892Sdrh */ 430313449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 4304ceea3321Sdrh sqlite3ExprCacheClear(pParse); 43051c9d835dSdrh if( groupBySort ){ 43061c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut); 43071c9d835dSdrh } 430813449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 430913449892Sdrh if( groupBySort ){ 43101c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 43111c9d835dSdrh if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); 431213449892Sdrh }else{ 431313449892Sdrh sAggInfo.directMode = 1; 43142dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 431513449892Sdrh } 431613449892Sdrh } 431716ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 4318b21e7c70Sdrh (char*)pKeyInfo, P4_KEYINFO); 431916ee60ffSdrh j1 = sqlite3VdbeCurrentAddr(v); 432016ee60ffSdrh sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); 432113449892Sdrh 432213449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 4323e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 432413449892Sdrh ** block. If there were no changes, this block is skipped. 432513449892Sdrh ** 432613449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 432713449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 432813449892Sdrh ** and resets the aggregate accumulator registers in preparation 432913449892Sdrh ** for the next GROUP BY batch. 433013449892Sdrh */ 4331b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 43322eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 4333d4e70ebdSdrh VdbeComment((v, "output one row")); 43343c84ddffSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); 4335d4e70ebdSdrh VdbeComment((v, "check abort flag")); 43362eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 4337d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 433813449892Sdrh 433913449892Sdrh /* Update the aggregate accumulators based on the content of 434013449892Sdrh ** the current row 434113449892Sdrh */ 434216ee60ffSdrh sqlite3VdbeJumpHere(v, j1); 434313449892Sdrh updateAccumulator(pParse, &sAggInfo); 43444c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 4345d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 434613449892Sdrh 434713449892Sdrh /* End of the loop 434813449892Sdrh */ 434913449892Sdrh if( groupBySort ){ 43501c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 435113449892Sdrh }else{ 435213449892Sdrh sqlite3WhereEnd(pWInfo); 435348f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 435413449892Sdrh } 435513449892Sdrh 435613449892Sdrh /* Output the final row of result 435713449892Sdrh */ 43582eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 4359d4e70ebdSdrh VdbeComment((v, "output final row")); 436013449892Sdrh 4361d176611bSdrh /* Jump over the subroutines 4362d176611bSdrh */ 4363d176611bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd); 4364d176611bSdrh 4365d176611bSdrh /* Generate a subroutine that outputs a single row of the result 4366d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 4367d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 4368d176611bSdrh ** the processing calls for the query to abort, this subroutine 4369d176611bSdrh ** increments the iAbortFlag memory location before returning in 4370d176611bSdrh ** order to signal the caller to abort. 4371d176611bSdrh */ 4372d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 4373d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 4374d176611bSdrh VdbeComment((v, "set abort flag")); 4375d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4376d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 4377d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 4378d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 4379d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 4380d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4381d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 4382d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 4383d176611bSdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 4384e8e4af76Sdrh &sDistinct, pDest, 4385d176611bSdrh addrOutputRow+1, addrSetAbort); 4386d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 4387d176611bSdrh VdbeComment((v, "end groupby result generator")); 4388d176611bSdrh 4389d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 4390d176611bSdrh */ 4391d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 4392d176611bSdrh resetAccumulator(pParse, &sAggInfo); 4393d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 4394d176611bSdrh 439543152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 439613449892Sdrh else { 4397dba0137eSdanielk1977 ExprList *pDel = 0; 4398a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 4399a5533162Sdanielk1977 Table *pTab; 4400a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 4401a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 4402a5533162Sdanielk1977 ** the SQL statement is of the form: 4403a5533162Sdanielk1977 ** 4404a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 4405a5533162Sdanielk1977 ** 4406a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 4407a5533162Sdanielk1977 ** 4408a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 4409a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 4410a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 4411a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 4412a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 4413a5533162Sdanielk1977 */ 4414a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 4415a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 4416a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 4417a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 4418a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 4419a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 4420a9d1ccb9Sdanielk1977 4421a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 4422a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 4423a5533162Sdanielk1977 4424a5533162Sdanielk1977 /* Search for the index that has the least amount of columns. If 4425a5533162Sdanielk1977 ** there is such an index, and it has less columns than the table 4426a5533162Sdanielk1977 ** does, then we can assume that it consumes less space on disk and 4427a5533162Sdanielk1977 ** will therefore be cheaper to scan to determine the query result. 4428a5533162Sdanielk1977 ** In this case set iRoot to the root page number of the index b-tree 4429a5533162Sdanielk1977 ** and pKeyInfo to the KeyInfo structure required to navigate the 4430a5533162Sdanielk1977 ** index. 4431a5533162Sdanielk1977 ** 44323e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 44333e9548b3Sdrh ** 4434a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 4435a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 4436a5533162Sdanielk1977 */ 4437a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 44383e9548b3Sdrh if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){ 4439a5533162Sdanielk1977 pBest = pIdx; 4440a5533162Sdanielk1977 } 4441a5533162Sdanielk1977 } 4442a5533162Sdanielk1977 if( pBest && pBest->nColumn<pTab->nCol ){ 4443a5533162Sdanielk1977 iRoot = pBest->tnum; 4444a5533162Sdanielk1977 pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest); 4445a5533162Sdanielk1977 } 4446a5533162Sdanielk1977 4447a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 4448a5533162Sdanielk1977 sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb); 4449a5533162Sdanielk1977 if( pKeyInfo ){ 4450a5533162Sdanielk1977 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF); 4451a5533162Sdanielk1977 } 4452a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 4453a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 4454ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 4455a5533162Sdanielk1977 }else 4456a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 4457a5533162Sdanielk1977 { 4458738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 4459738bdcfbSdanielk1977 ** 4460738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 4461738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 4462738bdcfbSdanielk1977 ** 4463738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 4464738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 4465738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 4466738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 4467738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 4468738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 4469738bdcfbSdanielk1977 ** value of x, the only row required). 4470738bdcfbSdanielk1977 ** 4471738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 4472738bdcfbSdanielk1977 ** modify behaviour as follows: 4473738bdcfbSdanielk1977 ** 4474738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 4475738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 4476738bdcfbSdanielk1977 ** for x. 4477738bdcfbSdanielk1977 ** 4478738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 4479738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 4480738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 4481738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 4482738bdcfbSdanielk1977 */ 4483a5533162Sdanielk1977 ExprList *pMinMax = 0; 4484a5533162Sdanielk1977 u8 flag = minMaxQuery(p); 4485a9d1ccb9Sdanielk1977 if( flag ){ 44866ab3a2ecSdanielk1977 assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) ); 448746ec5b63Sdrh assert( p->pEList->a[0].pExpr->x.pList->nExpr==1 ); 44886ab3a2ecSdanielk1977 pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0); 44896ab3a2ecSdanielk1977 pDel = pMinMax; 44900e359b30Sdrh if( pMinMax && !db->mallocFailed ){ 4491ea678832Sdrh pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; 4492a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 4493a9d1ccb9Sdanielk1977 } 44941013c932Sdrh } 4495a9d1ccb9Sdanielk1977 449613449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 449713449892Sdrh ** processing is much simpler since there is only a single row 449813449892Sdrh ** of output. 449913449892Sdrh */ 450013449892Sdrh resetAccumulator(pParse, &sAggInfo); 450146ec5b63Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0); 4502dba0137eSdanielk1977 if( pWInfo==0 ){ 4503633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 4504dba0137eSdanielk1977 goto select_end; 4505dba0137eSdanielk1977 } 450613449892Sdrh updateAccumulator(pParse, &sAggInfo); 450746c35f9bSdrh assert( pMinMax==0 || pMinMax->nExpr==1 ); 450846ec5b63Sdrh if( pWInfo->nOBSat>0 ){ 4509a9d1ccb9Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); 4510a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 4511a5533162Sdanielk1977 (flag==WHERE_ORDERBY_MIN?"min":"max"))); 4512a9d1ccb9Sdanielk1977 } 451313449892Sdrh sqlite3WhereEnd(pWInfo); 451413449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 45157a895a80Sdanielk1977 } 45167a895a80Sdanielk1977 451713449892Sdrh pOrderBy = 0; 451835573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 4519e8e4af76Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0, 4520a9671a22Sdrh pDest, addrEnd, addrEnd); 4521633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 452213449892Sdrh } 452313449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 452413449892Sdrh 452513449892Sdrh } /* endif aggregate query */ 45262282792aSdrh 4527e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 45282ce22453Sdan explainTempTable(pParse, "DISTINCT"); 45292ce22453Sdan } 45302ce22453Sdan 4531cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 4532cce7d176Sdrh ** and send them to the callback one by one. 4533cce7d176Sdrh */ 4534cce7d176Sdrh if( pOrderBy ){ 45352ce22453Sdan explainTempTable(pParse, "ORDER BY"); 45366c8c8ce0Sdanielk1977 generateSortTail(pParse, p, v, pEList->nExpr, pDest); 4537cce7d176Sdrh } 45386a535340Sdrh 4539ec7429aeSdrh /* Jump here to skip this query 4540ec7429aeSdrh */ 4541ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 4542ec7429aeSdrh 45431d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 45441d83f052Sdrh ** to indicate no errors. 45451d83f052Sdrh */ 45461d83f052Sdrh rc = 0; 45471d83f052Sdrh 45481d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 45491d83f052Sdrh ** successful coding of the SELECT. 45501d83f052Sdrh */ 45511d83f052Sdrh select_end: 455217c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 4553955de52cSdanielk1977 45547d10d5a6Sdrh /* Identify column names if results of the SELECT are to be output. 4555955de52cSdanielk1977 */ 45567d10d5a6Sdrh if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ 4557955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 4558955de52cSdanielk1977 } 4559955de52cSdanielk1977 4560633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 4561633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 45621d83f052Sdrh return rc; 4563cce7d176Sdrh } 4564485f0039Sdrh 4565678a9aa7Sdrh #if defined(SQLITE_ENABLE_TREE_EXPLAIN) 4566485f0039Sdrh /* 45677e02e5e6Sdrh ** Generate a human-readable description of a the Select object. 4568485f0039Sdrh */ 4569a84203a0Sdrh static void explainOneSelect(Vdbe *pVdbe, Select *p){ 45707e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "SELECT "); 45714e2a9c32Sdrh if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ 45724e2a9c32Sdrh if( p->selFlags & SF_Distinct ){ 45734e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, "DISTINCT "); 4574485f0039Sdrh } 45754e2a9c32Sdrh if( p->selFlags & SF_Aggregate ){ 45764e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, "agg_flag "); 4577485f0039Sdrh } 45784e2a9c32Sdrh sqlite3ExplainNL(pVdbe); 45794e2a9c32Sdrh sqlite3ExplainPrintf(pVdbe, " "); 4580485f0039Sdrh } 45817e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pEList); 45827e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 45837e02e5e6Sdrh if( p->pSrc && p->pSrc->nSrc ){ 4584485f0039Sdrh int i; 45857e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "FROM "); 45867e02e5e6Sdrh sqlite3ExplainPush(pVdbe); 4587485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 4588485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 458904b8342bSdrh sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor); 4590485f0039Sdrh if( pItem->pSelect ){ 45917e02e5e6Sdrh sqlite3ExplainSelect(pVdbe, pItem->pSelect); 4592485f0039Sdrh if( pItem->pTab ){ 459304b8342bSdrh sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName); 459404b8342bSdrh } 4595485f0039Sdrh }else if( pItem->zName ){ 45967e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName); 4597485f0039Sdrh } 4598485f0039Sdrh if( pItem->zAlias ){ 459904b8342bSdrh sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias); 4600485f0039Sdrh } 4601a84203a0Sdrh if( pItem->jointype & JT_LEFT ){ 4602a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN"); 4603485f0039Sdrh } 46047e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4605485f0039Sdrh } 46067e02e5e6Sdrh sqlite3ExplainPop(pVdbe); 4607485f0039Sdrh } 4608485f0039Sdrh if( p->pWhere ){ 46097e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "WHERE "); 46107e02e5e6Sdrh sqlite3ExplainExpr(pVdbe, p->pWhere); 46117e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4612485f0039Sdrh } 4613485f0039Sdrh if( p->pGroupBy ){ 46147e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "GROUPBY "); 46157e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pGroupBy); 46167e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4617485f0039Sdrh } 4618485f0039Sdrh if( p->pHaving ){ 46197e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "HAVING "); 46207e02e5e6Sdrh sqlite3ExplainExpr(pVdbe, p->pHaving); 46217e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4622485f0039Sdrh } 4623485f0039Sdrh if( p->pOrderBy ){ 46247e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "ORDERBY "); 46257e02e5e6Sdrh sqlite3ExplainExprList(pVdbe, p->pOrderBy); 46267e02e5e6Sdrh sqlite3ExplainNL(pVdbe); 4627485f0039Sdrh } 4628a84203a0Sdrh if( p->pLimit ){ 4629a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "LIMIT "); 4630a84203a0Sdrh sqlite3ExplainExpr(pVdbe, p->pLimit); 4631a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4632a84203a0Sdrh } 4633a84203a0Sdrh if( p->pOffset ){ 4634a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "OFFSET "); 4635a84203a0Sdrh sqlite3ExplainExpr(pVdbe, p->pOffset); 4636a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4637485f0039Sdrh } 4638485f0039Sdrh } 4639a84203a0Sdrh void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){ 4640a84203a0Sdrh if( p==0 ){ 4641a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "(null-select)"); 4642a84203a0Sdrh return; 4643a84203a0Sdrh } 4644a84203a0Sdrh while( p->pPrior ) p = p->pPrior; 4645a84203a0Sdrh sqlite3ExplainPush(pVdbe); 4646a84203a0Sdrh while( p ){ 4647a84203a0Sdrh explainOneSelect(pVdbe, p); 4648a84203a0Sdrh p = p->pNext; 4649a84203a0Sdrh if( p==0 ) break; 4650a84203a0Sdrh sqlite3ExplainNL(pVdbe); 4651a84203a0Sdrh sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op)); 4652a84203a0Sdrh } 46537e02e5e6Sdrh sqlite3ExplainPrintf(pVdbe, "END"); 4654a84203a0Sdrh sqlite3ExplainPop(pVdbe); 4655485f0039Sdrh } 46567e02e5e6Sdrh 4657485f0039Sdrh /* End of the structure debug printing code 4658485f0039Sdrh *****************************************************************************/ 465914a55b71Smistachkin #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */ 4660