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 17079a3072Sdrh /* 18abd4c723Sdrh ** Trace output macros 19abd4c723Sdrh */ 20abd4c723Sdrh #if SELECTTRACE_ENABLED 21abd4c723Sdrh /***/ int sqlite3SelectTrace = 0; 22eb9b884cSdrh # define SELECTTRACE(K,P,S,X) \ 23eb9b884cSdrh if(sqlite3SelectTrace&(K)) \ 24eb9b884cSdrh sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\ 25eb9b884cSdrh sqlite3DebugPrintf X 26abd4c723Sdrh #else 27eb9b884cSdrh # define SELECTTRACE(K,P,S,X) 28abd4c723Sdrh #endif 29abd4c723Sdrh 30abd4c723Sdrh 31abd4c723Sdrh /* 32079a3072Sdrh ** An instance of the following object is used to record information about 33079a3072Sdrh ** how to process the DISTINCT keyword, to simplify passing that information 34079a3072Sdrh ** into the selectInnerLoop() routine. 35079a3072Sdrh */ 36079a3072Sdrh typedef struct DistinctCtx DistinctCtx; 37079a3072Sdrh struct DistinctCtx { 38079a3072Sdrh u8 isTnct; /* True if the DISTINCT keyword is present */ 39079a3072Sdrh u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ 40079a3072Sdrh int tabTnct; /* Ephemeral table used for DISTINCT processing */ 41079a3072Sdrh int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ 42079a3072Sdrh }; 43079a3072Sdrh 44079a3072Sdrh /* 45079a3072Sdrh ** An instance of the following object is used to record information about 46079a3072Sdrh ** the ORDER BY (or GROUP BY) clause of query is being coded. 47079a3072Sdrh */ 48079a3072Sdrh typedef struct SortCtx SortCtx; 49079a3072Sdrh struct SortCtx { 50079a3072Sdrh ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ 51079a3072Sdrh int nOBSat; /* Number of ORDER BY terms satisfied by indices */ 52079a3072Sdrh int iECursor; /* Cursor number for the sorter */ 53079a3072Sdrh int regReturn; /* Register holding block-output return address */ 54079a3072Sdrh int labelBkOut; /* Start label for the block-output subroutine */ 55079a3072Sdrh int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ 56079a3072Sdrh u8 sortFlags; /* Zero or more SORTFLAG_* bits */ 57079a3072Sdrh }; 58079a3072Sdrh #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ 59315555caSdrh 60cce7d176Sdrh /* 61b87fbed5Sdrh ** Delete all the content of a Select structure. Deallocate the structure 62b87fbed5Sdrh ** itself only if bFree is true. 63eda639e1Sdrh */ 64b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){ 65b87fbed5Sdrh while( p ){ 66b87fbed5Sdrh Select *pPrior = p->pPrior; 67633e6d57Sdrh sqlite3ExprListDelete(db, p->pEList); 68633e6d57Sdrh sqlite3SrcListDelete(db, p->pSrc); 69633e6d57Sdrh sqlite3ExprDelete(db, p->pWhere); 70633e6d57Sdrh sqlite3ExprListDelete(db, p->pGroupBy); 71633e6d57Sdrh sqlite3ExprDelete(db, p->pHaving); 72633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 73633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 74633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 754e9119d9Sdan sqlite3WithDelete(db, p->pWith); 76b87fbed5Sdrh if( bFree ) sqlite3DbFree(db, p); 77b87fbed5Sdrh p = pPrior; 78b87fbed5Sdrh bFree = 1; 79b87fbed5Sdrh } 80eda639e1Sdrh } 81eda639e1Sdrh 821013c932Sdrh /* 831013c932Sdrh ** Initialize a SelectDest structure. 841013c932Sdrh */ 851013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 86ea678832Sdrh pDest->eDest = (u8)eDest; 872b596da8Sdrh pDest->iSDParm = iParm; 882b596da8Sdrh pDest->affSdst = 0; 892b596da8Sdrh pDest->iSdst = 0; 902b596da8Sdrh pDest->nSdst = 0; 911013c932Sdrh } 921013c932Sdrh 93eda639e1Sdrh 94eda639e1Sdrh /* 959bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 969bb61fe7Sdrh ** structure. 97cce7d176Sdrh */ 984adee20fSdanielk1977 Select *sqlite3SelectNew( 9917435752Sdrh Parse *pParse, /* Parsing context */ 100daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 101ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 102daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 103daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 104daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 105daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 106832ee3d4Sdrh u16 selFlags, /* Flag parameters, such as SF_Distinct */ 107a2dc3b1aSdanielk1977 Expr *pLimit, /* LIMIT value. NULL means not used */ 108a2dc3b1aSdanielk1977 Expr *pOffset /* OFFSET value. NULL means no offset */ 1099bb61fe7Sdrh ){ 1109bb61fe7Sdrh Select *pNew; 111eda639e1Sdrh Select standin; 11217435752Sdrh sqlite3 *db = pParse->db; 11317435752Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 114d72a276eSdrh assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */ 115daffd0e5Sdrh if( pNew==0 ){ 116338ec3e1Sdrh assert( db->mallocFailed ); 117eda639e1Sdrh pNew = &standin; 118eda639e1Sdrh memset(pNew, 0, sizeof(*pNew)); 119eda639e1Sdrh } 120b733d037Sdrh if( pEList==0 ){ 121b7916a78Sdrh pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0)); 122b733d037Sdrh } 1239bb61fe7Sdrh pNew->pEList = pEList; 1247b113babSdrh if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc)); 1259bb61fe7Sdrh pNew->pSrc = pSrc; 1269bb61fe7Sdrh pNew->pWhere = pWhere; 1279bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 1289bb61fe7Sdrh pNew->pHaving = pHaving; 1299bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 130832ee3d4Sdrh pNew->selFlags = selFlags; 13182c3d636Sdrh pNew->op = TK_SELECT; 132a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 133a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 134373cc2ddSdrh assert( pOffset==0 || pLimit!=0 ); 135b9bb7c18Sdrh pNew->addrOpenEphm[0] = -1; 136b9bb7c18Sdrh pNew->addrOpenEphm[1] = -1; 1370a846f96Sdrh if( db->mallocFailed ) { 138b87fbed5Sdrh clearSelect(db, pNew, pNew!=&standin); 139eda639e1Sdrh pNew = 0; 140a464c234Sdrh }else{ 141a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 142daffd0e5Sdrh } 143338ec3e1Sdrh assert( pNew!=&standin ); 1449bb61fe7Sdrh return pNew; 1459bb61fe7Sdrh } 1469bb61fe7Sdrh 147eb9b884cSdrh #if SELECTTRACE_ENABLED 148eb9b884cSdrh /* 149eb9b884cSdrh ** Set the name of a Select object 150eb9b884cSdrh */ 151eb9b884cSdrh void sqlite3SelectSetName(Select *p, const char *zName){ 152eb9b884cSdrh if( p && zName ){ 153eb9b884cSdrh sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName); 154eb9b884cSdrh } 155eb9b884cSdrh } 156eb9b884cSdrh #endif 157eb9b884cSdrh 158eb9b884cSdrh 1599bb61fe7Sdrh /* 160eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 161eda639e1Sdrh */ 162633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 163b87fbed5Sdrh clearSelect(db, p, 1); 164eda639e1Sdrh } 165eda639e1Sdrh 166eda639e1Sdrh /* 167d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound. 168d227a291Sdrh */ 169d227a291Sdrh static Select *findRightmost(Select *p){ 170d227a291Sdrh while( p->pNext ) p = p->pNext; 171d227a291Sdrh return p; 172d227a291Sdrh } 173d227a291Sdrh 174d227a291Sdrh /* 175f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the 17601f3f253Sdrh ** type of join. Return an integer constant that expresses that type 17701f3f253Sdrh ** in terms of the following bit values: 17801f3f253Sdrh ** 17901f3f253Sdrh ** JT_INNER 1803dec223cSdrh ** JT_CROSS 18101f3f253Sdrh ** JT_OUTER 18201f3f253Sdrh ** JT_NATURAL 18301f3f253Sdrh ** JT_LEFT 18401f3f253Sdrh ** JT_RIGHT 18501f3f253Sdrh ** 18601f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 18701f3f253Sdrh ** 18801f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 18901f3f253Sdrh ** a join type, but put an error in the pParse structure. 19001f3f253Sdrh */ 1914adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 19201f3f253Sdrh int jointype = 0; 19301f3f253Sdrh Token *apAll[3]; 19401f3f253Sdrh Token *p; 195373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 196373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 1975719628aSdrh static const struct { 198373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 199373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 200373cc2ddSdrh u8 code; /* Join type mask */ 201373cc2ddSdrh } aKeyword[] = { 202373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 203373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 204373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 205373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 206373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 207373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 208373cc2ddSdrh /* cross */ { 28, 5, JT_INNER|JT_CROSS }, 20901f3f253Sdrh }; 21001f3f253Sdrh int i, j; 21101f3f253Sdrh apAll[0] = pA; 21201f3f253Sdrh apAll[1] = pB; 21301f3f253Sdrh apAll[2] = pC; 214195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 21501f3f253Sdrh p = apAll[i]; 216373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 217373cc2ddSdrh if( p->n==aKeyword[j].nChar 218373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 219373cc2ddSdrh jointype |= aKeyword[j].code; 22001f3f253Sdrh break; 22101f3f253Sdrh } 22201f3f253Sdrh } 223373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 224373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 22501f3f253Sdrh jointype |= JT_ERROR; 22601f3f253Sdrh break; 22701f3f253Sdrh } 22801f3f253Sdrh } 229ad2d8307Sdrh if( 230ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 231195e6967Sdrh (jointype & JT_ERROR)!=0 232ad2d8307Sdrh ){ 233a9671a22Sdrh const char *zSp = " "; 234a9671a22Sdrh assert( pB!=0 ); 235a9671a22Sdrh if( pC==0 ){ zSp++; } 236ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 237a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 23801f3f253Sdrh jointype = JT_INNER; 239373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 240373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 2414adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 242da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 243195e6967Sdrh jointype = JT_INNER; 24401f3f253Sdrh } 24501f3f253Sdrh return jointype; 24601f3f253Sdrh } 24701f3f253Sdrh 24801f3f253Sdrh /* 249ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 250ad2d8307Sdrh ** is not contained in the table. 251ad2d8307Sdrh */ 252ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 253ad2d8307Sdrh int i; 254ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 2554adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 256ad2d8307Sdrh } 257ad2d8307Sdrh return -1; 258ad2d8307Sdrh } 259ad2d8307Sdrh 260ad2d8307Sdrh /* 2612179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 2622179b434Sdrh ** table that has a column named zCol. 2632179b434Sdrh ** 2642179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 2652179b434Sdrh ** of the matching column and return TRUE. 2662179b434Sdrh ** 2672179b434Sdrh ** If not found, return FALSE. 2682179b434Sdrh */ 2692179b434Sdrh static int tableAndColumnIndex( 2702179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 2712179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 2722179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 2732179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 2742179b434Sdrh int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 2752179b434Sdrh ){ 2762179b434Sdrh int i; /* For looping over tables in pSrc */ 2772179b434Sdrh int iCol; /* Index of column matching zCol */ 2782179b434Sdrh 2792179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 2802179b434Sdrh for(i=0; i<N; i++){ 2812179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 2822179b434Sdrh if( iCol>=0 ){ 2832179b434Sdrh if( piTab ){ 2842179b434Sdrh *piTab = i; 2852179b434Sdrh *piCol = iCol; 2862179b434Sdrh } 2872179b434Sdrh return 1; 2882179b434Sdrh } 2892179b434Sdrh } 2902179b434Sdrh return 0; 2912179b434Sdrh } 2922179b434Sdrh 2932179b434Sdrh /* 294f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 295f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 296f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 297f7b0b0adSdan ** 298f7b0b0adSdan ** (tab1.col1 = tab2.col2) 299f7b0b0adSdan ** 300f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 301f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 302f7b0b0adSdan ** column iColRight of tab2. 303ad2d8307Sdrh */ 304ad2d8307Sdrh static void addWhereTerm( 30517435752Sdrh Parse *pParse, /* Parsing context */ 306f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 3072179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 308f7b0b0adSdan int iColLeft, /* Index of column in first table */ 3092179b434Sdrh int iRight, /* Index of second table in pSrc */ 310f7b0b0adSdan int iColRight, /* Index of column in second table */ 311f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 312f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 313ad2d8307Sdrh ){ 314f7b0b0adSdan sqlite3 *db = pParse->db; 315f7b0b0adSdan Expr *pE1; 316f7b0b0adSdan Expr *pE2; 317f7b0b0adSdan Expr *pEq; 318ad2d8307Sdrh 3192179b434Sdrh assert( iLeft<iRight ); 3202179b434Sdrh assert( pSrc->nSrc>iRight ); 3212179b434Sdrh assert( pSrc->a[iLeft].pTab ); 3222179b434Sdrh assert( pSrc->a[iRight].pTab ); 323f7b0b0adSdan 3242179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 3252179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 326f7b0b0adSdan 327f7b0b0adSdan pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0); 328f7b0b0adSdan if( pEq && isOuterJoin ){ 329f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 330c5cd1249Sdrh assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); 331ebb6a65dSdrh ExprSetVVAProperty(pEq, EP_NoReduce); 332f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 333030530deSdrh } 334f7b0b0adSdan *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); 335ad2d8307Sdrh } 336ad2d8307Sdrh 337ad2d8307Sdrh /* 3381f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 33922d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 34022d6a53aSdrh ** expression. 3411cc093c2Sdrh ** 342e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 3431cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 3441f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 3451f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 3461f16230bSdrh ** WHERE clause during join processing but we need to remember that they 3471f16230bSdrh ** originated in the ON or USING clause. 34822d6a53aSdrh ** 34922d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 35022d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 35122d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 35222d6a53aSdrh ** for cases like this: 35322d6a53aSdrh ** 35422d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 35522d6a53aSdrh ** 35622d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 35722d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 35822d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 35922d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 36022d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 36122d6a53aSdrh ** the output, which is incorrect. 3621cc093c2Sdrh */ 36322d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 3641cc093c2Sdrh while( p ){ 3651f16230bSdrh ExprSetProperty(p, EP_FromJoin); 366c5cd1249Sdrh assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 367ebb6a65dSdrh ExprSetVVAProperty(p, EP_NoReduce); 368cf697396Sshane p->iRightJoinTable = (i16)iTable; 36922d6a53aSdrh setJoinExpr(p->pLeft, iTable); 3701cc093c2Sdrh p = p->pRight; 3711cc093c2Sdrh } 3721cc093c2Sdrh } 3731cc093c2Sdrh 3741cc093c2Sdrh /* 375ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 376ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 377ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 378ad2d8307Sdrh ** 37991bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 38091bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 38191bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 38291bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 38391bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 38491bb0eedSdrh ** also attached to the left entry. 38591bb0eedSdrh ** 386ad2d8307Sdrh ** This routine returns the number of errors encountered. 387ad2d8307Sdrh */ 388ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 38991bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 39091bb0eedSdrh int i, j; /* Loop counters */ 39191bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 39291bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 393ad2d8307Sdrh 39491bb0eedSdrh pSrc = p->pSrc; 39591bb0eedSdrh pLeft = &pSrc->a[0]; 39691bb0eedSdrh pRight = &pLeft[1]; 39791bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 39891bb0eedSdrh Table *pLeftTab = pLeft->pTab; 39991bb0eedSdrh Table *pRightTab = pRight->pTab; 400ad27e761Sdrh int isOuter; 40191bb0eedSdrh 4021c767f0dSdrh if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; 403ad27e761Sdrh isOuter = (pRight->jointype & JT_OUTER)!=0; 404ad2d8307Sdrh 405ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 406ad2d8307Sdrh ** every column that the two tables have in common. 407ad2d8307Sdrh */ 40861dfc31dSdrh if( pRight->jointype & JT_NATURAL ){ 40961dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 4104adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 411ad2d8307Sdrh "an ON or USING clause", 0); 412ad2d8307Sdrh return 1; 413ad2d8307Sdrh } 4142179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 4152179b434Sdrh char *zName; /* Name of column in the right table */ 4162179b434Sdrh int iLeft; /* Matching left table */ 4172179b434Sdrh int iLeftCol; /* Matching column in the left table */ 4182179b434Sdrh 4192179b434Sdrh zName = pRightTab->aCol[j].zName; 4202179b434Sdrh if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ 4212179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 4222179b434Sdrh isOuter, &p->pWhere); 423ad2d8307Sdrh } 424ad2d8307Sdrh } 425ad2d8307Sdrh } 426ad2d8307Sdrh 427ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 428ad2d8307Sdrh */ 42961dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 4304adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 431da93d238Sdrh "clauses in the same join"); 432ad2d8307Sdrh return 1; 433ad2d8307Sdrh } 434ad2d8307Sdrh 435ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 43691bb0eedSdrh ** an AND operator. 437ad2d8307Sdrh */ 43861dfc31dSdrh if( pRight->pOn ){ 439ad27e761Sdrh if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 44017435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 44161dfc31dSdrh pRight->pOn = 0; 442ad2d8307Sdrh } 443ad2d8307Sdrh 444ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 445ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 446ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 447ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 448ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 449ad2d8307Sdrh ** not contained in both tables to be joined. 450ad2d8307Sdrh */ 45161dfc31dSdrh if( pRight->pUsing ){ 45261dfc31dSdrh IdList *pList = pRight->pUsing; 453ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 4542179b434Sdrh char *zName; /* Name of the term in the USING clause */ 4552179b434Sdrh int iLeft; /* Table on the left with matching column name */ 4562179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 4572179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 4582179b434Sdrh 4592179b434Sdrh zName = pList->a[j].zName; 4602179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 4612179b434Sdrh if( iRightCol<0 4622179b434Sdrh || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) 4632179b434Sdrh ){ 4644adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 46591bb0eedSdrh "not present in both tables", zName); 466ad2d8307Sdrh return 1; 467ad2d8307Sdrh } 4682179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 4692179b434Sdrh isOuter, &p->pWhere); 470ad2d8307Sdrh } 471ad2d8307Sdrh } 472ad2d8307Sdrh } 473ad2d8307Sdrh return 0; 474ad2d8307Sdrh } 475ad2d8307Sdrh 476079a3072Sdrh /* Forward reference */ 477079a3072Sdrh static KeyInfo *keyInfoFromExprList( 478079a3072Sdrh Parse *pParse, /* Parsing context */ 479079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 480079a3072Sdrh int iStart, /* Begin with this column of pList */ 481079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 482079a3072Sdrh ); 483079a3072Sdrh 484ad2d8307Sdrh /* 485f45f2326Sdrh ** Generate code that will push the record in registers regData 486f45f2326Sdrh ** through regData+nData-1 onto the sorter. 487c926afbcSdrh */ 488d59ba6ceSdrh static void pushOntoSorter( 489d59ba6ceSdrh Parse *pParse, /* Parser context */ 490079a3072Sdrh SortCtx *pSort, /* Information about the ORDER BY clause */ 491b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 492f45f2326Sdrh int regData, /* First register holding data to be sorted */ 493fd0a2f97Sdrh int nData, /* Number of elements in the data array */ 494fd0a2f97Sdrh int nPrefixReg /* No. of reg prior to regData available for use */ 495d59ba6ceSdrh ){ 496f45f2326Sdrh Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 49778d58432Sdan int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 498f45f2326Sdrh int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 49978d58432Sdan int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 500fd0a2f97Sdrh int regBase; /* Regs for sorter record */ 501fb0d6e56Sdrh int regRecord = ++pParse->nMem; /* Assembled sorter record */ 50278d58432Sdan int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 503f45f2326Sdrh int op; /* Opcode to add sorter record to sorter */ 504f45f2326Sdrh 50578d58432Sdan assert( bSeq==0 || bSeq==1 ); 506fd0a2f97Sdrh if( nPrefixReg ){ 50778d58432Sdan assert( nPrefixReg==nExpr+bSeq ); 50878d58432Sdan regBase = regData - nExpr - bSeq; 509fd0a2f97Sdrh }else{ 510fb0d6e56Sdrh regBase = pParse->nMem + 1; 511fb0d6e56Sdrh pParse->nMem += nBase; 512fd0a2f97Sdrh } 51370f624c3Sdrh sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP); 51478d58432Sdan if( bSeq ){ 515079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 516fd0a2f97Sdrh } 51778d58432Sdan if( nPrefixReg==0 ){ 518236241aeSdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 51978d58432Sdan } 52078d58432Sdan 521f45f2326Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); 522079a3072Sdrh if( nOBSat>0 ){ 523079a3072Sdrh int regPrevKey; /* The first nOBSat columns of the previous row */ 524079a3072Sdrh int addrFirst; /* Address of the OP_IfNot opcode */ 525079a3072Sdrh int addrJmp; /* Address of the OP_Jump opcode */ 526079a3072Sdrh VdbeOp *pOp; /* Opcode that opens the sorter */ 527079a3072Sdrh int nKey; /* Number of sorting key columns, including OP_Sequence */ 528dbfca2b7Sdrh KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 529079a3072Sdrh 53026d7e7c6Sdrh regPrevKey = pParse->nMem+1; 53126d7e7c6Sdrh pParse->nMem += pSort->nOBSat; 53278d58432Sdan nKey = nExpr - pSort->nOBSat + bSeq; 53378d58432Sdan if( bSeq ){ 53478d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 53578d58432Sdan }else{ 53678d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 53778d58432Sdan } 53878d58432Sdan VdbeCoverage(v); 53926d7e7c6Sdrh sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 540079a3072Sdrh pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 54159b8f2e1Sdrh if( pParse->db->mallocFailed ) return; 542fb0d6e56Sdrh pOp->p2 = nKey + nData; 543dbfca2b7Sdrh pKI = pOp->p4.pKeyInfo; 544dbfca2b7Sdrh memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */ 545dbfca2b7Sdrh sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 546*fe201effSdrh testcase( pKI->nXField>2 ); 547*fe201effSdrh pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 548*fe201effSdrh pKI->nXField-1); 549079a3072Sdrh addrJmp = sqlite3VdbeCurrentAddr(v); 550079a3072Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 551079a3072Sdrh pSort->labelBkOut = sqlite3VdbeMakeLabel(v); 552079a3072Sdrh pSort->regReturn = ++pParse->nMem; 553079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 55465ea12cbSdrh sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 555079a3072Sdrh sqlite3VdbeJumpHere(v, addrFirst); 556236241aeSdrh sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 557079a3072Sdrh sqlite3VdbeJumpHere(v, addrJmp); 558079a3072Sdrh } 559079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 560c6aff30cSdrh op = OP_SorterInsert; 561c6aff30cSdrh }else{ 562c6aff30cSdrh op = OP_IdxInsert; 563c6aff30cSdrh } 564079a3072Sdrh sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord); 56592b01d53Sdrh if( pSelect->iLimit ){ 56615007a99Sdrh int addr1, addr2; 567b7654111Sdrh int iLimit; 5680acb7e48Sdrh if( pSelect->iOffset ){ 569b7654111Sdrh iLimit = pSelect->iOffset+1; 570b7654111Sdrh }else{ 571b7654111Sdrh iLimit = pSelect->iLimit; 572b7654111Sdrh } 573688852abSdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v); 574b7654111Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); 5753c84ddffSdrh addr2 = sqlite3VdbeAddOp0(v, OP_Goto); 576d59ba6ceSdrh sqlite3VdbeJumpHere(v, addr1); 577079a3072Sdrh sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); 578079a3072Sdrh sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); 57915007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 580d59ba6ceSdrh } 581c926afbcSdrh } 582c926afbcSdrh 583c926afbcSdrh /* 584ec7429aeSdrh ** Add code to implement the OFFSET 585ea48eb2eSdrh */ 586ec7429aeSdrh static void codeOffset( 587bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 588aa9ce707Sdrh int iOffset, /* Register holding the offset counter */ 589b7654111Sdrh int iContinue /* Jump here to skip the current record */ 590ea48eb2eSdrh ){ 591a22a75e5Sdrh if( iOffset>0 ){ 59215007a99Sdrh int addr; 5934336b0e6Sdrh addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v); 59466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); 595d4e70ebdSdrh VdbeComment((v, "skip OFFSET records")); 59615007a99Sdrh sqlite3VdbeJumpHere(v, addr); 597ea48eb2eSdrh } 598ea48eb2eSdrh } 599ea48eb2eSdrh 600ea48eb2eSdrh /* 60198757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 60298757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 603a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 604a2a49dc9Sdrh ** if the current N values are new. 605a2a49dc9Sdrh ** 606a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 607a2a49dc9Sdrh ** stack if the top N elements are not distinct. 608a2a49dc9Sdrh */ 609a2a49dc9Sdrh static void codeDistinct( 6102dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 611a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 612a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 613477df4b3Sdrh int N, /* Number of elements */ 614a2a49dc9Sdrh int iMem /* First element */ 615a2a49dc9Sdrh ){ 6162dcef11bSdrh Vdbe *v; 6172dcef11bSdrh int r1; 6182dcef11bSdrh 6192dcef11bSdrh v = pParse->pVdbe; 6202dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 621688852abSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); 6221db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 6232dcef11bSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); 6242dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 625a2a49dc9Sdrh } 626a2a49dc9Sdrh 627bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY 628a2a49dc9Sdrh /* 629e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression 630e305f43fSdrh ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 631bb7dd683Sdrh ** column. We do this in a subroutine because the error used to occur 632bb7dd683Sdrh ** in multiple places. (The error only occurs in one place now, but we 633bb7dd683Sdrh ** retain the subroutine to minimize code disruption.) 634e305f43fSdrh */ 6356c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError( 6366c8c8ce0Sdanielk1977 Parse *pParse, /* Parse context. */ 6376c8c8ce0Sdanielk1977 SelectDest *pDest, /* Destination of SELECT results */ 6386c8c8ce0Sdanielk1977 int nExpr /* Number of result columns returned by SELECT */ 6396c8c8ce0Sdanielk1977 ){ 6406c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 641e305f43fSdrh if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 642e305f43fSdrh sqlite3ErrorMsg(pParse, "only a single result allowed for " 643e305f43fSdrh "a SELECT that is part of an expression"); 644e305f43fSdrh return 1; 645e305f43fSdrh }else{ 646e305f43fSdrh return 0; 647e305f43fSdrh } 648e305f43fSdrh } 649bb7dd683Sdrh #endif 650c99130fdSdrh 651c99130fdSdrh /* 6522282792aSdrh ** This routine generates the code for the inside of the inner loop 6532282792aSdrh ** of a SELECT. 65482c3d636Sdrh ** 655340309fdSdrh ** If srcTab is negative, then the pEList expressions 656340309fdSdrh ** are evaluated in order to get the data for this row. If srcTab is 657340309fdSdrh ** zero or more, then data is pulled from srcTab and pEList is used only 658340309fdSdrh ** to get number columns and the datatype for each column. 6592282792aSdrh */ 660d2b3e23bSdrh static void selectInnerLoop( 6612282792aSdrh Parse *pParse, /* The parser context */ 662df199a25Sdrh Select *p, /* The complete select statement being coded */ 6632282792aSdrh ExprList *pEList, /* List of values being extracted */ 66482c3d636Sdrh int srcTab, /* Pull data from this table */ 665079a3072Sdrh SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ 666e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 6676c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 6682282792aSdrh int iContinue, /* Jump here to continue with next row */ 669a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 6702282792aSdrh ){ 6712282792aSdrh Vdbe *v = pParse->pVdbe; 672d847eaadSdrh int i; 673ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 674d847eaadSdrh int regResult; /* Start of memory holding result set */ 675d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 6762b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 677d847eaadSdrh int nResultCol; /* Number of result columns */ 678fd0a2f97Sdrh int nPrefixReg = 0; /* Number of extra registers before regResult */ 67938640e15Sdrh 6801c767f0dSdrh assert( v ); 68138640e15Sdrh assert( pEList!=0 ); 682e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 683079a3072Sdrh if( pSort && pSort->pOrderBy==0 ) pSort = 0; 684079a3072Sdrh if( pSort==0 && !hasDistinct ){ 685a22a75e5Sdrh assert( iContinue!=0 ); 686aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 687df199a25Sdrh } 688df199a25Sdrh 689967e8b73Sdrh /* Pull the requested columns. 6902282792aSdrh */ 691d847eaadSdrh nResultCol = pEList->nExpr; 69205a86c5cSdrh 6932b596da8Sdrh if( pDest->iSdst==0 ){ 694fd0a2f97Sdrh if( pSort ){ 69578d58432Sdan nPrefixReg = pSort->pOrderBy->nExpr; 69678d58432Sdan if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; 697fd0a2f97Sdrh pParse->nMem += nPrefixReg; 698fd0a2f97Sdrh } 6992b596da8Sdrh pDest->iSdst = pParse->nMem+1; 7000acb7e48Sdrh pParse->nMem += nResultCol; 70105a86c5cSdrh }else if( pDest->iSdst+nResultCol > pParse->nMem ){ 70205a86c5cSdrh /* This is an error condition that can result, for example, when a SELECT 70305a86c5cSdrh ** on the right-hand side of an INSERT contains more result columns than 70405a86c5cSdrh ** there are columns in the table on the left. The error will be caught 70505a86c5cSdrh ** and reported later. But we need to make sure enough memory is allocated 70605a86c5cSdrh ** to avoid other spurious errors in the meantime. */ 70705a86c5cSdrh pParse->nMem += nResultCol; 7081013c932Sdrh } 70905a86c5cSdrh pDest->nSdst = nResultCol; 7102b596da8Sdrh regResult = pDest->iSdst; 711340309fdSdrh if( srcTab>=0 ){ 712340309fdSdrh for(i=0; i<nResultCol; i++){ 713d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 714340309fdSdrh VdbeComment((v, "%s", pEList->a[i].zName)); 71582c3d636Sdrh } 7169ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 7179ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 7189ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 7199ed1dfa8Sdanielk1977 */ 720d1a01edaSdrh sqlite3ExprCodeExprList(pParse, pEList, regResult, 7216295524eSdrh (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0); 722a2a49dc9Sdrh } 7232282792aSdrh 724daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 725daffd0e5Sdrh ** and this row has been seen before, then do not make this row 726daffd0e5Sdrh ** part of the result. 7272282792aSdrh */ 728ea48eb2eSdrh if( hasDistinct ){ 729e8e4af76Sdrh switch( pDistinct->eTnctType ){ 730e8e4af76Sdrh case WHERE_DISTINCT_ORDERED: { 731e8e4af76Sdrh VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 732e8e4af76Sdrh int iJump; /* Jump destination */ 733e8e4af76Sdrh int regPrev; /* Previous row content */ 734e8e4af76Sdrh 735e8e4af76Sdrh /* Allocate space for the previous row */ 736e8e4af76Sdrh regPrev = pParse->nMem+1; 737340309fdSdrh pParse->nMem += nResultCol; 738e8e4af76Sdrh 739e8e4af76Sdrh /* Change the OP_OpenEphemeral coded earlier to an OP_Null 740e8e4af76Sdrh ** sets the MEM_Cleared bit on the first register of the 741e8e4af76Sdrh ** previous value. This will cause the OP_Ne below to always 742e8e4af76Sdrh ** fail on the first iteration of the loop even if the first 743e8e4af76Sdrh ** row is all NULLs. 744e8e4af76Sdrh */ 745e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 746e8e4af76Sdrh pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); 747e8e4af76Sdrh pOp->opcode = OP_Null; 748e8e4af76Sdrh pOp->p1 = 1; 749e8e4af76Sdrh pOp->p2 = regPrev; 750e8e4af76Sdrh 751340309fdSdrh iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; 752340309fdSdrh for(i=0; i<nResultCol; i++){ 753e8e4af76Sdrh CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr); 754340309fdSdrh if( i<nResultCol-1 ){ 755e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); 756688852abSdrh VdbeCoverage(v); 757e8e4af76Sdrh }else{ 758e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); 759688852abSdrh VdbeCoverage(v); 760e8e4af76Sdrh } 761e8e4af76Sdrh sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 762e8e4af76Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 763e8e4af76Sdrh } 764fcf2a775Sdrh assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); 765340309fdSdrh sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); 766e8e4af76Sdrh break; 767e8e4af76Sdrh } 768e8e4af76Sdrh 769e8e4af76Sdrh case WHERE_DISTINCT_UNIQUE: { 770e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 771e8e4af76Sdrh break; 772e8e4af76Sdrh } 773e8e4af76Sdrh 774e8e4af76Sdrh default: { 775e8e4af76Sdrh assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 776340309fdSdrh codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult); 777e8e4af76Sdrh break; 778e8e4af76Sdrh } 779e8e4af76Sdrh } 780079a3072Sdrh if( pSort==0 ){ 781aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 782ea48eb2eSdrh } 7832282792aSdrh } 78482c3d636Sdrh 785c926afbcSdrh switch( eDest ){ 78682c3d636Sdrh /* In this mode, write each query result to the key of the temporary 78782c3d636Sdrh ** table iParm. 7882282792aSdrh */ 78913449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 790c926afbcSdrh case SRT_Union: { 7919cbf3425Sdrh int r1; 7929cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 793340309fdSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); 7949cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 7959cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 796c926afbcSdrh break; 797c926afbcSdrh } 79882c3d636Sdrh 79982c3d636Sdrh /* Construct a record from the query result, but instead of 80082c3d636Sdrh ** saving that record, use it as a key to delete elements from 80182c3d636Sdrh ** the temporary table iParm. 80282c3d636Sdrh */ 803c926afbcSdrh case SRT_Except: { 804340309fdSdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); 805c926afbcSdrh break; 806c926afbcSdrh } 807781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 8085338a5f7Sdanielk1977 8095338a5f7Sdanielk1977 /* Store the result as data using a unique key. 8105338a5f7Sdanielk1977 */ 8118e1ee88cSdrh case SRT_Fifo: 8128e1ee88cSdrh case SRT_DistFifo: 8135338a5f7Sdanielk1977 case SRT_Table: 814b9bb7c18Sdrh case SRT_EphemTab: { 815fd0a2f97Sdrh int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 816373cc2ddSdrh testcase( eDest==SRT_Table ); 817373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 818fd0a2f97Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 8198ce7184bSdan #ifndef SQLITE_OMIT_CTE 8208e1ee88cSdrh if( eDest==SRT_DistFifo ){ 8218e1ee88cSdrh /* If the destination is DistFifo, then cursor (iParm+1) is open 8228ce7184bSdan ** on an ephemeral index. If the current row is already present 8238ce7184bSdan ** in the index, do not write it to the output. If not, add the 8248ce7184bSdan ** current row to the index and proceed with writing it to the 8258ce7184bSdan ** output table as well. */ 8268ce7184bSdan int addr = sqlite3VdbeCurrentAddr(v) + 4; 827688852abSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v); 8288ce7184bSdan sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1); 829079a3072Sdrh assert( pSort==0 ); 8308ce7184bSdan } 8318ce7184bSdan #endif 832079a3072Sdrh if( pSort ){ 833fd0a2f97Sdrh pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg); 8345338a5f7Sdanielk1977 }else{ 835b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 836b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 837b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 838b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 839b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 8405338a5f7Sdanielk1977 } 841fd0a2f97Sdrh sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 8425338a5f7Sdanielk1977 break; 8435338a5f7Sdanielk1977 } 8442282792aSdrh 84593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 8462282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 8472282792aSdrh ** then there should be a single item on the stack. Write this 8482282792aSdrh ** item into the set table with bogus data. 8492282792aSdrh */ 850c926afbcSdrh case SRT_Set: { 851340309fdSdrh assert( nResultCol==1 ); 852634d81deSdrh pDest->affSdst = 853634d81deSdrh sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst); 854079a3072Sdrh if( pSort ){ 855de941c60Sdrh /* At first glance you would think we could optimize out the 856de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 857de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 858de941c60Sdrh ** case the order does matter */ 859fd0a2f97Sdrh pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg); 860c926afbcSdrh }else{ 861b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 862634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1); 863da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, 1); 864b7654111Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 865b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 866c926afbcSdrh } 867c926afbcSdrh break; 868c926afbcSdrh } 86982c3d636Sdrh 870504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 871ec7429aeSdrh */ 872ec7429aeSdrh case SRT_Exists: { 8734c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 874ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 875ec7429aeSdrh break; 876ec7429aeSdrh } 877ec7429aeSdrh 8782282792aSdrh /* If this is a scalar select that is part of an expression, then 8792282792aSdrh ** store the results in the appropriate memory cell and break out 8802282792aSdrh ** of the scan loop. 8812282792aSdrh */ 882c926afbcSdrh case SRT_Mem: { 883340309fdSdrh assert( nResultCol==1 ); 884079a3072Sdrh if( pSort ){ 885fd0a2f97Sdrh pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg); 886c926afbcSdrh }else{ 88753932ce8Sdrh assert( regResult==iParm ); 888ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 889c926afbcSdrh } 890c926afbcSdrh break; 891c926afbcSdrh } 89293758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 8932282792aSdrh 89481cf13ecSdrh case SRT_Coroutine: /* Send data to a co-routine */ 89581cf13ecSdrh case SRT_Output: { /* Return the results */ 896373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 897373cc2ddSdrh testcase( eDest==SRT_Output ); 898079a3072Sdrh if( pSort ){ 899fd0a2f97Sdrh pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg); 900e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 9012b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 902c182d163Sdrh }else{ 903340309fdSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 904340309fdSdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 905ac82fcf5Sdrh } 906142e30dfSdrh break; 907142e30dfSdrh } 908142e30dfSdrh 909fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE 910fe1c6bb9Sdrh /* Write the results into a priority queue that is order according to 911fe1c6bb9Sdrh ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an 912fe1c6bb9Sdrh ** index with pSO->nExpr+2 columns. Build a key using pSO for the first 913fe1c6bb9Sdrh ** pSO->nExpr columns, then make sure all keys are unique by adding a 914fe1c6bb9Sdrh ** final OP_Sequence column. The last column is the record as a blob. 915fe1c6bb9Sdrh */ 916fe1c6bb9Sdrh case SRT_DistQueue: 917fe1c6bb9Sdrh case SRT_Queue: { 918fe1c6bb9Sdrh int nKey; 919fe1c6bb9Sdrh int r1, r2, r3; 920fe1c6bb9Sdrh int addrTest = 0; 921fe1c6bb9Sdrh ExprList *pSO; 922fe1c6bb9Sdrh pSO = pDest->pOrderBy; 923fe1c6bb9Sdrh assert( pSO ); 924fe1c6bb9Sdrh nKey = pSO->nExpr; 925fe1c6bb9Sdrh r1 = sqlite3GetTempReg(pParse); 926fe1c6bb9Sdrh r2 = sqlite3GetTempRange(pParse, nKey+2); 927fe1c6bb9Sdrh r3 = r2+nKey+1; 928fe1c6bb9Sdrh if( eDest==SRT_DistQueue ){ 929fe1c6bb9Sdrh /* If the destination is DistQueue, then cursor (iParm+1) is open 930fe1c6bb9Sdrh ** on a second ephemeral index that holds all values every previously 9317e4efaecSdrh ** added to the queue. */ 9327e4efaecSdrh addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 9337e4efaecSdrh regResult, nResultCol); 934688852abSdrh VdbeCoverage(v); 9357e4efaecSdrh } 9367e4efaecSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); 9377e4efaecSdrh if( eDest==SRT_DistQueue ){ 938fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); 939cfe24586Sdan sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 940fe1c6bb9Sdrh } 941fe1c6bb9Sdrh for(i=0; i<nKey; i++){ 942fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, 943fe1c6bb9Sdrh regResult + pSO->a[i].u.x.iOrderByCol - 1, 944fe1c6bb9Sdrh r2+i); 945fe1c6bb9Sdrh } 946fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); 947fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); 948fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 949fe1c6bb9Sdrh if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); 950fe1c6bb9Sdrh sqlite3ReleaseTempReg(pParse, r1); 951fe1c6bb9Sdrh sqlite3ReleaseTempRange(pParse, r2, nKey+2); 952fe1c6bb9Sdrh break; 953fe1c6bb9Sdrh } 954fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */ 955fe1c6bb9Sdrh 956fe1c6bb9Sdrh 957fe1c6bb9Sdrh 9586a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 959d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 960d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 961d7489c39Sdrh ** user-defined functions that have side effects. We do not care 962d7489c39Sdrh ** about the actual results of the select. 963d7489c39Sdrh */ 964c926afbcSdrh default: { 965f46f905aSdrh assert( eDest==SRT_Discard ); 966c926afbcSdrh break; 967c926afbcSdrh } 96893758c8dSdanielk1977 #endif 969c926afbcSdrh } 970ec7429aeSdrh 9715e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 9725e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 9735e87be87Sdrh ** the output for us. 974ec7429aeSdrh */ 975079a3072Sdrh if( pSort==0 && p->iLimit ){ 976688852abSdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v); 977ec7429aeSdrh } 97882c3d636Sdrh } 97982c3d636Sdrh 98082c3d636Sdrh /* 981ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and 982ad124329Sdrh ** X extra columns. 983323df790Sdrh */ 984ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 9852ec2fb22Sdrh KeyInfo *p = sqlite3DbMallocZero(0, 986ad124329Sdrh sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1)); 987323df790Sdrh if( p ){ 988ad124329Sdrh p->aSortOrder = (u8*)&p->aColl[N+X]; 989323df790Sdrh p->nField = (u16)N; 990ad124329Sdrh p->nXField = (u16)X; 991323df790Sdrh p->enc = ENC(db); 992323df790Sdrh p->db = db; 9932ec2fb22Sdrh p->nRef = 1; 9942ec2fb22Sdrh }else{ 9952ec2fb22Sdrh db->mallocFailed = 1; 996323df790Sdrh } 997323df790Sdrh return p; 998323df790Sdrh } 999323df790Sdrh 1000323df790Sdrh /* 10012ec2fb22Sdrh ** Deallocate a KeyInfo object 10022ec2fb22Sdrh */ 10032ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){ 10042ec2fb22Sdrh if( p ){ 10052ec2fb22Sdrh assert( p->nRef>0 ); 10062ec2fb22Sdrh p->nRef--; 1007c6efe12dSmistachkin if( p->nRef==0 ) sqlite3DbFree(0, p); 10082ec2fb22Sdrh } 10092ec2fb22Sdrh } 10102ec2fb22Sdrh 10112ec2fb22Sdrh /* 10122ec2fb22Sdrh ** Make a new pointer to a KeyInfo object 10132ec2fb22Sdrh */ 10142ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ 10152ec2fb22Sdrh if( p ){ 10162ec2fb22Sdrh assert( p->nRef>0 ); 10172ec2fb22Sdrh p->nRef++; 10182ec2fb22Sdrh } 10192ec2fb22Sdrh return p; 10202ec2fb22Sdrh } 10212ec2fb22Sdrh 10222ec2fb22Sdrh #ifdef SQLITE_DEBUG 10232ec2fb22Sdrh /* 10242ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change. The KeyInfo object 10252ec2fb22Sdrh ** can only be changed if this is just a single reference to the object. 10262ec2fb22Sdrh ** 10272ec2fb22Sdrh ** This routine is used only inside of assert() statements. 10282ec2fb22Sdrh */ 10292ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } 10302ec2fb22Sdrh #endif /* SQLITE_DEBUG */ 10312ec2fb22Sdrh 10322ec2fb22Sdrh /* 1033dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 1034dece1a84Sdrh ** the collating sequence for each expression in that expression list. 1035dece1a84Sdrh ** 10360342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 10370342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 10380342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 10390342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 10400342b1f5Sdrh ** index to implement a DISTINCT test. 10410342b1f5Sdrh ** 104260ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc. The calling 1043dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 10442ec2fb22Sdrh ** freed. 1045dece1a84Sdrh */ 1046079a3072Sdrh static KeyInfo *keyInfoFromExprList( 1047079a3072Sdrh Parse *pParse, /* Parsing context */ 1048079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 1049079a3072Sdrh int iStart, /* Begin with this column of pList */ 1050079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 1051079a3072Sdrh ){ 1052dece1a84Sdrh int nExpr; 1053dece1a84Sdrh KeyInfo *pInfo; 1054dece1a84Sdrh struct ExprList_item *pItem; 1055323df790Sdrh sqlite3 *db = pParse->db; 1056dece1a84Sdrh int i; 1057dece1a84Sdrh 1058dece1a84Sdrh nExpr = pList->nExpr; 10593f39bcf5Sdrh pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); 1060dece1a84Sdrh if( pInfo ){ 10612ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pInfo) ); 10626284db90Sdrh for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 1063dece1a84Sdrh CollSeq *pColl; 1064dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 1065323df790Sdrh if( !pColl ) pColl = db->pDfltColl; 10666284db90Sdrh pInfo->aColl[i-iStart] = pColl; 10676284db90Sdrh pInfo->aSortOrder[i-iStart] = pItem->sortOrder; 1068dece1a84Sdrh } 1069dece1a84Sdrh } 1070dece1a84Sdrh return pInfo; 1071dece1a84Sdrh } 1072dece1a84Sdrh 10737f61e92cSdan #ifndef SQLITE_OMIT_COMPOUND_SELECT 10747f61e92cSdan /* 10757f61e92cSdan ** Name of the connection operator, used for error messages. 10767f61e92cSdan */ 10777f61e92cSdan static const char *selectOpName(int id){ 10787f61e92cSdan char *z; 10797f61e92cSdan switch( id ){ 10807f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 10817f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 10827f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 10837f61e92cSdan default: z = "UNION"; break; 10847f61e92cSdan } 10857f61e92cSdan return z; 10867f61e92cSdan } 10877f61e92cSdan #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 10887f61e92cSdan 10892ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 109017c0bc0cSdan /* 109117c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 109217c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 109317c0bc0cSdan ** where the caption is of the form: 109417c0bc0cSdan ** 109517c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 109617c0bc0cSdan ** 109717c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 109817c0bc0cSdan ** is determined by the zUsage argument. 109917c0bc0cSdan */ 11002ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 11012ce22453Sdan if( pParse->explain==2 ){ 11022ce22453Sdan Vdbe *v = pParse->pVdbe; 11032ce22453Sdan char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); 11042ce22453Sdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 11052ce22453Sdan } 11062ce22453Sdan } 110717c0bc0cSdan 110817c0bc0cSdan /* 1109bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 1110bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 1111bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 1112bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 1113bb2b4418Sdan ** code with #ifndef directives. 1114bb2b4418Sdan */ 1115bb2b4418Sdan # define explainSetInteger(a, b) a = b 1116bb2b4418Sdan 1117bb2b4418Sdan #else 1118bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 1119bb2b4418Sdan # define explainTempTable(y,z) 1120bb2b4418Sdan # define explainSetInteger(y,z) 1121bb2b4418Sdan #endif 1122bb2b4418Sdan 1123bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) 1124bb2b4418Sdan /* 11257f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 11267f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 11277f61e92cSdan ** where the caption is of one of the two forms: 11287f61e92cSdan ** 11297f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" 11307f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" 11317f61e92cSdan ** 11327f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding 11337f61e92cSdan ** function parameters, and op is the text representation of the parameter 11347f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, 11357f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 11367f61e92cSdan ** false, or the second form if it is true. 11377f61e92cSdan */ 11387f61e92cSdan static void explainComposite( 11397f61e92cSdan Parse *pParse, /* Parse context */ 11407f61e92cSdan int op, /* One of TK_UNION, TK_EXCEPT etc. */ 11417f61e92cSdan int iSub1, /* Subquery id 1 */ 11427f61e92cSdan int iSub2, /* Subquery id 2 */ 11437f61e92cSdan int bUseTmp /* True if a temp table was used */ 11447f61e92cSdan ){ 11457f61e92cSdan assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); 11467f61e92cSdan if( pParse->explain==2 ){ 11477f61e92cSdan Vdbe *v = pParse->pVdbe; 11487f61e92cSdan char *zMsg = sqlite3MPrintf( 114930969d3fSdan pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, 11507f61e92cSdan bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) 11517f61e92cSdan ); 11527f61e92cSdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 11537f61e92cSdan } 11547f61e92cSdan } 11552ce22453Sdan #else 115617c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */ 11577f61e92cSdan # define explainComposite(v,w,x,y,z) 11582ce22453Sdan #endif 1159dece1a84Sdrh 1160dece1a84Sdrh /* 1161d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 1162d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 1163d8bc7086Sdrh ** we need to run the sorter and output the results. The following 1164d8bc7086Sdrh ** routine generates the code needed to do that. 1165d8bc7086Sdrh */ 1166c926afbcSdrh static void generateSortTail( 1167cdd536f0Sdrh Parse *pParse, /* Parsing context */ 1168c926afbcSdrh Select *p, /* The SELECT statement */ 1169079a3072Sdrh SortCtx *pSort, /* Information on the ORDER BY clause */ 1170c926afbcSdrh int nColumn, /* Number of columns of data */ 11716c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 1172c926afbcSdrh ){ 1173ddba0c22Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1174dc5ea5c7Sdrh int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ 1175dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 1176d8bc7086Sdrh int addr; 1177079a3072Sdrh int addrOnce = 0; 11780342b1f5Sdrh int iTab; 1179079a3072Sdrh ExprList *pOrderBy = pSort->pOrderBy; 11806c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 11812b596da8Sdrh int iParm = pDest->iSDParm; 11822d401ab8Sdrh int regRow; 11832d401ab8Sdrh int regRowid; 1184079a3072Sdrh int nKey; 1185f45f2326Sdrh int iSortTab; /* Sorter cursor to read from */ 1186f45f2326Sdrh int nSortData; /* Trailing values to read from sorter */ 1187f45f2326Sdrh int i; 118878d58432Sdan int bSeq; /* True if sorter record includes seq. no. */ 118970f624c3Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS 119070f624c3Sdrh struct ExprList_item *aOutEx = p->pEList->a; 119170f624c3Sdrh #endif 11922d401ab8Sdrh 1193079a3072Sdrh if( pSort->labelBkOut ){ 1194079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1195079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak); 1196079a3072Sdrh sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1197079a3072Sdrh } 1198079a3072Sdrh iTab = pSort->iECursor; 11997d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 12003e9ca094Sdrh regRowid = 0; 1201f45f2326Sdrh regRow = pDest->iSdst; 1202f45f2326Sdrh nSortData = nColumn; 12033e9ca094Sdrh }else{ 12043e9ca094Sdrh regRowid = sqlite3GetTempReg(pParse); 1205f45f2326Sdrh regRow = sqlite3GetTempReg(pParse); 1206f45f2326Sdrh nSortData = 1; 1207cdd536f0Sdrh } 1208079a3072Sdrh nKey = pOrderBy->nExpr - pSort->nOBSat; 1209079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1210c2bb3282Sdrh int regSortOut = ++pParse->nMem; 1211f45f2326Sdrh iSortTab = pParse->nTab++; 121283553eefSdrh if( pSort->labelBkOut ){ 121383553eefSdrh addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v); 121483553eefSdrh } 1215f45f2326Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData); 1216079a3072Sdrh if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); 1217c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 1218688852abSdrh VdbeCoverage(v); 1219aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 12206cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); 122178d58432Sdan bSeq = 0; 1222c6aff30cSdrh }else{ 1223688852abSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1224aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 1225f45f2326Sdrh iSortTab = iTab; 122678d58432Sdan bSeq = 1; 1227f45f2326Sdrh } 1228f45f2326Sdrh for(i=0; i<nSortData; i++){ 122978d58432Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i); 123070f624c3Sdrh VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan)); 1231c6aff30cSdrh } 1232c926afbcSdrh switch( eDest ){ 1233c926afbcSdrh case SRT_Table: 1234b9bb7c18Sdrh case SRT_EphemTab: { 12351c767f0dSdrh testcase( eDest==SRT_Table ); 12361c767f0dSdrh testcase( eDest==SRT_EphemTab ); 12372d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 12382d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 12392d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1240c926afbcSdrh break; 1241c926afbcSdrh } 124293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 1243c926afbcSdrh case SRT_Set: { 1244c926afbcSdrh assert( nColumn==1 ); 1245634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, 1246634d81deSdrh &pDest->affSdst, 1); 1247da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regRow, 1); 1248a7a8e14bSdanielk1977 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); 1249c926afbcSdrh break; 1250c926afbcSdrh } 1251c926afbcSdrh case SRT_Mem: { 1252c926afbcSdrh assert( nColumn==1 ); 1253b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regRow, iParm, 1); 1254ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1255c926afbcSdrh break; 1256c926afbcSdrh } 125793758c8dSdanielk1977 #endif 1258373cc2ddSdrh default: { 1259373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 12601c767f0dSdrh testcase( eDest==SRT_Output ); 12611c767f0dSdrh testcase( eDest==SRT_Coroutine ); 12627d10d5a6Sdrh if( eDest==SRT_Output ){ 12632b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 12642b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); 1265a9671a22Sdrh }else{ 12662b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1267ce665cf6Sdrh } 1268ac82fcf5Sdrh break; 1269ac82fcf5Sdrh } 1270c926afbcSdrh } 1271f45f2326Sdrh if( regRowid ){ 12722d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 12732d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1274f45f2326Sdrh } 1275ec7429aeSdrh /* The bottom of the loop 1276ec7429aeSdrh */ 1277dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1278079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1279688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); 1280c6aff30cSdrh }else{ 1281688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); 1282c6aff30cSdrh } 1283079a3072Sdrh if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); 1284dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 1285d8bc7086Sdrh } 1286d8bc7086Sdrh 1287d8bc7086Sdrh /* 1288517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1289517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1290e78e8284Sdrh ** 12915f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that 12925f3e5e74Sdrh ** result in *pEstWidth. 12935f3e5e74Sdrh ** 1294955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1295955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1296955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1297955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1298955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1299955de52cSdanielk1977 ** considered a column by this function. 1300e78e8284Sdrh ** 1301955de52cSdanielk1977 ** SELECT col FROM tbl; 1302955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1303955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1304955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1305955de52cSdanielk1977 ** 1306955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 13075f3e5e74Sdrh ** 13085f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not 13095f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1310fcb78a49Sdrh */ 13115f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 13125f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) 13135f3e5e74Sdrh static const char *columnTypeImpl( 1314955de52cSdanielk1977 NameContext *pNC, 1315955de52cSdanielk1977 Expr *pExpr, 13165f3e5e74Sdrh const char **pzOrigDb, 13175f3e5e74Sdrh const char **pzOrigTab, 13185f3e5e74Sdrh const char **pzOrigCol, 13195f3e5e74Sdrh u8 *pEstWidth 1320955de52cSdanielk1977 ){ 13215f3e5e74Sdrh char const *zOrigDb = 0; 13225f3e5e74Sdrh char const *zOrigTab = 0; 13235f3e5e74Sdrh char const *zOrigCol = 0; 13245f3e5e74Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 13255f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F) 13265f3e5e74Sdrh static const char *columnTypeImpl( 13275f3e5e74Sdrh NameContext *pNC, 13285f3e5e74Sdrh Expr *pExpr, 13295f3e5e74Sdrh u8 *pEstWidth 13305f3e5e74Sdrh ){ 13315f3e5e74Sdrh #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1332955de52cSdanielk1977 char const *zType = 0; 1333517eb646Sdanielk1977 int j; 13345f3e5e74Sdrh u8 estWidth = 1; 13355338a5f7Sdanielk1977 13365f3e5e74Sdrh if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; 133700e279d9Sdanielk1977 switch( pExpr->op ){ 133830bcf5dbSdrh case TK_AGG_COLUMN: 133900e279d9Sdanielk1977 case TK_COLUMN: { 1340955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1341955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1342955de52cSdanielk1977 ** database table or a subquery. 1343955de52cSdanielk1977 */ 1344955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1345955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1346955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 1347373cc2ddSdrh testcase( pExpr->op==TK_AGG_COLUMN ); 1348373cc2ddSdrh testcase( pExpr->op==TK_COLUMN ); 134943bc88bbSdan while( pNC && !pTab ){ 1350b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1351b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1352b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 13536a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1354955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1355b3bce662Sdanielk1977 }else{ 1356b3bce662Sdanielk1977 pNC = pNC->pNext; 1357b3bce662Sdanielk1977 } 1358b3bce662Sdanielk1977 } 1359955de52cSdanielk1977 136043bc88bbSdan if( pTab==0 ){ 1361417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1362417168adSdrh ** cause this condition to run. Since then, we have restructured how 1363417168adSdrh ** trigger code is generated and so this condition is no longer 136443bc88bbSdan ** possible. However, it can still be true for statements like 136543bc88bbSdan ** the following: 136643bc88bbSdan ** 136743bc88bbSdan ** CREATE TABLE t1(col INTEGER); 136843bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 136943bc88bbSdan ** 137043bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 137143bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 137243bc88bbSdan ** though it should really be "INTEGER". 137343bc88bbSdan ** 137443bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 137543bc88bbSdan ** used. When columnType() is called on the expression 137643bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 137743bc88bbSdan ** branch below. */ 13787e62779aSdrh break; 13797e62779aSdrh } 1380955de52cSdanielk1977 138143bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1382955de52cSdanielk1977 if( pS ){ 1383955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1384955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1385955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1386955de52cSdanielk1977 */ 13877b688edeSdrh if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ 1388955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1389955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1390955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1391955de52cSdanielk1977 */ 1392955de52cSdanielk1977 NameContext sNC; 1393955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1394955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 139543bc88bbSdan sNC.pNext = pNC; 1396955de52cSdanielk1977 sNC.pParse = pNC->pParse; 13975f3e5e74Sdrh zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); 1398955de52cSdanielk1977 } 139993c36bb3Sdrh }else if( pTab->pSchema ){ 1400955de52cSdanielk1977 /* A real table */ 1401955de52cSdanielk1977 assert( !pS ); 1402fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1403fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 14045f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1405fcb78a49Sdrh if( iCol<0 ){ 1406fcb78a49Sdrh zType = "INTEGER"; 14075f3e5e74Sdrh zOrigCol = "rowid"; 1408fcb78a49Sdrh }else{ 1409fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 14105f3e5e74Sdrh zOrigCol = pTab->aCol[iCol].zName; 14115f3e5e74Sdrh estWidth = pTab->aCol[iCol].szEst; 1412955de52cSdanielk1977 } 14135f3e5e74Sdrh zOrigTab = pTab->zName; 1414955de52cSdanielk1977 if( pNC->pParse ){ 1415955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 14165f3e5e74Sdrh zOrigDb = pNC->pParse->db->aDb[iDb].zName; 1417955de52cSdanielk1977 } 14185f3e5e74Sdrh #else 14195f3e5e74Sdrh if( iCol<0 ){ 14205f3e5e74Sdrh zType = "INTEGER"; 14215f3e5e74Sdrh }else{ 14225f3e5e74Sdrh zType = pTab->aCol[iCol].zType; 14235f3e5e74Sdrh estWidth = pTab->aCol[iCol].szEst; 14245f3e5e74Sdrh } 14255f3e5e74Sdrh #endif 1426fcb78a49Sdrh } 142700e279d9Sdanielk1977 break; 1428736c22b8Sdrh } 142993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 143000e279d9Sdanielk1977 case TK_SELECT: { 1431955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1432955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1433955de52cSdanielk1977 ** statement. 1434955de52cSdanielk1977 */ 1435b3bce662Sdanielk1977 NameContext sNC; 14366ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1437955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 14386ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1439955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1440b3bce662Sdanielk1977 sNC.pNext = pNC; 1441955de52cSdanielk1977 sNC.pParse = pNC->pParse; 14425f3e5e74Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); 144300e279d9Sdanielk1977 break; 1444fcb78a49Sdrh } 144593758c8dSdanielk1977 #endif 144600e279d9Sdanielk1977 } 144700e279d9Sdanielk1977 14485f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 14495f3e5e74Sdrh if( pzOrigDb ){ 14505f3e5e74Sdrh assert( pzOrigTab && pzOrigCol ); 14515f3e5e74Sdrh *pzOrigDb = zOrigDb; 14525f3e5e74Sdrh *pzOrigTab = zOrigTab; 14535f3e5e74Sdrh *pzOrigCol = zOrigCol; 1454955de52cSdanielk1977 } 14555f3e5e74Sdrh #endif 14565f3e5e74Sdrh if( pEstWidth ) *pEstWidth = estWidth; 1457517eb646Sdanielk1977 return zType; 1458517eb646Sdanielk1977 } 1459517eb646Sdanielk1977 1460517eb646Sdanielk1977 /* 1461517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1462517eb646Sdanielk1977 ** in the result set. 1463517eb646Sdanielk1977 */ 1464517eb646Sdanielk1977 static void generateColumnTypes( 1465517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1466517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1467517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1468517eb646Sdanielk1977 ){ 14693f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1470517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1471517eb646Sdanielk1977 int i; 1472b3bce662Sdanielk1977 NameContext sNC; 1473b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1474955de52cSdanielk1977 sNC.pParse = pParse; 1475517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1476517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 14773f913576Sdrh const char *zType; 14783f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1479955de52cSdanielk1977 const char *zOrigDb = 0; 1480955de52cSdanielk1977 const char *zOrigTab = 0; 1481955de52cSdanielk1977 const char *zOrigCol = 0; 14825f3e5e74Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0); 1483955de52cSdanielk1977 148485b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 14854b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 14864b1ae99dSdanielk1977 ** virtual machine is deleted. 1487fbcd585fSdanielk1977 */ 148810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 148910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 149010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 14913f913576Sdrh #else 14925f3e5e74Sdrh zType = columnType(&sNC, p, 0, 0, 0, 0); 14933f913576Sdrh #endif 149410fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1495fcb78a49Sdrh } 14965f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ 1497fcb78a49Sdrh } 1498fcb78a49Sdrh 1499fcb78a49Sdrh /* 1500fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1501fcb78a49Sdrh ** in the result set. This information is used to provide the 1502fcabd464Sdrh ** azCol[] values in the callback. 150382c3d636Sdrh */ 1504832508b7Sdrh static void generateColumnNames( 1505832508b7Sdrh Parse *pParse, /* Parser context */ 1506ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1507832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1508832508b7Sdrh ){ 1509d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 15106a3ea0e6Sdrh int i, j; 15119bb575fdSdrh sqlite3 *db = pParse->db; 1512fcabd464Sdrh int fullNames, shortNames; 1513fcabd464Sdrh 1514fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 15153cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 15163cf86063Sdanielk1977 if( pParse->explain ){ 151761de0d1bSdanielk1977 return; 15183cf86063Sdanielk1977 } 15195338a5f7Sdanielk1977 #endif 15203cf86063Sdanielk1977 1521e2f02bacSdrh if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; 1522d8bc7086Sdrh pParse->colNamesSet = 1; 1523fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1524fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 152522322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 152682c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 152782c3d636Sdrh Expr *p; 15285a38705eSdrh p = pEList->a[i].pExpr; 1529373cc2ddSdrh if( NEVER(p==0) ) continue; 153082c3d636Sdrh if( pEList->a[i].zName ){ 153182c3d636Sdrh char *zName = pEList->a[i].zName; 153210fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1533f018cc2eSdrh }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ 15346a3ea0e6Sdrh Table *pTab; 153597665873Sdrh char *zCol; 15368aff1015Sdrh int iCol = p->iColumn; 1537e2f02bacSdrh for(j=0; ALWAYS(j<pTabList->nSrc); j++){ 1538e2f02bacSdrh if( pTabList->a[j].iCursor==p->iTable ) break; 1539e2f02bacSdrh } 15406a3ea0e6Sdrh assert( j<pTabList->nSrc ); 15416a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 15428aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 154397665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1544b1363206Sdrh if( iCol<0 ){ 154547a6db2bSdrh zCol = "rowid"; 1546b1363206Sdrh }else{ 1547b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1548b1363206Sdrh } 1549e49b146fSdrh if( !shortNames && !fullNames ){ 155010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1551b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 15521c767f0dSdrh }else if( fullNames ){ 155382c3d636Sdrh char *zName = 0; 15541c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 155510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 155682c3d636Sdrh }else{ 155710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 155882c3d636Sdrh } 15591bee3d7bSdrh }else{ 1560859bc542Sdrh const char *z = pEList->a[i].zSpan; 1561859bc542Sdrh z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); 1562859bc542Sdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); 156382c3d636Sdrh } 156482c3d636Sdrh } 156576d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 15665080aaa7Sdrh } 156782c3d636Sdrh 1568d8bc7086Sdrh /* 156960ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions 15707d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 15717d10d5a6Sdrh ** column names for a table that would hold the expression list. 15727d10d5a6Sdrh ** 15737d10d5a6Sdrh ** All column names will be unique. 15747d10d5a6Sdrh ** 15757d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 15767d10d5a6Sdrh ** and other fields of Column are zeroed. 15777d10d5a6Sdrh ** 15787d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 15797d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1580315555caSdrh */ 15817d10d5a6Sdrh static int selectColumnsFromExprList( 15827d10d5a6Sdrh Parse *pParse, /* Parsing context */ 15837d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 1584d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 15857d10d5a6Sdrh Column **paCol /* Write the new column list here */ 15867d10d5a6Sdrh ){ 1587dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1588dc5ea5c7Sdrh int i, j; /* Loop counters */ 1589dc5ea5c7Sdrh int cnt; /* Index added to make the name unique */ 1590dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1591dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1592dc5ea5c7Sdrh Expr *p; /* Expression for a single result column */ 1593dc5ea5c7Sdrh char *zName; /* Column name */ 1594dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 159579d5f63fSdrh 15968c2e0f02Sdan if( pEList ){ 15978c2e0f02Sdan nCol = pEList->nExpr; 15988c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 15998c2e0f02Sdan testcase( aCol==0 ); 16008c2e0f02Sdan }else{ 16018c2e0f02Sdan nCol = 0; 16028c2e0f02Sdan aCol = 0; 16038c2e0f02Sdan } 16048c2e0f02Sdan *pnCol = nCol; 16058c2e0f02Sdan *paCol = aCol; 16068c2e0f02Sdan 16077d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 160879d5f63fSdrh /* Get an appropriate name for the column 160979d5f63fSdrh */ 1610580c8c18Sdrh p = sqlite3ExprSkipCollate(pEList->a[i].pExpr); 161191bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 161279d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 161317435752Sdrh zName = sqlite3DbStrDup(db, zName); 16147d10d5a6Sdrh }else{ 1615dc5ea5c7Sdrh Expr *pColExpr = p; /* The expression that is the result column name */ 1616dc5ea5c7Sdrh Table *pTab; /* Table associated with this expression */ 1617b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1618b07028f7Sdrh pColExpr = pColExpr->pRight; 1619b07028f7Sdrh assert( pColExpr!=0 ); 1620b07028f7Sdrh } 1621373cc2ddSdrh if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ 162293a960a0Sdrh /* For columns use the column name name */ 1623dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1624373cc2ddSdrh pTab = pColExpr->pTab; 1625f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1626f0209f74Sdrh zName = sqlite3MPrintf(db, "%s", 1627f0209f74Sdrh iCol>=0 ? pTab->aCol[iCol].zName : "rowid"); 1628b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 162933e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 163033e619fcSdrh zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); 163193a960a0Sdrh }else{ 163279d5f63fSdrh /* Use the original text of the column expression as its name */ 1633b7916a78Sdrh zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); 16347d10d5a6Sdrh } 163522f70c32Sdrh } 16367ce72f69Sdrh if( db->mallocFailed ){ 1637633e6d57Sdrh sqlite3DbFree(db, zName); 16387ce72f69Sdrh break; 1639dd5b2fa5Sdrh } 164079d5f63fSdrh 164179d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 164260ec914cSpeter.d.reid ** append an integer to the name so that it becomes unique. 164379d5f63fSdrh */ 1644ea678832Sdrh nName = sqlite3Strlen30(zName); 164579d5f63fSdrh for(j=cnt=0; j<i; j++){ 164679d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 1647633e6d57Sdrh char *zNewName; 1648fb777327Sdrh int k; 1649fb777327Sdrh for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){} 165019c6d96aSdrh if( k>=0 && zName[k]==':' ) nName = k; 16512564ef97Sdrh zName[nName] = 0; 1652633e6d57Sdrh zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt); 1653633e6d57Sdrh sqlite3DbFree(db, zName); 1654633e6d57Sdrh zName = zNewName; 165579d5f63fSdrh j = -1; 1656dd5b2fa5Sdrh if( zName==0 ) break; 165779d5f63fSdrh } 165879d5f63fSdrh } 165991bb0eedSdrh pCol->zName = zName; 16607d10d5a6Sdrh } 16617d10d5a6Sdrh if( db->mallocFailed ){ 16627d10d5a6Sdrh for(j=0; j<i; j++){ 16637d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 16647d10d5a6Sdrh } 16657d10d5a6Sdrh sqlite3DbFree(db, aCol); 16667d10d5a6Sdrh *paCol = 0; 16677d10d5a6Sdrh *pnCol = 0; 16687d10d5a6Sdrh return SQLITE_NOMEM; 16697d10d5a6Sdrh } 16707d10d5a6Sdrh return SQLITE_OK; 16717d10d5a6Sdrh } 1672e014a838Sdanielk1977 16737d10d5a6Sdrh /* 16747d10d5a6Sdrh ** Add type and collation information to a column list based on 16757d10d5a6Sdrh ** a SELECT statement. 16767d10d5a6Sdrh ** 16777d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 16787d10d5a6Sdrh ** The column list has only names, not types or collations. This 16797d10d5a6Sdrh ** routine goes through and adds the types and collations. 16807d10d5a6Sdrh ** 1681b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 16827d10d5a6Sdrh ** statement be resolved. 168379d5f63fSdrh */ 16847d10d5a6Sdrh static void selectAddColumnTypeAndCollation( 16857d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 1686186ad8ccSdrh Table *pTab, /* Add column type information to this table */ 16877d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 16887d10d5a6Sdrh ){ 16897d10d5a6Sdrh sqlite3 *db = pParse->db; 16907d10d5a6Sdrh NameContext sNC; 16917d10d5a6Sdrh Column *pCol; 16927d10d5a6Sdrh CollSeq *pColl; 16937d10d5a6Sdrh int i; 16947d10d5a6Sdrh Expr *p; 16957d10d5a6Sdrh struct ExprList_item *a; 1696186ad8ccSdrh u64 szAll = 0; 16977d10d5a6Sdrh 16987d10d5a6Sdrh assert( pSelect!=0 ); 16997d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 1700186ad8ccSdrh assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 17017d10d5a6Sdrh if( db->mallocFailed ) return; 1702c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1703b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 17047d10d5a6Sdrh a = pSelect->pEList->a; 1705186ad8ccSdrh for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 17067d10d5a6Sdrh p = a[i].pExpr; 17075f3e5e74Sdrh pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst)); 1708186ad8ccSdrh szAll += pCol->szEst; 1709c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1710c4a64facSdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE; 1711b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1712b3bf556eSdanielk1977 if( pColl ){ 171317435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 17140202b29eSdanielk1977 } 171522f70c32Sdrh } 1716186ad8ccSdrh pTab->szTabRow = sqlite3LogEst(szAll*4); 17177d10d5a6Sdrh } 17187d10d5a6Sdrh 17197d10d5a6Sdrh /* 17207d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 17217d10d5a6Sdrh ** the result set of that SELECT. 17227d10d5a6Sdrh */ 17237d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 17247d10d5a6Sdrh Table *pTab; 17257d10d5a6Sdrh sqlite3 *db = pParse->db; 17267d10d5a6Sdrh int savedFlags; 17277d10d5a6Sdrh 17287d10d5a6Sdrh savedFlags = db->flags; 17297d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 17307d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 17317d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 17327d10d5a6Sdrh if( pParse->nErr ) return 0; 17337d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 17347d10d5a6Sdrh db->flags = savedFlags; 17357d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 17367d10d5a6Sdrh if( pTab==0 ){ 17377d10d5a6Sdrh return 0; 17387d10d5a6Sdrh } 1739373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 1740b2468954Sdrh ** is disabled */ 1741373cc2ddSdrh assert( db->lookaside.bEnabled==0 ); 17427d10d5a6Sdrh pTab->nRef = 1; 17437d10d5a6Sdrh pTab->zName = 0; 1744cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 17457d10d5a6Sdrh selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 1746186ad8ccSdrh selectAddColumnTypeAndCollation(pParse, pTab, pSelect); 174722f70c32Sdrh pTab->iPKey = -1; 17487ce72f69Sdrh if( db->mallocFailed ){ 17491feeaed2Sdan sqlite3DeleteTable(db, pTab); 17507ce72f69Sdrh return 0; 17517ce72f69Sdrh } 175222f70c32Sdrh return pTab; 175322f70c32Sdrh } 175422f70c32Sdrh 175522f70c32Sdrh /* 1756d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1757d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1758d8bc7086Sdrh */ 17594adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1760d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1761d8bc7086Sdrh if( v==0 ){ 17629ac7962aSdrh v = pParse->pVdbe = sqlite3VdbeCreate(pParse); 1763aceb31b1Sdrh if( v ) sqlite3VdbeAddOp0(v, OP_Init); 1764e0e261a4Sdrh if( pParse->pToplevel==0 1765e0e261a4Sdrh && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) 1766e0e261a4Sdrh ){ 1767e0e261a4Sdrh pParse->okConstFactor = 1; 1768e0e261a4Sdrh } 1769e0e261a4Sdrh 1770d8bc7086Sdrh } 1771d8bc7086Sdrh return v; 1772d8bc7086Sdrh } 1773d8bc7086Sdrh 177415007a99Sdrh 1775d8bc7086Sdrh /* 17767b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1777ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 17787b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1779a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1780a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1781a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1782a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 17837b58daeaSdrh ** 1784d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1785ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 1786aa9ce707Sdrh ** iOffset should have been preset to appropriate default values (zero) 1787aa9ce707Sdrh ** prior to calling this routine. 1788aa9ce707Sdrh ** 1789aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value 1790aa9ce707Sdrh ** of the OFFSET. The iLimit register is initialized to LIMIT. Register 1791aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET. 1792aa9ce707Sdrh ** 1793ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 17947b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 17957b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 17967b58daeaSdrh ** SELECT statements. 17977b58daeaSdrh */ 1798ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 179902afc861Sdrh Vdbe *v = 0; 180002afc861Sdrh int iLimit = 0; 180115007a99Sdrh int iOffset; 18029b918ed1Sdrh int addr1, n; 18030acb7e48Sdrh if( p->iLimit ) return; 180415007a99Sdrh 18057b58daeaSdrh /* 18067b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 1807f7b5496eSdrh ** controversy about what the correct behavior should be. 18087b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 18097b58daeaSdrh ** no rows. 18107b58daeaSdrh */ 1811ceea3321Sdrh sqlite3ExprCacheClear(pParse); 1812373cc2ddSdrh assert( p->pOffset==0 || p->pLimit!=0 ); 1813a2dc3b1aSdanielk1977 if( p->pLimit ){ 18140a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 181515007a99Sdrh v = sqlite3GetVdbe(pParse); 1816aa9ce707Sdrh assert( v!=0 ); 18179b918ed1Sdrh if( sqlite3ExprIsInteger(p->pLimit, &n) ){ 18189b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 18199b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 1820456e4e4fSdrh if( n==0 ){ 1821456e4e4fSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 1822613ba1eaSdrh }else if( n>=0 && p->nSelectRow>(u64)n ){ 1823613ba1eaSdrh p->nSelectRow = n; 18249b918ed1Sdrh } 18259b918ed1Sdrh }else{ 1826b7654111Sdrh sqlite3ExprCode(pParse, p->pLimit, iLimit); 1827688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 1828d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 1829688852abSdrh sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v); 18309b918ed1Sdrh } 1831a2dc3b1aSdanielk1977 if( p->pOffset ){ 18320a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 1833b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 1834b7654111Sdrh sqlite3ExprCode(pParse, p->pOffset, iOffset); 1835688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 1836d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 1837688852abSdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v); 1838b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); 183915007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 1840b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1841d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 1842688852abSdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v); 1843b7654111Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); 1844b7654111Sdrh sqlite3VdbeJumpHere(v, addr1); 1845b7654111Sdrh } 1846d59ba6ceSdrh } 18477b58daeaSdrh } 18487b58daeaSdrh 1849b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1850fbc4ee7bSdrh /* 1851fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1852fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1853fbc4ee7bSdrh ** the column has no default collating sequence. 1854fbc4ee7bSdrh ** 1855fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1856fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1857fbc4ee7bSdrh */ 1858dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1859fbc4ee7bSdrh CollSeq *pRet; 1860dc1bdc4fSdanielk1977 if( p->pPrior ){ 1861dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1862fbc4ee7bSdrh }else{ 1863fbc4ee7bSdrh pRet = 0; 1864dc1bdc4fSdanielk1977 } 186510c081adSdrh assert( iCol>=0 ); 186610c081adSdrh if( pRet==0 && iCol<p->pEList->nExpr ){ 1867dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1868dc1bdc4fSdanielk1977 } 1869dc1bdc4fSdanielk1977 return pRet; 1870d3d39e93Sdrh } 187153bed45eSdan 187253bed45eSdan /* 187353bed45eSdan ** The select statement passed as the second parameter is a compound SELECT 187453bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo 187553bed45eSdan ** structure suitable for implementing the ORDER BY. 187653bed45eSdan ** 187753bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling 187853bed45eSdan ** function is responsible for ensuring that this structure is eventually 187953bed45eSdan ** freed. 188053bed45eSdan */ 188153bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ 188253bed45eSdan ExprList *pOrderBy = p->pOrderBy; 188353bed45eSdan int nOrderBy = p->pOrderBy->nExpr; 188453bed45eSdan sqlite3 *db = pParse->db; 188553bed45eSdan KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); 188653bed45eSdan if( pRet ){ 188753bed45eSdan int i; 188853bed45eSdan for(i=0; i<nOrderBy; i++){ 188953bed45eSdan struct ExprList_item *pItem = &pOrderBy->a[i]; 189053bed45eSdan Expr *pTerm = pItem->pExpr; 189153bed45eSdan CollSeq *pColl; 189253bed45eSdan 189353bed45eSdan if( pTerm->flags & EP_Collate ){ 189453bed45eSdan pColl = sqlite3ExprCollSeq(pParse, pTerm); 189553bed45eSdan }else{ 189653bed45eSdan pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); 189753bed45eSdan if( pColl==0 ) pColl = db->pDfltColl; 189853bed45eSdan pOrderBy->a[i].pExpr = 189953bed45eSdan sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); 190053bed45eSdan } 190153bed45eSdan assert( sqlite3KeyInfoIsWriteable(pRet) ); 190253bed45eSdan pRet->aColl[i] = pColl; 190353bed45eSdan pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder; 190453bed45eSdan } 190553bed45eSdan } 190653bed45eSdan 190753bed45eSdan return pRet; 190853bed45eSdan } 1909d3d39e93Sdrh 1910781def29Sdrh #ifndef SQLITE_OMIT_CTE 1911781def29Sdrh /* 1912781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 1913781def29Sdrh ** query of the form: 1914781def29Sdrh ** 1915781def29Sdrh ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 1916781def29Sdrh ** \___________/ \_______________/ 1917781def29Sdrh ** p->pPrior p 1918781def29Sdrh ** 1919781def29Sdrh ** 1920781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause 1921781def29Sdrh ** of recursive-query, marked with the SrcList->a[].isRecursive flag. 1922781def29Sdrh ** 1923781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go 1924781def29Sdrh ** into a Queue table. Rows are extracted from the Queue table one by 1925fe1c6bb9Sdrh ** one. Each row extracted from Queue is output to pDest. Then the single 1926fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the 1927fe1c6bb9Sdrh ** recursive-table for a recursive-query run. The output of the recursive-query 1928781def29Sdrh ** is added back into the Queue table. Then another row is extracted from Queue 1929781def29Sdrh ** and the iteration continues until the Queue table is empty. 1930781def29Sdrh ** 1931781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever 1932781def29Sdrh ** inserted into the Queue table. The iDistinct table keeps a copy of all rows 1933781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be 1934781def29Sdrh ** discarded. If the operator is UNION ALL, then duplicates are allowed. 1935781def29Sdrh ** 1936781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in 1937781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle. Without 1938781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO. 1939781def29Sdrh ** 1940781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows 1941781def29Sdrh ** have been output to pDest. A LIMIT of zero means to output no rows and a 1942781def29Sdrh ** negative LIMIT means to output all rows. If there is also an OFFSET clause 1943781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather 1944781def29Sdrh ** than being sent to pDest. The LIMIT count does not begin until after OFFSET 1945781def29Sdrh ** rows have been skipped. 1946781def29Sdrh */ 1947781def29Sdrh static void generateWithRecursiveQuery( 1948781def29Sdrh Parse *pParse, /* Parsing context */ 1949781def29Sdrh Select *p, /* The recursive SELECT to be coded */ 1950781def29Sdrh SelectDest *pDest /* What to do with query results */ 1951781def29Sdrh ){ 1952781def29Sdrh SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ 1953781def29Sdrh int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ 1954781def29Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ 1955781def29Sdrh Select *pSetup = p->pPrior; /* The setup query */ 1956781def29Sdrh int addrTop; /* Top of the loop */ 1957781def29Sdrh int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ 1958edf83d1eSdrh int iCurrent = 0; /* The Current table */ 1959781def29Sdrh int regCurrent; /* Register holding Current table */ 1960781def29Sdrh int iQueue; /* The Queue table */ 1961781def29Sdrh int iDistinct = 0; /* To ensure unique results if UNION */ 19628e1ee88cSdrh int eDest = SRT_Fifo; /* How to write to Queue */ 1963781def29Sdrh SelectDest destQueue; /* SelectDest targetting the Queue table */ 1964781def29Sdrh int i; /* Loop counter */ 1965781def29Sdrh int rc; /* Result code */ 1966fe1c6bb9Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 1967aa9ce707Sdrh Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */ 1968aa9ce707Sdrh int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ 1969781def29Sdrh 1970781def29Sdrh /* Obtain authorization to do a recursive query */ 1971781def29Sdrh if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; 1972781def29Sdrh 1973aa9ce707Sdrh /* Process the LIMIT and OFFSET clauses, if they exist */ 1974aa9ce707Sdrh addrBreak = sqlite3VdbeMakeLabel(v); 1975aa9ce707Sdrh computeLimitRegisters(pParse, p, addrBreak); 1976aa9ce707Sdrh pLimit = p->pLimit; 1977aa9ce707Sdrh pOffset = p->pOffset; 1978aa9ce707Sdrh regLimit = p->iLimit; 1979aa9ce707Sdrh regOffset = p->iOffset; 1980aa9ce707Sdrh p->pLimit = p->pOffset = 0; 1981aa9ce707Sdrh p->iLimit = p->iOffset = 0; 198253bed45eSdan pOrderBy = p->pOrderBy; 1983781def29Sdrh 1984781def29Sdrh /* Locate the cursor number of the Current table */ 1985781def29Sdrh for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 1986781def29Sdrh if( pSrc->a[i].isRecursive ){ 1987781def29Sdrh iCurrent = pSrc->a[i].iCursor; 1988781def29Sdrh break; 1989781def29Sdrh } 1990781def29Sdrh } 1991781def29Sdrh 1992fe1c6bb9Sdrh /* Allocate cursors numbers for Queue and Distinct. The cursor number for 1993781def29Sdrh ** the Distinct table must be exactly one greater than Queue in order 19948e1ee88cSdrh ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 1995781def29Sdrh iQueue = pParse->nTab++; 1996781def29Sdrh if( p->op==TK_UNION ){ 19978e1ee88cSdrh eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; 1998781def29Sdrh iDistinct = pParse->nTab++; 1999fe1c6bb9Sdrh }else{ 20008e1ee88cSdrh eDest = pOrderBy ? SRT_Queue : SRT_Fifo; 2001781def29Sdrh } 2002781def29Sdrh sqlite3SelectDestInit(&destQueue, eDest, iQueue); 2003781def29Sdrh 2004781def29Sdrh /* Allocate cursors for Current, Queue, and Distinct. */ 2005781def29Sdrh regCurrent = ++pParse->nMem; 2006781def29Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); 2007fe1c6bb9Sdrh if( pOrderBy ){ 200853bed45eSdan KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); 2009fe1c6bb9Sdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, 2010fe1c6bb9Sdrh (char*)pKeyInfo, P4_KEYINFO); 2011fe1c6bb9Sdrh destQueue.pOrderBy = pOrderBy; 2012fe1c6bb9Sdrh }else{ 2013781def29Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); 2014fe1c6bb9Sdrh } 2015fe1c6bb9Sdrh VdbeComment((v, "Queue table")); 2016781def29Sdrh if( iDistinct ){ 2017781def29Sdrh p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); 2018781def29Sdrh p->selFlags |= SF_UsesEphemeral; 2019781def29Sdrh } 2020781def29Sdrh 202153bed45eSdan /* Detach the ORDER BY clause from the compound SELECT */ 202253bed45eSdan p->pOrderBy = 0; 202353bed45eSdan 2024781def29Sdrh /* Store the results of the setup-query in Queue. */ 2025d227a291Sdrh pSetup->pNext = 0; 2026781def29Sdrh rc = sqlite3Select(pParse, pSetup, &destQueue); 2027d227a291Sdrh pSetup->pNext = p; 2028fe1c6bb9Sdrh if( rc ) goto end_of_recursive_query; 2029781def29Sdrh 2030781def29Sdrh /* Find the next row in the Queue and output that row */ 2031688852abSdrh addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); 2032781def29Sdrh 2033781def29Sdrh /* Transfer the next row in Queue over to Current */ 2034781def29Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ 2035fe1c6bb9Sdrh if( pOrderBy ){ 2036fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); 2037fe1c6bb9Sdrh }else{ 2038781def29Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2039fe1c6bb9Sdrh } 2040781def29Sdrh sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2041781def29Sdrh 2042fe1c6bb9Sdrh /* Output the single row in Current */ 2043fe1c6bb9Sdrh addrCont = sqlite3VdbeMakeLabel(v); 2044aa9ce707Sdrh codeOffset(v, regOffset, addrCont); 2045fe1c6bb9Sdrh selectInnerLoop(pParse, p, p->pEList, iCurrent, 2046079a3072Sdrh 0, 0, pDest, addrCont, addrBreak); 2047688852abSdrh if( regLimit ){ 2048688852abSdrh sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1); 2049688852abSdrh VdbeCoverage(v); 2050688852abSdrh } 2051fe1c6bb9Sdrh sqlite3VdbeResolveLabel(v, addrCont); 2052fe1c6bb9Sdrh 2053781def29Sdrh /* Execute the recursive SELECT taking the single row in Current as 2054781def29Sdrh ** the value for the recursive-table. Store the results in the Queue. 2055781def29Sdrh */ 2056781def29Sdrh p->pPrior = 0; 2057781def29Sdrh sqlite3Select(pParse, p, &destQueue); 2058781def29Sdrh assert( p->pPrior==0 ); 2059781def29Sdrh p->pPrior = pSetup; 2060781def29Sdrh 2061781def29Sdrh /* Keep running the loop until the Queue is empty */ 2062781def29Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); 2063781def29Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 2064fe1c6bb9Sdrh 2065fe1c6bb9Sdrh end_of_recursive_query: 20669afccba2Sdan sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2067fe1c6bb9Sdrh p->pOrderBy = pOrderBy; 2068aa9ce707Sdrh p->pLimit = pLimit; 2069aa9ce707Sdrh p->pOffset = pOffset; 2070fe1c6bb9Sdrh return; 2071781def29Sdrh } 2072b68b9778Sdan #endif /* SQLITE_OMIT_CTE */ 2073781def29Sdrh 2074781def29Sdrh /* Forward references */ 2075b21e7c70Sdrh static int multiSelectOrderBy( 2076b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2077b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2078a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2079b21e7c70Sdrh ); 2080b21e7c70Sdrh 208145f54a57Sdrh /* 208245f54a57Sdrh ** Error message for when two or more terms of a compound select have different 208345f54a57Sdrh ** size result sets. 208445f54a57Sdrh */ 208545f54a57Sdrh static void selectWrongNumTermsError(Parse *pParse, Select *p){ 208645f54a57Sdrh if( p->selFlags & SF_Values ){ 208745f54a57Sdrh sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 208845f54a57Sdrh }else{ 208945f54a57Sdrh sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 209045f54a57Sdrh " do not have the same number of result columns", selectOpName(p->op)); 209145f54a57Sdrh } 209245f54a57Sdrh } 209345f54a57Sdrh 209445f54a57Sdrh /* 209545f54a57Sdrh ** Handle the special case of a compound-select that originates from a 209645f54a57Sdrh ** VALUES clause. By handling this as a special case, we avoid deep 209745f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT 209845f54a57Sdrh ** on a VALUES clause. 209945f54a57Sdrh ** 210045f54a57Sdrh ** Because the Select object originates from a VALUES clause: 210145f54a57Sdrh ** (1) It has no LIMIT or OFFSET 210245f54a57Sdrh ** (2) All terms are UNION ALL 210345f54a57Sdrh ** (3) There is no ORDER BY clause 210445f54a57Sdrh */ 210545f54a57Sdrh static int multiSelectValues( 210645f54a57Sdrh Parse *pParse, /* Parsing context */ 210745f54a57Sdrh Select *p, /* The right-most of SELECTs to be coded */ 210845f54a57Sdrh SelectDest *pDest /* What to do with query results */ 210945f54a57Sdrh ){ 211045f54a57Sdrh Select *pPrior; 211145f54a57Sdrh int nExpr = p->pEList->nExpr; 211245f54a57Sdrh int nRow = 1; 211345f54a57Sdrh int rc = 0; 211445f54a57Sdrh assert( p->pNext==0 ); 211545f54a57Sdrh assert( p->selFlags & SF_AllValues ); 211645f54a57Sdrh do{ 211745f54a57Sdrh assert( p->selFlags & SF_Values ); 211845f54a57Sdrh assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); 211945f54a57Sdrh assert( p->pLimit==0 ); 212045f54a57Sdrh assert( p->pOffset==0 ); 212145f54a57Sdrh if( p->pEList->nExpr!=nExpr ){ 212245f54a57Sdrh selectWrongNumTermsError(pParse, p); 212345f54a57Sdrh return 1; 212445f54a57Sdrh } 212545f54a57Sdrh if( p->pPrior==0 ) break; 212645f54a57Sdrh assert( p->pPrior->pNext==p ); 212745f54a57Sdrh p = p->pPrior; 212845f54a57Sdrh nRow++; 212945f54a57Sdrh }while(1); 213045f54a57Sdrh while( p ){ 213145f54a57Sdrh pPrior = p->pPrior; 213245f54a57Sdrh p->pPrior = 0; 213345f54a57Sdrh rc = sqlite3Select(pParse, p, pDest); 213445f54a57Sdrh p->pPrior = pPrior; 213545f54a57Sdrh if( rc ) break; 213645f54a57Sdrh p->nSelectRow = nRow; 213745f54a57Sdrh p = p->pNext; 213845f54a57Sdrh } 213945f54a57Sdrh return rc; 214045f54a57Sdrh } 2141b21e7c70Sdrh 2142d3d39e93Sdrh /* 214316ee60ffSdrh ** This routine is called to process a compound query form from 214416ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 214516ee60ffSdrh ** INTERSECT 2146c926afbcSdrh ** 2147e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 2148e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 2149e78e8284Sdrh ** in which case this routine will be called recursively. 2150e78e8284Sdrh ** 2151e78e8284Sdrh ** The results of the total query are to be written into a destination 2152e78e8284Sdrh ** of type eDest with parameter iParm. 2153e78e8284Sdrh ** 2154e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 2155e78e8284Sdrh ** 2156e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 2157e78e8284Sdrh ** 2158e78e8284Sdrh ** This statement is parsed up as follows: 2159e78e8284Sdrh ** 2160e78e8284Sdrh ** SELECT c FROM t3 2161e78e8284Sdrh ** | 2162e78e8284Sdrh ** `-----> SELECT b FROM t2 2163e78e8284Sdrh ** | 21644b11c6d3Sjplyon ** `------> SELECT a FROM t1 2165e78e8284Sdrh ** 2166e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 2167e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 2168e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 2169e78e8284Sdrh ** 2170e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 2171e78e8284Sdrh ** individual selects always group from left to right. 217282c3d636Sdrh */ 217384ac9d02Sdanielk1977 static int multiSelect( 2174fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 2175fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 2176a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 217784ac9d02Sdanielk1977 ){ 217884ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 217910e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 218010e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 21811013c932Sdrh SelectDest dest; /* Alternative data destination */ 2182eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 2183633e6d57Sdrh sqlite3 *db; /* Database connection */ 21847f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 2185edf83d1eSdrh int iSub1 = 0; /* EQP id of left-hand query */ 2186edf83d1eSdrh int iSub2 = 0; /* EQP id of right-hand query */ 21877f61e92cSdan #endif 218882c3d636Sdrh 21897b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 2190fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 219182c3d636Sdrh */ 2192701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 2193eae73fbfSdan assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); 2194633e6d57Sdrh db = pParse->db; 2195d8bc7086Sdrh pPrior = p->pPrior; 2196bc10377aSdrh dest = *pDest; 2197d8bc7086Sdrh if( pPrior->pOrderBy ){ 21984adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 2199da93d238Sdrh selectOpName(p->op)); 220084ac9d02Sdanielk1977 rc = 1; 220184ac9d02Sdanielk1977 goto multi_select_end; 220282c3d636Sdrh } 2203a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 22044adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 22057b58daeaSdrh selectOpName(p->op)); 220684ac9d02Sdanielk1977 rc = 1; 220784ac9d02Sdanielk1977 goto multi_select_end; 22087b58daeaSdrh } 220982c3d636Sdrh 22104adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2211701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 2212d8bc7086Sdrh 22131cc3d75fSdrh /* Create the destination temporary table if necessary 22141cc3d75fSdrh */ 22156c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 2216b4964b72Sdanielk1977 assert( p->pEList ); 22172b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 2218d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 22196c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 22201cc3d75fSdrh } 22211cc3d75fSdrh 222245f54a57Sdrh /* Special handling for a compound-select that originates as a VALUES clause. 222345f54a57Sdrh */ 222445f54a57Sdrh if( p->selFlags & SF_AllValues ){ 222545f54a57Sdrh rc = multiSelectValues(pParse, p, &dest); 222645f54a57Sdrh goto multi_select_end; 222745f54a57Sdrh } 222845f54a57Sdrh 2229f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 2230f6e369a1Sdrh ** in their result sets. 2231f6e369a1Sdrh */ 2232f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 2233f6e369a1Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 223445f54a57Sdrh selectWrongNumTermsError(pParse, p); 2235f6e369a1Sdrh rc = 1; 2236f6e369a1Sdrh goto multi_select_end; 2237f6e369a1Sdrh } 2238f6e369a1Sdrh 2239eede6a53Sdan #ifndef SQLITE_OMIT_CTE 2240eae73fbfSdan if( p->selFlags & SF_Recursive ){ 2241781def29Sdrh generateWithRecursiveQuery(pParse, p, &dest); 22428ce7184bSdan }else 22438ce7184bSdan #endif 22448ce7184bSdan 2245a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 2246a9671a22Sdrh */ 2247f6e369a1Sdrh if( p->pOrderBy ){ 2248a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 2249eede6a53Sdan }else 2250f6e369a1Sdrh 2251f46f905aSdrh /* Generate code for the left and right SELECT statements. 2252d8bc7086Sdrh */ 225382c3d636Sdrh switch( p->op ){ 2254f46f905aSdrh case TK_ALL: { 2255ec7429aeSdrh int addr = 0; 225695aa47b1Sdrh int nLimit; 2257a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 2258547180baSdrh pPrior->iLimit = p->iLimit; 2259547180baSdrh pPrior->iOffset = p->iOffset; 2260a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 2261a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 22627f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 22637d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 2264ad68cb6bSdanielk1977 p->pLimit = 0; 2265ad68cb6bSdanielk1977 p->pOffset = 0; 226684ac9d02Sdanielk1977 if( rc ){ 226784ac9d02Sdanielk1977 goto multi_select_end; 226884ac9d02Sdanielk1977 } 2269f46f905aSdrh p->pPrior = 0; 22707b58daeaSdrh p->iLimit = pPrior->iLimit; 22717b58daeaSdrh p->iOffset = pPrior->iOffset; 227292b01d53Sdrh if( p->iLimit ){ 2273688852abSdrh addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v); 2274d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 2275ec7429aeSdrh } 22767f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 22777d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 2278373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2279eca7e01aSdanielk1977 pDelete = p->pPrior; 2280f46f905aSdrh p->pPrior = pPrior; 228195aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 228295aa47b1Sdrh if( pPrior->pLimit 228395aa47b1Sdrh && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) 2284613ba1eaSdrh && nLimit>0 && p->nSelectRow > (u64)nLimit 228595aa47b1Sdrh ){ 2286c63367efSdrh p->nSelectRow = nLimit; 228795aa47b1Sdrh } 2288ec7429aeSdrh if( addr ){ 2289ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 2290ec7429aeSdrh } 2291f46f905aSdrh break; 2292f46f905aSdrh } 229382c3d636Sdrh case TK_EXCEPT: 229482c3d636Sdrh case TK_UNION: { 2295d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 2296ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 2297d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 2298a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 2299dc1bdc4fSdanielk1977 int addr; 23006c8c8ce0Sdanielk1977 SelectDest uniondest; 230182c3d636Sdrh 2302373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 2303373cc2ddSdrh testcase( p->op==TK_UNION ); 230493a960a0Sdrh priorOp = SRT_Union; 2305d227a291Sdrh if( dest.eDest==priorOp ){ 2306d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 2307c926afbcSdrh ** right. 2308d8bc7086Sdrh */ 2309e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 2310e2f02bacSdrh assert( p->pOffset==0 ); /* Not allowed on leftward elements */ 23112b596da8Sdrh unionTab = dest.iSDParm; 231282c3d636Sdrh }else{ 2313d8bc7086Sdrh /* We will need to create our own temporary table to hold the 2314d8bc7086Sdrh ** intermediate results. 2315d8bc7086Sdrh */ 231682c3d636Sdrh unionTab = pParse->nTab++; 231793a960a0Sdrh assert( p->pOrderBy==0 ); 231866a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2319b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2320b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2321d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 232284ac9d02Sdanielk1977 assert( p->pEList ); 2323d8bc7086Sdrh } 2324d8bc7086Sdrh 2325d8bc7086Sdrh /* Code the SELECT statements to our left 2326d8bc7086Sdrh */ 2327b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 23281013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 23297f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 23307d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 233184ac9d02Sdanielk1977 if( rc ){ 233284ac9d02Sdanielk1977 goto multi_select_end; 233384ac9d02Sdanielk1977 } 2334d8bc7086Sdrh 2335d8bc7086Sdrh /* Code the current SELECT statement 2336d8bc7086Sdrh */ 23374cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 23384cfb22f7Sdrh op = SRT_Except; 23394cfb22f7Sdrh }else{ 23404cfb22f7Sdrh assert( p->op==TK_UNION ); 23414cfb22f7Sdrh op = SRT_Union; 2342d8bc7086Sdrh } 234382c3d636Sdrh p->pPrior = 0; 2344a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2345a2dc3b1aSdanielk1977 p->pLimit = 0; 2346a2dc3b1aSdanielk1977 pOffset = p->pOffset; 2347a2dc3b1aSdanielk1977 p->pOffset = 0; 23486c8c8ce0Sdanielk1977 uniondest.eDest = op; 23497f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 23507d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 2351373cc2ddSdrh testcase( rc!=SQLITE_OK ); 23525bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 23535bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 2354633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 2355eca7e01aSdanielk1977 pDelete = p->pPrior; 235682c3d636Sdrh p->pPrior = pPrior; 2357a9671a22Sdrh p->pOrderBy = 0; 235895aa47b1Sdrh if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow; 2359633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2360a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2361a2dc3b1aSdanielk1977 p->pOffset = pOffset; 236292b01d53Sdrh p->iLimit = 0; 236392b01d53Sdrh p->iOffset = 0; 2364d8bc7086Sdrh 2365d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2366d8bc7086Sdrh ** it is that we currently need. 2367d8bc7086Sdrh */ 23682b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2369373cc2ddSdrh if( dest.eDest!=priorOp ){ 23706b56344dSdrh int iCont, iBreak, iStart; 237182c3d636Sdrh assert( p->pEList ); 23727d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 237392378253Sdrh Select *pFirst = p; 237492378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 237592378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 237641202ccaSdrh } 23774adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 23784adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2379ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2380688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 23814adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 2382340309fdSdrh selectInnerLoop(pParse, p, p->pEList, unionTab, 2383079a3072Sdrh 0, 0, &dest, iCont, iBreak); 23844adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2385688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 23864adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 238766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 238882c3d636Sdrh } 238982c3d636Sdrh break; 239082c3d636Sdrh } 2391373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 239282c3d636Sdrh int tab1, tab2; 23936b56344dSdrh int iCont, iBreak, iStart; 2394a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 2395dc1bdc4fSdanielk1977 int addr; 23961013c932Sdrh SelectDest intersectdest; 23979cbf3425Sdrh int r1; 239882c3d636Sdrh 2399d8bc7086Sdrh /* INTERSECT is different from the others since it requires 24006206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2401d8bc7086Sdrh ** by allocating the tables we will need. 2402d8bc7086Sdrh */ 240382c3d636Sdrh tab1 = pParse->nTab++; 240482c3d636Sdrh tab2 = pParse->nTab++; 240593a960a0Sdrh assert( p->pOrderBy==0 ); 2406dc1bdc4fSdanielk1977 240766a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2408b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2409b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2410d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 241184ac9d02Sdanielk1977 assert( p->pEList ); 2412d8bc7086Sdrh 2413d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2414d8bc7086Sdrh */ 24151013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 24167f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 24177d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 241884ac9d02Sdanielk1977 if( rc ){ 241984ac9d02Sdanielk1977 goto multi_select_end; 242084ac9d02Sdanielk1977 } 2421d8bc7086Sdrh 2422d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2423d8bc7086Sdrh */ 242466a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2425b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2426b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 242782c3d636Sdrh p->pPrior = 0; 2428a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2429a2dc3b1aSdanielk1977 p->pLimit = 0; 2430a2dc3b1aSdanielk1977 pOffset = p->pOffset; 2431a2dc3b1aSdanielk1977 p->pOffset = 0; 24322b596da8Sdrh intersectdest.iSDParm = tab2; 24337f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 24347d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 2435373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2436eca7e01aSdanielk1977 pDelete = p->pPrior; 243782c3d636Sdrh p->pPrior = pPrior; 243895aa47b1Sdrh if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 2439633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2440a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2441a2dc3b1aSdanielk1977 p->pOffset = pOffset; 2442d8bc7086Sdrh 2443d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 2444d8bc7086Sdrh ** tables. 2445d8bc7086Sdrh */ 244682c3d636Sdrh assert( p->pEList ); 24477d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 244892378253Sdrh Select *pFirst = p; 244992378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 245092378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 245141202ccaSdrh } 24524adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 24534adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2454ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2455688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); 24569cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 24579cbf3425Sdrh iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 2458688852abSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); 24599cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 2460340309fdSdrh selectInnerLoop(pParse, p, p->pEList, tab1, 2461079a3072Sdrh 0, 0, &dest, iCont, iBreak); 24624adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2463688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); 24644adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 246566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 246666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 246782c3d636Sdrh break; 246882c3d636Sdrh } 246982c3d636Sdrh } 24708cdbf836Sdrh 24717f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); 24727f61e92cSdan 2473a9671a22Sdrh /* Compute collating sequences used by 2474a9671a22Sdrh ** temporary tables needed to implement the compound select. 2475a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 24768cdbf836Sdrh ** 24778cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 24788cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 24798cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 24808cdbf836Sdrh ** no temp tables are required. 2481fbc4ee7bSdrh */ 24827d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 2483fbc4ee7bSdrh int i; /* Loop counter */ 2484fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 24850342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 2486f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 248793a960a0Sdrh int nCol; /* Number of columns in result set */ 2488fbc4ee7bSdrh 2489d227a291Sdrh assert( p->pNext==0 ); 249093a960a0Sdrh nCol = p->pEList->nExpr; 2491ad124329Sdrh pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); 2492dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 2493dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 2494dc1bdc4fSdanielk1977 goto multi_select_end; 2495dc1bdc4fSdanielk1977 } 24960342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 24970342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 24980342b1f5Sdrh if( 0==*apColl ){ 2499633e6d57Sdrh *apColl = db->pDfltColl; 2500dc1bdc4fSdanielk1977 } 2501dc1bdc4fSdanielk1977 } 2502dc1bdc4fSdanielk1977 25030342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 25040342b1f5Sdrh for(i=0; i<2; i++){ 2505b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 25060342b1f5Sdrh if( addr<0 ){ 25070342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 25080342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 2509b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 25100342b1f5Sdrh break; 25110342b1f5Sdrh } 25120342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 25132ec2fb22Sdrh sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), 25142ec2fb22Sdrh P4_KEYINFO); 25150ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 25160342b1f5Sdrh } 2517dc1bdc4fSdanielk1977 } 25182ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyInfo); 2519dc1bdc4fSdanielk1977 } 2520dc1bdc4fSdanielk1977 2521dc1bdc4fSdanielk1977 multi_select_end: 25222b596da8Sdrh pDest->iSdst = dest.iSdst; 25232b596da8Sdrh pDest->nSdst = dest.nSdst; 2524633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 252584ac9d02Sdanielk1977 return rc; 25262282792aSdrh } 2527b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 25282282792aSdrh 2529b21e7c70Sdrh /* 2530b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 2531b21e7c70Sdrh ** SELECT statment. 25320acb7e48Sdrh ** 25332b596da8Sdrh ** The data to be output is contained in pIn->iSdst. There are 25342b596da8Sdrh ** pIn->nSdst columns to be output. pDest is where the output should 25350acb7e48Sdrh ** be sent. 25360acb7e48Sdrh ** 25370acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 25380acb7e48Sdrh ** return address. 25390acb7e48Sdrh ** 2540f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 25410acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 25420acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 25430acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 25440acb7e48Sdrh ** keys. 25450acb7e48Sdrh ** 25460acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 25470acb7e48Sdrh ** iBreak. 2548b21e7c70Sdrh */ 25490acb7e48Sdrh static int generateOutputSubroutine( 255092b01d53Sdrh Parse *pParse, /* Parsing context */ 255192b01d53Sdrh Select *p, /* The SELECT statement */ 255292b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 255392b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 255492b01d53Sdrh int regReturn, /* The return address register */ 25550acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 25560acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 255792b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 2558b21e7c70Sdrh ){ 2559b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 256092b01d53Sdrh int iContinue; 256192b01d53Sdrh int addr; 2562b21e7c70Sdrh 256392b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 256492b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 25650acb7e48Sdrh 25660acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 25670acb7e48Sdrh */ 25680acb7e48Sdrh if( regPrev ){ 25690acb7e48Sdrh int j1, j2; 2570688852abSdrh j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); 25712b596da8Sdrh j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 25722ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 2573688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v); 25740acb7e48Sdrh sqlite3VdbeJumpHere(v, j1); 2575e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 2576ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 25770acb7e48Sdrh } 25781f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 25790acb7e48Sdrh 2580d5578433Smistachkin /* Suppress the first OFFSET entries if there is an OFFSET clause 25810acb7e48Sdrh */ 2582aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 2583b21e7c70Sdrh 2584b21e7c70Sdrh switch( pDest->eDest ){ 2585b21e7c70Sdrh /* Store the result as data using a unique key. 2586b21e7c70Sdrh */ 2587b21e7c70Sdrh case SRT_Table: 2588b21e7c70Sdrh case SRT_EphemTab: { 2589b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 2590b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 2591373cc2ddSdrh testcase( pDest->eDest==SRT_Table ); 2592373cc2ddSdrh testcase( pDest->eDest==SRT_EphemTab ); 25932b596da8Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 25942b596da8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 25952b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 2596b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2597b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 2598b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2599b21e7c70Sdrh break; 2600b21e7c70Sdrh } 2601b21e7c70Sdrh 2602b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 2603b21e7c70Sdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 2604b21e7c70Sdrh ** then there should be a single item on the stack. Write this 2605b21e7c70Sdrh ** item into the set table with bogus data. 2606b21e7c70Sdrh */ 2607b21e7c70Sdrh case SRT_Set: { 26086fccc35aSdrh int r1; 26092b596da8Sdrh assert( pIn->nSdst==1 ); 2610634d81deSdrh pDest->affSdst = 26112b596da8Sdrh sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst); 2612b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 2613634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1); 26142b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1); 26152b596da8Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1); 2616b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2617b21e7c70Sdrh break; 2618b21e7c70Sdrh } 2619b21e7c70Sdrh 262085e9e22bSdrh #if 0 /* Never occurs on an ORDER BY query */ 2621b21e7c70Sdrh /* If any row exist in the result set, record that fact and abort. 2622b21e7c70Sdrh */ 2623b21e7c70Sdrh case SRT_Exists: { 26242b596da8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm); 2625b21e7c70Sdrh /* The LIMIT clause will terminate the loop for us */ 2626b21e7c70Sdrh break; 2627b21e7c70Sdrh } 262885e9e22bSdrh #endif 2629b21e7c70Sdrh 2630b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2631b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2632b21e7c70Sdrh ** of the scan loop. 2633b21e7c70Sdrh */ 2634b21e7c70Sdrh case SRT_Mem: { 26352b596da8Sdrh assert( pIn->nSdst==1 ); 26362b596da8Sdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); 2637b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 2638b21e7c70Sdrh break; 2639b21e7c70Sdrh } 2640b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2641b21e7c70Sdrh 26427d10d5a6Sdrh /* The results are stored in a sequence of registers 26432b596da8Sdrh ** starting at pDest->iSdst. Then the co-routine yields. 2644b21e7c70Sdrh */ 264592b01d53Sdrh case SRT_Coroutine: { 26462b596da8Sdrh if( pDest->iSdst==0 ){ 26472b596da8Sdrh pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 26482b596da8Sdrh pDest->nSdst = pIn->nSdst; 2649b21e7c70Sdrh } 26502b596da8Sdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst); 26512b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 265292b01d53Sdrh break; 265392b01d53Sdrh } 265492b01d53Sdrh 2655ccfcbceaSdrh /* If none of the above, then the result destination must be 2656ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2657ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2658ccfcbceaSdrh ** 2659ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2660ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2661ccfcbceaSdrh ** return the next row of result. 26627d10d5a6Sdrh */ 2663ccfcbceaSdrh default: { 2664ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 26652b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 26662b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 2667b21e7c70Sdrh break; 2668b21e7c70Sdrh } 2669b21e7c70Sdrh } 267092b01d53Sdrh 267192b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 267292b01d53Sdrh */ 267392b01d53Sdrh if( p->iLimit ){ 2674688852abSdrh sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v); 267592b01d53Sdrh } 267692b01d53Sdrh 267792b01d53Sdrh /* Generate the subroutine return 267892b01d53Sdrh */ 26790acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 268092b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 268192b01d53Sdrh 268292b01d53Sdrh return addr; 2683b21e7c70Sdrh } 2684b21e7c70Sdrh 2685b21e7c70Sdrh /* 2686b21e7c70Sdrh ** Alternative compound select code generator for cases when there 2687b21e7c70Sdrh ** is an ORDER BY clause. 2688b21e7c70Sdrh ** 2689b21e7c70Sdrh ** We assume a query of the following form: 2690b21e7c70Sdrh ** 2691b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 2692b21e7c70Sdrh ** 2693b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 2694b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 2695b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 2696b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 2697b21e7c70Sdrh ** selectB) there are 7 subroutines: 2698b21e7c70Sdrh ** 2699b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 2700b21e7c70Sdrh ** of the compound query. 2701b21e7c70Sdrh ** 2702b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 2703b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 2704b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 2705b21e7c70Sdrh ** appears only in B.) 2706b21e7c70Sdrh ** 2707b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 2708b21e7c70Sdrh ** 2709b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 2710b21e7c70Sdrh ** 2711b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 2712b21e7c70Sdrh ** 2713b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 2714b21e7c70Sdrh ** 2715b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 2716b21e7c70Sdrh ** 2717b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 2718b21e7c70Sdrh ** <operator> is used: 2719b21e7c70Sdrh ** 2720b21e7c70Sdrh ** 2721b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 2722b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 2723b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 2724b21e7c70Sdrh ** 27250acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 2726b21e7c70Sdrh ** 2727b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 2728b21e7c70Sdrh ** 27290acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 2730b21e7c70Sdrh ** 27310acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 27320acb7e48Sdrh ** 27330acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 27340acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 27350acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 27360acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 27370acb7e48Sdrh ** 27380acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 27390acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 27400acb7e48Sdrh ** output value. A comparison is made against this value and the output 27410acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 2742b21e7c70Sdrh ** 2743b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 2744b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 2745b21e7c70Sdrh ** 2746b21e7c70Sdrh ** goto Init 2747b21e7c70Sdrh ** coA: coroutine for left query (A) 2748b21e7c70Sdrh ** coB: coroutine for right query (B) 2749b21e7c70Sdrh ** outA: output one row of A 2750b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 2751b21e7c70Sdrh ** EofA: ... 2752b21e7c70Sdrh ** EofB: ... 2753b21e7c70Sdrh ** AltB: ... 2754b21e7c70Sdrh ** AeqB: ... 2755b21e7c70Sdrh ** AgtB: ... 2756b21e7c70Sdrh ** Init: initialize coroutine registers 2757b21e7c70Sdrh ** yield coA 2758b21e7c70Sdrh ** if eof(A) goto EofA 2759b21e7c70Sdrh ** yield coB 2760b21e7c70Sdrh ** if eof(B) goto EofB 2761b21e7c70Sdrh ** Cmpr: Compare A, B 2762b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 2763b21e7c70Sdrh ** End: ... 2764b21e7c70Sdrh ** 2765b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 2766b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 2767b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 2768b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 2769b21e7c70Sdrh */ 2770de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 2771b21e7c70Sdrh static int multiSelectOrderBy( 2772b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2773b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2774a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2775b21e7c70Sdrh ){ 27760acb7e48Sdrh int i, j; /* Loop counters */ 2777b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 2778b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 2779b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 2780b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 278192b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 278292b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 278392b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 278492b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 278592b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 278692b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 278792b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 2788b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 278992b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 279081cf13ecSdrh int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ 279192b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 279292b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 279392b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 279492b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 279592b01d53Sdrh int regLimitA; /* Limit register for select-A */ 279692b01d53Sdrh int regLimitB; /* Limit register for select-A */ 27970acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 279892b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 279992b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 280092b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 280192b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 28020acb7e48Sdrh int j1; /* Jump instructions that get retargetted */ 280392b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 280496067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 28050acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 28060acb7e48Sdrh sqlite3 *db; /* Database connection */ 28070acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 28080acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 28090acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 28107f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 28117f61e92cSdan int iSub1; /* EQP id of left-hand query */ 28127f61e92cSdan int iSub2; /* EQP id of right-hand query */ 28137f61e92cSdan #endif 2814b21e7c70Sdrh 281592b01d53Sdrh assert( p->pOrderBy!=0 ); 281696067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 28170acb7e48Sdrh db = pParse->db; 281892b01d53Sdrh v = pParse->pVdbe; 2819ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 282092b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 282192b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 28220acb7e48Sdrh 2823b21e7c70Sdrh 282492b01d53Sdrh /* Patch up the ORDER BY clause 282592b01d53Sdrh */ 282692b01d53Sdrh op = p->op; 2827b21e7c70Sdrh pPrior = p->pPrior; 282892b01d53Sdrh assert( pPrior->pOrderBy==0 ); 28290acb7e48Sdrh pOrderBy = p->pOrderBy; 283093a960a0Sdrh assert( pOrderBy ); 28310acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 283293a960a0Sdrh 28330acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 28340acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 28350acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 28360acb7e48Sdrh */ 28370acb7e48Sdrh if( op!=TK_ALL ){ 28380acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 28397d10d5a6Sdrh struct ExprList_item *pItem; 28407d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 2841c2acc4e4Sdrh assert( pItem->u.x.iOrderByCol>0 ); 2842c2acc4e4Sdrh if( pItem->u.x.iOrderByCol==i ) break; 28430acb7e48Sdrh } 28440acb7e48Sdrh if( j==nOrderBy ){ 2845b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 28460acb7e48Sdrh if( pNew==0 ) return SQLITE_NOMEM; 28470acb7e48Sdrh pNew->flags |= EP_IntValue; 284833e619fcSdrh pNew->u.iValue = i; 2849b7916a78Sdrh pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 2850c2acc4e4Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; 28510acb7e48Sdrh } 28520acb7e48Sdrh } 28530acb7e48Sdrh } 28540acb7e48Sdrh 28550acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 285610c081adSdrh ** the permutation used to determine if the next 28570acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 28580acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 28590acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 28600acb7e48Sdrh ** collation. 28610acb7e48Sdrh */ 28620acb7e48Sdrh aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); 28630acb7e48Sdrh if( aPermute ){ 28647d10d5a6Sdrh struct ExprList_item *pItem; 28657d10d5a6Sdrh for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){ 2866c2acc4e4Sdrh assert( pItem->u.x.iOrderByCol>0 2867c2acc4e4Sdrh && pItem->u.x.iOrderByCol<=p->pEList->nExpr ); 2868c2acc4e4Sdrh aPermute[i] = pItem->u.x.iOrderByCol - 1; 28690acb7e48Sdrh } 287053bed45eSdan pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); 28710acb7e48Sdrh }else{ 28720acb7e48Sdrh pKeyMerge = 0; 28730acb7e48Sdrh } 28740acb7e48Sdrh 28750acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 28760acb7e48Sdrh */ 28770acb7e48Sdrh p->pOrderBy = pOrderBy; 28786ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 28790acb7e48Sdrh 28800acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 28810acb7e48Sdrh ** for the logic that removes duplicate result rows when the 28820acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 28830acb7e48Sdrh */ 28840acb7e48Sdrh if( op==TK_ALL ){ 28850acb7e48Sdrh regPrev = 0; 28860acb7e48Sdrh }else{ 28870acb7e48Sdrh int nExpr = p->pEList->nExpr; 28881c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 2889c8ac0d16Sdrh regPrev = pParse->nMem+1; 2890c8ac0d16Sdrh pParse->nMem += nExpr+1; 28910acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 2892ad124329Sdrh pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); 28930acb7e48Sdrh if( pKeyDup ){ 28942ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); 28950acb7e48Sdrh for(i=0; i<nExpr; i++){ 28960acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 28970acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 28980acb7e48Sdrh } 28990acb7e48Sdrh } 29000acb7e48Sdrh } 290192b01d53Sdrh 290292b01d53Sdrh /* Separate the left and the right query from one another 290392b01d53Sdrh */ 290492b01d53Sdrh p->pPrior = 0; 2905d227a291Sdrh pPrior->pNext = 0; 29067d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 29070acb7e48Sdrh if( pPrior->pPrior==0 ){ 29087d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 29090acb7e48Sdrh } 291092b01d53Sdrh 291192b01d53Sdrh /* Compute the limit registers */ 291292b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 29130acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 291492b01d53Sdrh regLimitA = ++pParse->nMem; 291592b01d53Sdrh regLimitB = ++pParse->nMem; 291692b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 291792b01d53Sdrh regLimitA); 291892b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 291992b01d53Sdrh }else{ 292092b01d53Sdrh regLimitA = regLimitB = 0; 292192b01d53Sdrh } 2922633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 29230acb7e48Sdrh p->pLimit = 0; 2924633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 29250acb7e48Sdrh p->pOffset = 0; 292692b01d53Sdrh 2927b21e7c70Sdrh regAddrA = ++pParse->nMem; 2928b21e7c70Sdrh regAddrB = ++pParse->nMem; 2929b21e7c70Sdrh regOutA = ++pParse->nMem; 2930b21e7c70Sdrh regOutB = ++pParse->nMem; 2931b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 2932b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 2933b21e7c70Sdrh 293492b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 29350acb7e48Sdrh ** left of the compound operator - the "A" select. 29360acb7e48Sdrh */ 2937ed71a839Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; 2938ed71a839Sdrh j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); 2939ed71a839Sdrh VdbeComment((v, "left SELECT")); 294092b01d53Sdrh pPrior->iLimit = regLimitA; 29417f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 29427d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 294381cf13ecSdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA); 2944ed71a839Sdrh sqlite3VdbeJumpHere(v, j1); 2945b21e7c70Sdrh 294692b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 294792b01d53Sdrh ** the right - the "B" select 294892b01d53Sdrh */ 2949ed71a839Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; 2950ed71a839Sdrh j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); 2951ed71a839Sdrh VdbeComment((v, "right SELECT")); 295292b01d53Sdrh savedLimit = p->iLimit; 295392b01d53Sdrh savedOffset = p->iOffset; 295492b01d53Sdrh p->iLimit = regLimitB; 295592b01d53Sdrh p->iOffset = 0; 29567f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 29577d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 295892b01d53Sdrh p->iLimit = savedLimit; 295992b01d53Sdrh p->iOffset = savedOffset; 296081cf13ecSdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB); 2961b21e7c70Sdrh 296292b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 29630acb7e48Sdrh ** select as the next output row of the compound select. 296492b01d53Sdrh */ 2965b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 29660acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 29670acb7e48Sdrh p, &destA, pDest, regOutA, 29682ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 2969b21e7c70Sdrh 297092b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 29710acb7e48Sdrh ** select as the next output row of the compound select. 297292b01d53Sdrh */ 29730acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 2974b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 29750acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 29760acb7e48Sdrh p, &destB, pDest, regOutB, 29772ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 29780acb7e48Sdrh } 29792ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyDup); 2980b21e7c70Sdrh 298192b01d53Sdrh /* Generate a subroutine to run when the results from select A 298292b01d53Sdrh ** are exhausted and only data in select B remains. 298392b01d53Sdrh */ 298492b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 298581cf13ecSdrh addrEofA_noB = addrEofA = labelEnd; 298692b01d53Sdrh }else{ 298781cf13ecSdrh VdbeNoopComment((v, "eof-A subroutine")); 298881cf13ecSdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 298981cf13ecSdrh addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); 2990688852abSdrh VdbeCoverage(v); 29910acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); 299295aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 2993b21e7c70Sdrh } 2994b21e7c70Sdrh 299592b01d53Sdrh /* Generate a subroutine to run when the results from select B 299692b01d53Sdrh ** are exhausted and only data in select A remains. 299792b01d53Sdrh */ 2998b21e7c70Sdrh if( op==TK_INTERSECT ){ 299992b01d53Sdrh addrEofB = addrEofA; 300095aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 3001b21e7c70Sdrh }else{ 300292b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 300381cf13ecSdrh addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3004688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); 30050acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); 3006b21e7c70Sdrh } 3007b21e7c70Sdrh 300892b01d53Sdrh /* Generate code to handle the case of A<B 300992b01d53Sdrh */ 3010b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 30110acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3012688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 301392b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 3014b21e7c70Sdrh 301592b01d53Sdrh /* Generate code to handle the case of A==B 301692b01d53Sdrh */ 3017b21e7c70Sdrh if( op==TK_ALL ){ 3018b21e7c70Sdrh addrAeqB = addrAltB; 30190acb7e48Sdrh }else if( op==TK_INTERSECT ){ 30200acb7e48Sdrh addrAeqB = addrAltB; 30210acb7e48Sdrh addrAltB++; 302292b01d53Sdrh }else{ 3023b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 30240acb7e48Sdrh addrAeqB = 3025688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 302692b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 302792b01d53Sdrh } 3028b21e7c70Sdrh 302992b01d53Sdrh /* Generate code to handle the case of A>B 303092b01d53Sdrh */ 3031b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 3032b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 3033b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 3034b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 303592b01d53Sdrh } 3036688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 303792b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); 3038b21e7c70Sdrh 303992b01d53Sdrh /* This code runs once to initialize everything. 304092b01d53Sdrh */ 3041b21e7c70Sdrh sqlite3VdbeJumpHere(v, j1); 3042688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); 3043688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 304492b01d53Sdrh 304592b01d53Sdrh /* Implement the main merge loop 304692b01d53Sdrh */ 304792b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 30480acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 30492b596da8Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 30502ec2fb22Sdrh (char*)pKeyMerge, P4_KEYINFO); 3051953f7611Sdrh sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); 3052688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); 305392b01d53Sdrh 305492b01d53Sdrh /* Jump to the this point in order to terminate the query. 305592b01d53Sdrh */ 3056b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 3057b21e7c70Sdrh 305892b01d53Sdrh /* Set the number of output columns 305992b01d53Sdrh */ 30607d10d5a6Sdrh if( pDest->eDest==SRT_Output ){ 30610acb7e48Sdrh Select *pFirst = pPrior; 306292b01d53Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 306392b01d53Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 3064b21e7c70Sdrh } 306592b01d53Sdrh 30660acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 30670acb7e48Sdrh ** by the calling function */ 30685e7ad508Sdanielk1977 if( p->pPrior ){ 3069633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 30705e7ad508Sdanielk1977 } 30710acb7e48Sdrh p->pPrior = pPrior; 3072d227a291Sdrh pPrior->pNext = p; 307392b01d53Sdrh 307492b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 307592b01d53Sdrh **** subqueries ****/ 30767f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, 0); 307792b01d53Sdrh return SQLITE_OK; 307892b01d53Sdrh } 3079de3e41e3Sdanielk1977 #endif 3080b21e7c70Sdrh 30813514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 308217435752Sdrh /* Forward Declarations */ 308317435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*); 308417435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *); 308517435752Sdrh 30862282792aSdrh /* 3087832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 30886a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 308984e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 30906a3ea0e6Sdrh ** unchanged.) 3091832508b7Sdrh ** 3092832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 3093832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 3094832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 3095832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 3096832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 3097832508b7Sdrh ** of the subquery rather the result set of the subquery. 3098832508b7Sdrh */ 3099b7916a78Sdrh static Expr *substExpr( 310017435752Sdrh sqlite3 *db, /* Report malloc errors to this connection */ 310117435752Sdrh Expr *pExpr, /* Expr in which substitution occurs */ 310217435752Sdrh int iTable, /* Table to be substituted */ 310317435752Sdrh ExprList *pEList /* Substitute expressions */ 310417435752Sdrh ){ 3105b7916a78Sdrh if( pExpr==0 ) return 0; 310650350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 310750350a15Sdrh if( pExpr->iColumn<0 ){ 310850350a15Sdrh pExpr->op = TK_NULL; 310950350a15Sdrh }else{ 3110832508b7Sdrh Expr *pNew; 311184e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 31126ab3a2ecSdanielk1977 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 3113b7916a78Sdrh pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); 3114b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 3115b7916a78Sdrh pExpr = pNew; 311650350a15Sdrh } 3117832508b7Sdrh }else{ 3118b7916a78Sdrh pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); 3119b7916a78Sdrh pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); 31206ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 31216ab3a2ecSdanielk1977 substSelect(db, pExpr->x.pSelect, iTable, pEList); 31226ab3a2ecSdanielk1977 }else{ 31236ab3a2ecSdanielk1977 substExprList(db, pExpr->x.pList, iTable, pEList); 31246ab3a2ecSdanielk1977 } 3125832508b7Sdrh } 3126b7916a78Sdrh return pExpr; 3127832508b7Sdrh } 312817435752Sdrh static void substExprList( 312917435752Sdrh sqlite3 *db, /* Report malloc errors here */ 313017435752Sdrh ExprList *pList, /* List to scan and in which to make substitutes */ 313117435752Sdrh int iTable, /* Table to be substituted */ 313217435752Sdrh ExprList *pEList /* Substitute values */ 313317435752Sdrh ){ 3134832508b7Sdrh int i; 3135832508b7Sdrh if( pList==0 ) return; 3136832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 3137b7916a78Sdrh pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); 3138832508b7Sdrh } 3139832508b7Sdrh } 314017435752Sdrh static void substSelect( 314117435752Sdrh sqlite3 *db, /* Report malloc errors here */ 314217435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 314317435752Sdrh int iTable, /* Table to be replaced */ 314417435752Sdrh ExprList *pEList /* Substitute values */ 314517435752Sdrh ){ 3146588a9a1aSdrh SrcList *pSrc; 3147588a9a1aSdrh struct SrcList_item *pItem; 3148588a9a1aSdrh int i; 3149b3bce662Sdanielk1977 if( !p ) return; 315017435752Sdrh substExprList(db, p->pEList, iTable, pEList); 315117435752Sdrh substExprList(db, p->pGroupBy, iTable, pEList); 315217435752Sdrh substExprList(db, p->pOrderBy, iTable, pEList); 3153b7916a78Sdrh p->pHaving = substExpr(db, p->pHaving, iTable, pEList); 3154b7916a78Sdrh p->pWhere = substExpr(db, p->pWhere, iTable, pEList); 315517435752Sdrh substSelect(db, p->pPrior, iTable, pEList); 3156588a9a1aSdrh pSrc = p->pSrc; 3157e2f02bacSdrh assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ 3158e2f02bacSdrh if( ALWAYS(pSrc) ){ 3159588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 3160588a9a1aSdrh substSelect(db, pItem->pSelect, iTable, pEList); 3161588a9a1aSdrh } 3162588a9a1aSdrh } 3163b3bce662Sdanielk1977 } 31643514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3165832508b7Sdrh 31663514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3167832508b7Sdrh /* 3168630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 3169630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 31701350b030Sdrh ** 31711350b030Sdrh ** To understand the concept of flattening, consider the following 31721350b030Sdrh ** query: 31731350b030Sdrh ** 31741350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 31751350b030Sdrh ** 31761350b030Sdrh ** The default way of implementing this query is to execute the 31771350b030Sdrh ** subquery first and store the results in a temporary table, then 31781350b030Sdrh ** run the outer query on that temporary table. This requires two 31791350b030Sdrh ** passes over the data. Furthermore, because the temporary table 31801350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 3181832508b7Sdrh ** optimized. 31821350b030Sdrh ** 3183832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 31841350b030Sdrh ** a single flat select, like this: 31851350b030Sdrh ** 31861350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 31871350b030Sdrh ** 318860ec914cSpeter.d.reid ** The code generated for this simplification gives the same result 3189832508b7Sdrh ** but only has to scan the data once. And because indices might 3190832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 3191832508b7Sdrh ** avoided. 31921350b030Sdrh ** 3193832508b7Sdrh ** Flattening is only attempted if all of the following are true: 31941350b030Sdrh ** 3195832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 31961350b030Sdrh ** 3197832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 3198832508b7Sdrh ** 31992b300d5dSdrh ** (3) The subquery is not the right operand of a left outer join 320049ad330dSdan ** (Originally ticket #306. Strengthened by ticket #3300) 3201832508b7Sdrh ** 320249ad330dSdan ** (4) The subquery is not DISTINCT. 3203832508b7Sdrh ** 320449ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 320549ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 320649ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 3207832508b7Sdrh ** 3208832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 3209832508b7Sdrh ** DISTINCT. 3210832508b7Sdrh ** 3211630d296cSdrh ** (7) The subquery has a FROM clause. TODO: For subqueries without 3212630d296cSdrh ** A FROM clause, consider adding a FROM close with the special 3213630d296cSdrh ** table sqlite_once that consists of a single row containing a 3214630d296cSdrh ** single NULL. 321508192d5fSdrh ** 3216df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 3217df199a25Sdrh ** 3218df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 3219df199a25Sdrh ** aggregates. 3220df199a25Sdrh ** 32216092d2bcSdrh ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 32226092d2bcSdrh ** accidently carried the comment forward until 2014-09-15. Original 32236092d2bcSdrh ** text: "The subquery does not use aggregates or the outer query does not 32246092d2bcSdrh ** use LIMIT." 3225df199a25Sdrh ** 3226174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 3227174b6195Sdrh ** 32287b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 32292b300d5dSdrh ** a separate restriction deriving from ticket #350. 32303fc673e6Sdrh ** 323149ad330dSdan ** (13) The subquery and outer query do not both use LIMIT. 3232ac83963aSdrh ** 323349ad330dSdan ** (14) The subquery does not use OFFSET. 3234ac83963aSdrh ** 3235ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 3236f3913278Sdrh ** subquery does not have a LIMIT clause. 3237f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 3238ad91c6cdSdrh ** 3239c52e355dSdrh ** (16) The outer query is not an aggregate or the subquery does 3240c52e355dSdrh ** not contain ORDER BY. (Ticket #2942) This used to not matter 3241c52e355dSdrh ** until we introduced the group_concat() function. 3242c52e355dSdrh ** 3243f23329a2Sdanielk1977 ** (17) The sub-query is not a compound select, or it is a UNION ALL 32444914cf92Sdanielk1977 ** compound clause made up entirely of non-aggregate queries, and 3245f23329a2Sdanielk1977 ** the parent query: 3246f23329a2Sdanielk1977 ** 3247f23329a2Sdanielk1977 ** * is not itself part of a compound select, 3248f23329a2Sdanielk1977 ** * is not an aggregate or DISTINCT query, and 3249630d296cSdrh ** * is not a join 3250f23329a2Sdanielk1977 ** 32514914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 32524914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 3253630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 3254630d296cSdrh ** operator other than UNION ALL because all the other compound 3255630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 3256630d296cSdrh ** restriction (4). 3257f23329a2Sdanielk1977 ** 325867c70142Sdan ** Also, each component of the sub-query must return the same number 325967c70142Sdan ** of result columns. This is actually a requirement for any compound 326067c70142Sdan ** SELECT statement, but all the code here does is make sure that no 326167c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 326267c70142Sdan ** syntax error and return a detailed message. 326367c70142Sdan ** 326449fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 326549fc1f60Sdanielk1977 ** ORDER by clause of the parent must be simple references to 326649fc1f60Sdanielk1977 ** columns of the sub-query. 326749fc1f60Sdanielk1977 ** 3268229cf702Sdrh ** (19) The subquery does not use LIMIT or the outer query does not 3269229cf702Sdrh ** have a WHERE clause. 3270229cf702Sdrh ** 3271e8902a70Sdrh ** (20) If the sub-query is a compound select, then it must not use 3272e8902a70Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 3273e8902a70Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 3274630d296cSdrh ** appear as unmodified result columns in the outer query. But we 3275e8902a70Sdrh ** have other optimizations in mind to deal with that case. 3276e8902a70Sdrh ** 3277a91491e5Sshaneh ** (21) The subquery does not use LIMIT or the outer query is not 3278a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 3279a91491e5Sshaneh ** 32808290c2adSdan ** (22) The subquery is not a recursive CTE. 32818290c2adSdan ** 32828290c2adSdan ** (23) The parent is not a recursive CTE, or the sub-query is not a 32838290c2adSdan ** compound query. This restriction is because transforming the 32848290c2adSdan ** parent to a compound query confuses the code that handles 32858290c2adSdan ** recursive queries in multiSelect(). 32868290c2adSdan ** 32879588ad95Sdrh ** (24) The subquery is not an aggregate that uses the built-in min() or 32889588ad95Sdrh ** or max() functions. (Without this restriction, a query like: 32899588ad95Sdrh ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily 32909588ad95Sdrh ** return the value X for which Y was maximal.) 32919588ad95Sdrh ** 32928290c2adSdan ** 3293832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 3294832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 3295832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 3296832508b7Sdrh ** 3297665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 3298832508b7Sdrh ** If flattening is attempted this routine returns 1. 3299832508b7Sdrh ** 3300832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 3301832508b7Sdrh ** the subquery before this routine runs. 33021350b030Sdrh */ 33038c74a8caSdrh static int flattenSubquery( 3304524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 33058c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 33068c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 33078c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 33088c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 33098c74a8caSdrh ){ 3310524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 3311f23329a2Sdanielk1977 Select *pParent; 33120bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 3313f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 3314ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 3315ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 33160bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 33176a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 331891bb0eedSdrh int i; /* Loop counter */ 331991bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 332091bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 3321524cc21eSdanielk1977 sqlite3 *db = pParse->db; 33221350b030Sdrh 3323832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 3324832508b7Sdrh */ 3325a78c22c4Sdrh assert( p!=0 ); 3326a78c22c4Sdrh assert( p->pPrior==0 ); /* Unable to flatten compound queries */ 33277e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 3328832508b7Sdrh pSrc = p->pSrc; 3329ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 333091bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 333149fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 333291bb0eedSdrh pSub = pSubitem->pSelect; 3333832508b7Sdrh assert( pSub!=0 ); 3334ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 3335ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 3336832508b7Sdrh pSubSrc = pSub->pSrc; 3337832508b7Sdrh assert( pSubSrc ); 3338ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 333960ec914cSpeter.d.reid ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 3340ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 3341ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 3342ac83963aSdrh ** and (14). */ 3343ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 3344ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 3345d227a291Sdrh if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 3346ad91c6cdSdrh return 0; /* Restriction (15) */ 3347ad91c6cdSdrh } 3348ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 334949ad330dSdan if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ 335049ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 335149ad330dSdan return 0; /* Restrictions (8)(9) */ 3352df199a25Sdrh } 33537d10d5a6Sdrh if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ 33547d10d5a6Sdrh return 0; /* Restriction (6) */ 33557d10d5a6Sdrh } 33567d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 3357ac83963aSdrh return 0; /* Restriction (11) */ 3358ac83963aSdrh } 3359c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 3360229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 3361a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 3362a91491e5Sshaneh return 0; /* Restriction (21) */ 3363a91491e5Sshaneh } 33649588ad95Sdrh testcase( pSub->selFlags & SF_Recursive ); 33659588ad95Sdrh testcase( pSub->selFlags & SF_MinMaxAgg ); 33669588ad95Sdrh if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){ 33679588ad95Sdrh return 0; /* Restrictions (22) and (24) */ 33689588ad95Sdrh } 33699588ad95Sdrh if( (p->selFlags & SF_Recursive) && pSub->pPrior ){ 33709588ad95Sdrh return 0; /* Restriction (23) */ 33719588ad95Sdrh } 3372832508b7Sdrh 33732b300d5dSdrh /* OBSOLETE COMMENT 1: 33742b300d5dSdrh ** Restriction 3: If the subquery is a join, make sure the subquery is 33758af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 33768af4d3acSdrh ** is not allowed: 33778af4d3acSdrh ** 33788af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 33798af4d3acSdrh ** 33808af4d3acSdrh ** If we flatten the above, we would get 33818af4d3acSdrh ** 33828af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 33838af4d3acSdrh ** 33848af4d3acSdrh ** which is not at all the same thing. 33852b300d5dSdrh ** 33862b300d5dSdrh ** OBSOLETE COMMENT 2: 33872b300d5dSdrh ** Restriction 12: If the subquery is the right operand of a left outer 33883fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 33893fc673e6Sdrh ** An examples of why this is not allowed: 33903fc673e6Sdrh ** 33913fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 33923fc673e6Sdrh ** 33933fc673e6Sdrh ** If we flatten the above, we would get 33943fc673e6Sdrh ** 33953fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 33963fc673e6Sdrh ** 33973fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 33983fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 33992b300d5dSdrh ** 34002b300d5dSdrh ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: 34012b300d5dSdrh ** Ticket #3300 shows that flattening the right term of a LEFT JOIN 34022b300d5dSdrh ** is fraught with danger. Best to avoid the whole thing. If the 34032b300d5dSdrh ** subquery is the right term of a LEFT JOIN, then do not flatten. 34043fc673e6Sdrh */ 34052b300d5dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 ){ 34063fc673e6Sdrh return 0; 34073fc673e6Sdrh } 34083fc673e6Sdrh 3409f23329a2Sdanielk1977 /* Restriction 17: If the sub-query is a compound SELECT, then it must 3410f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 3411f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 3412f23329a2Sdanielk1977 ** queries. 3413f23329a2Sdanielk1977 */ 3414f23329a2Sdanielk1977 if( pSub->pPrior ){ 3415e8902a70Sdrh if( pSub->pOrderBy ){ 3416e8902a70Sdrh return 0; /* Restriction 20 */ 3417e8902a70Sdrh } 3418e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 3419f23329a2Sdanielk1977 return 0; 3420f23329a2Sdanielk1977 } 3421f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 3422ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 3423ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 34244b3ac73cSdrh assert( pSub->pSrc!=0 ); 34257d10d5a6Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 342680b3c548Sdanielk1977 || (pSub1->pPrior && pSub1->op!=TK_ALL) 34274b3ac73cSdrh || pSub1->pSrc->nSrc<1 342867c70142Sdan || pSub->pEList->nExpr!=pSub1->pEList->nExpr 342980b3c548Sdanielk1977 ){ 3430f23329a2Sdanielk1977 return 0; 3431f23329a2Sdanielk1977 } 34324b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 3433f23329a2Sdanielk1977 } 343449fc1f60Sdanielk1977 343549fc1f60Sdanielk1977 /* Restriction 18. */ 343649fc1f60Sdanielk1977 if( p->pOrderBy ){ 343749fc1f60Sdanielk1977 int ii; 343849fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 3439c2acc4e4Sdrh if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; 344049fc1f60Sdanielk1977 } 344149fc1f60Sdanielk1977 } 3442f23329a2Sdanielk1977 } 3443f23329a2Sdanielk1977 34447d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 3445eb9b884cSdrh SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n", 3446eb9b884cSdrh pSub->zSelName, pSub, iFrom)); 34477d10d5a6Sdrh 34487d10d5a6Sdrh /* Authorize the subquery */ 3449524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 3450a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 3451a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 3452524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 3453524cc21eSdanielk1977 34547d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 34557d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 34567d10d5a6Sdrh ** be of the form: 3457f23329a2Sdanielk1977 ** 3458f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 3459f23329a2Sdanielk1977 ** 3460f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 3461a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 3462f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 3463f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 3464f23329a2Sdanielk1977 ** select statements in the compound sub-query. 3465a78c22c4Sdrh ** 3466a78c22c4Sdrh ** Example: 3467a78c22c4Sdrh ** 3468a78c22c4Sdrh ** SELECT a+1 FROM ( 3469a78c22c4Sdrh ** SELECT x FROM tab 3470a78c22c4Sdrh ** UNION ALL 3471a78c22c4Sdrh ** SELECT y FROM tab 3472a78c22c4Sdrh ** UNION ALL 3473a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 3474a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 3475a78c22c4Sdrh ** 3476a78c22c4Sdrh ** Transformed into: 3477a78c22c4Sdrh ** 3478a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 3479a78c22c4Sdrh ** UNION ALL 3480a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 3481a78c22c4Sdrh ** UNION ALL 3482a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 3483a78c22c4Sdrh ** ORDER BY 1 3484a78c22c4Sdrh ** 3485a78c22c4Sdrh ** We call this the "compound-subquery flattening". 3486f23329a2Sdanielk1977 */ 3487f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 3488f23329a2Sdanielk1977 Select *pNew; 3489f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 34904b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 3491547180baSdrh Expr *pOffset = p->pOffset; 3492f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 3493f23329a2Sdanielk1977 p->pOrderBy = 0; 3494f23329a2Sdanielk1977 p->pSrc = 0; 3495f23329a2Sdanielk1977 p->pPrior = 0; 34964b86ef1dSdanielk1977 p->pLimit = 0; 3497547180baSdrh p->pOffset = 0; 34986ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 3499eb9b884cSdrh sqlite3SelectSetName(pNew, pSub->zSelName); 3500547180baSdrh p->pOffset = pOffset; 35014b86ef1dSdanielk1977 p->pLimit = pLimit; 3502a78c22c4Sdrh p->pOrderBy = pOrderBy; 3503a78c22c4Sdrh p->pSrc = pSrc; 3504a78c22c4Sdrh p->op = TK_ALL; 3505a78c22c4Sdrh if( pNew==0 ){ 3506d227a291Sdrh p->pPrior = pPrior; 3507a78c22c4Sdrh }else{ 3508a78c22c4Sdrh pNew->pPrior = pPrior; 3509d227a291Sdrh if( pPrior ) pPrior->pNext = pNew; 3510d227a291Sdrh pNew->pNext = p; 3511a78c22c4Sdrh p->pPrior = pNew; 3512eb9b884cSdrh SELECTTRACE(2,pParse,p, 3513eb9b884cSdrh ("compound-subquery flattener creates %s.%p as peer\n", 3514eb9b884cSdrh pNew->zSelName, pNew)); 3515d227a291Sdrh } 3516a78c22c4Sdrh if( db->mallocFailed ) return 1; 3517a78c22c4Sdrh } 3518f23329a2Sdanielk1977 35197d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 35207d10d5a6Sdrh ** in the outer query. 3521832508b7Sdrh */ 3522f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 3523c31c2eb8Sdrh 3524a78c22c4Sdrh /* Delete the transient table structure associated with the 3525a78c22c4Sdrh ** subquery 3526a78c22c4Sdrh */ 3527a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 3528a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 3529a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 3530a78c22c4Sdrh pSubitem->zDatabase = 0; 3531a78c22c4Sdrh pSubitem->zName = 0; 3532a78c22c4Sdrh pSubitem->zAlias = 0; 3533a78c22c4Sdrh pSubitem->pSelect = 0; 3534a78c22c4Sdrh 3535a78c22c4Sdrh /* Defer deleting the Table object associated with the 3536a78c22c4Sdrh ** subquery until code generation is 3537a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 3538a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 3539ccfcbceaSdrh ** 3540ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 3541a78c22c4Sdrh */ 3542ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 3543a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 3544a78c22c4Sdrh if( pTabToDel->nRef==1 ){ 354565a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 354665a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 354765a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 3548a78c22c4Sdrh }else{ 3549a78c22c4Sdrh pTabToDel->nRef--; 3550a78c22c4Sdrh } 3551a78c22c4Sdrh pSubitem->pTab = 0; 3552a78c22c4Sdrh } 3553a78c22c4Sdrh 3554a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 3555a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 3556a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 3557a78c22c4Sdrh ** then this loop only runs once. 3558a78c22c4Sdrh ** 3559a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 3560c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 3561c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 3562c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 3563c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 3564c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 3565c31c2eb8Sdrh ** elements we are now copying in. 3566c31c2eb8Sdrh */ 3567a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 3568a78c22c4Sdrh int nSubSrc; 3569ea678832Sdrh u8 jointype = 0; 3570a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 3571a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 3572a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 3573588a9a1aSdrh 3574a78c22c4Sdrh if( pSrc ){ 3575a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 3576a78c22c4Sdrh jointype = pSubitem->jointype; 3577588a9a1aSdrh }else{ 3578a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 3579a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 3580cfa063b3Sdrh if( pSrc==0 ){ 3581a78c22c4Sdrh assert( db->mallocFailed ); 3582a78c22c4Sdrh break; 3583cfa063b3Sdrh } 3584c31c2eb8Sdrh } 3585a78c22c4Sdrh 3586a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 3587a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 3588a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 3589a78c22c4Sdrh ** of the subquery. 3590a78c22c4Sdrh ** 3591a78c22c4Sdrh ** Example: 3592a78c22c4Sdrh ** 3593a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 3594a78c22c4Sdrh ** 3595a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 3596a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 3597a78c22c4Sdrh ** block of code will expand the out query to 4 slots. The middle 3598a78c22c4Sdrh ** slot is expanded to two slots in order to make space for the 3599a78c22c4Sdrh ** two elements in the FROM clause of the subquery. 3600a78c22c4Sdrh */ 3601a78c22c4Sdrh if( nSubSrc>1 ){ 3602a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 3603a78c22c4Sdrh if( db->mallocFailed ){ 3604a78c22c4Sdrh break; 3605c31c2eb8Sdrh } 3606c31c2eb8Sdrh } 3607a78c22c4Sdrh 3608a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 3609a78c22c4Sdrh ** outer query. 3610a78c22c4Sdrh */ 3611c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 3612c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 3613c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 3614c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 3615c31c2eb8Sdrh } 361661dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 3617c31c2eb8Sdrh 3618c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 3619c31c2eb8Sdrh ** references to the iParent in the outer query. 3620c31c2eb8Sdrh ** 3621c31c2eb8Sdrh ** Example: 3622c31c2eb8Sdrh ** 3623c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 3624c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 3625c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 3626c31c2eb8Sdrh ** 3627c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 3628c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 3629c31c2eb8Sdrh */ 3630f23329a2Sdanielk1977 pList = pParent->pEList; 3631832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 3632ccfcbceaSdrh if( pList->a[i].zName==0 ){ 363342fbf321Sdrh char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); 363442fbf321Sdrh sqlite3Dequote(zName); 363542fbf321Sdrh pList->a[i].zName = zName; 3636832508b7Sdrh } 3637ccfcbceaSdrh } 3638f23329a2Sdanielk1977 substExprList(db, pParent->pEList, iParent, pSub->pEList); 36391b2e0329Sdrh if( isAgg ){ 3640f23329a2Sdanielk1977 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList); 3641b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 36421b2e0329Sdrh } 3643174b6195Sdrh if( pSub->pOrderBy ){ 36447c0a4720Sdan /* At this point, any non-zero iOrderByCol values indicate that the 36457c0a4720Sdan ** ORDER BY column expression is identical to the iOrderByCol'th 36467c0a4720Sdan ** expression returned by SELECT statement pSub. Since these values 36477c0a4720Sdan ** do not necessarily correspond to columns in SELECT statement pParent, 36487c0a4720Sdan ** zero them before transfering the ORDER BY clause. 36497c0a4720Sdan ** 36507c0a4720Sdan ** Not doing this may cause an error if a subsequent call to this 36517c0a4720Sdan ** function attempts to flatten a compound sub-query into pParent 36527c0a4720Sdan ** (the only way this can happen is if the compound sub-query is 36537c0a4720Sdan ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 36547c0a4720Sdan ExprList *pOrderBy = pSub->pOrderBy; 36557c0a4720Sdan for(i=0; i<pOrderBy->nExpr; i++){ 36567c0a4720Sdan pOrderBy->a[i].u.x.iOrderByCol = 0; 36577c0a4720Sdan } 3658f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 36597c0a4720Sdan assert( pSub->pPrior==0 ); 36607c0a4720Sdan pParent->pOrderBy = pOrderBy; 3661174b6195Sdrh pSub->pOrderBy = 0; 3662f23329a2Sdanielk1977 }else if( pParent->pOrderBy ){ 3663f23329a2Sdanielk1977 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList); 3664174b6195Sdrh } 3665832508b7Sdrh if( pSub->pWhere ){ 36666ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 3667832508b7Sdrh }else{ 3668832508b7Sdrh pWhere = 0; 3669832508b7Sdrh } 3670832508b7Sdrh if( subqueryIsAgg ){ 3671f23329a2Sdanielk1977 assert( pParent->pHaving==0 ); 3672f23329a2Sdanielk1977 pParent->pHaving = pParent->pWhere; 3673f23329a2Sdanielk1977 pParent->pWhere = pWhere; 3674b7916a78Sdrh pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); 3675f23329a2Sdanielk1977 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 36766ab3a2ecSdanielk1977 sqlite3ExprDup(db, pSub->pHaving, 0)); 3677f23329a2Sdanielk1977 assert( pParent->pGroupBy==0 ); 36786ab3a2ecSdanielk1977 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); 3679832508b7Sdrh }else{ 3680b7916a78Sdrh pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList); 3681f23329a2Sdanielk1977 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); 3682832508b7Sdrh } 3683c31c2eb8Sdrh 3684c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 3685c31c2eb8Sdrh ** outer query is distinct. 3686c31c2eb8Sdrh */ 36877d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 36888c74a8caSdrh 3689a58fdfb1Sdanielk1977 /* 3690a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3691ac83963aSdrh ** 3692ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 3693ac83963aSdrh ** does not work if either limit is negative. 3694a58fdfb1Sdanielk1977 */ 3695a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 3696f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 3697a2dc3b1aSdanielk1977 pSub->pLimit = 0; 3698df199a25Sdrh } 3699f23329a2Sdanielk1977 } 37008c74a8caSdrh 3701c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 3702c31c2eb8Sdrh ** success. 3703c31c2eb8Sdrh */ 3704633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 3705f23329a2Sdanielk1977 3706c90713d3Sdrh #if SELECTTRACE_ENABLED 3707c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 3708c90713d3Sdrh sqlite3DebugPrintf("After flattening:\n"); 3709c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 3710c90713d3Sdrh } 3711c90713d3Sdrh #endif 3712c90713d3Sdrh 3713832508b7Sdrh return 1; 37141350b030Sdrh } 37153514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 37161350b030Sdrh 37171350b030Sdrh /* 37184ac391fcSdan ** Based on the contents of the AggInfo structure indicated by the first 37194ac391fcSdan ** argument, this function checks if the following are true: 3720a9d1ccb9Sdanielk1977 ** 37214ac391fcSdan ** * the query contains just a single aggregate function, 37224ac391fcSdan ** * the aggregate function is either min() or max(), and 37234ac391fcSdan ** * the argument to the aggregate function is a column value. 3724738bdcfbSdanielk1977 ** 37254ac391fcSdan ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX 37264ac391fcSdan ** is returned as appropriate. Also, *ppMinMax is set to point to the 37274ac391fcSdan ** list of arguments passed to the aggregate before returning. 37284ac391fcSdan ** 37294ac391fcSdan ** Or, if the conditions above are not met, *ppMinMax is set to 0 and 37304ac391fcSdan ** WHERE_ORDERBY_NORMAL is returned. 3731a9d1ccb9Sdanielk1977 */ 37324ac391fcSdan static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ 37334ac391fcSdan int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ 3734a9d1ccb9Sdanielk1977 37354ac391fcSdan *ppMinMax = 0; 37364ac391fcSdan if( pAggInfo->nFunc==1 ){ 37374ac391fcSdan Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ 37384ac391fcSdan ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ 37394ac391fcSdan 37404ac391fcSdan assert( pExpr->op==TK_AGG_FUNCTION ); 37414ac391fcSdan if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ 37424ac391fcSdan const char *zFunc = pExpr->u.zToken; 37434ac391fcSdan if( sqlite3StrICmp(zFunc, "min")==0 ){ 37444ac391fcSdan eRet = WHERE_ORDERBY_MIN; 37454ac391fcSdan *ppMinMax = pEList; 37464ac391fcSdan }else if( sqlite3StrICmp(zFunc, "max")==0 ){ 37474ac391fcSdan eRet = WHERE_ORDERBY_MAX; 37484ac391fcSdan *ppMinMax = pEList; 3749a9d1ccb9Sdanielk1977 } 37504ac391fcSdan } 37514ac391fcSdan } 37524ac391fcSdan 37534ac391fcSdan assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); 37544ac391fcSdan return eRet; 3755a9d1ccb9Sdanielk1977 } 3756a9d1ccb9Sdanielk1977 3757a9d1ccb9Sdanielk1977 /* 3758a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 375960ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This 3760a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 3761a5533162Sdanielk1977 ** 3762a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 3763a5533162Sdanielk1977 ** 3764a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 3765a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 3766a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 3767a5533162Sdanielk1977 */ 3768a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 3769a5533162Sdanielk1977 Table *pTab; 3770a5533162Sdanielk1977 Expr *pExpr; 3771a5533162Sdanielk1977 3772a5533162Sdanielk1977 assert( !p->pGroupBy ); 3773a5533162Sdanielk1977 37747a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 3775a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 3776a5533162Sdanielk1977 ){ 3777a5533162Sdanielk1977 return 0; 3778a5533162Sdanielk1977 } 3779a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 3780a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 378102f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 378202f33725Sdanielk1977 378302f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 3784a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 3785fb0a6081Sdrh if( NEVER(pAggInfo->nFunc==0) ) return 0; 3786d36e1041Sdrh if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; 3787a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 3788a5533162Sdanielk1977 3789a5533162Sdanielk1977 return pTab; 3790a5533162Sdanielk1977 } 3791a5533162Sdanielk1977 3792a5533162Sdanielk1977 /* 3793b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 3794b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 3795b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 3796b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 3797b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 3798b1c685b0Sdanielk1977 */ 3799b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 3800b1c685b0Sdanielk1977 if( pFrom->pTab && pFrom->zIndex ){ 3801b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 3802b1c685b0Sdanielk1977 char *zIndex = pFrom->zIndex; 3803b1c685b0Sdanielk1977 Index *pIdx; 3804b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 3805b1c685b0Sdanielk1977 pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 3806b1c685b0Sdanielk1977 pIdx=pIdx->pNext 3807b1c685b0Sdanielk1977 ); 3808b1c685b0Sdanielk1977 if( !pIdx ){ 3809b1c685b0Sdanielk1977 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0); 38101db95106Sdan pParse->checkSchema = 1; 3811b1c685b0Sdanielk1977 return SQLITE_ERROR; 3812b1c685b0Sdanielk1977 } 3813b1c685b0Sdanielk1977 pFrom->pIndex = pIdx; 3814b1c685b0Sdanielk1977 } 3815b1c685b0Sdanielk1977 return SQLITE_OK; 3816b1c685b0Sdanielk1977 } 3817c01b7306Sdrh /* 3818c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with 3819c01b7306Sdrh ** an alternative collating sequence. 3820c01b7306Sdrh ** 3821c01b7306Sdrh ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 3822c01b7306Sdrh ** 3823c01b7306Sdrh ** These are rewritten as a subquery: 3824c01b7306Sdrh ** 3825c01b7306Sdrh ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) 3826c01b7306Sdrh ** ORDER BY ... COLLATE ... 3827c01b7306Sdrh ** 3828c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine 3829c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause 3830c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the 3831c01b7306Sdrh ** result columns as on the ORDER BY clause. See ticket 3832c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a 3833c01b7306Sdrh ** 3834c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. 3835c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when 3836c01b7306Sdrh ** there are COLLATE terms in the ORDER BY. 3837c01b7306Sdrh */ 3838c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ 3839c01b7306Sdrh int i; 3840c01b7306Sdrh Select *pNew; 3841c01b7306Sdrh Select *pX; 3842c01b7306Sdrh sqlite3 *db; 3843c01b7306Sdrh struct ExprList_item *a; 3844c01b7306Sdrh SrcList *pNewSrc; 3845c01b7306Sdrh Parse *pParse; 3846c01b7306Sdrh Token dummy; 3847c01b7306Sdrh 3848c01b7306Sdrh if( p->pPrior==0 ) return WRC_Continue; 3849c01b7306Sdrh if( p->pOrderBy==0 ) return WRC_Continue; 3850c01b7306Sdrh for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} 3851c01b7306Sdrh if( pX==0 ) return WRC_Continue; 3852c01b7306Sdrh a = p->pOrderBy->a; 3853c01b7306Sdrh for(i=p->pOrderBy->nExpr-1; i>=0; i--){ 3854c01b7306Sdrh if( a[i].pExpr->flags & EP_Collate ) break; 3855c01b7306Sdrh } 3856c01b7306Sdrh if( i<0 ) return WRC_Continue; 3857c01b7306Sdrh 3858c01b7306Sdrh /* If we reach this point, that means the transformation is required. */ 3859c01b7306Sdrh 3860c01b7306Sdrh pParse = pWalker->pParse; 3861c01b7306Sdrh db = pParse->db; 3862c01b7306Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 3863c01b7306Sdrh if( pNew==0 ) return WRC_Abort; 3864c01b7306Sdrh memset(&dummy, 0, sizeof(dummy)); 3865c01b7306Sdrh pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); 3866c01b7306Sdrh if( pNewSrc==0 ) return WRC_Abort; 3867c01b7306Sdrh *pNew = *p; 3868c01b7306Sdrh p->pSrc = pNewSrc; 3869c01b7306Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0)); 3870c01b7306Sdrh p->op = TK_SELECT; 3871c01b7306Sdrh p->pWhere = 0; 3872c01b7306Sdrh pNew->pGroupBy = 0; 3873c01b7306Sdrh pNew->pHaving = 0; 3874c01b7306Sdrh pNew->pOrderBy = 0; 3875c01b7306Sdrh p->pPrior = 0; 38768af9ad95Sdrh p->pNext = 0; 38778af9ad95Sdrh p->selFlags &= ~SF_Compound; 3878a6e3a8c9Sdrh assert( pNew->pPrior!=0 ); 3879a6e3a8c9Sdrh pNew->pPrior->pNext = pNew; 3880c01b7306Sdrh pNew->pLimit = 0; 3881c01b7306Sdrh pNew->pOffset = 0; 3882c01b7306Sdrh return WRC_Continue; 3883c01b7306Sdrh } 3884b1c685b0Sdanielk1977 3885eede6a53Sdan #ifndef SQLITE_OMIT_CTE 3886eede6a53Sdan /* 3887eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested 3888eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by 3889eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE) 3890eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise 3891eede6a53Sdan ** return NULL. 389298f45e53Sdan ** 389398f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With 389498f45e53Sdan ** object that the returned CTE belongs to. 389560c1a2f0Sdrh */ 389698f45e53Sdan static struct Cte *searchWith( 389798f45e53Sdan With *pWith, /* Current outermost WITH clause */ 389898f45e53Sdan struct SrcList_item *pItem, /* FROM clause element to resolve */ 389998f45e53Sdan With **ppContext /* OUT: WITH clause return value belongs to */ 390098f45e53Sdan ){ 39017b19f252Sdrh const char *zName; 39027b19f252Sdrh if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ 3903eede6a53Sdan With *p; 3904eede6a53Sdan for(p=pWith; p; p=p->pOuter){ 39054e9119d9Sdan int i; 3906eede6a53Sdan for(i=0; i<p->nCte; i++){ 3907eede6a53Sdan if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 390898f45e53Sdan *ppContext = p; 3909eede6a53Sdan return &p->a[i]; 39104e9119d9Sdan } 39114e9119d9Sdan } 39124e9119d9Sdan } 39134e9119d9Sdan } 39144e9119d9Sdan return 0; 39154e9119d9Sdan } 39164e9119d9Sdan 3917c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses 3918c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack. 3919c49832c2Sdrh ** 3920b290f117Sdan ** This routine pushes the WITH clause passed as the second argument 3921b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this 3922b290f117Sdan ** WITH clause will never be popped from the stack. In this case it 3923b290f117Sdan ** should be freed along with the Parse object. In other cases, when 3924b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT 3925b290f117Sdan ** statement with which it is associated. 3926c49832c2Sdrh */ 3927b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 3928b290f117Sdan assert( bFree==0 || pParse->pWith==0 ); 39294e9119d9Sdan if( pWith ){ 39304e9119d9Sdan pWith->pOuter = pParse->pWith; 39314e9119d9Sdan pParse->pWith = pWith; 3932b290f117Sdan pParse->bFreeWith = bFree; 39334e9119d9Sdan } 39344e9119d9Sdan } 39354e9119d9Sdan 3936eede6a53Sdan /* 3937eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by 3938eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And, 3939eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive 3940eede6a53Sdan ** reference to the current CTE. 3941eede6a53Sdan ** 3942eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab 3943eede6a53Sdan ** and other fields are populated accordingly. The caller should check 3944eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match 3945eede6a53Sdan ** was found. 3946eede6a53Sdan ** 3947eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error 3948eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the 3949eede6a53Sdan ** parser and some error code other than SQLITE_OK returned. 3950eede6a53Sdan */ 39518ce7184bSdan static int withExpand( 39528ce7184bSdan Walker *pWalker, 3953eede6a53Sdan struct SrcList_item *pFrom 39548ce7184bSdan ){ 39558ce7184bSdan Parse *pParse = pWalker->pParse; 39568ce7184bSdan sqlite3 *db = pParse->db; 395798f45e53Sdan struct Cte *pCte; /* Matched CTE (or NULL if no match) */ 395898f45e53Sdan With *pWith; /* WITH clause that pCte belongs to */ 39598ce7184bSdan 39608ce7184bSdan assert( pFrom->pTab==0 ); 39618ce7184bSdan 396298f45e53Sdan pCte = searchWith(pParse->pWith, pFrom, &pWith); 3963eae73fbfSdan if( pCte ){ 396498f45e53Sdan Table *pTab; 39658ce7184bSdan ExprList *pEList; 39668ce7184bSdan Select *pSel; 396760e7068dSdan Select *pLeft; /* Left-most SELECT statement */ 3968f2655fe8Sdan int bMayRecursive; /* True if compound joined by UNION [ALL] */ 396998f45e53Sdan With *pSavedWith; /* Initial value of pParse->pWith */ 3970f2655fe8Sdan 3971f2655fe8Sdan /* If pCte->zErr is non-NULL at this point, then this is an illegal 3972f2655fe8Sdan ** recursive reference to CTE pCte. Leave an error in pParse and return 3973f2655fe8Sdan ** early. If pCte->zErr is NULL, then this is not a recursive reference. 3974f2655fe8Sdan ** In this case, proceed. */ 3975f2655fe8Sdan if( pCte->zErr ){ 3976f2655fe8Sdan sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName); 397798f45e53Sdan return SQLITE_ERROR; 3978f2655fe8Sdan } 39798ce7184bSdan 3980c25e2ebcSdrh assert( pFrom->pTab==0 ); 39818ce7184bSdan pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 39828ce7184bSdan if( pTab==0 ) return WRC_Abort; 39838ce7184bSdan pTab->nRef = 1; 39842d4dc5fcSdan pTab->zName = sqlite3DbStrDup(db, pCte->zName); 39858ce7184bSdan pTab->iPKey = -1; 3986cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 39878ce7184bSdan pTab->tabFlags |= TF_Ephemeral; 39888ce7184bSdan pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 39898ce7184bSdan if( db->mallocFailed ) return SQLITE_NOMEM; 39908ce7184bSdan assert( pFrom->pSelect ); 39918ce7184bSdan 3992eae73fbfSdan /* Check if this is a recursive CTE. */ 39938ce7184bSdan pSel = pFrom->pSelect; 3994f2655fe8Sdan bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 3995f2655fe8Sdan if( bMayRecursive ){ 3996eae73fbfSdan int i; 3997eae73fbfSdan SrcList *pSrc = pFrom->pSelect->pSrc; 3998eae73fbfSdan for(i=0; i<pSrc->nSrc; i++){ 3999eae73fbfSdan struct SrcList_item *pItem = &pSrc->a[i]; 4000eae73fbfSdan if( pItem->zDatabase==0 4001eae73fbfSdan && pItem->zName!=0 4002eae73fbfSdan && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 4003eae73fbfSdan ){ 4004eae73fbfSdan pItem->pTab = pTab; 4005eae73fbfSdan pItem->isRecursive = 1; 4006eae73fbfSdan pTab->nRef++; 4007eae73fbfSdan pSel->selFlags |= SF_Recursive; 40088ce7184bSdan } 4009eae73fbfSdan } 4010eae73fbfSdan } 4011eae73fbfSdan 4012eae73fbfSdan /* Only one recursive reference is permitted. */ 4013eae73fbfSdan if( pTab->nRef>2 ){ 4014eae73fbfSdan sqlite3ErrorMsg( 4015727a99f1Sdrh pParse, "multiple references to recursive table: %s", pCte->zName 4016eae73fbfSdan ); 401798f45e53Sdan return SQLITE_ERROR; 4018eae73fbfSdan } 4019eae73fbfSdan assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 )); 4020eae73fbfSdan 4021727a99f1Sdrh pCte->zErr = "circular reference: %s"; 402298f45e53Sdan pSavedWith = pParse->pWith; 402398f45e53Sdan pParse->pWith = pWith; 4024f2655fe8Sdan sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel); 40258ce7184bSdan 40268ce7184bSdan for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 40278ce7184bSdan pEList = pLeft->pEList; 402860e7068dSdan if( pCte->pCols ){ 402960e7068dSdan if( pEList->nExpr!=pCte->pCols->nExpr ){ 4030727a99f1Sdrh sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 403160e7068dSdan pCte->zName, pEList->nExpr, pCte->pCols->nExpr 403260e7068dSdan ); 403398f45e53Sdan pParse->pWith = pSavedWith; 403498f45e53Sdan return SQLITE_ERROR; 40358ce7184bSdan } 403660e7068dSdan pEList = pCte->pCols; 403760e7068dSdan } 40388ce7184bSdan 403998f45e53Sdan selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 4040f2655fe8Sdan if( bMayRecursive ){ 4041f2655fe8Sdan if( pSel->selFlags & SF_Recursive ){ 4042727a99f1Sdrh pCte->zErr = "multiple recursive references: %s"; 4043f2655fe8Sdan }else{ 4044727a99f1Sdrh pCte->zErr = "recursive reference in a subquery: %s"; 4045f2655fe8Sdan } 4046f2655fe8Sdan sqlite3WalkSelect(pWalker, pSel); 4047f2655fe8Sdan } 4048f2655fe8Sdan pCte->zErr = 0; 404998f45e53Sdan pParse->pWith = pSavedWith; 40508ce7184bSdan } 40518ce7184bSdan 40528ce7184bSdan return SQLITE_OK; 40538ce7184bSdan } 4054eede6a53Sdan #endif 40554e9119d9Sdan 4056b290f117Sdan #ifndef SQLITE_OMIT_CTE 405771856944Sdan /* 405871856944Sdan ** If the SELECT passed as the second argument has an associated WITH 405971856944Sdan ** clause, pop it from the stack stored as part of the Parse object. 406071856944Sdan ** 406171856944Sdan ** This function is used as the xSelectCallback2() callback by 406271856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table 406371856944Sdan ** names and other FROM clause elements. 406471856944Sdan */ 4065b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){ 4066b290f117Sdan Parse *pParse = pWalker->pParse; 4067d227a291Sdrh With *pWith = findRightmost(p)->pWith; 4068d227a291Sdrh if( pWith!=0 ){ 4069d227a291Sdrh assert( pParse->pWith==pWith ); 4070d227a291Sdrh pParse->pWith = pWith->pOuter; 4071b290f117Sdan } 4072b290f117Sdan } 4073b290f117Sdan #else 4074b290f117Sdan #define selectPopWith 0 4075b290f117Sdan #endif 4076b290f117Sdan 4077b1c685b0Sdanielk1977 /* 40787d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 40797d10d5a6Sdrh ** "Expanding" means to do the following: 40807d10d5a6Sdrh ** 40817d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 40827d10d5a6Sdrh ** element of the FROM clause. 40837d10d5a6Sdrh ** 40847d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 40857d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 40867d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 40877d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 40887d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 408960ec914cSpeter.d.reid ** without worrying about messing up the persistent representation 40907d10d5a6Sdrh ** of the view. 40917d10d5a6Sdrh ** 409260ec914cSpeter.d.reid ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword 40937d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 40947d10d5a6Sdrh ** 40957d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 40967d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 40977d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 40987d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 40997d10d5a6Sdrh ** 4100b3bce662Sdanielk1977 */ 41017d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 41027d10d5a6Sdrh Parse *pParse = pWalker->pParse; 41037d10d5a6Sdrh int i, j, k; 41047d10d5a6Sdrh SrcList *pTabList; 41057d10d5a6Sdrh ExprList *pEList; 41067d10d5a6Sdrh struct SrcList_item *pFrom; 41077d10d5a6Sdrh sqlite3 *db = pParse->db; 41083e3f1a5bSdrh Expr *pE, *pRight, *pExpr; 4109785097daSdrh u16 selFlags = p->selFlags; 41107d10d5a6Sdrh 4111785097daSdrh p->selFlags |= SF_Expanded; 41127d10d5a6Sdrh if( db->mallocFailed ){ 41137d10d5a6Sdrh return WRC_Abort; 41147d10d5a6Sdrh } 4115785097daSdrh if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ 41167d10d5a6Sdrh return WRC_Prune; 41177d10d5a6Sdrh } 41187d10d5a6Sdrh pTabList = p->pSrc; 41197d10d5a6Sdrh pEList = p->pEList; 41203afd2b4dSdrh if( pWalker->xSelectCallback2==selectPopWith ){ 4121d227a291Sdrh sqlite3WithPush(pParse, findRightmost(p)->pWith, 0); 41223afd2b4dSdrh } 41237d10d5a6Sdrh 41247d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 41257d10d5a6Sdrh ** the FROM clause of the SELECT statement. 41267d10d5a6Sdrh */ 41277d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 41287d10d5a6Sdrh 41297d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 41307d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 41317d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 41327d10d5a6Sdrh */ 41337d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 41347d10d5a6Sdrh Table *pTab; 4135eae73fbfSdan assert( pFrom->isRecursive==0 || pFrom->pTab ); 4136eae73fbfSdan if( pFrom->isRecursive ) continue; 41377d10d5a6Sdrh if( pFrom->pTab!=0 ){ 41387d10d5a6Sdrh /* This statement has already been prepared. There is no need 41397d10d5a6Sdrh ** to go further. */ 41407d10d5a6Sdrh assert( i==0 ); 4141b290f117Sdan #ifndef SQLITE_OMIT_CTE 4142b290f117Sdan selectPopWith(pWalker, p); 4143b290f117Sdan #endif 41447d10d5a6Sdrh return WRC_Prune; 41457d10d5a6Sdrh } 41464e9119d9Sdan #ifndef SQLITE_OMIT_CTE 4147eede6a53Sdan if( withExpand(pWalker, pFrom) ) return WRC_Abort; 4148eede6a53Sdan if( pFrom->pTab ) {} else 41494e9119d9Sdan #endif 41507d10d5a6Sdrh if( pFrom->zName==0 ){ 41517d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 41527d10d5a6Sdrh Select *pSel = pFrom->pSelect; 41537d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 41547d10d5a6Sdrh assert( pSel!=0 ); 41557d10d5a6Sdrh assert( pFrom->pTab==0 ); 41567d10d5a6Sdrh sqlite3WalkSelect(pWalker, pSel); 41577d10d5a6Sdrh pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 41587d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 41597d10d5a6Sdrh pTab->nRef = 1; 4160186ad8ccSdrh pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); 41617d10d5a6Sdrh while( pSel->pPrior ){ pSel = pSel->pPrior; } 41627d10d5a6Sdrh selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol); 41637d10d5a6Sdrh pTab->iPKey = -1; 4164cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 41657d10d5a6Sdrh pTab->tabFlags |= TF_Ephemeral; 41667d10d5a6Sdrh #endif 41677d10d5a6Sdrh }else{ 41687d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 41697d10d5a6Sdrh assert( pFrom->pTab==0 ); 417041fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 41717d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 4172d2a56238Sdrh if( pTab->nRef==0xffff ){ 4173d2a56238Sdrh sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 4174d2a56238Sdrh pTab->zName); 4175d2a56238Sdrh pFrom->pTab = 0; 4176d2a56238Sdrh return WRC_Abort; 4177d2a56238Sdrh } 41787d10d5a6Sdrh pTab->nRef++; 41797d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 41807d10d5a6Sdrh if( pTab->pSelect || IsVirtual(pTab) ){ 41817d10d5a6Sdrh /* We reach here if the named table is a really a view */ 41827d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 418343152cf8Sdrh assert( pFrom->pSelect==0 ); 41846ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 4185eb9b884cSdrh sqlite3SelectSetName(pFrom->pSelect, pTab->zName); 41867d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 41877d10d5a6Sdrh } 41887d10d5a6Sdrh #endif 41897d10d5a6Sdrh } 419085574e31Sdanielk1977 419185574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 4192b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 419385574e31Sdanielk1977 return WRC_Abort; 419485574e31Sdanielk1977 } 41957d10d5a6Sdrh } 41967d10d5a6Sdrh 41977d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 41987d10d5a6Sdrh */ 41997d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 42007d10d5a6Sdrh return WRC_Abort; 42017d10d5a6Sdrh } 42027d10d5a6Sdrh 42037d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 42047d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 42057d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 42067d10d5a6Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 42077d10d5a6Sdrh ** The following code just has to locate the TK_ALL expressions and expand 42087d10d5a6Sdrh ** each one to the list of all columns in all tables. 42097d10d5a6Sdrh ** 42107d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 42117d10d5a6Sdrh ** that need expanding. 42127d10d5a6Sdrh */ 42137d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 42143e3f1a5bSdrh pE = pEList->a[k].pExpr; 42157d10d5a6Sdrh if( pE->op==TK_ALL ) break; 421643152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 421743152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 421843152cf8Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; 42197d10d5a6Sdrh } 42207d10d5a6Sdrh if( k<pEList->nExpr ){ 42217d10d5a6Sdrh /* 42227d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 42237d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 42247d10d5a6Sdrh ** in the result set and expand them one by one. 42257d10d5a6Sdrh */ 42267d10d5a6Sdrh struct ExprList_item *a = pEList->a; 42277d10d5a6Sdrh ExprList *pNew = 0; 42287d10d5a6Sdrh int flags = pParse->db->flags; 42297d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 423038b384a0Sdrh && (flags & SQLITE_ShortColNames)==0; 423138b384a0Sdrh 423238b384a0Sdrh /* When processing FROM-clause subqueries, it is always the case 423338b384a0Sdrh ** that full_column_names=OFF and short_column_names=ON. The 423438b384a0Sdrh ** sqlite3ResultSetOfSelect() routine makes it so. */ 423538b384a0Sdrh assert( (p->selFlags & SF_NestedFrom)==0 423638b384a0Sdrh || ((flags & SQLITE_FullColNames)==0 && 423738b384a0Sdrh (flags & SQLITE_ShortColNames)!=0) ); 42387d10d5a6Sdrh 42397d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 42403e3f1a5bSdrh pE = a[k].pExpr; 42413e3f1a5bSdrh pRight = pE->pRight; 42423e3f1a5bSdrh assert( pE->op!=TK_DOT || pRight!=0 ); 42433e3f1a5bSdrh if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){ 42447d10d5a6Sdrh /* This particular expression does not need to be expanded. 42457d10d5a6Sdrh */ 4246b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 42477d10d5a6Sdrh if( pNew ){ 42487d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 4249b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 4250b7916a78Sdrh a[k].zName = 0; 4251b7916a78Sdrh a[k].zSpan = 0; 42527d10d5a6Sdrh } 42537d10d5a6Sdrh a[k].pExpr = 0; 42547d10d5a6Sdrh }else{ 42557d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 42567d10d5a6Sdrh ** expanded. */ 42577d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 42583e3f1a5bSdrh char *zTName = 0; /* text of name of TABLE */ 425943152cf8Sdrh if( pE->op==TK_DOT ){ 426043152cf8Sdrh assert( pE->pLeft!=0 ); 426133e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 426233e619fcSdrh zTName = pE->pLeft->u.zToken; 42637d10d5a6Sdrh } 42647d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 42657d10d5a6Sdrh Table *pTab = pFrom->pTab; 42663e3f1a5bSdrh Select *pSub = pFrom->pSelect; 42677d10d5a6Sdrh char *zTabName = pFrom->zAlias; 42683e3f1a5bSdrh const char *zSchemaName = 0; 4269c75e09c7Sdrh int iDb; 427043152cf8Sdrh if( zTabName==0 ){ 42717d10d5a6Sdrh zTabName = pTab->zName; 42727d10d5a6Sdrh } 42737d10d5a6Sdrh if( db->mallocFailed ) break; 42743e3f1a5bSdrh if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ 42753e3f1a5bSdrh pSub = 0; 42767d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 42777d10d5a6Sdrh continue; 42787d10d5a6Sdrh } 42793e3f1a5bSdrh iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 4280c75e09c7Sdrh zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*"; 42813e3f1a5bSdrh } 42827d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 42837d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 4284b7916a78Sdrh char *zColname; /* The computed column name */ 4285b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 4286b7916a78Sdrh Token sColname; /* Computed column name as a token */ 42877d10d5a6Sdrh 4288c75e09c7Sdrh assert( zName ); 42893e3f1a5bSdrh if( zTName && pSub 42903e3f1a5bSdrh && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 42913e3f1a5bSdrh ){ 42923e3f1a5bSdrh continue; 42933e3f1a5bSdrh } 42943e3f1a5bSdrh 42957d10d5a6Sdrh /* If a column is marked as 'hidden' (currently only possible 42967d10d5a6Sdrh ** for virtual tables), do not include it in the expanded 42977d10d5a6Sdrh ** result-set list. 42987d10d5a6Sdrh */ 42997d10d5a6Sdrh if( IsHiddenColumn(&pTab->aCol[j]) ){ 43007d10d5a6Sdrh assert(IsVirtual(pTab)); 43017d10d5a6Sdrh continue; 43027d10d5a6Sdrh } 43033e3f1a5bSdrh tableSeen = 1; 43047d10d5a6Sdrh 4305da55c48aSdrh if( i>0 && zTName==0 ){ 43062179b434Sdrh if( (pFrom->jointype & JT_NATURAL)!=0 43072179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 43082179b434Sdrh ){ 43097d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 43102179b434Sdrh ** table to the right of the join */ 43117d10d5a6Sdrh continue; 43127d10d5a6Sdrh } 43132179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 43147d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 43157d10d5a6Sdrh ** using clause from the table on the right. */ 43167d10d5a6Sdrh continue; 43177d10d5a6Sdrh } 43187d10d5a6Sdrh } 4319b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 4320b7916a78Sdrh zColname = zName; 4321b7916a78Sdrh zToFree = 0; 43227d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 4323b7916a78Sdrh Expr *pLeft; 4324b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 43257d10d5a6Sdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 432638b384a0Sdrh if( zSchemaName ){ 4327c75e09c7Sdrh pLeft = sqlite3Expr(db, TK_ID, zSchemaName); 4328c75e09c7Sdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0); 4329c75e09c7Sdrh } 4330b7916a78Sdrh if( longNames ){ 4331b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 4332b7916a78Sdrh zToFree = zColname; 4333b7916a78Sdrh } 43347d10d5a6Sdrh }else{ 43357d10d5a6Sdrh pExpr = pRight; 43367d10d5a6Sdrh } 4337b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 4338b7916a78Sdrh sColname.z = zColname; 4339b7916a78Sdrh sColname.n = sqlite3Strlen30(zColname); 4340b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 43418f25d18bSdrh if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ 43423e3f1a5bSdrh struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; 43433e3f1a5bSdrh if( pSub ){ 43443e3f1a5bSdrh pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); 4345c75e09c7Sdrh testcase( pX->zSpan==0 ); 43463e3f1a5bSdrh }else{ 43473e3f1a5bSdrh pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", 43483e3f1a5bSdrh zSchemaName, zTabName, zColname); 4349c75e09c7Sdrh testcase( pX->zSpan==0 ); 43503e3f1a5bSdrh } 43513e3f1a5bSdrh pX->bSpanIsTab = 1; 43528f25d18bSdrh } 4353b7916a78Sdrh sqlite3DbFree(db, zToFree); 43547d10d5a6Sdrh } 43557d10d5a6Sdrh } 43567d10d5a6Sdrh if( !tableSeen ){ 43577d10d5a6Sdrh if( zTName ){ 43587d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 43597d10d5a6Sdrh }else{ 43607d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 43617d10d5a6Sdrh } 43627d10d5a6Sdrh } 43637d10d5a6Sdrh } 43647d10d5a6Sdrh } 43657d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 43667d10d5a6Sdrh p->pEList = pNew; 43677d10d5a6Sdrh } 43687d10d5a6Sdrh #if SQLITE_MAX_COLUMN 43697d10d5a6Sdrh if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 43707d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 43717d10d5a6Sdrh } 43727d10d5a6Sdrh #endif 43737d10d5a6Sdrh return WRC_Continue; 43747d10d5a6Sdrh } 43757d10d5a6Sdrh 43767d10d5a6Sdrh /* 43777d10d5a6Sdrh ** No-op routine for the parse-tree walker. 43787d10d5a6Sdrh ** 43797d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 43807d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 43817d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 43827d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 43837d10d5a6Sdrh ** subquery in the parser tree. 43847d10d5a6Sdrh */ 438562c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 438662c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 43877d10d5a6Sdrh return WRC_Continue; 43887d10d5a6Sdrh } 43897d10d5a6Sdrh 43907d10d5a6Sdrh /* 43917d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 43927d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 43937d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 43947d10d5a6Sdrh ** 43957d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 43967d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 43977d10d5a6Sdrh ** name resolution is performed. 43987d10d5a6Sdrh ** 43997d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 44007d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 44017d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 44027d10d5a6Sdrh */ 44037d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 44047d10d5a6Sdrh Walker w; 4405aa87f9a6Sdrh memset(&w, 0, sizeof(w)); 44067d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 44077d10d5a6Sdrh w.pParse = pParse; 4408d58d3278Sdrh if( pParse->hasCompound ){ 4409d58d3278Sdrh w.xSelectCallback = convertCompoundSelectToSubquery; 44107d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 4411d58d3278Sdrh } 4412c01b7306Sdrh w.xSelectCallback = selectExpander; 44133afd2b4dSdrh if( (pSelect->selFlags & SF_AllValues)==0 ){ 4414b290f117Sdan w.xSelectCallback2 = selectPopWith; 44153afd2b4dSdrh } 4416c01b7306Sdrh sqlite3WalkSelect(&w, pSelect); 44177d10d5a6Sdrh } 44187d10d5a6Sdrh 44197d10d5a6Sdrh 44207d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 44217d10d5a6Sdrh /* 44227d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 44237d10d5a6Sdrh ** interface. 44247d10d5a6Sdrh ** 44257d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 44267d10d5a6Sdrh ** information to the Table structure that represents the result set 44277d10d5a6Sdrh ** of that subquery. 44287d10d5a6Sdrh ** 44297d10d5a6Sdrh ** The Table structure that represents the result set was constructed 44307d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 44317d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 44327d10d5a6Sdrh ** routine is called after identifier resolution. 44337d10d5a6Sdrh */ 4434b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 44357d10d5a6Sdrh Parse *pParse; 44367d10d5a6Sdrh int i; 44377d10d5a6Sdrh SrcList *pTabList; 44387d10d5a6Sdrh struct SrcList_item *pFrom; 44397d10d5a6Sdrh 44409d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 44415a29d9cbSdrh if( (p->selFlags & SF_HasTypeInfo)==0 ){ 44427d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 44437d10d5a6Sdrh pParse = pWalker->pParse; 44447d10d5a6Sdrh pTabList = p->pSrc; 44457d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 44467d10d5a6Sdrh Table *pTab = pFrom->pTab; 444743152cf8Sdrh if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){ 44487d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 44497d10d5a6Sdrh Select *pSel = pFrom->pSelect; 44508ce7184bSdan if( pSel ){ 44517d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 4452186ad8ccSdrh selectAddColumnTypeAndCollation(pParse, pTab, pSel); 44537d10d5a6Sdrh } 44547d10d5a6Sdrh } 44555a29d9cbSdrh } 44568ce7184bSdan } 44577d10d5a6Sdrh } 44587d10d5a6Sdrh #endif 44597d10d5a6Sdrh 44607d10d5a6Sdrh 44617d10d5a6Sdrh /* 44627d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 44637d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 44647d10d5a6Sdrh ** SELECT statement. 44657d10d5a6Sdrh ** 44667d10d5a6Sdrh ** Use this routine after name resolution. 44677d10d5a6Sdrh */ 44687d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 44697d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 44707d10d5a6Sdrh Walker w; 4471aa87f9a6Sdrh memset(&w, 0, sizeof(w)); 4472b290f117Sdan w.xSelectCallback2 = selectAddSubqueryTypeInfo; 44737d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 44747d10d5a6Sdrh w.pParse = pParse; 44757d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 44767d10d5a6Sdrh #endif 44777d10d5a6Sdrh } 44787d10d5a6Sdrh 44797d10d5a6Sdrh 44807d10d5a6Sdrh /* 4481030796dfSdrh ** This routine sets up a SELECT statement for processing. The 44827d10d5a6Sdrh ** following is accomplished: 44837d10d5a6Sdrh ** 44847d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 44857d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 44867d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 44877d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 44887d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 44897d10d5a6Sdrh ** 44907d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 44917d10d5a6Sdrh */ 44927d10d5a6Sdrh void sqlite3SelectPrep( 4493b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 4494b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 44957d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 4496b3bce662Sdanielk1977 ){ 44977d10d5a6Sdrh sqlite3 *db; 449843152cf8Sdrh if( NEVER(p==0) ) return; 44997d10d5a6Sdrh db = pParse->db; 4500785097daSdrh if( db->mallocFailed ) return; 45017d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 45027d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 45037d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 45047d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 45057d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 45067d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 4507f6bbe022Sdrh } 4508b3bce662Sdanielk1977 4509b3bce662Sdanielk1977 /* 451013449892Sdrh ** Reset the aggregate accumulator. 451113449892Sdrh ** 451213449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 451313449892Sdrh ** intermediate results while calculating an aggregate. This 4514030796dfSdrh ** routine generates code that stores NULLs in all of those memory 4515030796dfSdrh ** cells. 4516b3bce662Sdanielk1977 */ 451713449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 451813449892Sdrh Vdbe *v = pParse->pVdbe; 451913449892Sdrh int i; 4520c99130fdSdrh struct AggInfo_func *pFunc; 45217e61d18eSdrh int nReg = pAggInfo->nFunc + pAggInfo->nColumn; 45227e61d18eSdrh if( nReg==0 ) return; 45237e61d18eSdrh #ifdef SQLITE_DEBUG 45247e61d18eSdrh /* Verify that all AggInfo registers are within the range specified by 45257e61d18eSdrh ** AggInfo.mnReg..AggInfo.mxReg */ 45267e61d18eSdrh assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); 452713449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 45287e61d18eSdrh assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg 45297e61d18eSdrh && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); 453013449892Sdrh } 45317e61d18eSdrh for(i=0; i<pAggInfo->nFunc; i++){ 45327e61d18eSdrh assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg 45337e61d18eSdrh && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); 45347e61d18eSdrh } 45357e61d18eSdrh #endif 45367e61d18eSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); 4537c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 4538c99130fdSdrh if( pFunc->iDistinct>=0 ){ 4539c99130fdSdrh Expr *pE = pFunc->pExpr; 45406ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 45416ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 45420daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 45430daa002cSdrh "argument"); 4544c99130fdSdrh pFunc->iDistinct = -1; 4545c99130fdSdrh }else{ 4546079a3072Sdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0); 454766a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 45482ec2fb22Sdrh (char*)pKeyInfo, P4_KEYINFO); 4549c99130fdSdrh } 4550c99130fdSdrh } 455113449892Sdrh } 4552b3bce662Sdanielk1977 } 4553b3bce662Sdanielk1977 4554b3bce662Sdanielk1977 /* 455513449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 455613449892Sdrh ** in the AggInfo structure. 4557b3bce662Sdanielk1977 */ 455813449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 455913449892Sdrh Vdbe *v = pParse->pVdbe; 456013449892Sdrh int i; 456113449892Sdrh struct AggInfo_func *pF; 456213449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 45636ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 45646ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 456566a5167bSdrh sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 456666a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 4567b3bce662Sdanielk1977 } 456813449892Sdrh } 456913449892Sdrh 457013449892Sdrh /* 457113449892Sdrh ** Update the accumulator memory cells for an aggregate based on 457213449892Sdrh ** the current cursor position. 457313449892Sdrh */ 457413449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 457513449892Sdrh Vdbe *v = pParse->pVdbe; 457613449892Sdrh int i; 45777a95789cSdrh int regHit = 0; 45787a95789cSdrh int addrHitTest = 0; 457913449892Sdrh struct AggInfo_func *pF; 458013449892Sdrh struct AggInfo_col *pC; 458113449892Sdrh 458213449892Sdrh pAggInfo->directMode = 1; 458313449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 458413449892Sdrh int nArg; 4585c99130fdSdrh int addrNext = 0; 458698757157Sdrh int regAgg; 45876ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 45886ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 458913449892Sdrh if( pList ){ 459013449892Sdrh nArg = pList->nExpr; 4591892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 4592d1a01edaSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP); 459313449892Sdrh }else{ 459413449892Sdrh nArg = 0; 459598757157Sdrh regAgg = 0; 459613449892Sdrh } 4597c99130fdSdrh if( pF->iDistinct>=0 ){ 4598c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 4599c99130fdSdrh assert( nArg==1 ); 46002dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 4601c99130fdSdrh } 4602d36e1041Sdrh if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 460313449892Sdrh CollSeq *pColl = 0; 460413449892Sdrh struct ExprList_item *pItem; 460513449892Sdrh int j; 4606e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 460743617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 460813449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 460913449892Sdrh } 461013449892Sdrh if( !pColl ){ 461113449892Sdrh pColl = pParse->db->pDfltColl; 461213449892Sdrh } 46137a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 46147a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 461513449892Sdrh } 461698757157Sdrh sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, 461766a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 4618ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 4619da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 4620f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 4621c99130fdSdrh if( addrNext ){ 4622c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 4623ceea3321Sdrh sqlite3ExprCacheClear(pParse); 4624c99130fdSdrh } 462513449892Sdrh } 462667a6a40cSdan 462767a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 462867a6a40cSdan ** Otherwise, if any of the required column values are already present 462967a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 463067a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 463167a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 463267a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 463367a6a40cSdan ** 463467a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 463567a6a40cSdan ** values to an OP_Copy. 463667a6a40cSdan */ 46377a95789cSdrh if( regHit ){ 4638688852abSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); 46397a95789cSdrh } 464067a6a40cSdan sqlite3ExprCacheClear(pParse); 464113449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 4642389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 464313449892Sdrh } 464413449892Sdrh pAggInfo->directMode = 0; 4645ceea3321Sdrh sqlite3ExprCacheClear(pParse); 46467a95789cSdrh if( addrHitTest ){ 46477a95789cSdrh sqlite3VdbeJumpHere(v, addrHitTest); 46487a95789cSdrh } 464913449892Sdrh } 465013449892Sdrh 4651b3bce662Sdanielk1977 /* 4652ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 4653ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 4654ef7075deSdan */ 4655ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 4656ef7075deSdan static void explainSimpleCount( 4657ef7075deSdan Parse *pParse, /* Parse context */ 4658ef7075deSdan Table *pTab, /* Table being queried */ 4659ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 4660ef7075deSdan ){ 4661ef7075deSdan if( pParse->explain==2 ){ 466248dd1d8eSdrh int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); 46638a4380d7Sdrh char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", 4664ef7075deSdan pTab->zName, 4665e96f2df3Sdan bCover ? " USING COVERING INDEX " : "", 4666e96f2df3Sdan bCover ? pIdx->zName : "" 4667ef7075deSdan ); 4668ef7075deSdan sqlite3VdbeAddOp4( 4669ef7075deSdan pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC 4670ef7075deSdan ); 4671ef7075deSdan } 4672ef7075deSdan } 4673ef7075deSdan #else 4674ef7075deSdan # define explainSimpleCount(a,b,c) 4675ef7075deSdan #endif 4676ef7075deSdan 4677ef7075deSdan /* 46787d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 46799bb61fe7Sdrh ** 4680340309fdSdrh ** The results are returned according to the SelectDest structure. 4681340309fdSdrh ** See comments in sqliteInt.h for further information. 4682e78e8284Sdrh ** 46839bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 46849bb61fe7Sdrh ** encountered, then an appropriate error message is left in 46859bb61fe7Sdrh ** pParse->zErrMsg. 46869bb61fe7Sdrh ** 46879bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 46889bb61fe7Sdrh ** calling function needs to do that. 46899bb61fe7Sdrh */ 46904adee20fSdanielk1977 int sqlite3Select( 4691cce7d176Sdrh Parse *pParse, /* The parser context */ 46929bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 46937d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 4694cce7d176Sdrh ){ 469513449892Sdrh int i, j; /* Loop counters */ 469613449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 469713449892Sdrh Vdbe *v; /* The virtual machine under construction */ 4698b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 4699a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 4700ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 47019bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 47022282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 47032282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 47041d83f052Sdrh int rc = 1; /* Value to return from this function */ 4705e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 4706079a3072Sdrh SortCtx sSort; /* Info on how to code the ORDER BY clause */ 470713449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 4708ec7429aeSdrh int iEnd; /* Address of the end of the query */ 470917435752Sdrh sqlite3 *db; /* The database connection */ 47109bb61fe7Sdrh 47112ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 47122ce22453Sdan int iRestoreSelectId = pParse->iSelectId; 47132ce22453Sdan pParse->iSelectId = pParse->iNextSelectId++; 47142ce22453Sdan #endif 47152ce22453Sdan 471617435752Sdrh db = pParse->db; 471717435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 47186f7adc8aSdrh return 1; 47196f7adc8aSdrh } 47204adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 472113449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 4722eb9b884cSdrh #if SELECTTRACE_ENABLED 4723eb9b884cSdrh pParse->nSelectIndent++; 4724c90713d3Sdrh SELECTTRACE(1,pParse,p, ("begin processing:\n")); 4725c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 4726c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 4727c90713d3Sdrh } 4728eb9b884cSdrh #endif 4729daffd0e5Sdrh 47308e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); 47318e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); 47329afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); 47339afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); 47346c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 47359ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 47369afccba2Sdan pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || 47378e1ee88cSdrh pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || 47388e1ee88cSdrh pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); 4739ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 4740ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 4741ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 4742ccfcbceaSdrh p->pOrderBy = 0; 47437d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 47449a99334dSdrh } 47457d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 4746079a3072Sdrh memset(&sSort, 0, sizeof(sSort)); 4747079a3072Sdrh sSort.pOrderBy = p->pOrderBy; 4748b27b7f5dSdrh pTabList = p->pSrc; 4749b27b7f5dSdrh pEList = p->pEList; 4750956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 47519a99334dSdrh goto select_end; 47529a99334dSdrh } 47537d10d5a6Sdrh isAgg = (p->selFlags & SF_Aggregate)!=0; 475443152cf8Sdrh assert( pEList!=0 ); 4755cce7d176Sdrh 4756d820cb1bSdrh /* Begin generating code. 4757d820cb1bSdrh */ 47584adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 4759d820cb1bSdrh if( v==0 ) goto select_end; 4760d820cb1bSdrh 476174b617b2Sdan /* If writing to memory or generating a set 476274b617b2Sdan ** only a single column may be output. 476374b617b2Sdan */ 476474b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY 476574b617b2Sdan if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ 476674b617b2Sdan goto select_end; 476774b617b2Sdan } 476874b617b2Sdan #endif 476974b617b2Sdan 4770d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 4771d820cb1bSdrh */ 477251522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 4773f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 477413449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 47751013c932Sdrh SelectDest dest; 4776daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 4777f23329a2Sdanielk1977 int isAggSub; 4778c31c2eb8Sdrh 47795b6a9ed4Sdrh if( pSub==0 ) continue; 478021172c4cSdrh 478121172c4cSdrh /* Sometimes the code for a subquery will be generated more than 478221172c4cSdrh ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, 478321172c4cSdrh ** for example. In that case, do not regenerate the code to manifest 478421172c4cSdrh ** a view or the co-routine to implement a view. The first instance 478521172c4cSdrh ** is sufficient, though the subroutine to manifest the view does need 478621172c4cSdrh ** to be invoked again. */ 47875b6a9ed4Sdrh if( pItem->addrFillSub ){ 478821172c4cSdrh if( pItem->viaCoroutine==0 ){ 47895b6a9ed4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 479021172c4cSdrh } 47915b6a9ed4Sdrh continue; 47925b6a9ed4Sdrh } 4793daf79acbSdanielk1977 4794fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 4795f7b5496eSdrh ** tree referred to by this, the parent select. The child select 4796fc976065Sdanielk1977 ** may contain expression trees of at most 4797fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 4798fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 4799fc976065Sdanielk1977 ** an exact limit. 4800fc976065Sdanielk1977 */ 4801fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 4802daf79acbSdanielk1977 48037d10d5a6Sdrh isAggSub = (pSub->selFlags & SF_Aggregate)!=0; 4804524cc21eSdanielk1977 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ 48055b6a9ed4Sdrh /* This subquery can be absorbed into its parent. */ 4806f23329a2Sdanielk1977 if( isAggSub ){ 48077d10d5a6Sdrh isAgg = 1; 48087d10d5a6Sdrh p->selFlags |= SF_Aggregate; 4809daf79acbSdanielk1977 } 4810daf79acbSdanielk1977 i = -1; 4811ee06c99bSdrh }else if( pTabList->nSrc==1 4812a5759677Sdrh && OptimizationEnabled(db, SQLITE_SubqCoroutine) 4813a5759677Sdrh ){ 481421172c4cSdrh /* Implement a co-routine that will return a single row of the result 481521172c4cSdrh ** set on each invocation. 481621172c4cSdrh */ 4817725de29aSdrh int addrTop = sqlite3VdbeCurrentAddr(v)+1; 481821172c4cSdrh pItem->regReturn = ++pParse->nMem; 4819725de29aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 4820725de29aSdrh VdbeComment((v, "%s", pItem->pTab->zName)); 482121172c4cSdrh pItem->addrFillSub = addrTop; 482221172c4cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 482321172c4cSdrh explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 482421172c4cSdrh sqlite3Select(pParse, pSub, &dest); 4825cfc9df76Sdan pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow); 482621172c4cSdrh pItem->viaCoroutine = 1; 48275f612295Sdrh pItem->regResult = dest.iSdst; 482881cf13ecSdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn); 482921172c4cSdrh sqlite3VdbeJumpHere(v, addrTop-1); 483021172c4cSdrh sqlite3ClearTempRegCache(pParse); 4831daf79acbSdanielk1977 }else{ 48325b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 48335b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 48345b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 48355b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 48365b6a9ed4Sdrh */ 48377157e8eaSdrh int topAddr; 483848f2d3b1Sdrh int onceAddr = 0; 48397157e8eaSdrh int retAddr; 48405b6a9ed4Sdrh assert( pItem->addrFillSub==0 ); 48415b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 48427157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 48437157e8eaSdrh pItem->addrFillSub = topAddr+1; 48441d8cb21fSdan if( pItem->isCorrelated==0 ){ 4845ed17167eSdrh /* If the subquery is not correlated and if we are not inside of 48465b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 48475b6a9ed4Sdrh ** once. */ 48487d176105Sdrh onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v); 4849725de29aSdrh VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); 4850725de29aSdrh }else{ 4851725de29aSdrh VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); 48525b6a9ed4Sdrh } 48531013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 4854ce7e189dSdan explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 48557d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 4856cfc9df76Sdan pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow); 485748f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 48587157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 48597157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 48607157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 4861cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 4862daf79acbSdanielk1977 } 486343152cf8Sdrh if( /*pParse->nErr ||*/ db->mallocFailed ){ 4864cfa063b3Sdrh goto select_end; 4865cfa063b3Sdrh } 4866fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 4867832508b7Sdrh pTabList = p->pSrc; 48686c8c8ce0Sdanielk1977 if( !IgnorableOrderby(pDest) ){ 4869079a3072Sdrh sSort.pOrderBy = p->pOrderBy; 4870acd4c695Sdrh } 4871daf79acbSdanielk1977 } 4872daf79acbSdanielk1977 pEList = p->pEList; 4873daf79acbSdanielk1977 #endif 4874daf79acbSdanielk1977 pWhere = p->pWhere; 4875832508b7Sdrh pGroupBy = p->pGroupBy; 4876832508b7Sdrh pHaving = p->pHaving; 4877e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 4878832508b7Sdrh 4879f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 4880f23329a2Sdanielk1977 /* If there is are a sequence of queries, do the earlier ones first. 4881f23329a2Sdanielk1977 */ 4882f23329a2Sdanielk1977 if( p->pPrior ){ 48837f61e92cSdan rc = multiSelect(pParse, p, pDest); 488417c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 4885eb9b884cSdrh #if SELECTTRACE_ENABLED 4886eb9b884cSdrh SELECTTRACE(1,pParse,p,("end compound-select processing\n")); 4887eb9b884cSdrh pParse->nSelectIndent--; 4888eb9b884cSdrh #endif 48897f61e92cSdan return rc; 4890f23329a2Sdanielk1977 } 4891f23329a2Sdanielk1977 #endif 4892f23329a2Sdanielk1977 489350118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 489450118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 489550118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 489650118cdfSdan ** 489750118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 489850118cdfSdan ** 489950118cdfSdan ** is transformed to: 490050118cdfSdan ** 4901dea7d70dSdrh ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz 490250118cdfSdan ** 490350118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 490450118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 490550118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 490650118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 490750118cdfSdan */ 490850118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 4909079a3072Sdrh && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0 491050118cdfSdan ){ 491150118cdfSdan p->selFlags &= ~SF_Distinct; 491250118cdfSdan p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0); 491350118cdfSdan pGroupBy = p->pGroupBy; 4914e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 4915e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 4916e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 4917e8e4af76Sdrh assert( sDistinct.isTnct ); 491850118cdfSdan } 491950118cdfSdan 49208b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 49218b4c40d8Sdrh ** index might end up being unused if the data can be 49229d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 4923b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 49249d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 49259d2985c7Sdrh ** variable is used to facilitate that change. 49267cedc8d4Sdanielk1977 */ 4927079a3072Sdrh if( sSort.pOrderBy ){ 49280342b1f5Sdrh KeyInfo *pKeyInfo; 49293f39bcf5Sdrh pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr); 4930079a3072Sdrh sSort.iECursor = pParse->nTab++; 4931079a3072Sdrh sSort.addrSortIndex = 493266a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 4933f45f2326Sdrh sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 4934f45f2326Sdrh (char*)pKeyInfo, P4_KEYINFO 4935f45f2326Sdrh ); 49369d2985c7Sdrh }else{ 4937079a3072Sdrh sSort.addrSortIndex = -1; 49387cedc8d4Sdanielk1977 } 49397cedc8d4Sdanielk1977 49402d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 49412d0794e3Sdrh */ 49426c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 49432b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 49442d0794e3Sdrh } 49452d0794e3Sdrh 4946f42bacc2Sdrh /* Set the limiter. 4947f42bacc2Sdrh */ 4948f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 4949c63367efSdrh p->nSelectRow = LARGEST_INT64; 4950f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 4951079a3072Sdrh if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 4952079a3072Sdrh sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen; 4953079a3072Sdrh sSort.sortFlags |= SORTFLAG_UseSorter; 4954c6aff30cSdrh } 4955f42bacc2Sdrh 4956dece1a84Sdrh /* Open a virtual index to use for the distinct set. 4957cce7d176Sdrh */ 49582ce22453Sdan if( p->selFlags & SF_Distinct ){ 4959e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 4960e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 4961e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 4962079a3072Sdrh (char*)keyInfoFromExprList(pParse, p->pEList,0,0), 49632ec2fb22Sdrh P4_KEYINFO); 4964d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 4965e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 4966832508b7Sdrh }else{ 4967e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 4968efb7251dSdrh } 4969832508b7Sdrh 497013449892Sdrh if( !isAgg && pGroupBy==0 ){ 4971e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 49726457a353Sdrh u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); 497338cc40c2Sdan 497438cc40c2Sdan /* Begin the database scan. */ 4975079a3072Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, 4976079a3072Sdrh p->pEList, wctrlFlags, 0); 49771d83f052Sdrh if( pWInfo==0 ) goto select_end; 49786f32848dSdrh if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ 49796f32848dSdrh p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); 49806f32848dSdrh } 49816457a353Sdrh if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ 49826f32848dSdrh sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); 49836f32848dSdrh } 4984079a3072Sdrh if( sSort.pOrderBy ){ 4985079a3072Sdrh sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); 4986079a3072Sdrh if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ 4987079a3072Sdrh sSort.pOrderBy = 0; 4988079a3072Sdrh } 4989079a3072Sdrh } 4990cce7d176Sdrh 4991b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 4992b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 49939d2985c7Sdrh ** into an OP_Noop. 49949d2985c7Sdrh */ 4995079a3072Sdrh if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ 4996079a3072Sdrh sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 49979d2985c7Sdrh } 49989d2985c7Sdrh 499938cc40c2Sdan /* Use the standard inner loop. */ 5000079a3072Sdrh selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest, 50016f32848dSdrh sqlite3WhereContinueLabel(pWInfo), 50026f32848dSdrh sqlite3WhereBreakLabel(pWInfo)); 50032282792aSdrh 5004cce7d176Sdrh /* End the database scan loop. 5005cce7d176Sdrh */ 50064adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 500713449892Sdrh }else{ 5008e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 5009e8e4af76Sdrh ** or both */ 501013449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 501113449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 501213449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 501313449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 501413449892Sdrh ** one row of the input to the aggregator has been 501513449892Sdrh ** processed */ 501613449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 501713449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 5018d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 50191c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 50201c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 5021374cd78cSdan int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ 5022d176611bSdrh 5023d176611bSdrh /* Remove any and all aliases between the result set and the 5024d176611bSdrh ** GROUP BY clause. 5025d176611bSdrh */ 5026d176611bSdrh if( pGroupBy ){ 5027dc5ea5c7Sdrh int k; /* Loop counter */ 5028d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 5029d176611bSdrh 5030dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 5031c2acc4e4Sdrh pItem->u.x.iAlias = 0; 5032d176611bSdrh } 5033dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 5034c2acc4e4Sdrh pItem->u.x.iAlias = 0; 5035d176611bSdrh } 5036c63367efSdrh if( p->nSelectRow>100 ) p->nSelectRow = 100; 503795aa47b1Sdrh }else{ 5038c63367efSdrh p->nSelectRow = 1; 5039d176611bSdrh } 5040cce7d176Sdrh 504113449892Sdrh 5042374cd78cSdan /* If there is both a GROUP BY and an ORDER BY clause and they are 5043374cd78cSdan ** identical, then it may be possible to disable the ORDER BY clause 5044374cd78cSdan ** on the grounds that the GROUP BY will cause elements to come out 5045374cd78cSdan ** in the correct order. It also may not - the GROUP BY may use a 5046374cd78cSdan ** database index that causes rows to be grouped together as required 5047374cd78cSdan ** but not actually sorted. Either way, record the fact that the 5048374cd78cSdan ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 5049374cd78cSdan ** variable. */ 5050374cd78cSdan if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 5051374cd78cSdan orderByGrp = 1; 5052374cd78cSdan } 5053374cd78cSdan 5054d176611bSdrh /* Create a label to jump to when we want to abort the query */ 505513449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 505613449892Sdrh 505713449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 505813449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 505913449892Sdrh ** SELECT statement. 50602282792aSdrh */ 506113449892Sdrh memset(&sNC, 0, sizeof(sNC)); 506213449892Sdrh sNC.pParse = pParse; 506313449892Sdrh sNC.pSrcList = pTabList; 506413449892Sdrh sNC.pAggInfo = &sAggInfo; 50657e61d18eSdrh sAggInfo.mnReg = pParse->nMem+1; 5066dd23c6bfSdan sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; 50679d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 5068d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 5069079a3072Sdrh sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); 5070d2b3e23bSdrh if( pHaving ){ 5071d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 507213449892Sdrh } 507313449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 507413449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 50756ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 50763a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 50776ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 50783a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 507913449892Sdrh } 50807e61d18eSdrh sAggInfo.mxReg = pParse->nMem; 508117435752Sdrh if( db->mallocFailed ) goto select_end; 508213449892Sdrh 508313449892Sdrh /* Processing for aggregates with GROUP BY is very different and 50843c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 508513449892Sdrh */ 508613449892Sdrh if( pGroupBy ){ 508713449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 5088d176611bSdrh int j1; /* A-vs-B comparision jump */ 5089d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 5090d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 5091d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 5092d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 5093d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 5094d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 5095d176611bSdrh int regReset; /* Return address register for reset subroutine */ 509613449892Sdrh 509713449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 509813449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 50991c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 510013449892Sdrh ** will be converted into a Noop. 510113449892Sdrh */ 510213449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 51033f39bcf5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn); 51041c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 5105cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 51062ec2fb22Sdrh 0, (char*)pKeyInfo, P4_KEYINFO); 510713449892Sdrh 510813449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 510913449892Sdrh */ 51100a07c107Sdrh iUseFlag = ++pParse->nMem; 51110a07c107Sdrh iAbortFlag = ++pParse->nMem; 5112d176611bSdrh regOutputRow = ++pParse->nMem; 5113d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 5114d176611bSdrh regReset = ++pParse->nMem; 5115d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 51160a07c107Sdrh iAMem = pParse->nMem + 1; 511713449892Sdrh pParse->nMem += pGroupBy->nExpr; 51180a07c107Sdrh iBMem = pParse->nMem + 1; 511913449892Sdrh pParse->nMem += pGroupBy->nExpr; 51204c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 5121d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 51224c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 5123d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 5124b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 5125e313382eSdrh 512613449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 512713449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 512813449892Sdrh ** it might be a single loop that uses an index to extract information 512913449892Sdrh ** in the right order to begin with. 513013449892Sdrh */ 51312eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 513293ec45d5Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 5133374cd78cSdan WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 5134374cd78cSdan ); 51355360ad34Sdrh if( pWInfo==0 ) goto select_end; 5136ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ 513713449892Sdrh /* The optimizer is able to deliver rows in group by order so 5138b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 513913449892Sdrh ** cancelled later because we still need to use the pKeyInfo 514013449892Sdrh */ 514113449892Sdrh groupBySort = 0; 514213449892Sdrh }else{ 514313449892Sdrh /* Rows are coming out in undetermined order. We have to push 514413449892Sdrh ** each row into a sorting index, terminate the first loop, 514513449892Sdrh ** then loop over the sorting index in order to get the output 514613449892Sdrh ** in sorted order 514713449892Sdrh */ 5148892d3179Sdrh int regBase; 5149892d3179Sdrh int regRecord; 5150892d3179Sdrh int nCol; 5151892d3179Sdrh int nGroupBy; 5152892d3179Sdrh 51532ce22453Sdan explainTempTable(pParse, 5154e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 5155e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 51562ce22453Sdan 515713449892Sdrh groupBySort = 1; 5158892d3179Sdrh nGroupBy = pGroupBy->nExpr; 5159dd23c6bfSdan nCol = nGroupBy; 5160dd23c6bfSdan j = nGroupBy; 516113449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 5162892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 5163892d3179Sdrh nCol++; 516413449892Sdrh j++; 516513449892Sdrh } 5166892d3179Sdrh } 5167892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 5168ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5169191b54cbSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); 5170dd23c6bfSdan j = nGroupBy; 5171892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 5172892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 5173892d3179Sdrh if( pCol->iSorterColumn>=j ){ 5174e55cbd72Sdrh int r1 = j + regBase; 51756a012f04Sdrh int r2; 5176701bb3b4Sdrh 51776a012f04Sdrh r2 = sqlite3ExprCodeGetColumn(pParse, 5178a748fdccSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0); 51796a012f04Sdrh if( r1!=r2 ){ 51806a012f04Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); 51816a012f04Sdrh } 51826a012f04Sdrh j++; 5183892d3179Sdrh } 5184892d3179Sdrh } 5185892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 51861db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 51871c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 5188892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 5189892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 519013449892Sdrh sqlite3WhereEnd(pWInfo); 51915134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 51921c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 51931c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 51941c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 5195688852abSdrh VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); 519613449892Sdrh sAggInfo.useSortingIdx = 1; 5197ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5198374cd78cSdan 5199374cd78cSdan } 5200374cd78cSdan 5201374cd78cSdan /* If the index or temporary table used by the GROUP BY sort 5202374cd78cSdan ** will naturally deliver rows in the order required by the ORDER BY 5203374cd78cSdan ** clause, cancel the ephemeral table open coded earlier. 5204374cd78cSdan ** 5205374cd78cSdan ** This is an optimization - the correct answer should result regardless. 5206374cd78cSdan ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 5207374cd78cSdan ** disable this optimization for testing purposes. */ 5208374cd78cSdan if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 5209374cd78cSdan && (groupBySort || sqlite3WhereIsSorted(pWInfo)) 5210374cd78cSdan ){ 5211374cd78cSdan sSort.pOrderBy = 0; 5212374cd78cSdan sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 521313449892Sdrh } 521413449892Sdrh 521513449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 521613449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 521713449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 521813449892Sdrh ** from the previous row currently stored in a0, a1, a2... 521913449892Sdrh */ 522013449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 5221ceea3321Sdrh sqlite3ExprCacheClear(pParse); 52221c9d835dSdrh if( groupBySort ){ 52236cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab); 52241c9d835dSdrh } 522513449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 522613449892Sdrh if( groupBySort ){ 52271c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 522813449892Sdrh }else{ 522913449892Sdrh sAggInfo.directMode = 1; 52302dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 523113449892Sdrh } 523213449892Sdrh } 523316ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 52342ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 523516ee60ffSdrh j1 = sqlite3VdbeCurrentAddr(v); 5236688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v); 523713449892Sdrh 523813449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 5239e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 524013449892Sdrh ** block. If there were no changes, this block is skipped. 524113449892Sdrh ** 524213449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 524313449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 524413449892Sdrh ** and resets the aggregate accumulator registers in preparation 524513449892Sdrh ** for the next GROUP BY batch. 524613449892Sdrh */ 5247b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 52482eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 5249d4e70ebdSdrh VdbeComment((v, "output one row")); 5250688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 5251d4e70ebdSdrh VdbeComment((v, "check abort flag")); 52522eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 5253d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 525413449892Sdrh 525513449892Sdrh /* Update the aggregate accumulators based on the content of 525613449892Sdrh ** the current row 525713449892Sdrh */ 525816ee60ffSdrh sqlite3VdbeJumpHere(v, j1); 525913449892Sdrh updateAccumulator(pParse, &sAggInfo); 52604c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 5261d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 526213449892Sdrh 526313449892Sdrh /* End of the loop 526413449892Sdrh */ 526513449892Sdrh if( groupBySort ){ 52661c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 5267688852abSdrh VdbeCoverage(v); 526813449892Sdrh }else{ 526913449892Sdrh sqlite3WhereEnd(pWInfo); 527048f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 527113449892Sdrh } 527213449892Sdrh 527313449892Sdrh /* Output the final row of result 527413449892Sdrh */ 52752eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 5276d4e70ebdSdrh VdbeComment((v, "output final row")); 527713449892Sdrh 5278d176611bSdrh /* Jump over the subroutines 5279d176611bSdrh */ 5280d176611bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd); 5281d176611bSdrh 5282d176611bSdrh /* Generate a subroutine that outputs a single row of the result 5283d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 5284d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 5285d176611bSdrh ** the processing calls for the query to abort, this subroutine 5286d176611bSdrh ** increments the iAbortFlag memory location before returning in 5287d176611bSdrh ** order to signal the caller to abort. 5288d176611bSdrh */ 5289d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 5290d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 5291d176611bSdrh VdbeComment((v, "set abort flag")); 5292d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5293d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 5294d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 5295688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v); 5296d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 5297d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5298d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 5299d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 5300079a3072Sdrh selectInnerLoop(pParse, p, p->pEList, -1, &sSort, 5301e8e4af76Sdrh &sDistinct, pDest, 5302d176611bSdrh addrOutputRow+1, addrSetAbort); 5303d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5304d176611bSdrh VdbeComment((v, "end groupby result generator")); 5305d176611bSdrh 5306d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 5307d176611bSdrh */ 5308d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 5309d176611bSdrh resetAccumulator(pParse, &sAggInfo); 5310d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 5311d176611bSdrh 531243152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 531313449892Sdrh else { 5314dba0137eSdanielk1977 ExprList *pDel = 0; 5315a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 5316a5533162Sdanielk1977 Table *pTab; 5317a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 5318a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 5319a5533162Sdanielk1977 ** the SQL statement is of the form: 5320a5533162Sdanielk1977 ** 5321a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 5322a5533162Sdanielk1977 ** 5323a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 5324a5533162Sdanielk1977 ** 5325a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 5326a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 5327a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 5328a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 5329a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 5330a5533162Sdanielk1977 */ 5331a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 5332a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 5333a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 5334a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 5335a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 5336a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 5337a9d1ccb9Sdanielk1977 5338a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 5339a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 5340a5533162Sdanielk1977 5341d9e3cad2Sdrh /* Search for the index that has the lowest scan cost. 5342a5533162Sdanielk1977 ** 53433e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 53443e9548b3Sdrh ** 5345abcc1941Sdrh ** (2013-10-03) Do not count the entries in a partial index. 53465f33f375Sdrh ** 5347a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 5348a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 5349a5533162Sdanielk1977 */ 53505c7917e4Sdrh if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); 5351a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 5352d9e3cad2Sdrh if( pIdx->bUnordered==0 5353e13e9f54Sdrh && pIdx->szIdxRow<pTab->szTabRow 5354d3037a41Sdrh && pIdx->pPartIdxWhere==0 5355e13e9f54Sdrh && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) 5356d9e3cad2Sdrh ){ 5357a5533162Sdanielk1977 pBest = pIdx; 5358a5533162Sdanielk1977 } 5359a5533162Sdanielk1977 } 5360d9e3cad2Sdrh if( pBest ){ 5361a5533162Sdanielk1977 iRoot = pBest->tnum; 53622ec2fb22Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); 5363a5533162Sdanielk1977 } 5364a5533162Sdanielk1977 5365a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 5366261c02d9Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); 5367a5533162Sdanielk1977 if( pKeyInfo ){ 53682ec2fb22Sdrh sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); 5369a5533162Sdanielk1977 } 5370a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 5371a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 5372ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 5373a5533162Sdanielk1977 }else 5374a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 5375a5533162Sdanielk1977 { 5376738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 5377738bdcfbSdanielk1977 ** 5378738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 5379738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 5380738bdcfbSdanielk1977 ** 5381738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 5382738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 5383738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 5384738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 5385738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 5386738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 5387738bdcfbSdanielk1977 ** value of x, the only row required). 5388738bdcfbSdanielk1977 ** 5389738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 539048864df9Smistachkin ** modify behavior as follows: 5391738bdcfbSdanielk1977 ** 5392738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 5393738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 5394738bdcfbSdanielk1977 ** for x. 5395738bdcfbSdanielk1977 ** 5396738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 5397738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 5398738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 5399738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 5400738bdcfbSdanielk1977 */ 5401a5533162Sdanielk1977 ExprList *pMinMax = 0; 54024ac391fcSdan u8 flag = WHERE_ORDERBY_NORMAL; 54034ac391fcSdan 54044ac391fcSdan assert( p->pGroupBy==0 ); 54054ac391fcSdan assert( flag==0 ); 54064ac391fcSdan if( p->pHaving==0 ){ 54074ac391fcSdan flag = minMaxQuery(&sAggInfo, &pMinMax); 54084ac391fcSdan } 54094ac391fcSdan assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); 54104ac391fcSdan 5411a9d1ccb9Sdanielk1977 if( flag ){ 54124ac391fcSdan pMinMax = sqlite3ExprListDup(db, pMinMax, 0); 54136ab3a2ecSdanielk1977 pDel = pMinMax; 54140e359b30Sdrh if( pMinMax && !db->mallocFailed ){ 5415ea678832Sdrh pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; 5416a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 5417a9d1ccb9Sdanielk1977 } 54181013c932Sdrh } 5419a9d1ccb9Sdanielk1977 542013449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 542113449892Sdrh ** processing is much simpler since there is only a single row 542213449892Sdrh ** of output. 542313449892Sdrh */ 542413449892Sdrh resetAccumulator(pParse, &sAggInfo); 542546ec5b63Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0); 5426dba0137eSdanielk1977 if( pWInfo==0 ){ 5427633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 5428dba0137eSdanielk1977 goto select_end; 5429dba0137eSdanielk1977 } 543013449892Sdrh updateAccumulator(pParse, &sAggInfo); 543146c35f9bSdrh assert( pMinMax==0 || pMinMax->nExpr==1 ); 5432ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)>0 ){ 54336f32848dSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo)); 5434a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 5435a5533162Sdanielk1977 (flag==WHERE_ORDERBY_MIN?"min":"max"))); 5436a9d1ccb9Sdanielk1977 } 543713449892Sdrh sqlite3WhereEnd(pWInfo); 543813449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 54397a895a80Sdanielk1977 } 54407a895a80Sdanielk1977 5441079a3072Sdrh sSort.pOrderBy = 0; 544235573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 5443079a3072Sdrh selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, 5444a9671a22Sdrh pDest, addrEnd, addrEnd); 5445633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 544613449892Sdrh } 544713449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 544813449892Sdrh 544913449892Sdrh } /* endif aggregate query */ 54502282792aSdrh 5451e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 54522ce22453Sdan explainTempTable(pParse, "DISTINCT"); 54532ce22453Sdan } 54542ce22453Sdan 5455cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 5456cce7d176Sdrh ** and send them to the callback one by one. 5457cce7d176Sdrh */ 5458079a3072Sdrh if( sSort.pOrderBy ){ 54596284db90Sdrh explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); 5460079a3072Sdrh generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 5461cce7d176Sdrh } 54626a535340Sdrh 5463ec7429aeSdrh /* Jump here to skip this query 5464ec7429aeSdrh */ 5465ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 5466ec7429aeSdrh 54671d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 54681d83f052Sdrh ** to indicate no errors. 54691d83f052Sdrh */ 54701d83f052Sdrh rc = 0; 54711d83f052Sdrh 54721d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 54731d83f052Sdrh ** successful coding of the SELECT. 54741d83f052Sdrh */ 54751d83f052Sdrh select_end: 547617c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 5477955de52cSdanielk1977 54787d10d5a6Sdrh /* Identify column names if results of the SELECT are to be output. 5479955de52cSdanielk1977 */ 54807d10d5a6Sdrh if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ 5481955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 5482955de52cSdanielk1977 } 5483955de52cSdanielk1977 5484633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 5485633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 5486eb9b884cSdrh #if SELECTTRACE_ENABLED 5487eb9b884cSdrh SELECTTRACE(1,pParse,p,("end processing\n")); 5488eb9b884cSdrh pParse->nSelectIndent--; 5489eb9b884cSdrh #endif 54901d83f052Sdrh return rc; 5491cce7d176Sdrh } 5492485f0039Sdrh 54934fa4a54fSdrh #ifdef SQLITE_DEBUG 5494485f0039Sdrh /* 54957e02e5e6Sdrh ** Generate a human-readable description of a the Select object. 5496485f0039Sdrh */ 54974fa4a54fSdrh void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){ 5498b08cd3f3Sdrh int n = 0; 54994fa4a54fSdrh pView = sqlite3TreeViewPush(pView, moreToFollow); 55004fa4a54fSdrh sqlite3TreeViewLine(pView, "SELECT%s%s", 55014fa4a54fSdrh ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""), 55024fa4a54fSdrh ((p->selFlags & SF_Aggregate) ? " agg_flag" : "") 55034fa4a54fSdrh ); 5504b08cd3f3Sdrh if( p->pSrc && p->pSrc->nSrc ) n++; 5505b08cd3f3Sdrh if( p->pWhere ) n++; 5506b08cd3f3Sdrh if( p->pGroupBy ) n++; 5507b08cd3f3Sdrh if( p->pHaving ) n++; 5508b08cd3f3Sdrh if( p->pOrderBy ) n++; 5509b08cd3f3Sdrh if( p->pLimit ) n++; 5510b08cd3f3Sdrh if( p->pOffset ) n++; 5511b08cd3f3Sdrh if( p->pPrior ) n++; 5512b08cd3f3Sdrh sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set"); 55137e02e5e6Sdrh if( p->pSrc && p->pSrc->nSrc ){ 5514485f0039Sdrh int i; 5515b08cd3f3Sdrh pView = sqlite3TreeViewPush(pView, (n--)>0); 55164fa4a54fSdrh sqlite3TreeViewLine(pView, "FROM"); 5517485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 5518485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 55194fa4a54fSdrh StrAccum x; 55204fa4a54fSdrh char zLine[100]; 55214fa4a54fSdrh sqlite3StrAccumInit(&x, zLine, sizeof(zLine), 0); 55224fa4a54fSdrh sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor); 55234fa4a54fSdrh if( pItem->zDatabase ){ 55244fa4a54fSdrh sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName); 5525485f0039Sdrh }else if( pItem->zName ){ 55264fa4a54fSdrh sqlite3XPrintf(&x, 0, " %s", pItem->zName); 55274fa4a54fSdrh } 55284fa4a54fSdrh if( pItem->pTab ){ 55294fa4a54fSdrh sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName); 5530485f0039Sdrh } 5531485f0039Sdrh if( pItem->zAlias ){ 55324fa4a54fSdrh sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias); 5533485f0039Sdrh } 5534a84203a0Sdrh if( pItem->jointype & JT_LEFT ){ 55354fa4a54fSdrh sqlite3XPrintf(&x, 0, " LEFT-JOIN"); 5536485f0039Sdrh } 55374fa4a54fSdrh sqlite3StrAccumFinish(&x); 55384fa4a54fSdrh sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1); 55394fa4a54fSdrh if( pItem->pSelect ){ 55404fa4a54fSdrh sqlite3TreeViewSelect(pView, pItem->pSelect, 0); 5541485f0039Sdrh } 55424fa4a54fSdrh sqlite3TreeViewPop(pView); 55434fa4a54fSdrh } 55444fa4a54fSdrh sqlite3TreeViewPop(pView); 5545485f0039Sdrh } 5546485f0039Sdrh if( p->pWhere ){ 5547b08cd3f3Sdrh sqlite3TreeViewItem(pView, "WHERE", (n--)>0); 55484fa4a54fSdrh sqlite3TreeViewExpr(pView, p->pWhere, 0); 55494fa4a54fSdrh sqlite3TreeViewPop(pView); 5550485f0039Sdrh } 5551485f0039Sdrh if( p->pGroupBy ){ 5552b08cd3f3Sdrh sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY"); 5553485f0039Sdrh } 5554485f0039Sdrh if( p->pHaving ){ 5555b08cd3f3Sdrh sqlite3TreeViewItem(pView, "HAVING", (n--)>0); 55564fa4a54fSdrh sqlite3TreeViewExpr(pView, p->pHaving, 0); 55574fa4a54fSdrh sqlite3TreeViewPop(pView); 5558485f0039Sdrh } 5559485f0039Sdrh if( p->pOrderBy ){ 5560b08cd3f3Sdrh sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY"); 5561485f0039Sdrh } 5562a84203a0Sdrh if( p->pLimit ){ 5563b08cd3f3Sdrh sqlite3TreeViewItem(pView, "LIMIT", (n--)>0); 55644fa4a54fSdrh sqlite3TreeViewExpr(pView, p->pLimit, 0); 55654fa4a54fSdrh sqlite3TreeViewPop(pView); 5566a84203a0Sdrh } 5567a84203a0Sdrh if( p->pOffset ){ 5568b08cd3f3Sdrh sqlite3TreeViewItem(pView, "OFFSET", (n--)>0); 55694fa4a54fSdrh sqlite3TreeViewExpr(pView, p->pOffset, 0); 55704fa4a54fSdrh sqlite3TreeViewPop(pView); 5571485f0039Sdrh } 55724fa4a54fSdrh if( p->pPrior ){ 55734fa4a54fSdrh const char *zOp = "UNION"; 55744fa4a54fSdrh switch( p->op ){ 55754fa4a54fSdrh case TK_ALL: zOp = "UNION ALL"; break; 55764fa4a54fSdrh case TK_INTERSECT: zOp = "INTERSECT"; break; 55774fa4a54fSdrh case TK_EXCEPT: zOp = "EXCEPT"; break; 5578485f0039Sdrh } 5579b08cd3f3Sdrh sqlite3TreeViewItem(pView, zOp, (n--)>0); 5580b08cd3f3Sdrh sqlite3TreeViewSelect(pView, p->pPrior, 0); 55814fa4a54fSdrh sqlite3TreeViewPop(pView); 5582a84203a0Sdrh } 55834fa4a54fSdrh sqlite3TreeViewPop(pView); 5584a84203a0Sdrh } 55854fa4a54fSdrh #endif /* SQLITE_DEBUG */ 5586