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)) \ 2438b4149cSdrh sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\ 2538b4149cSdrh (S)->zSelName,(S)),\ 26eb9b884cSdrh sqlite3DebugPrintf X 27abd4c723Sdrh #else 28eb9b884cSdrh # define SELECTTRACE(K,P,S,X) 29abd4c723Sdrh #endif 30abd4c723Sdrh 31abd4c723Sdrh 32abd4c723Sdrh /* 33079a3072Sdrh ** An instance of the following object is used to record information about 34079a3072Sdrh ** how to process the DISTINCT keyword, to simplify passing that information 35079a3072Sdrh ** into the selectInnerLoop() routine. 36079a3072Sdrh */ 37079a3072Sdrh typedef struct DistinctCtx DistinctCtx; 38079a3072Sdrh struct DistinctCtx { 39079a3072Sdrh u8 isTnct; /* True if the DISTINCT keyword is present */ 40079a3072Sdrh u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ 41079a3072Sdrh int tabTnct; /* Ephemeral table used for DISTINCT processing */ 42079a3072Sdrh int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ 43079a3072Sdrh }; 44079a3072Sdrh 45079a3072Sdrh /* 46079a3072Sdrh ** An instance of the following object is used to record information about 47079a3072Sdrh ** the ORDER BY (or GROUP BY) clause of query is being coded. 48079a3072Sdrh */ 49079a3072Sdrh typedef struct SortCtx SortCtx; 50079a3072Sdrh struct SortCtx { 51079a3072Sdrh ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ 52079a3072Sdrh int nOBSat; /* Number of ORDER BY terms satisfied by indices */ 53079a3072Sdrh int iECursor; /* Cursor number for the sorter */ 54079a3072Sdrh int regReturn; /* Register holding block-output return address */ 55079a3072Sdrh int labelBkOut; /* Start label for the block-output subroutine */ 56079a3072Sdrh int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ 57079a3072Sdrh u8 sortFlags; /* Zero or more SORTFLAG_* bits */ 58079a3072Sdrh }; 59079a3072Sdrh #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ 60315555caSdrh 61cce7d176Sdrh /* 62b87fbed5Sdrh ** Delete all the content of a Select structure. Deallocate the structure 63b87fbed5Sdrh ** itself only if bFree is true. 64eda639e1Sdrh */ 65b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){ 66b87fbed5Sdrh while( p ){ 67b87fbed5Sdrh Select *pPrior = p->pPrior; 68633e6d57Sdrh sqlite3ExprListDelete(db, p->pEList); 69633e6d57Sdrh sqlite3SrcListDelete(db, p->pSrc); 70633e6d57Sdrh sqlite3ExprDelete(db, p->pWhere); 71633e6d57Sdrh sqlite3ExprListDelete(db, p->pGroupBy); 72633e6d57Sdrh sqlite3ExprDelete(db, p->pHaving); 73633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 74633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 75633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 764e9119d9Sdan sqlite3WithDelete(db, p->pWith); 77b87fbed5Sdrh if( bFree ) sqlite3DbFree(db, p); 78b87fbed5Sdrh p = pPrior; 79b87fbed5Sdrh bFree = 1; 80b87fbed5Sdrh } 81eda639e1Sdrh } 82eda639e1Sdrh 831013c932Sdrh /* 841013c932Sdrh ** Initialize a SelectDest structure. 851013c932Sdrh */ 861013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 87ea678832Sdrh pDest->eDest = (u8)eDest; 882b596da8Sdrh pDest->iSDParm = iParm; 892b596da8Sdrh pDest->affSdst = 0; 902b596da8Sdrh pDest->iSdst = 0; 912b596da8Sdrh pDest->nSdst = 0; 921013c932Sdrh } 931013c932Sdrh 94eda639e1Sdrh 95eda639e1Sdrh /* 969bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 979bb61fe7Sdrh ** structure. 98cce7d176Sdrh */ 994adee20fSdanielk1977 Select *sqlite3SelectNew( 10017435752Sdrh Parse *pParse, /* Parsing context */ 101daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 102ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 103daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 104daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 105daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 106daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 107832ee3d4Sdrh u16 selFlags, /* Flag parameters, such as SF_Distinct */ 108a2dc3b1aSdanielk1977 Expr *pLimit, /* LIMIT value. NULL means not used */ 109a2dc3b1aSdanielk1977 Expr *pOffset /* OFFSET value. NULL means no offset */ 1109bb61fe7Sdrh ){ 1119bb61fe7Sdrh Select *pNew; 112eda639e1Sdrh Select standin; 11317435752Sdrh sqlite3 *db = pParse->db; 11417435752Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 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; 134b8289a8bSdrh assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=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; 369606f2344Sdrh if( p->op==TK_FUNCTION && p->x.pList ){ 370606f2344Sdrh int i; 371606f2344Sdrh for(i=0; i<p->x.pList->nExpr; i++){ 372606f2344Sdrh setJoinExpr(p->x.pList->a[i].pExpr, iTable); 373606f2344Sdrh } 374606f2344Sdrh } 37522d6a53aSdrh setJoinExpr(p->pLeft, iTable); 3761cc093c2Sdrh p = p->pRight; 3771cc093c2Sdrh } 3781cc093c2Sdrh } 3791cc093c2Sdrh 3801cc093c2Sdrh /* 381ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 382ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 383ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 384ad2d8307Sdrh ** 38591bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 38691bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 38791bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 38891bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 38991bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 39091bb0eedSdrh ** also attached to the left entry. 39191bb0eedSdrh ** 392ad2d8307Sdrh ** This routine returns the number of errors encountered. 393ad2d8307Sdrh */ 394ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 39591bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 39691bb0eedSdrh int i, j; /* Loop counters */ 39791bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 39891bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 399ad2d8307Sdrh 40091bb0eedSdrh pSrc = p->pSrc; 40191bb0eedSdrh pLeft = &pSrc->a[0]; 40291bb0eedSdrh pRight = &pLeft[1]; 40391bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 40491bb0eedSdrh Table *pLeftTab = pLeft->pTab; 40591bb0eedSdrh Table *pRightTab = pRight->pTab; 406ad27e761Sdrh int isOuter; 40791bb0eedSdrh 4081c767f0dSdrh if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; 4098a48b9c0Sdrh isOuter = (pRight->fg.jointype & JT_OUTER)!=0; 410ad2d8307Sdrh 411ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 412ad2d8307Sdrh ** every column that the two tables have in common. 413ad2d8307Sdrh */ 4148a48b9c0Sdrh if( pRight->fg.jointype & JT_NATURAL ){ 41561dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 4164adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 417ad2d8307Sdrh "an ON or USING clause", 0); 418ad2d8307Sdrh return 1; 419ad2d8307Sdrh } 4202179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 4212179b434Sdrh char *zName; /* Name of column in the right table */ 4222179b434Sdrh int iLeft; /* Matching left table */ 4232179b434Sdrh int iLeftCol; /* Matching column in the left table */ 4242179b434Sdrh 4252179b434Sdrh zName = pRightTab->aCol[j].zName; 4262179b434Sdrh if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ 4272179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 4282179b434Sdrh isOuter, &p->pWhere); 429ad2d8307Sdrh } 430ad2d8307Sdrh } 431ad2d8307Sdrh } 432ad2d8307Sdrh 433ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 434ad2d8307Sdrh */ 43561dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 4364adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 437da93d238Sdrh "clauses in the same join"); 438ad2d8307Sdrh return 1; 439ad2d8307Sdrh } 440ad2d8307Sdrh 441ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 44291bb0eedSdrh ** an AND operator. 443ad2d8307Sdrh */ 44461dfc31dSdrh if( pRight->pOn ){ 445ad27e761Sdrh if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 44617435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 44761dfc31dSdrh pRight->pOn = 0; 448ad2d8307Sdrh } 449ad2d8307Sdrh 450ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 451ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 452ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 453ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 454ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 455ad2d8307Sdrh ** not contained in both tables to be joined. 456ad2d8307Sdrh */ 45761dfc31dSdrh if( pRight->pUsing ){ 45861dfc31dSdrh IdList *pList = pRight->pUsing; 459ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 4602179b434Sdrh char *zName; /* Name of the term in the USING clause */ 4612179b434Sdrh int iLeft; /* Table on the left with matching column name */ 4622179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 4632179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 4642179b434Sdrh 4652179b434Sdrh zName = pList->a[j].zName; 4662179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 4672179b434Sdrh if( iRightCol<0 4682179b434Sdrh || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) 4692179b434Sdrh ){ 4704adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 47191bb0eedSdrh "not present in both tables", zName); 472ad2d8307Sdrh return 1; 473ad2d8307Sdrh } 4742179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 4752179b434Sdrh isOuter, &p->pWhere); 476ad2d8307Sdrh } 477ad2d8307Sdrh } 478ad2d8307Sdrh } 479ad2d8307Sdrh return 0; 480ad2d8307Sdrh } 481ad2d8307Sdrh 482079a3072Sdrh /* Forward reference */ 483079a3072Sdrh static KeyInfo *keyInfoFromExprList( 484079a3072Sdrh Parse *pParse, /* Parsing context */ 485079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 486079a3072Sdrh int iStart, /* Begin with this column of pList */ 487079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 488079a3072Sdrh ); 489079a3072Sdrh 490ad2d8307Sdrh /* 491f45f2326Sdrh ** Generate code that will push the record in registers regData 492f45f2326Sdrh ** through regData+nData-1 onto the sorter. 493c926afbcSdrh */ 494d59ba6ceSdrh static void pushOntoSorter( 495d59ba6ceSdrh Parse *pParse, /* Parser context */ 496079a3072Sdrh SortCtx *pSort, /* Information about the ORDER BY clause */ 497b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 498f45f2326Sdrh int regData, /* First register holding data to be sorted */ 4995579d59fSdrh int regOrigData, /* First register holding data before packing */ 500fd0a2f97Sdrh int nData, /* Number of elements in the data array */ 501fd0a2f97Sdrh int nPrefixReg /* No. of reg prior to regData available for use */ 502d59ba6ceSdrh ){ 503f45f2326Sdrh Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 50478d58432Sdan int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 505f45f2326Sdrh int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 50678d58432Sdan int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 507fd0a2f97Sdrh int regBase; /* Regs for sorter record */ 508fb0d6e56Sdrh int regRecord = ++pParse->nMem; /* Assembled sorter record */ 50978d58432Sdan int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 510f45f2326Sdrh int op; /* Opcode to add sorter record to sorter */ 511f45f2326Sdrh 51278d58432Sdan assert( bSeq==0 || bSeq==1 ); 5135579d59fSdrh assert( nData==1 || regData==regOrigData ); 514fd0a2f97Sdrh if( nPrefixReg ){ 51578d58432Sdan assert( nPrefixReg==nExpr+bSeq ); 51678d58432Sdan regBase = regData - nExpr - bSeq; 517fd0a2f97Sdrh }else{ 518fb0d6e56Sdrh regBase = pParse->nMem + 1; 519fb0d6e56Sdrh pParse->nMem += nBase; 520fd0a2f97Sdrh } 5215579d59fSdrh sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, 5225579d59fSdrh SQLITE_ECEL_DUP|SQLITE_ECEL_REF); 52378d58432Sdan if( bSeq ){ 524079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 525fd0a2f97Sdrh } 52678d58432Sdan if( nPrefixReg==0 ){ 527236241aeSdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 52878d58432Sdan } 52978d58432Sdan 530f45f2326Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); 531079a3072Sdrh if( nOBSat>0 ){ 532079a3072Sdrh int regPrevKey; /* The first nOBSat columns of the previous row */ 533079a3072Sdrh int addrFirst; /* Address of the OP_IfNot opcode */ 534079a3072Sdrh int addrJmp; /* Address of the OP_Jump opcode */ 535079a3072Sdrh VdbeOp *pOp; /* Opcode that opens the sorter */ 536079a3072Sdrh int nKey; /* Number of sorting key columns, including OP_Sequence */ 537dbfca2b7Sdrh KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 538079a3072Sdrh 53926d7e7c6Sdrh regPrevKey = pParse->nMem+1; 54026d7e7c6Sdrh pParse->nMem += pSort->nOBSat; 54178d58432Sdan nKey = nExpr - pSort->nOBSat + bSeq; 54278d58432Sdan if( bSeq ){ 54378d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 54478d58432Sdan }else{ 54578d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 54678d58432Sdan } 54778d58432Sdan VdbeCoverage(v); 54826d7e7c6Sdrh sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 549079a3072Sdrh pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 55059b8f2e1Sdrh if( pParse->db->mallocFailed ) return; 551fb0d6e56Sdrh pOp->p2 = nKey + nData; 552dbfca2b7Sdrh pKI = pOp->p4.pKeyInfo; 553dbfca2b7Sdrh memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */ 554dbfca2b7Sdrh sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 555fe201effSdrh testcase( pKI->nXField>2 ); 556fe201effSdrh pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 557fe201effSdrh pKI->nXField-1); 558079a3072Sdrh addrJmp = sqlite3VdbeCurrentAddr(v); 559079a3072Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 560079a3072Sdrh pSort->labelBkOut = sqlite3VdbeMakeLabel(v); 561079a3072Sdrh pSort->regReturn = ++pParse->nMem; 562079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 56365ea12cbSdrh sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 564079a3072Sdrh sqlite3VdbeJumpHere(v, addrFirst); 565236241aeSdrh sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 566079a3072Sdrh sqlite3VdbeJumpHere(v, addrJmp); 567079a3072Sdrh } 568079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 569c6aff30cSdrh op = OP_SorterInsert; 570c6aff30cSdrh }else{ 571c6aff30cSdrh op = OP_IdxInsert; 572c6aff30cSdrh } 573079a3072Sdrh sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord); 57492b01d53Sdrh if( pSelect->iLimit ){ 57516897072Sdrh int addr; 576b7654111Sdrh int iLimit; 5770acb7e48Sdrh if( pSelect->iOffset ){ 578b7654111Sdrh iLimit = pSelect->iOffset+1; 579b7654111Sdrh }else{ 580b7654111Sdrh iLimit = pSelect->iLimit; 581b7654111Sdrh } 5828b0cf38aSdrh addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v); 583079a3072Sdrh sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); 584079a3072Sdrh sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); 58516897072Sdrh sqlite3VdbeJumpHere(v, addr); 586d59ba6ceSdrh } 587c926afbcSdrh } 588c926afbcSdrh 589c926afbcSdrh /* 590ec7429aeSdrh ** Add code to implement the OFFSET 591ea48eb2eSdrh */ 592ec7429aeSdrh static void codeOffset( 593bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 594aa9ce707Sdrh int iOffset, /* Register holding the offset counter */ 595b7654111Sdrh int iContinue /* Jump here to skip the current record */ 596ea48eb2eSdrh ){ 597a22a75e5Sdrh if( iOffset>0 ){ 5988b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); 5998b0cf38aSdrh VdbeComment((v, "OFFSET")); 600ea48eb2eSdrh } 601ea48eb2eSdrh } 602ea48eb2eSdrh 603ea48eb2eSdrh /* 60498757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 60598757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 606a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 607a2a49dc9Sdrh ** if the current N values are new. 608a2a49dc9Sdrh ** 609a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 610a2a49dc9Sdrh ** stack if the top N elements are not distinct. 611a2a49dc9Sdrh */ 612a2a49dc9Sdrh static void codeDistinct( 6132dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 614a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 615a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 616477df4b3Sdrh int N, /* Number of elements */ 617a2a49dc9Sdrh int iMem /* First element */ 618a2a49dc9Sdrh ){ 6192dcef11bSdrh Vdbe *v; 6202dcef11bSdrh int r1; 6212dcef11bSdrh 6222dcef11bSdrh v = pParse->pVdbe; 6232dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 624688852abSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); 6251db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 6262dcef11bSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); 6272dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 628a2a49dc9Sdrh } 629a2a49dc9Sdrh 630bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY 631a2a49dc9Sdrh /* 632e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression 633e305f43fSdrh ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 634bb7dd683Sdrh ** column. We do this in a subroutine because the error used to occur 635bb7dd683Sdrh ** in multiple places. (The error only occurs in one place now, but we 636bb7dd683Sdrh ** retain the subroutine to minimize code disruption.) 637e305f43fSdrh */ 6386c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError( 6396c8c8ce0Sdanielk1977 Parse *pParse, /* Parse context. */ 6406c8c8ce0Sdanielk1977 SelectDest *pDest, /* Destination of SELECT results */ 6416c8c8ce0Sdanielk1977 int nExpr /* Number of result columns returned by SELECT */ 6426c8c8ce0Sdanielk1977 ){ 6436c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 644e305f43fSdrh if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 645e305f43fSdrh sqlite3ErrorMsg(pParse, "only a single result allowed for " 646e305f43fSdrh "a SELECT that is part of an expression"); 647e305f43fSdrh return 1; 648e305f43fSdrh }else{ 649e305f43fSdrh return 0; 650e305f43fSdrh } 651e305f43fSdrh } 652bb7dd683Sdrh #endif 653c99130fdSdrh 654c99130fdSdrh /* 6552282792aSdrh ** This routine generates the code for the inside of the inner loop 6562282792aSdrh ** of a SELECT. 65782c3d636Sdrh ** 658340309fdSdrh ** If srcTab is negative, then the pEList expressions 659340309fdSdrh ** are evaluated in order to get the data for this row. If srcTab is 660340309fdSdrh ** zero or more, then data is pulled from srcTab and pEList is used only 661340309fdSdrh ** to get number columns and the datatype for each column. 6622282792aSdrh */ 663d2b3e23bSdrh static void selectInnerLoop( 6642282792aSdrh Parse *pParse, /* The parser context */ 665df199a25Sdrh Select *p, /* The complete select statement being coded */ 6662282792aSdrh ExprList *pEList, /* List of values being extracted */ 66782c3d636Sdrh int srcTab, /* Pull data from this table */ 668079a3072Sdrh SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ 669e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 6706c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 6712282792aSdrh int iContinue, /* Jump here to continue with next row */ 672a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 6732282792aSdrh ){ 6742282792aSdrh Vdbe *v = pParse->pVdbe; 675d847eaadSdrh int i; 676ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 677d847eaadSdrh int regResult; /* Start of memory holding result set */ 678d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 6792b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 680d847eaadSdrh int nResultCol; /* Number of result columns */ 681fd0a2f97Sdrh int nPrefixReg = 0; /* Number of extra registers before regResult */ 68238640e15Sdrh 6831c767f0dSdrh assert( v ); 68438640e15Sdrh assert( pEList!=0 ); 685e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 686079a3072Sdrh if( pSort && pSort->pOrderBy==0 ) pSort = 0; 687079a3072Sdrh if( pSort==0 && !hasDistinct ){ 688a22a75e5Sdrh assert( iContinue!=0 ); 689aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 690df199a25Sdrh } 691df199a25Sdrh 692967e8b73Sdrh /* Pull the requested columns. 6932282792aSdrh */ 694d847eaadSdrh nResultCol = pEList->nExpr; 69505a86c5cSdrh 6962b596da8Sdrh if( pDest->iSdst==0 ){ 697fd0a2f97Sdrh if( pSort ){ 69878d58432Sdan nPrefixReg = pSort->pOrderBy->nExpr; 69978d58432Sdan if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; 700fd0a2f97Sdrh pParse->nMem += nPrefixReg; 701fd0a2f97Sdrh } 7022b596da8Sdrh pDest->iSdst = pParse->nMem+1; 7030acb7e48Sdrh pParse->nMem += nResultCol; 70405a86c5cSdrh }else if( pDest->iSdst+nResultCol > pParse->nMem ){ 70505a86c5cSdrh /* This is an error condition that can result, for example, when a SELECT 70605a86c5cSdrh ** on the right-hand side of an INSERT contains more result columns than 70705a86c5cSdrh ** there are columns in the table on the left. The error will be caught 70805a86c5cSdrh ** and reported later. But we need to make sure enough memory is allocated 70905a86c5cSdrh ** to avoid other spurious errors in the meantime. */ 71005a86c5cSdrh pParse->nMem += nResultCol; 7111013c932Sdrh } 71205a86c5cSdrh pDest->nSdst = nResultCol; 7132b596da8Sdrh regResult = pDest->iSdst; 714340309fdSdrh if( srcTab>=0 ){ 715340309fdSdrh for(i=0; i<nResultCol; i++){ 716d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 717340309fdSdrh VdbeComment((v, "%s", pEList->a[i].zName)); 71882c3d636Sdrh } 7199ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 7209ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 7219ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 7229ed1dfa8Sdanielk1977 */ 723df553659Sdrh u8 ecelFlags; 724df553659Sdrh if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ 725df553659Sdrh ecelFlags = SQLITE_ECEL_DUP; 726df553659Sdrh }else{ 727df553659Sdrh ecelFlags = 0; 728df553659Sdrh } 7295579d59fSdrh sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags); 730a2a49dc9Sdrh } 7312282792aSdrh 732daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 733daffd0e5Sdrh ** and this row has been seen before, then do not make this row 734daffd0e5Sdrh ** part of the result. 7352282792aSdrh */ 736ea48eb2eSdrh if( hasDistinct ){ 737e8e4af76Sdrh switch( pDistinct->eTnctType ){ 738e8e4af76Sdrh case WHERE_DISTINCT_ORDERED: { 739e8e4af76Sdrh VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 740e8e4af76Sdrh int iJump; /* Jump destination */ 741e8e4af76Sdrh int regPrev; /* Previous row content */ 742e8e4af76Sdrh 743e8e4af76Sdrh /* Allocate space for the previous row */ 744e8e4af76Sdrh regPrev = pParse->nMem+1; 745340309fdSdrh pParse->nMem += nResultCol; 746e8e4af76Sdrh 747e8e4af76Sdrh /* Change the OP_OpenEphemeral coded earlier to an OP_Null 748e8e4af76Sdrh ** sets the MEM_Cleared bit on the first register of the 749e8e4af76Sdrh ** previous value. This will cause the OP_Ne below to always 750e8e4af76Sdrh ** fail on the first iteration of the loop even if the first 751e8e4af76Sdrh ** row is all NULLs. 752e8e4af76Sdrh */ 753e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 754e8e4af76Sdrh pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); 755e8e4af76Sdrh pOp->opcode = OP_Null; 756e8e4af76Sdrh pOp->p1 = 1; 757e8e4af76Sdrh pOp->p2 = regPrev; 758e8e4af76Sdrh 759340309fdSdrh iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; 760340309fdSdrh for(i=0; i<nResultCol; i++){ 761e8e4af76Sdrh CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr); 762340309fdSdrh if( i<nResultCol-1 ){ 763e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); 764688852abSdrh VdbeCoverage(v); 765e8e4af76Sdrh }else{ 766e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); 767688852abSdrh VdbeCoverage(v); 768e8e4af76Sdrh } 769e8e4af76Sdrh sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 770e8e4af76Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 771e8e4af76Sdrh } 772fcf2a775Sdrh assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); 773340309fdSdrh sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); 774e8e4af76Sdrh break; 775e8e4af76Sdrh } 776e8e4af76Sdrh 777e8e4af76Sdrh case WHERE_DISTINCT_UNIQUE: { 778e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 779e8e4af76Sdrh break; 780e8e4af76Sdrh } 781e8e4af76Sdrh 782e8e4af76Sdrh default: { 783e8e4af76Sdrh assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 78438b4149cSdrh codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, 78538b4149cSdrh regResult); 786e8e4af76Sdrh break; 787e8e4af76Sdrh } 788e8e4af76Sdrh } 789079a3072Sdrh if( pSort==0 ){ 790aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 791ea48eb2eSdrh } 7922282792aSdrh } 79382c3d636Sdrh 794c926afbcSdrh switch( eDest ){ 79582c3d636Sdrh /* In this mode, write each query result to the key of the temporary 79682c3d636Sdrh ** table iParm. 7972282792aSdrh */ 79813449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 799c926afbcSdrh case SRT_Union: { 8009cbf3425Sdrh int r1; 8019cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 802340309fdSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); 8039cbf3425Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 8049cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 805c926afbcSdrh break; 806c926afbcSdrh } 80782c3d636Sdrh 80882c3d636Sdrh /* Construct a record from the query result, but instead of 80982c3d636Sdrh ** saving that record, use it as a key to delete elements from 81082c3d636Sdrh ** the temporary table iParm. 81182c3d636Sdrh */ 812c926afbcSdrh case SRT_Except: { 813340309fdSdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); 814c926afbcSdrh break; 815c926afbcSdrh } 816781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 8175338a5f7Sdanielk1977 8185338a5f7Sdanielk1977 /* Store the result as data using a unique key. 8195338a5f7Sdanielk1977 */ 8208e1ee88cSdrh case SRT_Fifo: 8218e1ee88cSdrh case SRT_DistFifo: 8225338a5f7Sdanielk1977 case SRT_Table: 823b9bb7c18Sdrh case SRT_EphemTab: { 824fd0a2f97Sdrh int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 825373cc2ddSdrh testcase( eDest==SRT_Table ); 826373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 827e2248cfdSdrh testcase( eDest==SRT_Fifo ); 828e2248cfdSdrh testcase( eDest==SRT_DistFifo ); 829fd0a2f97Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 8308ce7184bSdan #ifndef SQLITE_OMIT_CTE 8318e1ee88cSdrh if( eDest==SRT_DistFifo ){ 8328e1ee88cSdrh /* If the destination is DistFifo, then cursor (iParm+1) is open 8338ce7184bSdan ** on an ephemeral index. If the current row is already present 8348ce7184bSdan ** in the index, do not write it to the output. If not, add the 8358ce7184bSdan ** current row to the index and proceed with writing it to the 8368ce7184bSdan ** output table as well. */ 8378ce7184bSdan int addr = sqlite3VdbeCurrentAddr(v) + 4; 83838b4149cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); 83938b4149cSdrh VdbeCoverage(v); 8408ce7184bSdan sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1); 841079a3072Sdrh assert( pSort==0 ); 8428ce7184bSdan } 8438ce7184bSdan #endif 844079a3072Sdrh if( pSort ){ 8455579d59fSdrh pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg); 8465338a5f7Sdanielk1977 }else{ 847b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 848b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 849b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 850b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 851b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 8525338a5f7Sdanielk1977 } 853fd0a2f97Sdrh sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 8545338a5f7Sdanielk1977 break; 8555338a5f7Sdanielk1977 } 8562282792aSdrh 85793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 8582282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 8592282792aSdrh ** then there should be a single item on the stack. Write this 8602282792aSdrh ** item into the set table with bogus data. 8612282792aSdrh */ 862c926afbcSdrh case SRT_Set: { 863340309fdSdrh assert( nResultCol==1 ); 864634d81deSdrh pDest->affSdst = 865634d81deSdrh sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst); 866079a3072Sdrh if( pSort ){ 867de941c60Sdrh /* At first glance you would think we could optimize out the 868de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 869de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 870de941c60Sdrh ** case the order does matter */ 8715579d59fSdrh pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg); 872c926afbcSdrh }else{ 873b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 874634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1); 875da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regResult, 1); 876b7654111Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 877b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 878c926afbcSdrh } 879c926afbcSdrh break; 880c926afbcSdrh } 88182c3d636Sdrh 882504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 883ec7429aeSdrh */ 884ec7429aeSdrh case SRT_Exists: { 8854c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 886ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 887ec7429aeSdrh break; 888ec7429aeSdrh } 889ec7429aeSdrh 8902282792aSdrh /* If this is a scalar select that is part of an expression, then 8912282792aSdrh ** store the results in the appropriate memory cell and break out 8922282792aSdrh ** of the scan loop. 8932282792aSdrh */ 894c926afbcSdrh case SRT_Mem: { 895340309fdSdrh assert( nResultCol==1 ); 896079a3072Sdrh if( pSort ){ 8975579d59fSdrh pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg); 898c926afbcSdrh }else{ 89953932ce8Sdrh assert( regResult==iParm ); 900ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 901c926afbcSdrh } 902c926afbcSdrh break; 903c926afbcSdrh } 90493758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 9052282792aSdrh 90681cf13ecSdrh case SRT_Coroutine: /* Send data to a co-routine */ 90781cf13ecSdrh case SRT_Output: { /* Return the results */ 908373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 909373cc2ddSdrh testcase( eDest==SRT_Output ); 910079a3072Sdrh if( pSort ){ 9115579d59fSdrh pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol, 9125579d59fSdrh nPrefixReg); 913e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 9142b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 915c182d163Sdrh }else{ 916340309fdSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 917340309fdSdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 918ac82fcf5Sdrh } 919142e30dfSdrh break; 920142e30dfSdrh } 921142e30dfSdrh 922fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE 923fe1c6bb9Sdrh /* Write the results into a priority queue that is order according to 924fe1c6bb9Sdrh ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an 925fe1c6bb9Sdrh ** index with pSO->nExpr+2 columns. Build a key using pSO for the first 926fe1c6bb9Sdrh ** pSO->nExpr columns, then make sure all keys are unique by adding a 927fe1c6bb9Sdrh ** final OP_Sequence column. The last column is the record as a blob. 928fe1c6bb9Sdrh */ 929fe1c6bb9Sdrh case SRT_DistQueue: 930fe1c6bb9Sdrh case SRT_Queue: { 931fe1c6bb9Sdrh int nKey; 932fe1c6bb9Sdrh int r1, r2, r3; 933fe1c6bb9Sdrh int addrTest = 0; 934fe1c6bb9Sdrh ExprList *pSO; 935fe1c6bb9Sdrh pSO = pDest->pOrderBy; 936fe1c6bb9Sdrh assert( pSO ); 937fe1c6bb9Sdrh nKey = pSO->nExpr; 938fe1c6bb9Sdrh r1 = sqlite3GetTempReg(pParse); 939fe1c6bb9Sdrh r2 = sqlite3GetTempRange(pParse, nKey+2); 940fe1c6bb9Sdrh r3 = r2+nKey+1; 941fe1c6bb9Sdrh if( eDest==SRT_DistQueue ){ 942fe1c6bb9Sdrh /* If the destination is DistQueue, then cursor (iParm+1) is open 943fe1c6bb9Sdrh ** on a second ephemeral index that holds all values every previously 9447e4efaecSdrh ** added to the queue. */ 9457e4efaecSdrh addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 9467e4efaecSdrh regResult, nResultCol); 947688852abSdrh VdbeCoverage(v); 9487e4efaecSdrh } 9497e4efaecSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); 9507e4efaecSdrh if( eDest==SRT_DistQueue ){ 951fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); 952cfe24586Sdan sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 953fe1c6bb9Sdrh } 954fe1c6bb9Sdrh for(i=0; i<nKey; i++){ 955fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, 956fe1c6bb9Sdrh regResult + pSO->a[i].u.x.iOrderByCol - 1, 957fe1c6bb9Sdrh r2+i); 958fe1c6bb9Sdrh } 959fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); 960fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); 961fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); 962fe1c6bb9Sdrh if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); 963fe1c6bb9Sdrh sqlite3ReleaseTempReg(pParse, r1); 964fe1c6bb9Sdrh sqlite3ReleaseTempRange(pParse, r2, nKey+2); 965fe1c6bb9Sdrh break; 966fe1c6bb9Sdrh } 967fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */ 968fe1c6bb9Sdrh 969fe1c6bb9Sdrh 970fe1c6bb9Sdrh 9716a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 972d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 973d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 974d7489c39Sdrh ** user-defined functions that have side effects. We do not care 975d7489c39Sdrh ** about the actual results of the select. 976d7489c39Sdrh */ 977c926afbcSdrh default: { 978f46f905aSdrh assert( eDest==SRT_Discard ); 979c926afbcSdrh break; 980c926afbcSdrh } 98193758c8dSdanielk1977 #endif 982c926afbcSdrh } 983ec7429aeSdrh 9845e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 9855e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 9865e87be87Sdrh ** the output for us. 987ec7429aeSdrh */ 988079a3072Sdrh if( pSort==0 && p->iLimit ){ 98916897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 990ec7429aeSdrh } 99182c3d636Sdrh } 99282c3d636Sdrh 99382c3d636Sdrh /* 994ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and 995ad124329Sdrh ** X extra columns. 996323df790Sdrh */ 997ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 9982ec2fb22Sdrh KeyInfo *p = sqlite3DbMallocZero(0, 999ad124329Sdrh sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1)); 1000323df790Sdrh if( p ){ 1001ad124329Sdrh p->aSortOrder = (u8*)&p->aColl[N+X]; 1002323df790Sdrh p->nField = (u16)N; 1003ad124329Sdrh p->nXField = (u16)X; 1004323df790Sdrh p->enc = ENC(db); 1005323df790Sdrh p->db = db; 10062ec2fb22Sdrh p->nRef = 1; 10072ec2fb22Sdrh }else{ 10082ec2fb22Sdrh db->mallocFailed = 1; 1009323df790Sdrh } 1010323df790Sdrh return p; 1011323df790Sdrh } 1012323df790Sdrh 1013323df790Sdrh /* 10142ec2fb22Sdrh ** Deallocate a KeyInfo object 10152ec2fb22Sdrh */ 10162ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){ 10172ec2fb22Sdrh if( p ){ 10182ec2fb22Sdrh assert( p->nRef>0 ); 10192ec2fb22Sdrh p->nRef--; 1020c6efe12dSmistachkin if( p->nRef==0 ) sqlite3DbFree(0, p); 10212ec2fb22Sdrh } 10222ec2fb22Sdrh } 10232ec2fb22Sdrh 10242ec2fb22Sdrh /* 10252ec2fb22Sdrh ** Make a new pointer to a KeyInfo object 10262ec2fb22Sdrh */ 10272ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ 10282ec2fb22Sdrh if( p ){ 10292ec2fb22Sdrh assert( p->nRef>0 ); 10302ec2fb22Sdrh p->nRef++; 10312ec2fb22Sdrh } 10322ec2fb22Sdrh return p; 10332ec2fb22Sdrh } 10342ec2fb22Sdrh 10352ec2fb22Sdrh #ifdef SQLITE_DEBUG 10362ec2fb22Sdrh /* 10372ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change. The KeyInfo object 10382ec2fb22Sdrh ** can only be changed if this is just a single reference to the object. 10392ec2fb22Sdrh ** 10402ec2fb22Sdrh ** This routine is used only inside of assert() statements. 10412ec2fb22Sdrh */ 10422ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } 10432ec2fb22Sdrh #endif /* SQLITE_DEBUG */ 10442ec2fb22Sdrh 10452ec2fb22Sdrh /* 1046dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 1047dece1a84Sdrh ** the collating sequence for each expression in that expression list. 1048dece1a84Sdrh ** 10490342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 10500342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 10510342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 10520342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 10530342b1f5Sdrh ** index to implement a DISTINCT test. 10540342b1f5Sdrh ** 105560ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc. The calling 1056dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 10572ec2fb22Sdrh ** freed. 1058dece1a84Sdrh */ 1059079a3072Sdrh static KeyInfo *keyInfoFromExprList( 1060079a3072Sdrh Parse *pParse, /* Parsing context */ 1061079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 1062079a3072Sdrh int iStart, /* Begin with this column of pList */ 1063079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 1064079a3072Sdrh ){ 1065dece1a84Sdrh int nExpr; 1066dece1a84Sdrh KeyInfo *pInfo; 1067dece1a84Sdrh struct ExprList_item *pItem; 1068323df790Sdrh sqlite3 *db = pParse->db; 1069dece1a84Sdrh int i; 1070dece1a84Sdrh 1071dece1a84Sdrh nExpr = pList->nExpr; 10723f39bcf5Sdrh pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); 1073dece1a84Sdrh if( pInfo ){ 10742ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pInfo) ); 10756284db90Sdrh for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 1076dece1a84Sdrh CollSeq *pColl; 1077dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 1078323df790Sdrh if( !pColl ) pColl = db->pDfltColl; 10796284db90Sdrh pInfo->aColl[i-iStart] = pColl; 10806284db90Sdrh pInfo->aSortOrder[i-iStart] = pItem->sortOrder; 1081dece1a84Sdrh } 1082dece1a84Sdrh } 1083dece1a84Sdrh return pInfo; 1084dece1a84Sdrh } 1085dece1a84Sdrh 10867f61e92cSdan /* 10877f61e92cSdan ** Name of the connection operator, used for error messages. 10887f61e92cSdan */ 10897f61e92cSdan static const char *selectOpName(int id){ 10907f61e92cSdan char *z; 10917f61e92cSdan switch( id ){ 10927f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 10937f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 10947f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 10957f61e92cSdan default: z = "UNION"; break; 10967f61e92cSdan } 10977f61e92cSdan return z; 10987f61e92cSdan } 10997f61e92cSdan 11002ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 110117c0bc0cSdan /* 110217c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 110317c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 110417c0bc0cSdan ** where the caption is of the form: 110517c0bc0cSdan ** 110617c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 110717c0bc0cSdan ** 110817c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 110917c0bc0cSdan ** is determined by the zUsage argument. 111017c0bc0cSdan */ 11112ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 11122ce22453Sdan if( pParse->explain==2 ){ 11132ce22453Sdan Vdbe *v = pParse->pVdbe; 11142ce22453Sdan char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); 11152ce22453Sdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 11162ce22453Sdan } 11172ce22453Sdan } 111817c0bc0cSdan 111917c0bc0cSdan /* 1120bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 1121bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 1122bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 1123bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 1124bb2b4418Sdan ** code with #ifndef directives. 1125bb2b4418Sdan */ 1126bb2b4418Sdan # define explainSetInteger(a, b) a = b 1127bb2b4418Sdan 1128bb2b4418Sdan #else 1129bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 1130bb2b4418Sdan # define explainTempTable(y,z) 1131bb2b4418Sdan # define explainSetInteger(y,z) 1132bb2b4418Sdan #endif 1133bb2b4418Sdan 1134bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) 1135bb2b4418Sdan /* 11367f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 11377f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 11387f61e92cSdan ** where the caption is of one of the two forms: 11397f61e92cSdan ** 11407f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" 11417f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" 11427f61e92cSdan ** 11437f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding 11447f61e92cSdan ** function parameters, and op is the text representation of the parameter 11457f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, 11467f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 11477f61e92cSdan ** false, or the second form if it is true. 11487f61e92cSdan */ 11497f61e92cSdan static void explainComposite( 11507f61e92cSdan Parse *pParse, /* Parse context */ 11517f61e92cSdan int op, /* One of TK_UNION, TK_EXCEPT etc. */ 11527f61e92cSdan int iSub1, /* Subquery id 1 */ 11537f61e92cSdan int iSub2, /* Subquery id 2 */ 11547f61e92cSdan int bUseTmp /* True if a temp table was used */ 11557f61e92cSdan ){ 11567f61e92cSdan assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); 11577f61e92cSdan if( pParse->explain==2 ){ 11587f61e92cSdan Vdbe *v = pParse->pVdbe; 11597f61e92cSdan char *zMsg = sqlite3MPrintf( 116030969d3fSdan pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, 11617f61e92cSdan bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) 11627f61e92cSdan ); 11637f61e92cSdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 11647f61e92cSdan } 11657f61e92cSdan } 11662ce22453Sdan #else 116717c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */ 11687f61e92cSdan # define explainComposite(v,w,x,y,z) 11692ce22453Sdan #endif 1170dece1a84Sdrh 1171dece1a84Sdrh /* 1172d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 1173d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 1174d8bc7086Sdrh ** we need to run the sorter and output the results. The following 1175d8bc7086Sdrh ** routine generates the code needed to do that. 1176d8bc7086Sdrh */ 1177c926afbcSdrh static void generateSortTail( 1178cdd536f0Sdrh Parse *pParse, /* Parsing context */ 1179c926afbcSdrh Select *p, /* The SELECT statement */ 1180079a3072Sdrh SortCtx *pSort, /* Information on the ORDER BY clause */ 1181c926afbcSdrh int nColumn, /* Number of columns of data */ 11826c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 1183c926afbcSdrh ){ 1184ddba0c22Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1185dc5ea5c7Sdrh int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ 1186dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 1187d8bc7086Sdrh int addr; 1188079a3072Sdrh int addrOnce = 0; 11890342b1f5Sdrh int iTab; 1190079a3072Sdrh ExprList *pOrderBy = pSort->pOrderBy; 11916c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 11922b596da8Sdrh int iParm = pDest->iSDParm; 11932d401ab8Sdrh int regRow; 11942d401ab8Sdrh int regRowid; 1195079a3072Sdrh int nKey; 1196f45f2326Sdrh int iSortTab; /* Sorter cursor to read from */ 1197f45f2326Sdrh int nSortData; /* Trailing values to read from sorter */ 1198f45f2326Sdrh int i; 119978d58432Sdan int bSeq; /* True if sorter record includes seq. no. */ 120070f624c3Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS 120170f624c3Sdrh struct ExprList_item *aOutEx = p->pEList->a; 120270f624c3Sdrh #endif 12032d401ab8Sdrh 1204079a3072Sdrh if( pSort->labelBkOut ){ 1205079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1206076e85f5Sdrh sqlite3VdbeGoto(v, addrBreak); 1207079a3072Sdrh sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1208079a3072Sdrh } 1209079a3072Sdrh iTab = pSort->iECursor; 12107d10d5a6Sdrh if( eDest==SRT_Output || eDest==SRT_Coroutine ){ 12113e9ca094Sdrh regRowid = 0; 1212f45f2326Sdrh regRow = pDest->iSdst; 1213f45f2326Sdrh nSortData = nColumn; 12143e9ca094Sdrh }else{ 12153e9ca094Sdrh regRowid = sqlite3GetTempReg(pParse); 1216f45f2326Sdrh regRow = sqlite3GetTempReg(pParse); 1217f45f2326Sdrh nSortData = 1; 1218cdd536f0Sdrh } 1219079a3072Sdrh nKey = pOrderBy->nExpr - pSort->nOBSat; 1220079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1221c2bb3282Sdrh int regSortOut = ++pParse->nMem; 1222f45f2326Sdrh iSortTab = pParse->nTab++; 122383553eefSdrh if( pSort->labelBkOut ){ 122483553eefSdrh addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v); 122583553eefSdrh } 1226f45f2326Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData); 1227079a3072Sdrh if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); 1228c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 1229688852abSdrh VdbeCoverage(v); 1230aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 12316cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); 123278d58432Sdan bSeq = 0; 1233c6aff30cSdrh }else{ 1234688852abSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1235aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 1236f45f2326Sdrh iSortTab = iTab; 123778d58432Sdan bSeq = 1; 1238f45f2326Sdrh } 1239f45f2326Sdrh for(i=0; i<nSortData; i++){ 124078d58432Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i); 124170f624c3Sdrh VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan)); 1242c6aff30cSdrh } 1243c926afbcSdrh switch( eDest ){ 1244b9bb7c18Sdrh case SRT_EphemTab: { 12452d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 12462d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 12472d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1248c926afbcSdrh break; 1249c926afbcSdrh } 125093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 1251c926afbcSdrh case SRT_Set: { 1252c926afbcSdrh assert( nColumn==1 ); 1253634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, 1254634d81deSdrh &pDest->affSdst, 1); 1255da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regRow, 1); 1256a7a8e14bSdanielk1977 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); 1257c926afbcSdrh break; 1258c926afbcSdrh } 1259c926afbcSdrh case SRT_Mem: { 1260c926afbcSdrh assert( nColumn==1 ); 1261b21e7c70Sdrh sqlite3ExprCodeMove(pParse, regRow, iParm, 1); 1262ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1263c926afbcSdrh break; 1264c926afbcSdrh } 126593758c8dSdanielk1977 #endif 1266373cc2ddSdrh default: { 1267373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 12681c767f0dSdrh testcase( eDest==SRT_Output ); 12691c767f0dSdrh testcase( eDest==SRT_Coroutine ); 12707d10d5a6Sdrh if( eDest==SRT_Output ){ 12712b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 12722b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); 1273a9671a22Sdrh }else{ 12742b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1275ce665cf6Sdrh } 1276ac82fcf5Sdrh break; 1277ac82fcf5Sdrh } 1278c926afbcSdrh } 1279f45f2326Sdrh if( regRowid ){ 12802d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 12812d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1282f45f2326Sdrh } 1283ec7429aeSdrh /* The bottom of the loop 1284ec7429aeSdrh */ 1285dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1286079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1287688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); 1288c6aff30cSdrh }else{ 1289688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); 1290c6aff30cSdrh } 1291079a3072Sdrh if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); 1292dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 1293d8bc7086Sdrh } 1294d8bc7086Sdrh 1295d8bc7086Sdrh /* 1296517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1297517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1298e78e8284Sdrh ** 12995f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that 13005f3e5e74Sdrh ** result in *pEstWidth. 13015f3e5e74Sdrh ** 1302955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1303955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1304955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1305955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1306955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1307955de52cSdanielk1977 ** considered a column by this function. 1308e78e8284Sdrh ** 1309955de52cSdanielk1977 ** SELECT col FROM tbl; 1310955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1311955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1312955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1313955de52cSdanielk1977 ** 1314955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 13155f3e5e74Sdrh ** 13165f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not 13175f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1318fcb78a49Sdrh */ 13195f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 13205f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) 1321b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1322b121dd14Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F) 1323b121dd14Sdrh #endif 13245f3e5e74Sdrh static const char *columnTypeImpl( 1325955de52cSdanielk1977 NameContext *pNC, 1326955de52cSdanielk1977 Expr *pExpr, 1327b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 13285f3e5e74Sdrh const char **pzOrigDb, 13295f3e5e74Sdrh const char **pzOrigTab, 13305f3e5e74Sdrh const char **pzOrigCol, 1331b121dd14Sdrh #endif 13325f3e5e74Sdrh u8 *pEstWidth 1333955de52cSdanielk1977 ){ 1334955de52cSdanielk1977 char const *zType = 0; 1335517eb646Sdanielk1977 int j; 13365f3e5e74Sdrh u8 estWidth = 1; 1337b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1338b121dd14Sdrh char const *zOrigDb = 0; 1339b121dd14Sdrh char const *zOrigTab = 0; 1340b121dd14Sdrh char const *zOrigCol = 0; 1341b121dd14Sdrh #endif 13425338a5f7Sdanielk1977 13435f3e5e74Sdrh if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; 134400e279d9Sdanielk1977 switch( pExpr->op ){ 134530bcf5dbSdrh case TK_AGG_COLUMN: 134600e279d9Sdanielk1977 case TK_COLUMN: { 1347955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1348955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1349955de52cSdanielk1977 ** database table or a subquery. 1350955de52cSdanielk1977 */ 1351955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1352955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1353955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 1354373cc2ddSdrh testcase( pExpr->op==TK_AGG_COLUMN ); 1355373cc2ddSdrh testcase( pExpr->op==TK_COLUMN ); 135643bc88bbSdan while( pNC && !pTab ){ 1357b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1358b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1359b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 13606a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1361955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1362b3bce662Sdanielk1977 }else{ 1363b3bce662Sdanielk1977 pNC = pNC->pNext; 1364b3bce662Sdanielk1977 } 1365b3bce662Sdanielk1977 } 1366955de52cSdanielk1977 136743bc88bbSdan if( pTab==0 ){ 1368417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1369417168adSdrh ** cause this condition to run. Since then, we have restructured how 1370417168adSdrh ** trigger code is generated and so this condition is no longer 137143bc88bbSdan ** possible. However, it can still be true for statements like 137243bc88bbSdan ** the following: 137343bc88bbSdan ** 137443bc88bbSdan ** CREATE TABLE t1(col INTEGER); 137543bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 137643bc88bbSdan ** 137743bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 137843bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 137943bc88bbSdan ** though it should really be "INTEGER". 138043bc88bbSdan ** 138143bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 138243bc88bbSdan ** used. When columnType() is called on the expression 138343bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 138443bc88bbSdan ** branch below. */ 13857e62779aSdrh break; 13867e62779aSdrh } 1387955de52cSdanielk1977 138843bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1389955de52cSdanielk1977 if( pS ){ 1390955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1391955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1392955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1393955de52cSdanielk1977 */ 13942ec18a3cSdrh if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ 1395955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1396955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1397955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 13982ec18a3cSdrh ** 13992ec18a3cSdrh ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been 14002ec18a3cSdrh ** caught already by name resolution. 1401955de52cSdanielk1977 */ 1402955de52cSdanielk1977 NameContext sNC; 1403955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1404955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 140543bc88bbSdan sNC.pNext = pNC; 1406955de52cSdanielk1977 sNC.pParse = pNC->pParse; 14075f3e5e74Sdrh zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); 1408955de52cSdanielk1977 } 140993c36bb3Sdrh }else if( pTab->pSchema ){ 1410955de52cSdanielk1977 /* A real table */ 1411955de52cSdanielk1977 assert( !pS ); 1412fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1413fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 14145f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1415fcb78a49Sdrh if( iCol<0 ){ 1416fcb78a49Sdrh zType = "INTEGER"; 14175f3e5e74Sdrh zOrigCol = "rowid"; 1418fcb78a49Sdrh }else{ 1419fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 14205f3e5e74Sdrh zOrigCol = pTab->aCol[iCol].zName; 14215f3e5e74Sdrh estWidth = pTab->aCol[iCol].szEst; 1422955de52cSdanielk1977 } 14235f3e5e74Sdrh zOrigTab = pTab->zName; 1424955de52cSdanielk1977 if( pNC->pParse ){ 1425955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 14265f3e5e74Sdrh zOrigDb = pNC->pParse->db->aDb[iDb].zName; 1427955de52cSdanielk1977 } 14285f3e5e74Sdrh #else 14295f3e5e74Sdrh if( iCol<0 ){ 14305f3e5e74Sdrh zType = "INTEGER"; 14315f3e5e74Sdrh }else{ 14325f3e5e74Sdrh zType = pTab->aCol[iCol].zType; 14335f3e5e74Sdrh estWidth = pTab->aCol[iCol].szEst; 14345f3e5e74Sdrh } 14355f3e5e74Sdrh #endif 1436fcb78a49Sdrh } 143700e279d9Sdanielk1977 break; 1438736c22b8Sdrh } 143993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 144000e279d9Sdanielk1977 case TK_SELECT: { 1441955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1442955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1443955de52cSdanielk1977 ** statement. 1444955de52cSdanielk1977 */ 1445b3bce662Sdanielk1977 NameContext sNC; 14466ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1447955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 14486ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1449955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1450b3bce662Sdanielk1977 sNC.pNext = pNC; 1451955de52cSdanielk1977 sNC.pParse = pNC->pParse; 14525f3e5e74Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); 145300e279d9Sdanielk1977 break; 1454fcb78a49Sdrh } 145593758c8dSdanielk1977 #endif 145600e279d9Sdanielk1977 } 145700e279d9Sdanielk1977 14585f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 14595f3e5e74Sdrh if( pzOrigDb ){ 14605f3e5e74Sdrh assert( pzOrigTab && pzOrigCol ); 14615f3e5e74Sdrh *pzOrigDb = zOrigDb; 14625f3e5e74Sdrh *pzOrigTab = zOrigTab; 14635f3e5e74Sdrh *pzOrigCol = zOrigCol; 1464955de52cSdanielk1977 } 14655f3e5e74Sdrh #endif 14665f3e5e74Sdrh if( pEstWidth ) *pEstWidth = estWidth; 1467517eb646Sdanielk1977 return zType; 1468517eb646Sdanielk1977 } 1469517eb646Sdanielk1977 1470517eb646Sdanielk1977 /* 1471517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1472517eb646Sdanielk1977 ** in the result set. 1473517eb646Sdanielk1977 */ 1474517eb646Sdanielk1977 static void generateColumnTypes( 1475517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1476517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1477517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1478517eb646Sdanielk1977 ){ 14793f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1480517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1481517eb646Sdanielk1977 int i; 1482b3bce662Sdanielk1977 NameContext sNC; 1483b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1484955de52cSdanielk1977 sNC.pParse = pParse; 1485517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1486517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 14873f913576Sdrh const char *zType; 14883f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1489955de52cSdanielk1977 const char *zOrigDb = 0; 1490955de52cSdanielk1977 const char *zOrigTab = 0; 1491955de52cSdanielk1977 const char *zOrigCol = 0; 14925f3e5e74Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0); 1493955de52cSdanielk1977 149485b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 14954b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 14964b1ae99dSdanielk1977 ** virtual machine is deleted. 1497fbcd585fSdanielk1977 */ 149810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 149910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 150010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 15013f913576Sdrh #else 15025f3e5e74Sdrh zType = columnType(&sNC, p, 0, 0, 0, 0); 15033f913576Sdrh #endif 150410fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1505fcb78a49Sdrh } 15065f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ 1507fcb78a49Sdrh } 1508fcb78a49Sdrh 1509fcb78a49Sdrh /* 1510fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1511fcb78a49Sdrh ** in the result set. This information is used to provide the 1512fcabd464Sdrh ** azCol[] values in the callback. 151382c3d636Sdrh */ 1514832508b7Sdrh static void generateColumnNames( 1515832508b7Sdrh Parse *pParse, /* Parser context */ 1516ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1517832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1518832508b7Sdrh ){ 1519d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 15206a3ea0e6Sdrh int i, j; 15219bb575fdSdrh sqlite3 *db = pParse->db; 1522fcabd464Sdrh int fullNames, shortNames; 1523fcabd464Sdrh 1524fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 15253cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 15263cf86063Sdanielk1977 if( pParse->explain ){ 152761de0d1bSdanielk1977 return; 15283cf86063Sdanielk1977 } 15295338a5f7Sdanielk1977 #endif 15303cf86063Sdanielk1977 1531e2f02bacSdrh if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; 1532d8bc7086Sdrh pParse->colNamesSet = 1; 1533fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1534fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 153522322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 153682c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 153782c3d636Sdrh Expr *p; 15385a38705eSdrh p = pEList->a[i].pExpr; 1539373cc2ddSdrh if( NEVER(p==0) ) continue; 154082c3d636Sdrh if( pEList->a[i].zName ){ 154182c3d636Sdrh char *zName = pEList->a[i].zName; 154210fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1543f018cc2eSdrh }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ 15446a3ea0e6Sdrh Table *pTab; 154597665873Sdrh char *zCol; 15468aff1015Sdrh int iCol = p->iColumn; 1547e2f02bacSdrh for(j=0; ALWAYS(j<pTabList->nSrc); j++){ 1548e2f02bacSdrh if( pTabList->a[j].iCursor==p->iTable ) break; 1549e2f02bacSdrh } 15506a3ea0e6Sdrh assert( j<pTabList->nSrc ); 15516a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 15528aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 155397665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1554b1363206Sdrh if( iCol<0 ){ 155547a6db2bSdrh zCol = "rowid"; 1556b1363206Sdrh }else{ 1557b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1558b1363206Sdrh } 1559e49b146fSdrh if( !shortNames && !fullNames ){ 156010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1561b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 15621c767f0dSdrh }else if( fullNames ){ 156382c3d636Sdrh char *zName = 0; 15641c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 156510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 156682c3d636Sdrh }else{ 156710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 156882c3d636Sdrh } 15691bee3d7bSdrh }else{ 1570859bc542Sdrh const char *z = pEList->a[i].zSpan; 1571859bc542Sdrh z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); 1572859bc542Sdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); 157382c3d636Sdrh } 157482c3d636Sdrh } 157576d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 15765080aaa7Sdrh } 157782c3d636Sdrh 1578d8bc7086Sdrh /* 157960ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions 15807d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 15817d10d5a6Sdrh ** column names for a table that would hold the expression list. 15827d10d5a6Sdrh ** 15837d10d5a6Sdrh ** All column names will be unique. 15847d10d5a6Sdrh ** 15857d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 15867d10d5a6Sdrh ** and other fields of Column are zeroed. 15877d10d5a6Sdrh ** 15887d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 15897d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1590315555caSdrh */ 15918981b904Sdrh int sqlite3ColumnsFromExprList( 15927d10d5a6Sdrh Parse *pParse, /* Parsing context */ 15937d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 1594d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 15957d10d5a6Sdrh Column **paCol /* Write the new column list here */ 15967d10d5a6Sdrh ){ 1597dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1598dc5ea5c7Sdrh int i, j; /* Loop counters */ 1599dc5ea5c7Sdrh int cnt; /* Index added to make the name unique */ 1600dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1601dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1602dc5ea5c7Sdrh Expr *p; /* Expression for a single result column */ 1603dc5ea5c7Sdrh char *zName; /* Column name */ 1604dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 160579d5f63fSdrh 16068c2e0f02Sdan if( pEList ){ 16078c2e0f02Sdan nCol = pEList->nExpr; 16088c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 16098c2e0f02Sdan testcase( aCol==0 ); 16108c2e0f02Sdan }else{ 16118c2e0f02Sdan nCol = 0; 16128c2e0f02Sdan aCol = 0; 16138c2e0f02Sdan } 16148c2e0f02Sdan *pnCol = nCol; 16158c2e0f02Sdan *paCol = aCol; 16168c2e0f02Sdan 16177d10d5a6Sdrh for(i=0, pCol=aCol; i<nCol; i++, pCol++){ 161879d5f63fSdrh /* Get an appropriate name for the column 161979d5f63fSdrh */ 1620580c8c18Sdrh p = sqlite3ExprSkipCollate(pEList->a[i].pExpr); 162191bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 162279d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 162317435752Sdrh zName = sqlite3DbStrDup(db, zName); 16247d10d5a6Sdrh }else{ 1625dc5ea5c7Sdrh Expr *pColExpr = p; /* The expression that is the result column name */ 1626dc5ea5c7Sdrh Table *pTab; /* Table associated with this expression */ 1627b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1628b07028f7Sdrh pColExpr = pColExpr->pRight; 1629b07028f7Sdrh assert( pColExpr!=0 ); 1630b07028f7Sdrh } 1631373cc2ddSdrh if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ 163293a960a0Sdrh /* For columns use the column name name */ 1633dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1634373cc2ddSdrh pTab = pColExpr->pTab; 1635f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1636f0209f74Sdrh zName = sqlite3MPrintf(db, "%s", 1637f0209f74Sdrh iCol>=0 ? pTab->aCol[iCol].zName : "rowid"); 1638b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 163933e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 164033e619fcSdrh zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); 164193a960a0Sdrh }else{ 164279d5f63fSdrh /* Use the original text of the column expression as its name */ 1643b7916a78Sdrh zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); 16447d10d5a6Sdrh } 164522f70c32Sdrh } 16467ce72f69Sdrh if( db->mallocFailed ){ 1647633e6d57Sdrh sqlite3DbFree(db, zName); 16487ce72f69Sdrh break; 1649dd5b2fa5Sdrh } 165079d5f63fSdrh 165179d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 165260ec914cSpeter.d.reid ** append an integer to the name so that it becomes unique. 165379d5f63fSdrh */ 1654ea678832Sdrh nName = sqlite3Strlen30(zName); 165579d5f63fSdrh for(j=cnt=0; j<i; j++){ 165679d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 1657633e6d57Sdrh char *zNewName; 1658fb777327Sdrh int k; 1659fb777327Sdrh for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){} 166019c6d96aSdrh if( k>=0 && zName[k]==':' ) nName = k; 16612564ef97Sdrh zName[nName] = 0; 1662633e6d57Sdrh zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt); 1663633e6d57Sdrh sqlite3DbFree(db, zName); 1664633e6d57Sdrh zName = zNewName; 166579d5f63fSdrh j = -1; 1666dd5b2fa5Sdrh if( zName==0 ) break; 166779d5f63fSdrh } 166879d5f63fSdrh } 166991bb0eedSdrh pCol->zName = zName; 16707d10d5a6Sdrh } 16717d10d5a6Sdrh if( db->mallocFailed ){ 16727d10d5a6Sdrh for(j=0; j<i; j++){ 16737d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 16747d10d5a6Sdrh } 16757d10d5a6Sdrh sqlite3DbFree(db, aCol); 16767d10d5a6Sdrh *paCol = 0; 16777d10d5a6Sdrh *pnCol = 0; 16787d10d5a6Sdrh return SQLITE_NOMEM; 16797d10d5a6Sdrh } 16807d10d5a6Sdrh return SQLITE_OK; 16817d10d5a6Sdrh } 1682e014a838Sdanielk1977 16837d10d5a6Sdrh /* 16847d10d5a6Sdrh ** Add type and collation information to a column list based on 16857d10d5a6Sdrh ** a SELECT statement. 16867d10d5a6Sdrh ** 16877d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 16887d10d5a6Sdrh ** The column list has only names, not types or collations. This 16897d10d5a6Sdrh ** routine goes through and adds the types and collations. 16907d10d5a6Sdrh ** 1691b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 16927d10d5a6Sdrh ** statement be resolved. 169379d5f63fSdrh */ 16947d10d5a6Sdrh static void selectAddColumnTypeAndCollation( 16957d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 1696186ad8ccSdrh Table *pTab, /* Add column type information to this table */ 16977d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 16987d10d5a6Sdrh ){ 16997d10d5a6Sdrh sqlite3 *db = pParse->db; 17007d10d5a6Sdrh NameContext sNC; 17017d10d5a6Sdrh Column *pCol; 17027d10d5a6Sdrh CollSeq *pColl; 17037d10d5a6Sdrh int i; 17047d10d5a6Sdrh Expr *p; 17057d10d5a6Sdrh struct ExprList_item *a; 1706186ad8ccSdrh u64 szAll = 0; 17077d10d5a6Sdrh 17087d10d5a6Sdrh assert( pSelect!=0 ); 17097d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 1710186ad8ccSdrh assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 17117d10d5a6Sdrh if( db->mallocFailed ) return; 1712c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1713b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 17147d10d5a6Sdrh a = pSelect->pEList->a; 1715186ad8ccSdrh for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 17167d10d5a6Sdrh p = a[i].pExpr; 17171cb50c88Sdrh if( pCol->zType==0 ){ 171838b4149cSdrh pCol->zType = sqlite3DbStrDup(db, 171938b4149cSdrh columnType(&sNC, p,0,0,0, &pCol->szEst)); 17201cb50c88Sdrh } 1721186ad8ccSdrh szAll += pCol->szEst; 1722c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 172305883a34Sdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB; 1724b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 17251cb50c88Sdrh if( pColl && pCol->zColl==0 ){ 172617435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 17270202b29eSdanielk1977 } 172822f70c32Sdrh } 1729186ad8ccSdrh pTab->szTabRow = sqlite3LogEst(szAll*4); 17307d10d5a6Sdrh } 17317d10d5a6Sdrh 17327d10d5a6Sdrh /* 17337d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 17347d10d5a6Sdrh ** the result set of that SELECT. 17357d10d5a6Sdrh */ 17367d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 17377d10d5a6Sdrh Table *pTab; 17387d10d5a6Sdrh sqlite3 *db = pParse->db; 17397d10d5a6Sdrh int savedFlags; 17407d10d5a6Sdrh 17417d10d5a6Sdrh savedFlags = db->flags; 17427d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 17437d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 17447d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 17457d10d5a6Sdrh if( pParse->nErr ) return 0; 17467d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 17477d10d5a6Sdrh db->flags = savedFlags; 17487d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 17497d10d5a6Sdrh if( pTab==0 ){ 17507d10d5a6Sdrh return 0; 17517d10d5a6Sdrh } 1752373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 1753b2468954Sdrh ** is disabled */ 1754373cc2ddSdrh assert( db->lookaside.bEnabled==0 ); 17557d10d5a6Sdrh pTab->nRef = 1; 17567d10d5a6Sdrh pTab->zName = 0; 1757cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 17588981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 1759186ad8ccSdrh selectAddColumnTypeAndCollation(pParse, pTab, pSelect); 176022f70c32Sdrh pTab->iPKey = -1; 17617ce72f69Sdrh if( db->mallocFailed ){ 17621feeaed2Sdan sqlite3DeleteTable(db, pTab); 17637ce72f69Sdrh return 0; 17647ce72f69Sdrh } 176522f70c32Sdrh return pTab; 176622f70c32Sdrh } 176722f70c32Sdrh 176822f70c32Sdrh /* 1769d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1770d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1771d8bc7086Sdrh */ 17724adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1773d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1774d8bc7086Sdrh if( v==0 ){ 17759ac7962aSdrh v = pParse->pVdbe = sqlite3VdbeCreate(pParse); 1776aceb31b1Sdrh if( v ) sqlite3VdbeAddOp0(v, OP_Init); 1777e0e261a4Sdrh if( pParse->pToplevel==0 1778e0e261a4Sdrh && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) 1779e0e261a4Sdrh ){ 1780e0e261a4Sdrh pParse->okConstFactor = 1; 1781e0e261a4Sdrh } 1782e0e261a4Sdrh 1783d8bc7086Sdrh } 1784d8bc7086Sdrh return v; 1785d8bc7086Sdrh } 1786d8bc7086Sdrh 178715007a99Sdrh 1788d8bc7086Sdrh /* 17897b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1790ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 17917b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1792a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1793a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1794a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1795a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 17967b58daeaSdrh ** 1797d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1798ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 1799aa9ce707Sdrh ** iOffset should have been preset to appropriate default values (zero) 1800aa9ce707Sdrh ** prior to calling this routine. 1801aa9ce707Sdrh ** 1802aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value 1803aa9ce707Sdrh ** of the OFFSET. The iLimit register is initialized to LIMIT. Register 1804aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET. 1805aa9ce707Sdrh ** 1806ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 18077b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 18087b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 18097b58daeaSdrh ** SELECT statements. 18107b58daeaSdrh */ 1811ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 181202afc861Sdrh Vdbe *v = 0; 181302afc861Sdrh int iLimit = 0; 181415007a99Sdrh int iOffset; 18158b0cf38aSdrh int n; 18160acb7e48Sdrh if( p->iLimit ) return; 181715007a99Sdrh 18187b58daeaSdrh /* 18197b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 1820f7b5496eSdrh ** controversy about what the correct behavior should be. 18217b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 18227b58daeaSdrh ** no rows. 18237b58daeaSdrh */ 1824ceea3321Sdrh sqlite3ExprCacheClear(pParse); 1825373cc2ddSdrh assert( p->pOffset==0 || p->pLimit!=0 ); 1826a2dc3b1aSdanielk1977 if( p->pLimit ){ 18270a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 182815007a99Sdrh v = sqlite3GetVdbe(pParse); 1829aa9ce707Sdrh assert( v!=0 ); 18309b918ed1Sdrh if( sqlite3ExprIsInteger(p->pLimit, &n) ){ 18319b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 18329b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 1833456e4e4fSdrh if( n==0 ){ 1834076e85f5Sdrh sqlite3VdbeGoto(v, iBreak); 1835613ba1eaSdrh }else if( n>=0 && p->nSelectRow>(u64)n ){ 1836613ba1eaSdrh p->nSelectRow = n; 18379b918ed1Sdrh } 18389b918ed1Sdrh }else{ 1839b7654111Sdrh sqlite3ExprCode(pParse, p->pLimit, iLimit); 1840688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 1841d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 184216897072Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); 18439b918ed1Sdrh } 1844a2dc3b1aSdanielk1977 if( p->pOffset ){ 18450a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 1846b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 1847b7654111Sdrh sqlite3ExprCode(pParse, p->pOffset, iOffset); 1848688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 1849d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 18508b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iOffset, iOffset, 0); 1851b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); 1852d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 18538b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iLimit, iOffset+1, -1); 1854b7654111Sdrh } 1855d59ba6ceSdrh } 18567b58daeaSdrh } 18577b58daeaSdrh 1858b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1859fbc4ee7bSdrh /* 1860fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1861fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1862fbc4ee7bSdrh ** the column has no default collating sequence. 1863fbc4ee7bSdrh ** 1864fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1865fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1866fbc4ee7bSdrh */ 1867dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1868fbc4ee7bSdrh CollSeq *pRet; 1869dc1bdc4fSdanielk1977 if( p->pPrior ){ 1870dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1871fbc4ee7bSdrh }else{ 1872fbc4ee7bSdrh pRet = 0; 1873dc1bdc4fSdanielk1977 } 187410c081adSdrh assert( iCol>=0 ); 18752ec18a3cSdrh /* iCol must be less than p->pEList->nExpr. Otherwise an error would 18762ec18a3cSdrh ** have been thrown during name resolution and we would not have gotten 18772ec18a3cSdrh ** this far */ 18782ec18a3cSdrh if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ 1879dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1880dc1bdc4fSdanielk1977 } 1881dc1bdc4fSdanielk1977 return pRet; 1882d3d39e93Sdrh } 188353bed45eSdan 188453bed45eSdan /* 188553bed45eSdan ** The select statement passed as the second parameter is a compound SELECT 188653bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo 188753bed45eSdan ** structure suitable for implementing the ORDER BY. 188853bed45eSdan ** 188953bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling 189053bed45eSdan ** function is responsible for ensuring that this structure is eventually 189153bed45eSdan ** freed. 189253bed45eSdan */ 189353bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ 189453bed45eSdan ExprList *pOrderBy = p->pOrderBy; 189553bed45eSdan int nOrderBy = p->pOrderBy->nExpr; 189653bed45eSdan sqlite3 *db = pParse->db; 189753bed45eSdan KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); 189853bed45eSdan if( pRet ){ 189953bed45eSdan int i; 190053bed45eSdan for(i=0; i<nOrderBy; i++){ 190153bed45eSdan struct ExprList_item *pItem = &pOrderBy->a[i]; 190253bed45eSdan Expr *pTerm = pItem->pExpr; 190353bed45eSdan CollSeq *pColl; 190453bed45eSdan 190553bed45eSdan if( pTerm->flags & EP_Collate ){ 190653bed45eSdan pColl = sqlite3ExprCollSeq(pParse, pTerm); 190753bed45eSdan }else{ 190853bed45eSdan pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); 190953bed45eSdan if( pColl==0 ) pColl = db->pDfltColl; 191053bed45eSdan pOrderBy->a[i].pExpr = 191153bed45eSdan sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); 191253bed45eSdan } 191353bed45eSdan assert( sqlite3KeyInfoIsWriteable(pRet) ); 191453bed45eSdan pRet->aColl[i] = pColl; 191553bed45eSdan pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder; 191653bed45eSdan } 191753bed45eSdan } 191853bed45eSdan 191953bed45eSdan return pRet; 192053bed45eSdan } 1921d3d39e93Sdrh 1922781def29Sdrh #ifndef SQLITE_OMIT_CTE 1923781def29Sdrh /* 1924781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 1925781def29Sdrh ** query of the form: 1926781def29Sdrh ** 1927781def29Sdrh ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 1928781def29Sdrh ** \___________/ \_______________/ 1929781def29Sdrh ** p->pPrior p 1930781def29Sdrh ** 1931781def29Sdrh ** 1932781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause 19338a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. 1934781def29Sdrh ** 1935781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go 1936781def29Sdrh ** into a Queue table. Rows are extracted from the Queue table one by 1937fe1c6bb9Sdrh ** one. Each row extracted from Queue is output to pDest. Then the single 1938fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the 1939fe1c6bb9Sdrh ** recursive-table for a recursive-query run. The output of the recursive-query 1940781def29Sdrh ** is added back into the Queue table. Then another row is extracted from Queue 1941781def29Sdrh ** and the iteration continues until the Queue table is empty. 1942781def29Sdrh ** 1943781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever 1944781def29Sdrh ** inserted into the Queue table. The iDistinct table keeps a copy of all rows 1945781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be 1946781def29Sdrh ** discarded. If the operator is UNION ALL, then duplicates are allowed. 1947781def29Sdrh ** 1948781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in 1949781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle. Without 1950781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO. 1951781def29Sdrh ** 1952781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows 1953781def29Sdrh ** have been output to pDest. A LIMIT of zero means to output no rows and a 1954781def29Sdrh ** negative LIMIT means to output all rows. If there is also an OFFSET clause 1955781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather 1956781def29Sdrh ** than being sent to pDest. The LIMIT count does not begin until after OFFSET 1957781def29Sdrh ** rows have been skipped. 1958781def29Sdrh */ 1959781def29Sdrh static void generateWithRecursiveQuery( 1960781def29Sdrh Parse *pParse, /* Parsing context */ 1961781def29Sdrh Select *p, /* The recursive SELECT to be coded */ 1962781def29Sdrh SelectDest *pDest /* What to do with query results */ 1963781def29Sdrh ){ 1964781def29Sdrh SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ 1965781def29Sdrh int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ 1966781def29Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ 1967781def29Sdrh Select *pSetup = p->pPrior; /* The setup query */ 1968781def29Sdrh int addrTop; /* Top of the loop */ 1969781def29Sdrh int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ 1970edf83d1eSdrh int iCurrent = 0; /* The Current table */ 1971781def29Sdrh int regCurrent; /* Register holding Current table */ 1972781def29Sdrh int iQueue; /* The Queue table */ 1973781def29Sdrh int iDistinct = 0; /* To ensure unique results if UNION */ 19748e1ee88cSdrh int eDest = SRT_Fifo; /* How to write to Queue */ 1975781def29Sdrh SelectDest destQueue; /* SelectDest targetting the Queue table */ 1976781def29Sdrh int i; /* Loop counter */ 1977781def29Sdrh int rc; /* Result code */ 1978fe1c6bb9Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 1979aa9ce707Sdrh Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */ 1980aa9ce707Sdrh int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ 1981781def29Sdrh 1982781def29Sdrh /* Obtain authorization to do a recursive query */ 1983781def29Sdrh if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; 1984781def29Sdrh 1985aa9ce707Sdrh /* Process the LIMIT and OFFSET clauses, if they exist */ 1986aa9ce707Sdrh addrBreak = sqlite3VdbeMakeLabel(v); 1987aa9ce707Sdrh computeLimitRegisters(pParse, p, addrBreak); 1988aa9ce707Sdrh pLimit = p->pLimit; 1989aa9ce707Sdrh pOffset = p->pOffset; 1990aa9ce707Sdrh regLimit = p->iLimit; 1991aa9ce707Sdrh regOffset = p->iOffset; 1992aa9ce707Sdrh p->pLimit = p->pOffset = 0; 1993aa9ce707Sdrh p->iLimit = p->iOffset = 0; 199453bed45eSdan pOrderBy = p->pOrderBy; 1995781def29Sdrh 1996781def29Sdrh /* Locate the cursor number of the Current table */ 1997781def29Sdrh for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 19988a48b9c0Sdrh if( pSrc->a[i].fg.isRecursive ){ 1999781def29Sdrh iCurrent = pSrc->a[i].iCursor; 2000781def29Sdrh break; 2001781def29Sdrh } 2002781def29Sdrh } 2003781def29Sdrh 2004fe1c6bb9Sdrh /* Allocate cursors numbers for Queue and Distinct. The cursor number for 2005781def29Sdrh ** the Distinct table must be exactly one greater than Queue in order 20068e1ee88cSdrh ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 2007781def29Sdrh iQueue = pParse->nTab++; 2008781def29Sdrh if( p->op==TK_UNION ){ 20098e1ee88cSdrh eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; 2010781def29Sdrh iDistinct = pParse->nTab++; 2011fe1c6bb9Sdrh }else{ 20128e1ee88cSdrh eDest = pOrderBy ? SRT_Queue : SRT_Fifo; 2013781def29Sdrh } 2014781def29Sdrh sqlite3SelectDestInit(&destQueue, eDest, iQueue); 2015781def29Sdrh 2016781def29Sdrh /* Allocate cursors for Current, Queue, and Distinct. */ 2017781def29Sdrh regCurrent = ++pParse->nMem; 2018781def29Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); 2019fe1c6bb9Sdrh if( pOrderBy ){ 202053bed45eSdan KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); 2021fe1c6bb9Sdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, 2022fe1c6bb9Sdrh (char*)pKeyInfo, P4_KEYINFO); 2023fe1c6bb9Sdrh destQueue.pOrderBy = pOrderBy; 2024fe1c6bb9Sdrh }else{ 2025781def29Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); 2026fe1c6bb9Sdrh } 2027fe1c6bb9Sdrh VdbeComment((v, "Queue table")); 2028781def29Sdrh if( iDistinct ){ 2029781def29Sdrh p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); 2030781def29Sdrh p->selFlags |= SF_UsesEphemeral; 2031781def29Sdrh } 2032781def29Sdrh 203353bed45eSdan /* Detach the ORDER BY clause from the compound SELECT */ 203453bed45eSdan p->pOrderBy = 0; 203553bed45eSdan 2036781def29Sdrh /* Store the results of the setup-query in Queue. */ 2037d227a291Sdrh pSetup->pNext = 0; 2038781def29Sdrh rc = sqlite3Select(pParse, pSetup, &destQueue); 2039d227a291Sdrh pSetup->pNext = p; 2040fe1c6bb9Sdrh if( rc ) goto end_of_recursive_query; 2041781def29Sdrh 2042781def29Sdrh /* Find the next row in the Queue and output that row */ 2043688852abSdrh addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); 2044781def29Sdrh 2045781def29Sdrh /* Transfer the next row in Queue over to Current */ 2046781def29Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ 2047fe1c6bb9Sdrh if( pOrderBy ){ 2048fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); 2049fe1c6bb9Sdrh }else{ 2050781def29Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2051fe1c6bb9Sdrh } 2052781def29Sdrh sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2053781def29Sdrh 2054fe1c6bb9Sdrh /* Output the single row in Current */ 2055fe1c6bb9Sdrh addrCont = sqlite3VdbeMakeLabel(v); 2056aa9ce707Sdrh codeOffset(v, regOffset, addrCont); 2057fe1c6bb9Sdrh selectInnerLoop(pParse, p, p->pEList, iCurrent, 2058079a3072Sdrh 0, 0, pDest, addrCont, addrBreak); 2059688852abSdrh if( regLimit ){ 206016897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); 2061688852abSdrh VdbeCoverage(v); 2062688852abSdrh } 2063fe1c6bb9Sdrh sqlite3VdbeResolveLabel(v, addrCont); 2064fe1c6bb9Sdrh 2065781def29Sdrh /* Execute the recursive SELECT taking the single row in Current as 2066781def29Sdrh ** the value for the recursive-table. Store the results in the Queue. 2067781def29Sdrh */ 2068b63ce02fSdrh if( p->selFlags & SF_Aggregate ){ 2069b63ce02fSdrh sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); 2070b63ce02fSdrh }else{ 2071781def29Sdrh p->pPrior = 0; 2072781def29Sdrh sqlite3Select(pParse, p, &destQueue); 2073781def29Sdrh assert( p->pPrior==0 ); 2074781def29Sdrh p->pPrior = pSetup; 2075b63ce02fSdrh } 2076781def29Sdrh 2077781def29Sdrh /* Keep running the loop until the Queue is empty */ 2078076e85f5Sdrh sqlite3VdbeGoto(v, addrTop); 2079781def29Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 2080fe1c6bb9Sdrh 2081fe1c6bb9Sdrh end_of_recursive_query: 20829afccba2Sdan sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2083fe1c6bb9Sdrh p->pOrderBy = pOrderBy; 2084aa9ce707Sdrh p->pLimit = pLimit; 2085aa9ce707Sdrh p->pOffset = pOffset; 2086fe1c6bb9Sdrh return; 2087781def29Sdrh } 2088b68b9778Sdan #endif /* SQLITE_OMIT_CTE */ 2089781def29Sdrh 2090781def29Sdrh /* Forward references */ 2091b21e7c70Sdrh static int multiSelectOrderBy( 2092b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2093b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2094a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2095b21e7c70Sdrh ); 2096b21e7c70Sdrh 209745f54a57Sdrh /* 209845f54a57Sdrh ** Handle the special case of a compound-select that originates from a 209945f54a57Sdrh ** VALUES clause. By handling this as a special case, we avoid deep 210045f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT 210145f54a57Sdrh ** on a VALUES clause. 210245f54a57Sdrh ** 210345f54a57Sdrh ** Because the Select object originates from a VALUES clause: 210445f54a57Sdrh ** (1) It has no LIMIT or OFFSET 210545f54a57Sdrh ** (2) All terms are UNION ALL 210645f54a57Sdrh ** (3) There is no ORDER BY clause 210745f54a57Sdrh */ 210845f54a57Sdrh static int multiSelectValues( 210945f54a57Sdrh Parse *pParse, /* Parsing context */ 211045f54a57Sdrh Select *p, /* The right-most of SELECTs to be coded */ 211145f54a57Sdrh SelectDest *pDest /* What to do with query results */ 211245f54a57Sdrh ){ 211345f54a57Sdrh Select *pPrior; 211445f54a57Sdrh int nRow = 1; 211545f54a57Sdrh int rc = 0; 2116772460fdSdrh assert( p->selFlags & SF_MultiValue ); 211745f54a57Sdrh do{ 211845f54a57Sdrh assert( p->selFlags & SF_Values ); 211945f54a57Sdrh assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); 212045f54a57Sdrh assert( p->pLimit==0 ); 212145f54a57Sdrh assert( p->pOffset==0 ); 2122923cadb1Sdan assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); 212345f54a57Sdrh if( p->pPrior==0 ) break; 212445f54a57Sdrh assert( p->pPrior->pNext==p ); 212545f54a57Sdrh p = p->pPrior; 212645f54a57Sdrh nRow++; 212745f54a57Sdrh }while(1); 212845f54a57Sdrh while( p ){ 212945f54a57Sdrh pPrior = p->pPrior; 213045f54a57Sdrh p->pPrior = 0; 213145f54a57Sdrh rc = sqlite3Select(pParse, p, pDest); 213245f54a57Sdrh p->pPrior = pPrior; 213345f54a57Sdrh if( rc ) break; 213445f54a57Sdrh p->nSelectRow = nRow; 213545f54a57Sdrh p = p->pNext; 213645f54a57Sdrh } 213745f54a57Sdrh return rc; 213845f54a57Sdrh } 2139b21e7c70Sdrh 2140d3d39e93Sdrh /* 214116ee60ffSdrh ** This routine is called to process a compound query form from 214216ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 214316ee60ffSdrh ** INTERSECT 2144c926afbcSdrh ** 2145e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 2146e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 2147e78e8284Sdrh ** in which case this routine will be called recursively. 2148e78e8284Sdrh ** 2149e78e8284Sdrh ** The results of the total query are to be written into a destination 2150e78e8284Sdrh ** of type eDest with parameter iParm. 2151e78e8284Sdrh ** 2152e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 2153e78e8284Sdrh ** 2154e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 2155e78e8284Sdrh ** 2156e78e8284Sdrh ** This statement is parsed up as follows: 2157e78e8284Sdrh ** 2158e78e8284Sdrh ** SELECT c FROM t3 2159e78e8284Sdrh ** | 2160e78e8284Sdrh ** `-----> SELECT b FROM t2 2161e78e8284Sdrh ** | 21624b11c6d3Sjplyon ** `------> SELECT a FROM t1 2163e78e8284Sdrh ** 2164e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 2165e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 2166e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 2167e78e8284Sdrh ** 2168e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 2169e78e8284Sdrh ** individual selects always group from left to right. 217082c3d636Sdrh */ 217184ac9d02Sdanielk1977 static int multiSelect( 2172fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 2173fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 2174a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 217584ac9d02Sdanielk1977 ){ 217684ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 217710e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 217810e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 21791013c932Sdrh SelectDest dest; /* Alternative data destination */ 2180eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 2181633e6d57Sdrh sqlite3 *db; /* Database connection */ 21827f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 2183edf83d1eSdrh int iSub1 = 0; /* EQP id of left-hand query */ 2184edf83d1eSdrh int iSub2 = 0; /* EQP id of right-hand query */ 21857f61e92cSdan #endif 218682c3d636Sdrh 21877b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 2188fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 218982c3d636Sdrh */ 2190701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 2191eae73fbfSdan assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); 2192633e6d57Sdrh db = pParse->db; 2193d8bc7086Sdrh pPrior = p->pPrior; 2194bc10377aSdrh dest = *pDest; 2195d8bc7086Sdrh if( pPrior->pOrderBy ){ 21964adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 2197da93d238Sdrh selectOpName(p->op)); 219884ac9d02Sdanielk1977 rc = 1; 219984ac9d02Sdanielk1977 goto multi_select_end; 220082c3d636Sdrh } 2201a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 22024adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 22037b58daeaSdrh selectOpName(p->op)); 220484ac9d02Sdanielk1977 rc = 1; 220584ac9d02Sdanielk1977 goto multi_select_end; 22067b58daeaSdrh } 220782c3d636Sdrh 22084adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2209701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 2210d8bc7086Sdrh 22111cc3d75fSdrh /* Create the destination temporary table if necessary 22121cc3d75fSdrh */ 22136c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 2214b4964b72Sdanielk1977 assert( p->pEList ); 22152b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 2216d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 22176c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 22181cc3d75fSdrh } 22191cc3d75fSdrh 222045f54a57Sdrh /* Special handling for a compound-select that originates as a VALUES clause. 222145f54a57Sdrh */ 2222772460fdSdrh if( p->selFlags & SF_MultiValue ){ 222345f54a57Sdrh rc = multiSelectValues(pParse, p, &dest); 222445f54a57Sdrh goto multi_select_end; 222545f54a57Sdrh } 222645f54a57Sdrh 2227f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 2228f6e369a1Sdrh ** in their result sets. 2229f6e369a1Sdrh */ 2230f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 2231923cadb1Sdan assert( p->pEList->nExpr==pPrior->pEList->nExpr ); 2232f6e369a1Sdrh 2233eede6a53Sdan #ifndef SQLITE_OMIT_CTE 2234eae73fbfSdan if( p->selFlags & SF_Recursive ){ 2235781def29Sdrh generateWithRecursiveQuery(pParse, p, &dest); 22368ce7184bSdan }else 22378ce7184bSdan #endif 22388ce7184bSdan 2239a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 2240a9671a22Sdrh */ 2241f6e369a1Sdrh if( p->pOrderBy ){ 2242a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 2243eede6a53Sdan }else 2244f6e369a1Sdrh 2245f46f905aSdrh /* Generate code for the left and right SELECT statements. 2246d8bc7086Sdrh */ 224782c3d636Sdrh switch( p->op ){ 2248f46f905aSdrh case TK_ALL: { 2249ec7429aeSdrh int addr = 0; 225095aa47b1Sdrh int nLimit; 2251a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 2252547180baSdrh pPrior->iLimit = p->iLimit; 2253547180baSdrh pPrior->iOffset = p->iOffset; 2254a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 2255a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 22567f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 22577d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 2258ad68cb6bSdanielk1977 p->pLimit = 0; 2259ad68cb6bSdanielk1977 p->pOffset = 0; 226084ac9d02Sdanielk1977 if( rc ){ 226184ac9d02Sdanielk1977 goto multi_select_end; 226284ac9d02Sdanielk1977 } 2263f46f905aSdrh p->pPrior = 0; 22647b58daeaSdrh p->iLimit = pPrior->iLimit; 22657b58daeaSdrh p->iOffset = pPrior->iOffset; 226692b01d53Sdrh if( p->iLimit ){ 226716897072Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); 2268d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 22699f1ef45fSdrh if( p->iOffset ){ 22708b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iOffset, p->iOffset, 0); 22719f1ef45fSdrh sqlite3VdbeAddOp3(v, OP_Add, p->iLimit, p->iOffset, p->iOffset+1); 22728b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iLimit, p->iOffset+1, -1); 22739f1ef45fSdrh } 2274ec7429aeSdrh } 22757f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 22767d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 2277373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2278eca7e01aSdanielk1977 pDelete = p->pPrior; 2279f46f905aSdrh p->pPrior = pPrior; 228095aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 228195aa47b1Sdrh if( pPrior->pLimit 228295aa47b1Sdrh && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) 2283613ba1eaSdrh && nLimit>0 && p->nSelectRow > (u64)nLimit 228495aa47b1Sdrh ){ 2285c63367efSdrh p->nSelectRow = nLimit; 228695aa47b1Sdrh } 2287ec7429aeSdrh if( addr ){ 2288ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 2289ec7429aeSdrh } 2290f46f905aSdrh break; 2291f46f905aSdrh } 229282c3d636Sdrh case TK_EXCEPT: 229382c3d636Sdrh case TK_UNION: { 2294d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 2295ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 2296d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 2297a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 2298dc1bdc4fSdanielk1977 int addr; 22996c8c8ce0Sdanielk1977 SelectDest uniondest; 230082c3d636Sdrh 2301373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 2302373cc2ddSdrh testcase( p->op==TK_UNION ); 230393a960a0Sdrh priorOp = SRT_Union; 2304d227a291Sdrh if( dest.eDest==priorOp ){ 2305d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 2306c926afbcSdrh ** right. 2307d8bc7086Sdrh */ 2308e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 2309e2f02bacSdrh assert( p->pOffset==0 ); /* Not allowed on leftward elements */ 23102b596da8Sdrh unionTab = dest.iSDParm; 231182c3d636Sdrh }else{ 2312d8bc7086Sdrh /* We will need to create our own temporary table to hold the 2313d8bc7086Sdrh ** intermediate results. 2314d8bc7086Sdrh */ 231582c3d636Sdrh unionTab = pParse->nTab++; 231693a960a0Sdrh assert( p->pOrderBy==0 ); 231766a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2318b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2319b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2320d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 232184ac9d02Sdanielk1977 assert( p->pEList ); 2322d8bc7086Sdrh } 2323d8bc7086Sdrh 2324d8bc7086Sdrh /* Code the SELECT statements to our left 2325d8bc7086Sdrh */ 2326b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 23271013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 23287f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 23297d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 233084ac9d02Sdanielk1977 if( rc ){ 233184ac9d02Sdanielk1977 goto multi_select_end; 233284ac9d02Sdanielk1977 } 2333d8bc7086Sdrh 2334d8bc7086Sdrh /* Code the current SELECT statement 2335d8bc7086Sdrh */ 23364cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 23374cfb22f7Sdrh op = SRT_Except; 23384cfb22f7Sdrh }else{ 23394cfb22f7Sdrh assert( p->op==TK_UNION ); 23404cfb22f7Sdrh op = SRT_Union; 2341d8bc7086Sdrh } 234282c3d636Sdrh p->pPrior = 0; 2343a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2344a2dc3b1aSdanielk1977 p->pLimit = 0; 2345a2dc3b1aSdanielk1977 pOffset = p->pOffset; 2346a2dc3b1aSdanielk1977 p->pOffset = 0; 23476c8c8ce0Sdanielk1977 uniondest.eDest = op; 23487f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 23497d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 2350373cc2ddSdrh testcase( rc!=SQLITE_OK ); 23515bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 23525bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 2353633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 2354eca7e01aSdanielk1977 pDelete = p->pPrior; 235582c3d636Sdrh p->pPrior = pPrior; 2356a9671a22Sdrh p->pOrderBy = 0; 235795aa47b1Sdrh if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow; 2358633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2359a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2360a2dc3b1aSdanielk1977 p->pOffset = pOffset; 236192b01d53Sdrh p->iLimit = 0; 236292b01d53Sdrh p->iOffset = 0; 2363d8bc7086Sdrh 2364d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2365d8bc7086Sdrh ** it is that we currently need. 2366d8bc7086Sdrh */ 23672b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2368373cc2ddSdrh if( dest.eDest!=priorOp ){ 23696b56344dSdrh int iCont, iBreak, iStart; 237082c3d636Sdrh assert( p->pEList ); 23717d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 237292378253Sdrh Select *pFirst = p; 237392378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 237492378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 237541202ccaSdrh } 23764adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 23774adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2378ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2379688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 23804adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 2381340309fdSdrh selectInnerLoop(pParse, p, p->pEList, unionTab, 2382079a3072Sdrh 0, 0, &dest, iCont, iBreak); 23834adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2384688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 23854adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 238666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 238782c3d636Sdrh } 238882c3d636Sdrh break; 238982c3d636Sdrh } 2390373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 239182c3d636Sdrh int tab1, tab2; 23926b56344dSdrh int iCont, iBreak, iStart; 2393a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 2394dc1bdc4fSdanielk1977 int addr; 23951013c932Sdrh SelectDest intersectdest; 23969cbf3425Sdrh int r1; 239782c3d636Sdrh 2398d8bc7086Sdrh /* INTERSECT is different from the others since it requires 23996206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2400d8bc7086Sdrh ** by allocating the tables we will need. 2401d8bc7086Sdrh */ 240282c3d636Sdrh tab1 = pParse->nTab++; 240382c3d636Sdrh tab2 = pParse->nTab++; 240493a960a0Sdrh assert( p->pOrderBy==0 ); 2405dc1bdc4fSdanielk1977 240666a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2407b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2408b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2409d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 241084ac9d02Sdanielk1977 assert( p->pEList ); 2411d8bc7086Sdrh 2412d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2413d8bc7086Sdrh */ 24141013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 24157f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 24167d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 241784ac9d02Sdanielk1977 if( rc ){ 241884ac9d02Sdanielk1977 goto multi_select_end; 241984ac9d02Sdanielk1977 } 2420d8bc7086Sdrh 2421d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2422d8bc7086Sdrh */ 242366a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2424b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2425b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 242682c3d636Sdrh p->pPrior = 0; 2427a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2428a2dc3b1aSdanielk1977 p->pLimit = 0; 2429a2dc3b1aSdanielk1977 pOffset = p->pOffset; 2430a2dc3b1aSdanielk1977 p->pOffset = 0; 24312b596da8Sdrh intersectdest.iSDParm = tab2; 24327f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 24337d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 2434373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2435eca7e01aSdanielk1977 pDelete = p->pPrior; 243682c3d636Sdrh p->pPrior = pPrior; 243795aa47b1Sdrh if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 2438633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2439a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2440a2dc3b1aSdanielk1977 p->pOffset = pOffset; 2441d8bc7086Sdrh 2442d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 2443d8bc7086Sdrh ** tables. 2444d8bc7086Sdrh */ 244582c3d636Sdrh assert( p->pEList ); 24467d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 244792378253Sdrh Select *pFirst = p; 244892378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 244992378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 245041202ccaSdrh } 24514adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 24524adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2453ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2454688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); 24559cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 24569cbf3425Sdrh iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); 2457688852abSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); 24589cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 2459340309fdSdrh selectInnerLoop(pParse, p, p->pEList, tab1, 2460079a3072Sdrh 0, 0, &dest, iCont, iBreak); 24614adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2462688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); 24634adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 246466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 246566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 246682c3d636Sdrh break; 246782c3d636Sdrh } 246882c3d636Sdrh } 24698cdbf836Sdrh 24707f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); 24717f61e92cSdan 2472a9671a22Sdrh /* Compute collating sequences used by 2473a9671a22Sdrh ** temporary tables needed to implement the compound select. 2474a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 24758cdbf836Sdrh ** 24768cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 24778cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 24788cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 24798cdbf836Sdrh ** no temp tables are required. 2480fbc4ee7bSdrh */ 24817d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 2482fbc4ee7bSdrh int i; /* Loop counter */ 2483fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 24840342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 2485f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 248693a960a0Sdrh int nCol; /* Number of columns in result set */ 2487fbc4ee7bSdrh 2488d227a291Sdrh assert( p->pNext==0 ); 248993a960a0Sdrh nCol = p->pEList->nExpr; 2490ad124329Sdrh pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); 2491dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 2492dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 2493dc1bdc4fSdanielk1977 goto multi_select_end; 2494dc1bdc4fSdanielk1977 } 24950342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 24960342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 24970342b1f5Sdrh if( 0==*apColl ){ 2498633e6d57Sdrh *apColl = db->pDfltColl; 2499dc1bdc4fSdanielk1977 } 2500dc1bdc4fSdanielk1977 } 2501dc1bdc4fSdanielk1977 25020342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 25030342b1f5Sdrh for(i=0; i<2; i++){ 2504b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 25050342b1f5Sdrh if( addr<0 ){ 25060342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 25070342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 2508b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 25090342b1f5Sdrh break; 25100342b1f5Sdrh } 25110342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 25122ec2fb22Sdrh sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), 25132ec2fb22Sdrh P4_KEYINFO); 25140ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 25150342b1f5Sdrh } 2516dc1bdc4fSdanielk1977 } 25172ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyInfo); 2518dc1bdc4fSdanielk1977 } 2519dc1bdc4fSdanielk1977 2520dc1bdc4fSdanielk1977 multi_select_end: 25212b596da8Sdrh pDest->iSdst = dest.iSdst; 25222b596da8Sdrh pDest->nSdst = dest.nSdst; 2523633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 252484ac9d02Sdanielk1977 return rc; 25252282792aSdrh } 2526b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 25272282792aSdrh 2528b21e7c70Sdrh /* 252989b31d73Smistachkin ** Error message for when two or more terms of a compound select have different 253089b31d73Smistachkin ** size result sets. 253189b31d73Smistachkin */ 253289b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ 253389b31d73Smistachkin if( p->selFlags & SF_Values ){ 253489b31d73Smistachkin sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 253589b31d73Smistachkin }else{ 253689b31d73Smistachkin sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 253789b31d73Smistachkin " do not have the same number of result columns", selectOpName(p->op)); 253889b31d73Smistachkin } 253989b31d73Smistachkin } 254089b31d73Smistachkin 254189b31d73Smistachkin /* 2542b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 2543b21e7c70Sdrh ** SELECT statment. 25440acb7e48Sdrh ** 25452b596da8Sdrh ** The data to be output is contained in pIn->iSdst. There are 25462b596da8Sdrh ** pIn->nSdst columns to be output. pDest is where the output should 25470acb7e48Sdrh ** be sent. 25480acb7e48Sdrh ** 25490acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 25500acb7e48Sdrh ** return address. 25510acb7e48Sdrh ** 2552f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 25530acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 25540acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 25550acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 25560acb7e48Sdrh ** keys. 25570acb7e48Sdrh ** 25580acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 25590acb7e48Sdrh ** iBreak. 2560b21e7c70Sdrh */ 25610acb7e48Sdrh static int generateOutputSubroutine( 256292b01d53Sdrh Parse *pParse, /* Parsing context */ 256392b01d53Sdrh Select *p, /* The SELECT statement */ 256492b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 256592b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 256692b01d53Sdrh int regReturn, /* The return address register */ 25670acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 25680acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 256992b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 2570b21e7c70Sdrh ){ 2571b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 257292b01d53Sdrh int iContinue; 257392b01d53Sdrh int addr; 2574b21e7c70Sdrh 257592b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 257692b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 25770acb7e48Sdrh 25780acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 25790acb7e48Sdrh */ 25800acb7e48Sdrh if( regPrev ){ 2581728e0f91Sdrh int addr1, addr2; 2582728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); 2583728e0f91Sdrh addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 25842ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 2585728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); 2586728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 2587e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 2588ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 25890acb7e48Sdrh } 25901f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 25910acb7e48Sdrh 2592d5578433Smistachkin /* Suppress the first OFFSET entries if there is an OFFSET clause 25930acb7e48Sdrh */ 2594aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 2595b21e7c70Sdrh 2596e2248cfdSdrh assert( pDest->eDest!=SRT_Exists ); 2597e2248cfdSdrh assert( pDest->eDest!=SRT_Table ); 2598b21e7c70Sdrh switch( pDest->eDest ){ 2599b21e7c70Sdrh /* Store the result as data using a unique key. 2600b21e7c70Sdrh */ 2601b21e7c70Sdrh case SRT_EphemTab: { 2602b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 2603b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 26042b596da8Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 26052b596da8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 26062b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 2607b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2608b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 2609b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2610b21e7c70Sdrh break; 2611b21e7c70Sdrh } 2612b21e7c70Sdrh 2613b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 2614b21e7c70Sdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 2615b21e7c70Sdrh ** then there should be a single item on the stack. Write this 2616b21e7c70Sdrh ** item into the set table with bogus data. 2617b21e7c70Sdrh */ 2618b21e7c70Sdrh case SRT_Set: { 26196fccc35aSdrh int r1; 26209af8646dSdrh assert( pIn->nSdst==1 || pParse->nErr>0 ); 2621634d81deSdrh pDest->affSdst = 26222b596da8Sdrh sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst); 2623b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 2624634d81deSdrh sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1); 26252b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1); 26262b596da8Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1); 2627b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2628b21e7c70Sdrh break; 2629b21e7c70Sdrh } 2630b21e7c70Sdrh 2631b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2632b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2633b21e7c70Sdrh ** of the scan loop. 2634b21e7c70Sdrh */ 2635b21e7c70Sdrh case SRT_Mem: { 2636a276e3fdSdrh assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 ); 26372b596da8Sdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); 2638b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 2639b21e7c70Sdrh break; 2640b21e7c70Sdrh } 2641b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2642b21e7c70Sdrh 26437d10d5a6Sdrh /* The results are stored in a sequence of registers 26442b596da8Sdrh ** starting at pDest->iSdst. Then the co-routine yields. 2645b21e7c70Sdrh */ 264692b01d53Sdrh case SRT_Coroutine: { 26472b596da8Sdrh if( pDest->iSdst==0 ){ 26482b596da8Sdrh pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 26492b596da8Sdrh pDest->nSdst = pIn->nSdst; 2650b21e7c70Sdrh } 26514b79bde7Sdan sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); 26522b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 265392b01d53Sdrh break; 265492b01d53Sdrh } 265592b01d53Sdrh 2656ccfcbceaSdrh /* If none of the above, then the result destination must be 2657ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2658ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2659ccfcbceaSdrh ** 2660ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2661ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2662ccfcbceaSdrh ** return the next row of result. 26637d10d5a6Sdrh */ 2664ccfcbceaSdrh default: { 2665ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 26662b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 26672b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 2668b21e7c70Sdrh break; 2669b21e7c70Sdrh } 2670b21e7c70Sdrh } 267192b01d53Sdrh 267292b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 267392b01d53Sdrh */ 267492b01d53Sdrh if( p->iLimit ){ 267516897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 267692b01d53Sdrh } 267792b01d53Sdrh 267892b01d53Sdrh /* Generate the subroutine return 267992b01d53Sdrh */ 26800acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 268192b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 268292b01d53Sdrh 268392b01d53Sdrh return addr; 2684b21e7c70Sdrh } 2685b21e7c70Sdrh 2686b21e7c70Sdrh /* 2687b21e7c70Sdrh ** Alternative compound select code generator for cases when there 2688b21e7c70Sdrh ** is an ORDER BY clause. 2689b21e7c70Sdrh ** 2690b21e7c70Sdrh ** We assume a query of the following form: 2691b21e7c70Sdrh ** 2692b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 2693b21e7c70Sdrh ** 2694b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 2695b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 2696b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 2697b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 2698b21e7c70Sdrh ** selectB) there are 7 subroutines: 2699b21e7c70Sdrh ** 2700b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 2701b21e7c70Sdrh ** of the compound query. 2702b21e7c70Sdrh ** 2703b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 2704b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 2705b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 2706b21e7c70Sdrh ** appears only in B.) 2707b21e7c70Sdrh ** 2708b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 2709b21e7c70Sdrh ** 2710b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 2711b21e7c70Sdrh ** 2712b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 2713b21e7c70Sdrh ** 2714b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 2715b21e7c70Sdrh ** 2716b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 2717b21e7c70Sdrh ** 2718b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 2719b21e7c70Sdrh ** <operator> is used: 2720b21e7c70Sdrh ** 2721b21e7c70Sdrh ** 2722b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 2723b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 2724b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 2725b21e7c70Sdrh ** 27260acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 2727b21e7c70Sdrh ** 2728b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 2729b21e7c70Sdrh ** 27300acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 2731b21e7c70Sdrh ** 27320acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 27330acb7e48Sdrh ** 27340acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 27350acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 27360acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 27370acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 27380acb7e48Sdrh ** 27390acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 27400acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 27410acb7e48Sdrh ** output value. A comparison is made against this value and the output 27420acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 2743b21e7c70Sdrh ** 2744b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 2745b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 2746b21e7c70Sdrh ** 2747b21e7c70Sdrh ** goto Init 2748b21e7c70Sdrh ** coA: coroutine for left query (A) 2749b21e7c70Sdrh ** coB: coroutine for right query (B) 2750b21e7c70Sdrh ** outA: output one row of A 2751b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 2752b21e7c70Sdrh ** EofA: ... 2753b21e7c70Sdrh ** EofB: ... 2754b21e7c70Sdrh ** AltB: ... 2755b21e7c70Sdrh ** AeqB: ... 2756b21e7c70Sdrh ** AgtB: ... 2757b21e7c70Sdrh ** Init: initialize coroutine registers 2758b21e7c70Sdrh ** yield coA 2759b21e7c70Sdrh ** if eof(A) goto EofA 2760b21e7c70Sdrh ** yield coB 2761b21e7c70Sdrh ** if eof(B) goto EofB 2762b21e7c70Sdrh ** Cmpr: Compare A, B 2763b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 2764b21e7c70Sdrh ** End: ... 2765b21e7c70Sdrh ** 2766b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 2767b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 2768b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 2769b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 2770b21e7c70Sdrh */ 2771de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 2772b21e7c70Sdrh static int multiSelectOrderBy( 2773b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2774b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2775a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2776b21e7c70Sdrh ){ 27770acb7e48Sdrh int i, j; /* Loop counters */ 2778b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 2779b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 2780b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 2781b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 278292b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 278392b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 278492b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 278592b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 278692b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 278792b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 278892b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 2789b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 279092b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 279181cf13ecSdrh int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ 279292b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 279392b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 279492b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 279592b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 279692b01d53Sdrh int regLimitA; /* Limit register for select-A */ 279792b01d53Sdrh int regLimitB; /* Limit register for select-A */ 27980acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 279992b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 280092b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 280192b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 280292b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 2803728e0f91Sdrh int addr1; /* Jump instructions that get retargetted */ 280492b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 280596067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 28060acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 28070acb7e48Sdrh sqlite3 *db; /* Database connection */ 28080acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 28090acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 28100acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 28117f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 28127f61e92cSdan int iSub1; /* EQP id of left-hand query */ 28137f61e92cSdan int iSub2; /* EQP id of right-hand query */ 28147f61e92cSdan #endif 2815b21e7c70Sdrh 281692b01d53Sdrh assert( p->pOrderBy!=0 ); 281796067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 28180acb7e48Sdrh db = pParse->db; 281992b01d53Sdrh v = pParse->pVdbe; 2820ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 282192b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 282292b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 28230acb7e48Sdrh 2824b21e7c70Sdrh 282592b01d53Sdrh /* Patch up the ORDER BY clause 282692b01d53Sdrh */ 282792b01d53Sdrh op = p->op; 2828b21e7c70Sdrh pPrior = p->pPrior; 282992b01d53Sdrh assert( pPrior->pOrderBy==0 ); 28300acb7e48Sdrh pOrderBy = p->pOrderBy; 283193a960a0Sdrh assert( pOrderBy ); 28320acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 283393a960a0Sdrh 28340acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 28350acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 28360acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 28370acb7e48Sdrh */ 28380acb7e48Sdrh if( op!=TK_ALL ){ 28390acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 28407d10d5a6Sdrh struct ExprList_item *pItem; 28417d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 2842c2acc4e4Sdrh assert( pItem->u.x.iOrderByCol>0 ); 2843c2acc4e4Sdrh if( pItem->u.x.iOrderByCol==i ) break; 28440acb7e48Sdrh } 28450acb7e48Sdrh if( j==nOrderBy ){ 2846b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 28470acb7e48Sdrh if( pNew==0 ) return SQLITE_NOMEM; 28480acb7e48Sdrh pNew->flags |= EP_IntValue; 284933e619fcSdrh pNew->u.iValue = i; 2850b7916a78Sdrh pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 2851c2acc4e4Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; 28520acb7e48Sdrh } 28530acb7e48Sdrh } 28540acb7e48Sdrh } 28550acb7e48Sdrh 28560acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 285710c081adSdrh ** the permutation used to determine if the next 28580acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 28590acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 28600acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 28610acb7e48Sdrh ** collation. 28620acb7e48Sdrh */ 28630acb7e48Sdrh aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); 28640acb7e48Sdrh if( aPermute ){ 28657d10d5a6Sdrh struct ExprList_item *pItem; 28667d10d5a6Sdrh for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){ 28676736618aSdrh assert( pItem->u.x.iOrderByCol>0 ); 28682ec18a3cSdrh assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); 2869c2acc4e4Sdrh aPermute[i] = pItem->u.x.iOrderByCol - 1; 28700acb7e48Sdrh } 287153bed45eSdan pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); 28720acb7e48Sdrh }else{ 28730acb7e48Sdrh pKeyMerge = 0; 28740acb7e48Sdrh } 28750acb7e48Sdrh 28760acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 28770acb7e48Sdrh */ 28780acb7e48Sdrh p->pOrderBy = pOrderBy; 28796ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 28800acb7e48Sdrh 28810acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 28820acb7e48Sdrh ** for the logic that removes duplicate result rows when the 28830acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 28840acb7e48Sdrh */ 28850acb7e48Sdrh if( op==TK_ALL ){ 28860acb7e48Sdrh regPrev = 0; 28870acb7e48Sdrh }else{ 28880acb7e48Sdrh int nExpr = p->pEList->nExpr; 28891c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 2890c8ac0d16Sdrh regPrev = pParse->nMem+1; 2891c8ac0d16Sdrh pParse->nMem += nExpr+1; 28920acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 2893ad124329Sdrh pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); 28940acb7e48Sdrh if( pKeyDup ){ 28952ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); 28960acb7e48Sdrh for(i=0; i<nExpr; i++){ 28970acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 28980acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 28990acb7e48Sdrh } 29000acb7e48Sdrh } 29010acb7e48Sdrh } 290292b01d53Sdrh 290392b01d53Sdrh /* Separate the left and the right query from one another 290492b01d53Sdrh */ 290592b01d53Sdrh p->pPrior = 0; 2906d227a291Sdrh pPrior->pNext = 0; 29077d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 29080acb7e48Sdrh if( pPrior->pPrior==0 ){ 29097d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 29100acb7e48Sdrh } 291192b01d53Sdrh 291292b01d53Sdrh /* Compute the limit registers */ 291392b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 29140acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 291592b01d53Sdrh regLimitA = ++pParse->nMem; 291692b01d53Sdrh regLimitB = ++pParse->nMem; 291792b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 291892b01d53Sdrh regLimitA); 291992b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 292092b01d53Sdrh }else{ 292192b01d53Sdrh regLimitA = regLimitB = 0; 292292b01d53Sdrh } 2923633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 29240acb7e48Sdrh p->pLimit = 0; 2925633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 29260acb7e48Sdrh p->pOffset = 0; 292792b01d53Sdrh 2928b21e7c70Sdrh regAddrA = ++pParse->nMem; 2929b21e7c70Sdrh regAddrB = ++pParse->nMem; 2930b21e7c70Sdrh regOutA = ++pParse->nMem; 2931b21e7c70Sdrh regOutB = ++pParse->nMem; 2932b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 2933b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 2934b21e7c70Sdrh 293592b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 29360acb7e48Sdrh ** left of the compound operator - the "A" select. 29370acb7e48Sdrh */ 2938ed71a839Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; 2939728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); 2940ed71a839Sdrh VdbeComment((v, "left SELECT")); 294192b01d53Sdrh pPrior->iLimit = regLimitA; 29427f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 29437d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 294481cf13ecSdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA); 2945728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 2946b21e7c70Sdrh 294792b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 294892b01d53Sdrh ** the right - the "B" select 294992b01d53Sdrh */ 2950ed71a839Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; 2951728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); 2952ed71a839Sdrh VdbeComment((v, "right SELECT")); 295392b01d53Sdrh savedLimit = p->iLimit; 295492b01d53Sdrh savedOffset = p->iOffset; 295592b01d53Sdrh p->iLimit = regLimitB; 295692b01d53Sdrh p->iOffset = 0; 29577f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 29587d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 295992b01d53Sdrh p->iLimit = savedLimit; 296092b01d53Sdrh p->iOffset = savedOffset; 296181cf13ecSdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB); 2962b21e7c70Sdrh 296392b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 29640acb7e48Sdrh ** select as the next output row of the compound select. 296592b01d53Sdrh */ 2966b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 29670acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 29680acb7e48Sdrh p, &destA, pDest, regOutA, 29692ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 2970b21e7c70Sdrh 297192b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 29720acb7e48Sdrh ** select as the next output row of the compound select. 297392b01d53Sdrh */ 29740acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 2975b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 29760acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 29770acb7e48Sdrh p, &destB, pDest, regOutB, 29782ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 29790acb7e48Sdrh } 29802ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyDup); 2981b21e7c70Sdrh 298292b01d53Sdrh /* Generate a subroutine to run when the results from select A 298392b01d53Sdrh ** are exhausted and only data in select B remains. 298492b01d53Sdrh */ 298592b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 298681cf13ecSdrh addrEofA_noB = addrEofA = labelEnd; 298792b01d53Sdrh }else{ 298881cf13ecSdrh VdbeNoopComment((v, "eof-A subroutine")); 298981cf13ecSdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 299081cf13ecSdrh addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); 2991688852abSdrh VdbeCoverage(v); 2992076e85f5Sdrh sqlite3VdbeGoto(v, addrEofA); 299395aa47b1Sdrh p->nSelectRow += pPrior->nSelectRow; 2994b21e7c70Sdrh } 2995b21e7c70Sdrh 299692b01d53Sdrh /* Generate a subroutine to run when the results from select B 299792b01d53Sdrh ** are exhausted and only data in select A remains. 299892b01d53Sdrh */ 2999b21e7c70Sdrh if( op==TK_INTERSECT ){ 300092b01d53Sdrh addrEofB = addrEofA; 300195aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 3002b21e7c70Sdrh }else{ 300392b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 300481cf13ecSdrh addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3005688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); 3006076e85f5Sdrh sqlite3VdbeGoto(v, addrEofB); 3007b21e7c70Sdrh } 3008b21e7c70Sdrh 300992b01d53Sdrh /* Generate code to handle the case of A<B 301092b01d53Sdrh */ 3011b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 30120acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3013688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3014076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3015b21e7c70Sdrh 301692b01d53Sdrh /* Generate code to handle the case of A==B 301792b01d53Sdrh */ 3018b21e7c70Sdrh if( op==TK_ALL ){ 3019b21e7c70Sdrh addrAeqB = addrAltB; 30200acb7e48Sdrh }else if( op==TK_INTERSECT ){ 30210acb7e48Sdrh addrAeqB = addrAltB; 30220acb7e48Sdrh addrAltB++; 302392b01d53Sdrh }else{ 3024b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 30250acb7e48Sdrh addrAeqB = 3026688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3027076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 302892b01d53Sdrh } 3029b21e7c70Sdrh 303092b01d53Sdrh /* Generate code to handle the case of A>B 303192b01d53Sdrh */ 3032b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 3033b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 3034b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 3035b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 303692b01d53Sdrh } 3037688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 3038076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3039b21e7c70Sdrh 304092b01d53Sdrh /* This code runs once to initialize everything. 304192b01d53Sdrh */ 3042728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3043688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); 3044688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 304592b01d53Sdrh 304692b01d53Sdrh /* Implement the main merge loop 304792b01d53Sdrh */ 304892b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 30490acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 30502b596da8Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 30512ec2fb22Sdrh (char*)pKeyMerge, P4_KEYINFO); 3052953f7611Sdrh sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); 3053688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); 305492b01d53Sdrh 305592b01d53Sdrh /* Jump to the this point in order to terminate the query. 305692b01d53Sdrh */ 3057b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 3058b21e7c70Sdrh 305992b01d53Sdrh /* Set the number of output columns 306092b01d53Sdrh */ 30617d10d5a6Sdrh if( pDest->eDest==SRT_Output ){ 30620acb7e48Sdrh Select *pFirst = pPrior; 306392b01d53Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 306492b01d53Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 3065b21e7c70Sdrh } 306692b01d53Sdrh 30670acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 30680acb7e48Sdrh ** by the calling function */ 30695e7ad508Sdanielk1977 if( p->pPrior ){ 3070633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 30715e7ad508Sdanielk1977 } 30720acb7e48Sdrh p->pPrior = pPrior; 3073d227a291Sdrh pPrior->pNext = p; 307492b01d53Sdrh 307592b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 307692b01d53Sdrh **** subqueries ****/ 30777f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, 0); 30783dc4cc66Sdrh return pParse->nErr!=0; 307992b01d53Sdrh } 3080de3e41e3Sdanielk1977 #endif 3081b21e7c70Sdrh 30823514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 308317435752Sdrh /* Forward Declarations */ 308417435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*); 3085d12b6363Sdrh static void substSelect(sqlite3*, Select *, int, ExprList*, int); 308617435752Sdrh 30872282792aSdrh /* 3088832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 30896a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 309084e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 30916a3ea0e6Sdrh ** unchanged.) 3092832508b7Sdrh ** 3093832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 3094832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 3095832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 3096832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 3097832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 3098832508b7Sdrh ** of the subquery rather the result set of the subquery. 3099832508b7Sdrh */ 3100b7916a78Sdrh static Expr *substExpr( 310117435752Sdrh sqlite3 *db, /* Report malloc errors to this connection */ 310217435752Sdrh Expr *pExpr, /* Expr in which substitution occurs */ 310317435752Sdrh int iTable, /* Table to be substituted */ 310417435752Sdrh ExprList *pEList /* Substitute expressions */ 310517435752Sdrh ){ 3106b7916a78Sdrh if( pExpr==0 ) return 0; 310750350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 310850350a15Sdrh if( pExpr->iColumn<0 ){ 310950350a15Sdrh pExpr->op = TK_NULL; 311050350a15Sdrh }else{ 3111832508b7Sdrh Expr *pNew; 311284e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 31136ab3a2ecSdanielk1977 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 3114b7916a78Sdrh pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); 3115b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 3116b7916a78Sdrh pExpr = pNew; 311750350a15Sdrh } 3118832508b7Sdrh }else{ 3119b7916a78Sdrh pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); 3120b7916a78Sdrh pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); 31216ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 3122d12b6363Sdrh substSelect(db, pExpr->x.pSelect, iTable, pEList, 1); 31236ab3a2ecSdanielk1977 }else{ 31246ab3a2ecSdanielk1977 substExprList(db, pExpr->x.pList, iTable, pEList); 31256ab3a2ecSdanielk1977 } 3126832508b7Sdrh } 3127b7916a78Sdrh return pExpr; 3128832508b7Sdrh } 312917435752Sdrh static void substExprList( 313017435752Sdrh sqlite3 *db, /* Report malloc errors here */ 313117435752Sdrh ExprList *pList, /* List to scan and in which to make substitutes */ 313217435752Sdrh int iTable, /* Table to be substituted */ 313317435752Sdrh ExprList *pEList /* Substitute values */ 313417435752Sdrh ){ 3135832508b7Sdrh int i; 3136832508b7Sdrh if( pList==0 ) return; 3137832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 3138b7916a78Sdrh pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); 3139832508b7Sdrh } 3140832508b7Sdrh } 314117435752Sdrh static void substSelect( 314217435752Sdrh sqlite3 *db, /* Report malloc errors here */ 314317435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 314417435752Sdrh int iTable, /* Table to be replaced */ 3145d12b6363Sdrh ExprList *pEList, /* Substitute values */ 3146d12b6363Sdrh int doPrior /* Do substitutes on p->pPrior too */ 314717435752Sdrh ){ 3148588a9a1aSdrh SrcList *pSrc; 3149588a9a1aSdrh struct SrcList_item *pItem; 3150588a9a1aSdrh int i; 3151b3bce662Sdanielk1977 if( !p ) return; 3152d12b6363Sdrh do{ 315317435752Sdrh substExprList(db, p->pEList, iTable, pEList); 315417435752Sdrh substExprList(db, p->pGroupBy, iTable, pEList); 315517435752Sdrh substExprList(db, p->pOrderBy, iTable, pEList); 3156b7916a78Sdrh p->pHaving = substExpr(db, p->pHaving, iTable, pEList); 3157b7916a78Sdrh p->pWhere = substExpr(db, p->pWhere, iTable, pEList); 3158588a9a1aSdrh pSrc = p->pSrc; 31592906490bSdrh assert( pSrc!=0 ); 3160588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 3161d12b6363Sdrh substSelect(db, pItem->pSelect, iTable, pEList, 1); 3162d12b6363Sdrh if( pItem->fg.isTabFunc ){ 3163d12b6363Sdrh substExprList(db, pItem->u1.pFuncArg, iTable, pEList); 3164588a9a1aSdrh } 3165588a9a1aSdrh } 3166d12b6363Sdrh }while( doPrior && (p = p->pPrior)!=0 ); 3167d12b6363Sdrh } 31683514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3169832508b7Sdrh 31703514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3171832508b7Sdrh /* 3172630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 3173630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 31741350b030Sdrh ** 31751350b030Sdrh ** To understand the concept of flattening, consider the following 31761350b030Sdrh ** query: 31771350b030Sdrh ** 31781350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 31791350b030Sdrh ** 31801350b030Sdrh ** The default way of implementing this query is to execute the 31811350b030Sdrh ** subquery first and store the results in a temporary table, then 31821350b030Sdrh ** run the outer query on that temporary table. This requires two 31831350b030Sdrh ** passes over the data. Furthermore, because the temporary table 31841350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 3185832508b7Sdrh ** optimized. 31861350b030Sdrh ** 3187832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 31881350b030Sdrh ** a single flat select, like this: 31891350b030Sdrh ** 31901350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 31911350b030Sdrh ** 319260ec914cSpeter.d.reid ** The code generated for this simplification gives the same result 3193832508b7Sdrh ** but only has to scan the data once. And because indices might 3194832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 3195832508b7Sdrh ** avoided. 31961350b030Sdrh ** 3197832508b7Sdrh ** Flattening is only attempted if all of the following are true: 31981350b030Sdrh ** 3199832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 32001350b030Sdrh ** 3201885a5b03Sdrh ** (2) The subquery is not an aggregate or (2a) the outer query is not a join 3202885a5b03Sdrh ** and (2b) the outer query does not use subqueries other than the one 3203885a5b03Sdrh ** FROM-clause subquery that is a candidate for flattening. (2b is 3204885a5b03Sdrh ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.) 3205832508b7Sdrh ** 32062b300d5dSdrh ** (3) The subquery is not the right operand of a left outer join 320749ad330dSdan ** (Originally ticket #306. Strengthened by ticket #3300) 3208832508b7Sdrh ** 320949ad330dSdan ** (4) The subquery is not DISTINCT. 3210832508b7Sdrh ** 321149ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 321249ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 321349ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 3214832508b7Sdrh ** 3215832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 3216832508b7Sdrh ** DISTINCT. 3217832508b7Sdrh ** 3218630d296cSdrh ** (7) The subquery has a FROM clause. TODO: For subqueries without 3219630d296cSdrh ** A FROM clause, consider adding a FROM close with the special 3220630d296cSdrh ** table sqlite_once that consists of a single row containing a 3221630d296cSdrh ** single NULL. 322208192d5fSdrh ** 3223df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 3224df199a25Sdrh ** 3225df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 3226df199a25Sdrh ** aggregates. 3227df199a25Sdrh ** 32286092d2bcSdrh ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 32296092d2bcSdrh ** accidently carried the comment forward until 2014-09-15. Original 323038b4149cSdrh ** text: "The subquery does not use aggregates or the outer query 323138b4149cSdrh ** does not use LIMIT." 3232df199a25Sdrh ** 3233174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 3234174b6195Sdrh ** 32357b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 32362b300d5dSdrh ** a separate restriction deriving from ticket #350. 32373fc673e6Sdrh ** 323849ad330dSdan ** (13) The subquery and outer query do not both use LIMIT. 3239ac83963aSdrh ** 324049ad330dSdan ** (14) The subquery does not use OFFSET. 3241ac83963aSdrh ** 3242ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 3243f3913278Sdrh ** subquery does not have a LIMIT clause. 3244f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 3245ad91c6cdSdrh ** 3246c52e355dSdrh ** (16) The outer query is not an aggregate or the subquery does 3247c52e355dSdrh ** not contain ORDER BY. (Ticket #2942) This used to not matter 3248c52e355dSdrh ** until we introduced the group_concat() function. 3249c52e355dSdrh ** 3250f23329a2Sdanielk1977 ** (17) The sub-query is not a compound select, or it is a UNION ALL 32514914cf92Sdanielk1977 ** compound clause made up entirely of non-aggregate queries, and 3252f23329a2Sdanielk1977 ** the parent query: 3253f23329a2Sdanielk1977 ** 3254f23329a2Sdanielk1977 ** * is not itself part of a compound select, 3255f23329a2Sdanielk1977 ** * is not an aggregate or DISTINCT query, and 3256630d296cSdrh ** * is not a join 3257f23329a2Sdanielk1977 ** 32584914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 32594914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 3260630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 3261630d296cSdrh ** operator other than UNION ALL because all the other compound 3262630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 3263630d296cSdrh ** restriction (4). 3264f23329a2Sdanielk1977 ** 326567c70142Sdan ** Also, each component of the sub-query must return the same number 326667c70142Sdan ** of result columns. This is actually a requirement for any compound 326767c70142Sdan ** SELECT statement, but all the code here does is make sure that no 326867c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 326967c70142Sdan ** syntax error and return a detailed message. 327067c70142Sdan ** 327149fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 327249fc1f60Sdanielk1977 ** ORDER by clause of the parent must be simple references to 327349fc1f60Sdanielk1977 ** columns of the sub-query. 327449fc1f60Sdanielk1977 ** 3275229cf702Sdrh ** (19) The subquery does not use LIMIT or the outer query does not 3276229cf702Sdrh ** have a WHERE clause. 3277229cf702Sdrh ** 3278e8902a70Sdrh ** (20) If the sub-query is a compound select, then it must not use 3279e8902a70Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 3280e8902a70Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 3281630d296cSdrh ** appear as unmodified result columns in the outer query. But we 3282e8902a70Sdrh ** have other optimizations in mind to deal with that case. 3283e8902a70Sdrh ** 3284a91491e5Sshaneh ** (21) The subquery does not use LIMIT or the outer query is not 3285a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 3286a91491e5Sshaneh ** 32878290c2adSdan ** (22) The subquery is not a recursive CTE. 32888290c2adSdan ** 32898290c2adSdan ** (23) The parent is not a recursive CTE, or the sub-query is not a 32908290c2adSdan ** compound query. This restriction is because transforming the 32918290c2adSdan ** parent to a compound query confuses the code that handles 32928290c2adSdan ** recursive queries in multiSelect(). 32938290c2adSdan ** 32949588ad95Sdrh ** (24) The subquery is not an aggregate that uses the built-in min() or 32959588ad95Sdrh ** or max() functions. (Without this restriction, a query like: 32969588ad95Sdrh ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily 32979588ad95Sdrh ** return the value X for which Y was maximal.) 32989588ad95Sdrh ** 32998290c2adSdan ** 3300832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 3301832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 3302832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 3303832508b7Sdrh ** 3304665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 3305832508b7Sdrh ** If flattening is attempted this routine returns 1. 3306832508b7Sdrh ** 3307832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 3308832508b7Sdrh ** the subquery before this routine runs. 33091350b030Sdrh */ 33108c74a8caSdrh static int flattenSubquery( 3311524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 33128c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 33138c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 33148c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 33158c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 33168c74a8caSdrh ){ 3317524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 3318d12b6363Sdrh Select *pParent; /* Current UNION ALL term of the other query */ 33190bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 3320f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 3321ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 3322ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 33230bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 33246a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 332591bb0eedSdrh int i; /* Loop counter */ 332691bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 332791bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 3328524cc21eSdanielk1977 sqlite3 *db = pParse->db; 33291350b030Sdrh 3330832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 3331832508b7Sdrh */ 3332a78c22c4Sdrh assert( p!=0 ); 3333a78c22c4Sdrh assert( p->pPrior==0 ); /* Unable to flatten compound queries */ 33347e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 3335832508b7Sdrh pSrc = p->pSrc; 3336ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 333791bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 333849fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 333991bb0eedSdrh pSub = pSubitem->pSelect; 3340832508b7Sdrh assert( pSub!=0 ); 3341885a5b03Sdrh if( subqueryIsAgg ){ 3342885a5b03Sdrh if( isAgg ) return 0; /* Restriction (1) */ 3343885a5b03Sdrh if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */ 3344885a5b03Sdrh if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery)) 33452308ed38Sdrh || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0 33462308ed38Sdrh || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0 3347885a5b03Sdrh ){ 3348885a5b03Sdrh return 0; /* Restriction (2b) */ 3349885a5b03Sdrh } 3350885a5b03Sdrh } 3351885a5b03Sdrh 3352832508b7Sdrh pSubSrc = pSub->pSrc; 3353832508b7Sdrh assert( pSubSrc ); 3354ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 335560ec914cSpeter.d.reid ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 3356ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 3357ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 3358ac83963aSdrh ** and (14). */ 3359ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 3360ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 3361d227a291Sdrh if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 3362ad91c6cdSdrh return 0; /* Restriction (15) */ 3363ad91c6cdSdrh } 3364ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 336549ad330dSdan if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ 336649ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 336749ad330dSdan return 0; /* Restrictions (8)(9) */ 3368df199a25Sdrh } 33697d10d5a6Sdrh if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ 33707d10d5a6Sdrh return 0; /* Restriction (6) */ 33717d10d5a6Sdrh } 33727d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 3373ac83963aSdrh return 0; /* Restriction (11) */ 3374ac83963aSdrh } 3375c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 3376229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 3377a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 3378a91491e5Sshaneh return 0; /* Restriction (21) */ 3379a91491e5Sshaneh } 33809588ad95Sdrh testcase( pSub->selFlags & SF_Recursive ); 33819588ad95Sdrh testcase( pSub->selFlags & SF_MinMaxAgg ); 33829588ad95Sdrh if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){ 33839588ad95Sdrh return 0; /* Restrictions (22) and (24) */ 33849588ad95Sdrh } 33859588ad95Sdrh if( (p->selFlags & SF_Recursive) && pSub->pPrior ){ 33869588ad95Sdrh return 0; /* Restriction (23) */ 33879588ad95Sdrh } 3388832508b7Sdrh 33892b300d5dSdrh /* OBSOLETE COMMENT 1: 33902b300d5dSdrh ** Restriction 3: If the subquery is a join, make sure the subquery is 33918af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 33928af4d3acSdrh ** is not allowed: 33938af4d3acSdrh ** 33948af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 33958af4d3acSdrh ** 33968af4d3acSdrh ** If we flatten the above, we would get 33978af4d3acSdrh ** 33988af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 33998af4d3acSdrh ** 34008af4d3acSdrh ** which is not at all the same thing. 34012b300d5dSdrh ** 34022b300d5dSdrh ** OBSOLETE COMMENT 2: 34032b300d5dSdrh ** Restriction 12: If the subquery is the right operand of a left outer 34043fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 34053fc673e6Sdrh ** An examples of why this is not allowed: 34063fc673e6Sdrh ** 34073fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 34083fc673e6Sdrh ** 34093fc673e6Sdrh ** If we flatten the above, we would get 34103fc673e6Sdrh ** 34113fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 34123fc673e6Sdrh ** 34133fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 34143fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 34152b300d5dSdrh ** 34162b300d5dSdrh ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: 34172b300d5dSdrh ** Ticket #3300 shows that flattening the right term of a LEFT JOIN 34182b300d5dSdrh ** is fraught with danger. Best to avoid the whole thing. If the 34192b300d5dSdrh ** subquery is the right term of a LEFT JOIN, then do not flatten. 34203fc673e6Sdrh */ 34218a48b9c0Sdrh if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ 34223fc673e6Sdrh return 0; 34233fc673e6Sdrh } 34243fc673e6Sdrh 3425f23329a2Sdanielk1977 /* Restriction 17: If the sub-query is a compound SELECT, then it must 3426f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 3427f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 3428f23329a2Sdanielk1977 ** queries. 3429f23329a2Sdanielk1977 */ 3430f23329a2Sdanielk1977 if( pSub->pPrior ){ 3431e8902a70Sdrh if( pSub->pOrderBy ){ 3432e8902a70Sdrh return 0; /* Restriction 20 */ 3433e8902a70Sdrh } 3434e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 3435f23329a2Sdanielk1977 return 0; 3436f23329a2Sdanielk1977 } 3437f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 3438ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 3439ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 34404b3ac73cSdrh assert( pSub->pSrc!=0 ); 34412ec18a3cSdrh assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); 34427d10d5a6Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 344380b3c548Sdanielk1977 || (pSub1->pPrior && pSub1->op!=TK_ALL) 34444b3ac73cSdrh || pSub1->pSrc->nSrc<1 344580b3c548Sdanielk1977 ){ 3446f23329a2Sdanielk1977 return 0; 3447f23329a2Sdanielk1977 } 34484b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 3449f23329a2Sdanielk1977 } 345049fc1f60Sdanielk1977 345149fc1f60Sdanielk1977 /* Restriction 18. */ 345249fc1f60Sdanielk1977 if( p->pOrderBy ){ 345349fc1f60Sdanielk1977 int ii; 345449fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 3455c2acc4e4Sdrh if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; 345649fc1f60Sdanielk1977 } 345749fc1f60Sdanielk1977 } 3458f23329a2Sdanielk1977 } 3459f23329a2Sdanielk1977 34607d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 3461eb9b884cSdrh SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n", 3462eb9b884cSdrh pSub->zSelName, pSub, iFrom)); 34637d10d5a6Sdrh 34647d10d5a6Sdrh /* Authorize the subquery */ 3465524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 3466a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 3467a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 3468524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 3469524cc21eSdanielk1977 34707d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 34717d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 34727d10d5a6Sdrh ** be of the form: 3473f23329a2Sdanielk1977 ** 3474f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 3475f23329a2Sdanielk1977 ** 3476f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 3477a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 3478f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 3479f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 3480f23329a2Sdanielk1977 ** select statements in the compound sub-query. 3481a78c22c4Sdrh ** 3482a78c22c4Sdrh ** Example: 3483a78c22c4Sdrh ** 3484a78c22c4Sdrh ** SELECT a+1 FROM ( 3485a78c22c4Sdrh ** SELECT x FROM tab 3486a78c22c4Sdrh ** UNION ALL 3487a78c22c4Sdrh ** SELECT y FROM tab 3488a78c22c4Sdrh ** UNION ALL 3489a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 3490a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 3491a78c22c4Sdrh ** 3492a78c22c4Sdrh ** Transformed into: 3493a78c22c4Sdrh ** 3494a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 3495a78c22c4Sdrh ** UNION ALL 3496a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 3497a78c22c4Sdrh ** UNION ALL 3498a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 3499a78c22c4Sdrh ** ORDER BY 1 3500a78c22c4Sdrh ** 3501a78c22c4Sdrh ** We call this the "compound-subquery flattening". 3502f23329a2Sdanielk1977 */ 3503f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 3504f23329a2Sdanielk1977 Select *pNew; 3505f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 35064b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 3507547180baSdrh Expr *pOffset = p->pOffset; 3508f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 3509f23329a2Sdanielk1977 p->pOrderBy = 0; 3510f23329a2Sdanielk1977 p->pSrc = 0; 3511f23329a2Sdanielk1977 p->pPrior = 0; 35124b86ef1dSdanielk1977 p->pLimit = 0; 3513547180baSdrh p->pOffset = 0; 35146ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 3515eb9b884cSdrh sqlite3SelectSetName(pNew, pSub->zSelName); 3516547180baSdrh p->pOffset = pOffset; 35174b86ef1dSdanielk1977 p->pLimit = pLimit; 3518a78c22c4Sdrh p->pOrderBy = pOrderBy; 3519a78c22c4Sdrh p->pSrc = pSrc; 3520a78c22c4Sdrh p->op = TK_ALL; 3521a78c22c4Sdrh if( pNew==0 ){ 3522d227a291Sdrh p->pPrior = pPrior; 3523a78c22c4Sdrh }else{ 3524a78c22c4Sdrh pNew->pPrior = pPrior; 3525d227a291Sdrh if( pPrior ) pPrior->pNext = pNew; 3526d227a291Sdrh pNew->pNext = p; 3527a78c22c4Sdrh p->pPrior = pNew; 3528eb9b884cSdrh SELECTTRACE(2,pParse,p, 3529eb9b884cSdrh ("compound-subquery flattener creates %s.%p as peer\n", 3530eb9b884cSdrh pNew->zSelName, pNew)); 3531d227a291Sdrh } 3532a78c22c4Sdrh if( db->mallocFailed ) return 1; 3533a78c22c4Sdrh } 3534f23329a2Sdanielk1977 35357d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 35367d10d5a6Sdrh ** in the outer query. 3537832508b7Sdrh */ 3538f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 3539c31c2eb8Sdrh 3540a78c22c4Sdrh /* Delete the transient table structure associated with the 3541a78c22c4Sdrh ** subquery 3542a78c22c4Sdrh */ 3543a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 3544a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 3545a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 3546a78c22c4Sdrh pSubitem->zDatabase = 0; 3547a78c22c4Sdrh pSubitem->zName = 0; 3548a78c22c4Sdrh pSubitem->zAlias = 0; 3549a78c22c4Sdrh pSubitem->pSelect = 0; 3550a78c22c4Sdrh 3551a78c22c4Sdrh /* Defer deleting the Table object associated with the 3552a78c22c4Sdrh ** subquery until code generation is 3553a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 3554a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 3555ccfcbceaSdrh ** 3556ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 3557a78c22c4Sdrh */ 3558ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 3559a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 3560a78c22c4Sdrh if( pTabToDel->nRef==1 ){ 356165a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 356265a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 356365a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 3564a78c22c4Sdrh }else{ 3565a78c22c4Sdrh pTabToDel->nRef--; 3566a78c22c4Sdrh } 3567a78c22c4Sdrh pSubitem->pTab = 0; 3568a78c22c4Sdrh } 3569a78c22c4Sdrh 3570a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 3571a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 3572a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 3573a78c22c4Sdrh ** then this loop only runs once. 3574a78c22c4Sdrh ** 3575a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 3576c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 3577c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 3578c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 3579c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 3580c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 3581c31c2eb8Sdrh ** elements we are now copying in. 3582c31c2eb8Sdrh */ 3583a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 3584a78c22c4Sdrh int nSubSrc; 3585ea678832Sdrh u8 jointype = 0; 3586a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 3587a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 3588a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 3589588a9a1aSdrh 3590a78c22c4Sdrh if( pSrc ){ 3591a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 35928a48b9c0Sdrh jointype = pSubitem->fg.jointype; 3593588a9a1aSdrh }else{ 3594a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 3595a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 3596cfa063b3Sdrh if( pSrc==0 ){ 3597a78c22c4Sdrh assert( db->mallocFailed ); 3598a78c22c4Sdrh break; 3599cfa063b3Sdrh } 3600c31c2eb8Sdrh } 3601a78c22c4Sdrh 3602a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 3603a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 3604a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 3605a78c22c4Sdrh ** of the subquery. 3606a78c22c4Sdrh ** 3607a78c22c4Sdrh ** Example: 3608a78c22c4Sdrh ** 3609a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 3610a78c22c4Sdrh ** 3611a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 3612a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 3613d12b6363Sdrh ** block of code will expand the outer query FROM clause to 4 slots. 3614d12b6363Sdrh ** The middle slot is expanded to two slots in order to make space 3615d12b6363Sdrh ** for the two elements in the FROM clause of the subquery. 3616a78c22c4Sdrh */ 3617a78c22c4Sdrh if( nSubSrc>1 ){ 3618a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 3619a78c22c4Sdrh if( db->mallocFailed ){ 3620a78c22c4Sdrh break; 3621c31c2eb8Sdrh } 3622c31c2eb8Sdrh } 3623a78c22c4Sdrh 3624a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 3625a78c22c4Sdrh ** outer query. 3626a78c22c4Sdrh */ 3627c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 3628c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 3629c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 3630c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 3631c31c2eb8Sdrh } 36328a48b9c0Sdrh pSrc->a[iFrom].fg.jointype = jointype; 3633c31c2eb8Sdrh 3634c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 3635c31c2eb8Sdrh ** references to the iParent in the outer query. 3636c31c2eb8Sdrh ** 3637c31c2eb8Sdrh ** Example: 3638c31c2eb8Sdrh ** 3639c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 3640c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 3641c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 3642c31c2eb8Sdrh ** 3643c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 3644c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 3645c31c2eb8Sdrh */ 3646f23329a2Sdanielk1977 pList = pParent->pEList; 3647832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 3648ccfcbceaSdrh if( pList->a[i].zName==0 ){ 364942fbf321Sdrh char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); 365042fbf321Sdrh sqlite3Dequote(zName); 365142fbf321Sdrh pList->a[i].zName = zName; 3652832508b7Sdrh } 3653ccfcbceaSdrh } 3654174b6195Sdrh if( pSub->pOrderBy ){ 36557c0a4720Sdan /* At this point, any non-zero iOrderByCol values indicate that the 36567c0a4720Sdan ** ORDER BY column expression is identical to the iOrderByCol'th 36577c0a4720Sdan ** expression returned by SELECT statement pSub. Since these values 36587c0a4720Sdan ** do not necessarily correspond to columns in SELECT statement pParent, 36597c0a4720Sdan ** zero them before transfering the ORDER BY clause. 36607c0a4720Sdan ** 36617c0a4720Sdan ** Not doing this may cause an error if a subsequent call to this 36627c0a4720Sdan ** function attempts to flatten a compound sub-query into pParent 36637c0a4720Sdan ** (the only way this can happen is if the compound sub-query is 36647c0a4720Sdan ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 36657c0a4720Sdan ExprList *pOrderBy = pSub->pOrderBy; 36667c0a4720Sdan for(i=0; i<pOrderBy->nExpr; i++){ 36677c0a4720Sdan pOrderBy->a[i].u.x.iOrderByCol = 0; 36687c0a4720Sdan } 3669f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 36707c0a4720Sdan assert( pSub->pPrior==0 ); 36717c0a4720Sdan pParent->pOrderBy = pOrderBy; 3672174b6195Sdrh pSub->pOrderBy = 0; 3673174b6195Sdrh } 36746ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 3675832508b7Sdrh if( subqueryIsAgg ){ 3676f23329a2Sdanielk1977 assert( pParent->pHaving==0 ); 3677f23329a2Sdanielk1977 pParent->pHaving = pParent->pWhere; 3678f23329a2Sdanielk1977 pParent->pWhere = pWhere; 3679f23329a2Sdanielk1977 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 36806ab3a2ecSdanielk1977 sqlite3ExprDup(db, pSub->pHaving, 0)); 3681f23329a2Sdanielk1977 assert( pParent->pGroupBy==0 ); 36826ab3a2ecSdanielk1977 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); 3683832508b7Sdrh }else{ 3684f23329a2Sdanielk1977 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); 3685832508b7Sdrh } 3686d12b6363Sdrh substSelect(db, pParent, iParent, pSub->pEList, 0); 3687c31c2eb8Sdrh 3688c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 3689c31c2eb8Sdrh ** outer query is distinct. 3690c31c2eb8Sdrh */ 36917d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 36928c74a8caSdrh 3693a58fdfb1Sdanielk1977 /* 3694a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3695ac83963aSdrh ** 3696ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 3697ac83963aSdrh ** does not work if either limit is negative. 3698a58fdfb1Sdanielk1977 */ 3699a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 3700f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 3701a2dc3b1aSdanielk1977 pSub->pLimit = 0; 3702df199a25Sdrh } 3703f23329a2Sdanielk1977 } 37048c74a8caSdrh 3705c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 3706c31c2eb8Sdrh ** success. 3707c31c2eb8Sdrh */ 3708633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 3709f23329a2Sdanielk1977 3710c90713d3Sdrh #if SELECTTRACE_ENABLED 3711c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 3712bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After flattening:\n")); 3713c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 3714c90713d3Sdrh } 3715c90713d3Sdrh #endif 3716c90713d3Sdrh 3717832508b7Sdrh return 1; 37181350b030Sdrh } 37193514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 37201350b030Sdrh 372169b72d5aSdrh 372269b72d5aSdrh 372369b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 372469b72d5aSdrh /* 372569b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into 372669b72d5aSdrh ** the WHERE clause of subquery. Example: 372769b72d5aSdrh ** 372869b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; 372969b72d5aSdrh ** 373069b72d5aSdrh ** Transformed into: 373169b72d5aSdrh ** 373269b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) 373369b72d5aSdrh ** WHERE x=5 AND y=10; 373469b72d5aSdrh ** 373569b72d5aSdrh ** The hope is that the terms added to the inner query will make it more 373669b72d5aSdrh ** efficient. 373769b72d5aSdrh ** 373869b72d5aSdrh ** Do not attempt this optimization if: 373969b72d5aSdrh ** 374069b72d5aSdrh ** (1) The inner query is an aggregate. (In that case, we'd really want 374169b72d5aSdrh ** to copy the outer WHERE-clause terms onto the HAVING clause of the 374269b72d5aSdrh ** inner query. But they probably won't help there so do not bother.) 374369b72d5aSdrh ** 374469b72d5aSdrh ** (2) The inner query is the recursive part of a common table expression. 374569b72d5aSdrh ** 374669b72d5aSdrh ** (3) The inner query has a LIMIT clause (since the changes to the WHERE 374769b72d5aSdrh ** close would change the meaning of the LIMIT). 374869b72d5aSdrh ** 374969b72d5aSdrh ** (4) The inner query is the right operand of a LEFT JOIN. (The caller 375069b72d5aSdrh ** enforces this restriction since this routine does not have enough 375169b72d5aSdrh ** information to know.) 375269b72d5aSdrh ** 375338978dd4Sdrh ** (5) The WHERE clause expression originates in the ON or USING clause 375438978dd4Sdrh ** of a LEFT JOIN. 375538978dd4Sdrh ** 375669b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause 375769b72d5aSdrh ** terms are duplicated into the subquery. 375869b72d5aSdrh */ 375969b72d5aSdrh static int pushDownWhereTerms( 376069b72d5aSdrh sqlite3 *db, /* The database connection (for malloc()) */ 376169b72d5aSdrh Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ 376269b72d5aSdrh Expr *pWhere, /* The WHERE clause of the outer query */ 376369b72d5aSdrh int iCursor /* Cursor number of the subquery */ 376469b72d5aSdrh ){ 376569b72d5aSdrh Expr *pNew; 376669b72d5aSdrh int nChng = 0; 376769b72d5aSdrh if( pWhere==0 ) return 0; 376869b72d5aSdrh if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){ 376969b72d5aSdrh return 0; /* restrictions (1) and (2) */ 377069b72d5aSdrh } 377169b72d5aSdrh if( pSubq->pLimit!=0 ){ 377269b72d5aSdrh return 0; /* restriction (3) */ 377369b72d5aSdrh } 377469b72d5aSdrh while( pWhere->op==TK_AND ){ 377569b72d5aSdrh nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor); 377669b72d5aSdrh pWhere = pWhere->pLeft; 377769b72d5aSdrh } 377838978dd4Sdrh if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */ 377969b72d5aSdrh if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ 378069b72d5aSdrh nChng++; 378169b72d5aSdrh while( pSubq ){ 378269b72d5aSdrh pNew = sqlite3ExprDup(db, pWhere, 0); 378369b72d5aSdrh pNew = substExpr(db, pNew, iCursor, pSubq->pEList); 378469b72d5aSdrh pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew); 378569b72d5aSdrh pSubq = pSubq->pPrior; 378669b72d5aSdrh } 378769b72d5aSdrh } 378869b72d5aSdrh return nChng; 378969b72d5aSdrh } 379069b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 379169b72d5aSdrh 37921350b030Sdrh /* 37934ac391fcSdan ** Based on the contents of the AggInfo structure indicated by the first 37944ac391fcSdan ** argument, this function checks if the following are true: 3795a9d1ccb9Sdanielk1977 ** 37964ac391fcSdan ** * the query contains just a single aggregate function, 37974ac391fcSdan ** * the aggregate function is either min() or max(), and 37984ac391fcSdan ** * the argument to the aggregate function is a column value. 3799738bdcfbSdanielk1977 ** 38004ac391fcSdan ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX 38014ac391fcSdan ** is returned as appropriate. Also, *ppMinMax is set to point to the 38024ac391fcSdan ** list of arguments passed to the aggregate before returning. 38034ac391fcSdan ** 38044ac391fcSdan ** Or, if the conditions above are not met, *ppMinMax is set to 0 and 38054ac391fcSdan ** WHERE_ORDERBY_NORMAL is returned. 3806a9d1ccb9Sdanielk1977 */ 38074ac391fcSdan static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ 38084ac391fcSdan int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ 3809a9d1ccb9Sdanielk1977 38104ac391fcSdan *ppMinMax = 0; 38114ac391fcSdan if( pAggInfo->nFunc==1 ){ 38124ac391fcSdan Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ 38134ac391fcSdan ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ 38144ac391fcSdan 38154ac391fcSdan assert( pExpr->op==TK_AGG_FUNCTION ); 38164ac391fcSdan if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ 38174ac391fcSdan const char *zFunc = pExpr->u.zToken; 38184ac391fcSdan if( sqlite3StrICmp(zFunc, "min")==0 ){ 38194ac391fcSdan eRet = WHERE_ORDERBY_MIN; 38204ac391fcSdan *ppMinMax = pEList; 38214ac391fcSdan }else if( sqlite3StrICmp(zFunc, "max")==0 ){ 38224ac391fcSdan eRet = WHERE_ORDERBY_MAX; 38234ac391fcSdan *ppMinMax = pEList; 3824a9d1ccb9Sdanielk1977 } 38254ac391fcSdan } 38264ac391fcSdan } 38274ac391fcSdan 38284ac391fcSdan assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); 38294ac391fcSdan return eRet; 3830a9d1ccb9Sdanielk1977 } 3831a9d1ccb9Sdanielk1977 3832a9d1ccb9Sdanielk1977 /* 3833a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 383460ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This 3835a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 3836a5533162Sdanielk1977 ** 3837a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 3838a5533162Sdanielk1977 ** 3839a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 3840a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 3841a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 3842a5533162Sdanielk1977 */ 3843a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 3844a5533162Sdanielk1977 Table *pTab; 3845a5533162Sdanielk1977 Expr *pExpr; 3846a5533162Sdanielk1977 3847a5533162Sdanielk1977 assert( !p->pGroupBy ); 3848a5533162Sdanielk1977 38497a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 3850a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 3851a5533162Sdanielk1977 ){ 3852a5533162Sdanielk1977 return 0; 3853a5533162Sdanielk1977 } 3854a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 3855a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 385602f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 385702f33725Sdanielk1977 385802f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 3859a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 3860fb0a6081Sdrh if( NEVER(pAggInfo->nFunc==0) ) return 0; 3861d36e1041Sdrh if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; 3862a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 3863a5533162Sdanielk1977 3864a5533162Sdanielk1977 return pTab; 3865a5533162Sdanielk1977 } 3866a5533162Sdanielk1977 3867a5533162Sdanielk1977 /* 3868b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 3869b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 3870b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 3871b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 3872b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 3873b1c685b0Sdanielk1977 */ 3874b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 38758a48b9c0Sdrh if( pFrom->pTab && pFrom->fg.isIndexedBy ){ 3876b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 38778a48b9c0Sdrh char *zIndexedBy = pFrom->u1.zIndexedBy; 3878b1c685b0Sdanielk1977 Index *pIdx; 3879b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 3880d62fbb50Sdrh pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 3881b1c685b0Sdanielk1977 pIdx=pIdx->pNext 3882b1c685b0Sdanielk1977 ); 3883b1c685b0Sdanielk1977 if( !pIdx ){ 3884d62fbb50Sdrh sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); 38851db95106Sdan pParse->checkSchema = 1; 3886b1c685b0Sdanielk1977 return SQLITE_ERROR; 3887b1c685b0Sdanielk1977 } 38888a48b9c0Sdrh pFrom->pIBIndex = pIdx; 3889b1c685b0Sdanielk1977 } 3890b1c685b0Sdanielk1977 return SQLITE_OK; 3891b1c685b0Sdanielk1977 } 3892c01b7306Sdrh /* 3893c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with 3894c01b7306Sdrh ** an alternative collating sequence. 3895c01b7306Sdrh ** 3896c01b7306Sdrh ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 3897c01b7306Sdrh ** 3898c01b7306Sdrh ** These are rewritten as a subquery: 3899c01b7306Sdrh ** 3900c01b7306Sdrh ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) 3901c01b7306Sdrh ** ORDER BY ... COLLATE ... 3902c01b7306Sdrh ** 3903c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine 3904c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause 3905c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the 3906c01b7306Sdrh ** result columns as on the ORDER BY clause. See ticket 3907c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a 3908c01b7306Sdrh ** 3909c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. 3910c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when 3911c01b7306Sdrh ** there are COLLATE terms in the ORDER BY. 3912c01b7306Sdrh */ 3913c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ 3914c01b7306Sdrh int i; 3915c01b7306Sdrh Select *pNew; 3916c01b7306Sdrh Select *pX; 3917c01b7306Sdrh sqlite3 *db; 3918c01b7306Sdrh struct ExprList_item *a; 3919c01b7306Sdrh SrcList *pNewSrc; 3920c01b7306Sdrh Parse *pParse; 3921c01b7306Sdrh Token dummy; 3922c01b7306Sdrh 3923c01b7306Sdrh if( p->pPrior==0 ) return WRC_Continue; 3924c01b7306Sdrh if( p->pOrderBy==0 ) return WRC_Continue; 3925c01b7306Sdrh for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} 3926c01b7306Sdrh if( pX==0 ) return WRC_Continue; 3927c01b7306Sdrh a = p->pOrderBy->a; 3928c01b7306Sdrh for(i=p->pOrderBy->nExpr-1; i>=0; i--){ 3929c01b7306Sdrh if( a[i].pExpr->flags & EP_Collate ) break; 3930c01b7306Sdrh } 3931c01b7306Sdrh if( i<0 ) return WRC_Continue; 3932c01b7306Sdrh 3933c01b7306Sdrh /* If we reach this point, that means the transformation is required. */ 3934c01b7306Sdrh 3935c01b7306Sdrh pParse = pWalker->pParse; 3936c01b7306Sdrh db = pParse->db; 3937c01b7306Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 3938c01b7306Sdrh if( pNew==0 ) return WRC_Abort; 3939c01b7306Sdrh memset(&dummy, 0, sizeof(dummy)); 3940c01b7306Sdrh pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); 3941c01b7306Sdrh if( pNewSrc==0 ) return WRC_Abort; 3942c01b7306Sdrh *pNew = *p; 3943c01b7306Sdrh p->pSrc = pNewSrc; 3944c01b7306Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0)); 3945c01b7306Sdrh p->op = TK_SELECT; 3946c01b7306Sdrh p->pWhere = 0; 3947c01b7306Sdrh pNew->pGroupBy = 0; 3948c01b7306Sdrh pNew->pHaving = 0; 3949c01b7306Sdrh pNew->pOrderBy = 0; 3950c01b7306Sdrh p->pPrior = 0; 39518af9ad95Sdrh p->pNext = 0; 3952f932f714Sdrh p->pWith = 0; 39538af9ad95Sdrh p->selFlags &= ~SF_Compound; 3954b33c50f2Sdan assert( (p->selFlags & SF_Converted)==0 ); 3955b33c50f2Sdan p->selFlags |= SF_Converted; 3956a6e3a8c9Sdrh assert( pNew->pPrior!=0 ); 3957a6e3a8c9Sdrh pNew->pPrior->pNext = pNew; 3958c01b7306Sdrh pNew->pLimit = 0; 3959c01b7306Sdrh pNew->pOffset = 0; 3960c01b7306Sdrh return WRC_Continue; 3961c01b7306Sdrh } 3962b1c685b0Sdanielk1977 3963eede6a53Sdan #ifndef SQLITE_OMIT_CTE 3964eede6a53Sdan /* 3965eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested 3966eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by 3967eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE) 3968eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise 3969eede6a53Sdan ** return NULL. 397098f45e53Sdan ** 397198f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With 397298f45e53Sdan ** object that the returned CTE belongs to. 397360c1a2f0Sdrh */ 397498f45e53Sdan static struct Cte *searchWith( 397598f45e53Sdan With *pWith, /* Current outermost WITH clause */ 397698f45e53Sdan struct SrcList_item *pItem, /* FROM clause element to resolve */ 397798f45e53Sdan With **ppContext /* OUT: WITH clause return value belongs to */ 397898f45e53Sdan ){ 39797b19f252Sdrh const char *zName; 39807b19f252Sdrh if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ 3981eede6a53Sdan With *p; 3982eede6a53Sdan for(p=pWith; p; p=p->pOuter){ 39834e9119d9Sdan int i; 3984eede6a53Sdan for(i=0; i<p->nCte; i++){ 3985eede6a53Sdan if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 398698f45e53Sdan *ppContext = p; 3987eede6a53Sdan return &p->a[i]; 39884e9119d9Sdan } 39894e9119d9Sdan } 39904e9119d9Sdan } 39914e9119d9Sdan } 39924e9119d9Sdan return 0; 39934e9119d9Sdan } 39944e9119d9Sdan 3995c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses 3996c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack. 3997c49832c2Sdrh ** 3998b290f117Sdan ** This routine pushes the WITH clause passed as the second argument 3999b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this 4000b290f117Sdan ** WITH clause will never be popped from the stack. In this case it 4001b290f117Sdan ** should be freed along with the Parse object. In other cases, when 4002b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT 4003b290f117Sdan ** statement with which it is associated. 4004c49832c2Sdrh */ 4005b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 4006b290f117Sdan assert( bFree==0 || pParse->pWith==0 ); 40074e9119d9Sdan if( pWith ){ 40084e9119d9Sdan pWith->pOuter = pParse->pWith; 40094e9119d9Sdan pParse->pWith = pWith; 4010b290f117Sdan pParse->bFreeWith = bFree; 40114e9119d9Sdan } 40124e9119d9Sdan } 40134e9119d9Sdan 4014eede6a53Sdan /* 4015eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by 4016eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And, 4017eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive 4018eede6a53Sdan ** reference to the current CTE. 4019eede6a53Sdan ** 4020eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab 4021eede6a53Sdan ** and other fields are populated accordingly. The caller should check 4022eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match 4023eede6a53Sdan ** was found. 4024eede6a53Sdan ** 4025eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error 4026eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the 4027eede6a53Sdan ** parser and some error code other than SQLITE_OK returned. 4028eede6a53Sdan */ 40298ce7184bSdan static int withExpand( 40308ce7184bSdan Walker *pWalker, 4031eede6a53Sdan struct SrcList_item *pFrom 40328ce7184bSdan ){ 40338ce7184bSdan Parse *pParse = pWalker->pParse; 40348ce7184bSdan sqlite3 *db = pParse->db; 403598f45e53Sdan struct Cte *pCte; /* Matched CTE (or NULL if no match) */ 403698f45e53Sdan With *pWith; /* WITH clause that pCte belongs to */ 40378ce7184bSdan 40388ce7184bSdan assert( pFrom->pTab==0 ); 40398ce7184bSdan 404098f45e53Sdan pCte = searchWith(pParse->pWith, pFrom, &pWith); 4041eae73fbfSdan if( pCte ){ 404298f45e53Sdan Table *pTab; 40438ce7184bSdan ExprList *pEList; 40448ce7184bSdan Select *pSel; 404560e7068dSdan Select *pLeft; /* Left-most SELECT statement */ 4046f2655fe8Sdan int bMayRecursive; /* True if compound joined by UNION [ALL] */ 404798f45e53Sdan With *pSavedWith; /* Initial value of pParse->pWith */ 4048f2655fe8Sdan 40490576bc59Sdrh /* If pCte->zCteErr is non-NULL at this point, then this is an illegal 4050f2655fe8Sdan ** recursive reference to CTE pCte. Leave an error in pParse and return 40510576bc59Sdrh ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. 4052f2655fe8Sdan ** In this case, proceed. */ 40530576bc59Sdrh if( pCte->zCteErr ){ 40540576bc59Sdrh sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); 405598f45e53Sdan return SQLITE_ERROR; 4056f2655fe8Sdan } 40578ce7184bSdan 4058c25e2ebcSdrh assert( pFrom->pTab==0 ); 40598ce7184bSdan pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 40608ce7184bSdan if( pTab==0 ) return WRC_Abort; 40618ce7184bSdan pTab->nRef = 1; 40622d4dc5fcSdan pTab->zName = sqlite3DbStrDup(db, pCte->zName); 40638ce7184bSdan pTab->iPKey = -1; 4064cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 4065fccda8a1Sdrh pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; 40668ce7184bSdan pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 40678ce7184bSdan if( db->mallocFailed ) return SQLITE_NOMEM; 40688ce7184bSdan assert( pFrom->pSelect ); 40698ce7184bSdan 4070eae73fbfSdan /* Check if this is a recursive CTE. */ 40718ce7184bSdan pSel = pFrom->pSelect; 4072f2655fe8Sdan bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 4073f2655fe8Sdan if( bMayRecursive ){ 4074eae73fbfSdan int i; 4075eae73fbfSdan SrcList *pSrc = pFrom->pSelect->pSrc; 4076eae73fbfSdan for(i=0; i<pSrc->nSrc; i++){ 4077eae73fbfSdan struct SrcList_item *pItem = &pSrc->a[i]; 4078eae73fbfSdan if( pItem->zDatabase==0 4079eae73fbfSdan && pItem->zName!=0 4080eae73fbfSdan && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 4081eae73fbfSdan ){ 4082eae73fbfSdan pItem->pTab = pTab; 40838a48b9c0Sdrh pItem->fg.isRecursive = 1; 4084eae73fbfSdan pTab->nRef++; 4085eae73fbfSdan pSel->selFlags |= SF_Recursive; 40868ce7184bSdan } 4087eae73fbfSdan } 4088eae73fbfSdan } 4089eae73fbfSdan 4090eae73fbfSdan /* Only one recursive reference is permitted. */ 4091eae73fbfSdan if( pTab->nRef>2 ){ 4092eae73fbfSdan sqlite3ErrorMsg( 4093727a99f1Sdrh pParse, "multiple references to recursive table: %s", pCte->zName 4094eae73fbfSdan ); 409598f45e53Sdan return SQLITE_ERROR; 4096eae73fbfSdan } 4097eae73fbfSdan assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 )); 4098eae73fbfSdan 40990576bc59Sdrh pCte->zCteErr = "circular reference: %s"; 410098f45e53Sdan pSavedWith = pParse->pWith; 410198f45e53Sdan pParse->pWith = pWith; 4102f2655fe8Sdan sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel); 41038ce7184bSdan 41048ce7184bSdan for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 41058ce7184bSdan pEList = pLeft->pEList; 410660e7068dSdan if( pCte->pCols ){ 41078f9d0b2bSdrh if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ 4108727a99f1Sdrh sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 410960e7068dSdan pCte->zName, pEList->nExpr, pCte->pCols->nExpr 411060e7068dSdan ); 411198f45e53Sdan pParse->pWith = pSavedWith; 411298f45e53Sdan return SQLITE_ERROR; 41138ce7184bSdan } 411460e7068dSdan pEList = pCte->pCols; 411560e7068dSdan } 41168ce7184bSdan 41178981b904Sdrh sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 4118f2655fe8Sdan if( bMayRecursive ){ 4119f2655fe8Sdan if( pSel->selFlags & SF_Recursive ){ 41200576bc59Sdrh pCte->zCteErr = "multiple recursive references: %s"; 4121f2655fe8Sdan }else{ 41220576bc59Sdrh pCte->zCteErr = "recursive reference in a subquery: %s"; 4123f2655fe8Sdan } 4124f2655fe8Sdan sqlite3WalkSelect(pWalker, pSel); 4125f2655fe8Sdan } 41260576bc59Sdrh pCte->zCteErr = 0; 412798f45e53Sdan pParse->pWith = pSavedWith; 41288ce7184bSdan } 41298ce7184bSdan 41308ce7184bSdan return SQLITE_OK; 41318ce7184bSdan } 4132eede6a53Sdan #endif 41334e9119d9Sdan 4134b290f117Sdan #ifndef SQLITE_OMIT_CTE 413571856944Sdan /* 413671856944Sdan ** If the SELECT passed as the second argument has an associated WITH 413771856944Sdan ** clause, pop it from the stack stored as part of the Parse object. 413871856944Sdan ** 413971856944Sdan ** This function is used as the xSelectCallback2() callback by 414071856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table 414171856944Sdan ** names and other FROM clause elements. 414271856944Sdan */ 4143b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){ 4144b290f117Sdan Parse *pParse = pWalker->pParse; 4145d227a291Sdrh With *pWith = findRightmost(p)->pWith; 4146d227a291Sdrh if( pWith!=0 ){ 4147d227a291Sdrh assert( pParse->pWith==pWith ); 4148d227a291Sdrh pParse->pWith = pWith->pOuter; 4149b290f117Sdan } 4150b290f117Sdan } 4151b290f117Sdan #else 4152b290f117Sdan #define selectPopWith 0 4153b290f117Sdan #endif 4154b290f117Sdan 4155b1c685b0Sdanielk1977 /* 41567d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 41577d10d5a6Sdrh ** "Expanding" means to do the following: 41587d10d5a6Sdrh ** 41597d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 41607d10d5a6Sdrh ** element of the FROM clause. 41617d10d5a6Sdrh ** 41627d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 41637d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 41647d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 41657d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 41667d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 416760ec914cSpeter.d.reid ** without worrying about messing up the persistent representation 41687d10d5a6Sdrh ** of the view. 41697d10d5a6Sdrh ** 417060ec914cSpeter.d.reid ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword 41717d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 41727d10d5a6Sdrh ** 41737d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 41747d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 41757d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 41767d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 41777d10d5a6Sdrh ** 4178b3bce662Sdanielk1977 */ 41797d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 41807d10d5a6Sdrh Parse *pParse = pWalker->pParse; 41817d10d5a6Sdrh int i, j, k; 41827d10d5a6Sdrh SrcList *pTabList; 41837d10d5a6Sdrh ExprList *pEList; 41847d10d5a6Sdrh struct SrcList_item *pFrom; 41857d10d5a6Sdrh sqlite3 *db = pParse->db; 41863e3f1a5bSdrh Expr *pE, *pRight, *pExpr; 4187785097daSdrh u16 selFlags = p->selFlags; 41887d10d5a6Sdrh 4189785097daSdrh p->selFlags |= SF_Expanded; 41907d10d5a6Sdrh if( db->mallocFailed ){ 41917d10d5a6Sdrh return WRC_Abort; 41927d10d5a6Sdrh } 4193785097daSdrh if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ 41947d10d5a6Sdrh return WRC_Prune; 41957d10d5a6Sdrh } 41967d10d5a6Sdrh pTabList = p->pSrc; 41977d10d5a6Sdrh pEList = p->pEList; 41983afd2b4dSdrh if( pWalker->xSelectCallback2==selectPopWith ){ 4199d227a291Sdrh sqlite3WithPush(pParse, findRightmost(p)->pWith, 0); 42003afd2b4dSdrh } 42017d10d5a6Sdrh 42027d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 42037d10d5a6Sdrh ** the FROM clause of the SELECT statement. 42047d10d5a6Sdrh */ 42057d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 42067d10d5a6Sdrh 42077d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 42087d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 42097d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 42107d10d5a6Sdrh */ 42117d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 42127d10d5a6Sdrh Table *pTab; 4213e2b7d7a0Sdrh assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); 42148a48b9c0Sdrh if( pFrom->fg.isRecursive ) continue; 4215e2b7d7a0Sdrh assert( pFrom->pTab==0 ); 42164e9119d9Sdan #ifndef SQLITE_OMIT_CTE 4217eede6a53Sdan if( withExpand(pWalker, pFrom) ) return WRC_Abort; 4218eede6a53Sdan if( pFrom->pTab ) {} else 42194e9119d9Sdan #endif 42207d10d5a6Sdrh if( pFrom->zName==0 ){ 42217d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 42227d10d5a6Sdrh Select *pSel = pFrom->pSelect; 42237d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 42247d10d5a6Sdrh assert( pSel!=0 ); 42257d10d5a6Sdrh assert( pFrom->pTab==0 ); 42262b8c5a00Sdrh if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; 42277d10d5a6Sdrh pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 42287d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 42297d10d5a6Sdrh pTab->nRef = 1; 4230186ad8ccSdrh pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); 42317d10d5a6Sdrh while( pSel->pPrior ){ pSel = pSel->pPrior; } 42328981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); 42337d10d5a6Sdrh pTab->iPKey = -1; 4234cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 42357d10d5a6Sdrh pTab->tabFlags |= TF_Ephemeral; 42367d10d5a6Sdrh #endif 42377d10d5a6Sdrh }else{ 42387d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 42397d10d5a6Sdrh assert( pFrom->pTab==0 ); 424041fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 42417d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 4242d2a56238Sdrh if( pTab->nRef==0xffff ){ 4243d2a56238Sdrh sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 4244d2a56238Sdrh pTab->zName); 4245d2a56238Sdrh pFrom->pTab = 0; 4246d2a56238Sdrh return WRC_Abort; 4247d2a56238Sdrh } 42487d10d5a6Sdrh pTab->nRef++; 42497d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 42507d10d5a6Sdrh if( pTab->pSelect || IsVirtual(pTab) ){ 4251bfad7be7Sdrh i16 nCol; 42527d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 425343152cf8Sdrh assert( pFrom->pSelect==0 ); 42546230212fSdrh if( pFrom->fg.isTabFunc && !IsVirtual(pTab) ){ 42556230212fSdrh sqlite3ErrorMsg(pParse, "'%s' is not a function", pTab->zName); 42566230212fSdrh return WRC_Abort; 42576230212fSdrh } 42586ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 4259eb9b884cSdrh sqlite3SelectSetName(pFrom->pSelect, pTab->zName); 4260bfad7be7Sdrh nCol = pTab->nCol; 4261bfad7be7Sdrh pTab->nCol = -1; 42627d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 4263bfad7be7Sdrh pTab->nCol = nCol; 42647d10d5a6Sdrh } 42657d10d5a6Sdrh #endif 42667d10d5a6Sdrh } 426785574e31Sdanielk1977 426885574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 4269b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 427085574e31Sdanielk1977 return WRC_Abort; 427185574e31Sdanielk1977 } 42727d10d5a6Sdrh } 42737d10d5a6Sdrh 42747d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 42757d10d5a6Sdrh */ 42767d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 42777d10d5a6Sdrh return WRC_Abort; 42787d10d5a6Sdrh } 42797d10d5a6Sdrh 42807d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 42817d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 42827d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 42837d10d5a6Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 42847d10d5a6Sdrh ** The following code just has to locate the TK_ALL expressions and expand 42857d10d5a6Sdrh ** each one to the list of all columns in all tables. 42867d10d5a6Sdrh ** 42877d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 42887d10d5a6Sdrh ** that need expanding. 42897d10d5a6Sdrh */ 42907d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 42913e3f1a5bSdrh pE = pEList->a[k].pExpr; 42927d10d5a6Sdrh if( pE->op==TK_ALL ) break; 429343152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 429443152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 429543152cf8Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; 42967d10d5a6Sdrh } 42977d10d5a6Sdrh if( k<pEList->nExpr ){ 42987d10d5a6Sdrh /* 42997d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 43007d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 43017d10d5a6Sdrh ** in the result set and expand them one by one. 43027d10d5a6Sdrh */ 43037d10d5a6Sdrh struct ExprList_item *a = pEList->a; 43047d10d5a6Sdrh ExprList *pNew = 0; 43057d10d5a6Sdrh int flags = pParse->db->flags; 43067d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 430738b384a0Sdrh && (flags & SQLITE_ShortColNames)==0; 430838b384a0Sdrh 43097d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 43103e3f1a5bSdrh pE = a[k].pExpr; 43113e3f1a5bSdrh pRight = pE->pRight; 43123e3f1a5bSdrh assert( pE->op!=TK_DOT || pRight!=0 ); 43133e3f1a5bSdrh if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){ 43147d10d5a6Sdrh /* This particular expression does not need to be expanded. 43157d10d5a6Sdrh */ 4316b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 43177d10d5a6Sdrh if( pNew ){ 43187d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 4319b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 4320b7916a78Sdrh a[k].zName = 0; 4321b7916a78Sdrh a[k].zSpan = 0; 43227d10d5a6Sdrh } 43237d10d5a6Sdrh a[k].pExpr = 0; 43247d10d5a6Sdrh }else{ 43257d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 43267d10d5a6Sdrh ** expanded. */ 43277d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 43283e3f1a5bSdrh char *zTName = 0; /* text of name of TABLE */ 432943152cf8Sdrh if( pE->op==TK_DOT ){ 433043152cf8Sdrh assert( pE->pLeft!=0 ); 433133e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 433233e619fcSdrh zTName = pE->pLeft->u.zToken; 43337d10d5a6Sdrh } 43347d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 43357d10d5a6Sdrh Table *pTab = pFrom->pTab; 43363e3f1a5bSdrh Select *pSub = pFrom->pSelect; 43377d10d5a6Sdrh char *zTabName = pFrom->zAlias; 43383e3f1a5bSdrh const char *zSchemaName = 0; 4339c75e09c7Sdrh int iDb; 434043152cf8Sdrh if( zTabName==0 ){ 43417d10d5a6Sdrh zTabName = pTab->zName; 43427d10d5a6Sdrh } 43437d10d5a6Sdrh if( db->mallocFailed ) break; 43443e3f1a5bSdrh if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ 43453e3f1a5bSdrh pSub = 0; 43467d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 43477d10d5a6Sdrh continue; 43487d10d5a6Sdrh } 43493e3f1a5bSdrh iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 4350c75e09c7Sdrh zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*"; 43513e3f1a5bSdrh } 43527d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 43537d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 4354b7916a78Sdrh char *zColname; /* The computed column name */ 4355b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 4356b7916a78Sdrh Token sColname; /* Computed column name as a token */ 43577d10d5a6Sdrh 4358c75e09c7Sdrh assert( zName ); 43593e3f1a5bSdrh if( zTName && pSub 43603e3f1a5bSdrh && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 43613e3f1a5bSdrh ){ 43623e3f1a5bSdrh continue; 43633e3f1a5bSdrh } 43643e3f1a5bSdrh 43657d10d5a6Sdrh /* If a column is marked as 'hidden' (currently only possible 43667d10d5a6Sdrh ** for virtual tables), do not include it in the expanded 43677d10d5a6Sdrh ** result-set list. 43687d10d5a6Sdrh */ 43697d10d5a6Sdrh if( IsHiddenColumn(&pTab->aCol[j]) ){ 43707d10d5a6Sdrh assert(IsVirtual(pTab)); 43717d10d5a6Sdrh continue; 43727d10d5a6Sdrh } 43733e3f1a5bSdrh tableSeen = 1; 43747d10d5a6Sdrh 4375da55c48aSdrh if( i>0 && zTName==0 ){ 43768a48b9c0Sdrh if( (pFrom->fg.jointype & JT_NATURAL)!=0 43772179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 43782179b434Sdrh ){ 43797d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 43802179b434Sdrh ** table to the right of the join */ 43817d10d5a6Sdrh continue; 43827d10d5a6Sdrh } 43832179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 43847d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 43857d10d5a6Sdrh ** using clause from the table on the right. */ 43867d10d5a6Sdrh continue; 43877d10d5a6Sdrh } 43887d10d5a6Sdrh } 4389b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 4390b7916a78Sdrh zColname = zName; 4391b7916a78Sdrh zToFree = 0; 43927d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 4393b7916a78Sdrh Expr *pLeft; 4394b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 43957d10d5a6Sdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); 439638b384a0Sdrh if( zSchemaName ){ 4397c75e09c7Sdrh pLeft = sqlite3Expr(db, TK_ID, zSchemaName); 4398c75e09c7Sdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0); 4399c75e09c7Sdrh } 4400b7916a78Sdrh if( longNames ){ 4401b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 4402b7916a78Sdrh zToFree = zColname; 4403b7916a78Sdrh } 44047d10d5a6Sdrh }else{ 44057d10d5a6Sdrh pExpr = pRight; 44067d10d5a6Sdrh } 4407b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 4408b7916a78Sdrh sColname.z = zColname; 4409b7916a78Sdrh sColname.n = sqlite3Strlen30(zColname); 4410b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 44118f25d18bSdrh if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ 44123e3f1a5bSdrh struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; 44133e3f1a5bSdrh if( pSub ){ 44143e3f1a5bSdrh pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); 4415c75e09c7Sdrh testcase( pX->zSpan==0 ); 44163e3f1a5bSdrh }else{ 44173e3f1a5bSdrh pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", 44183e3f1a5bSdrh zSchemaName, zTabName, zColname); 4419c75e09c7Sdrh testcase( pX->zSpan==0 ); 44203e3f1a5bSdrh } 44213e3f1a5bSdrh pX->bSpanIsTab = 1; 44228f25d18bSdrh } 4423b7916a78Sdrh sqlite3DbFree(db, zToFree); 44247d10d5a6Sdrh } 44257d10d5a6Sdrh } 44267d10d5a6Sdrh if( !tableSeen ){ 44277d10d5a6Sdrh if( zTName ){ 44287d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 44297d10d5a6Sdrh }else{ 44307d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 44317d10d5a6Sdrh } 44327d10d5a6Sdrh } 44337d10d5a6Sdrh } 44347d10d5a6Sdrh } 44357d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 44367d10d5a6Sdrh p->pEList = pNew; 44377d10d5a6Sdrh } 44387d10d5a6Sdrh #if SQLITE_MAX_COLUMN 44397d10d5a6Sdrh if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 44407d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 44417d10d5a6Sdrh } 44427d10d5a6Sdrh #endif 44437d10d5a6Sdrh return WRC_Continue; 44447d10d5a6Sdrh } 44457d10d5a6Sdrh 44467d10d5a6Sdrh /* 44477d10d5a6Sdrh ** No-op routine for the parse-tree walker. 44487d10d5a6Sdrh ** 44497d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 44507d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 44517d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 44527d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 44537d10d5a6Sdrh ** subquery in the parser tree. 44547d10d5a6Sdrh */ 445562c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 445662c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 44577d10d5a6Sdrh return WRC_Continue; 44587d10d5a6Sdrh } 44597d10d5a6Sdrh 44607d10d5a6Sdrh /* 44617d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 44627d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 44637d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 44647d10d5a6Sdrh ** 44657d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 44667d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 44677d10d5a6Sdrh ** name resolution is performed. 44687d10d5a6Sdrh ** 44697d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 44707d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 44717d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 44727d10d5a6Sdrh */ 44737d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 44747d10d5a6Sdrh Walker w; 4475aa87f9a6Sdrh memset(&w, 0, sizeof(w)); 44767d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 44777d10d5a6Sdrh w.pParse = pParse; 4478d58d3278Sdrh if( pParse->hasCompound ){ 4479d58d3278Sdrh w.xSelectCallback = convertCompoundSelectToSubquery; 44807d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 4481d58d3278Sdrh } 4482c01b7306Sdrh w.xSelectCallback = selectExpander; 4483772460fdSdrh if( (pSelect->selFlags & SF_MultiValue)==0 ){ 4484b290f117Sdan w.xSelectCallback2 = selectPopWith; 44853afd2b4dSdrh } 4486c01b7306Sdrh sqlite3WalkSelect(&w, pSelect); 44877d10d5a6Sdrh } 44887d10d5a6Sdrh 44897d10d5a6Sdrh 44907d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 44917d10d5a6Sdrh /* 44927d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 44937d10d5a6Sdrh ** interface. 44947d10d5a6Sdrh ** 44957d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 44967d10d5a6Sdrh ** information to the Table structure that represents the result set 44977d10d5a6Sdrh ** of that subquery. 44987d10d5a6Sdrh ** 44997d10d5a6Sdrh ** The Table structure that represents the result set was constructed 45007d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 45017d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 45027d10d5a6Sdrh ** routine is called after identifier resolution. 45037d10d5a6Sdrh */ 4504b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 45057d10d5a6Sdrh Parse *pParse; 45067d10d5a6Sdrh int i; 45077d10d5a6Sdrh SrcList *pTabList; 45087d10d5a6Sdrh struct SrcList_item *pFrom; 45097d10d5a6Sdrh 45109d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 4511e2b7d7a0Sdrh assert( (p->selFlags & SF_HasTypeInfo)==0 ); 45127d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 45137d10d5a6Sdrh pParse = pWalker->pParse; 45147d10d5a6Sdrh pTabList = p->pSrc; 45157d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 45167d10d5a6Sdrh Table *pTab = pFrom->pTab; 4517e2b7d7a0Sdrh assert( pTab!=0 ); 4518e2b7d7a0Sdrh if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ 45197d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 45207d10d5a6Sdrh Select *pSel = pFrom->pSelect; 45218ce7184bSdan if( pSel ){ 45227d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 4523186ad8ccSdrh selectAddColumnTypeAndCollation(pParse, pTab, pSel); 45247d10d5a6Sdrh } 45257d10d5a6Sdrh } 45265a29d9cbSdrh } 45278ce7184bSdan } 45287d10d5a6Sdrh #endif 45297d10d5a6Sdrh 45307d10d5a6Sdrh 45317d10d5a6Sdrh /* 45327d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 45337d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 45347d10d5a6Sdrh ** SELECT statement. 45357d10d5a6Sdrh ** 45367d10d5a6Sdrh ** Use this routine after name resolution. 45377d10d5a6Sdrh */ 45387d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 45397d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 45407d10d5a6Sdrh Walker w; 4541aa87f9a6Sdrh memset(&w, 0, sizeof(w)); 4542b290f117Sdan w.xSelectCallback2 = selectAddSubqueryTypeInfo; 45437d10d5a6Sdrh w.xExprCallback = exprWalkNoop; 45447d10d5a6Sdrh w.pParse = pParse; 45457d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 45467d10d5a6Sdrh #endif 45477d10d5a6Sdrh } 45487d10d5a6Sdrh 45497d10d5a6Sdrh 45507d10d5a6Sdrh /* 4551030796dfSdrh ** This routine sets up a SELECT statement for processing. The 45527d10d5a6Sdrh ** following is accomplished: 45537d10d5a6Sdrh ** 45547d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 45557d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 45567d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 45577d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 45587d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 45597d10d5a6Sdrh ** 45607d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 45617d10d5a6Sdrh */ 45627d10d5a6Sdrh void sqlite3SelectPrep( 4563b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 4564b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 45657d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 4566b3bce662Sdanielk1977 ){ 45677d10d5a6Sdrh sqlite3 *db; 456843152cf8Sdrh if( NEVER(p==0) ) return; 45697d10d5a6Sdrh db = pParse->db; 4570785097daSdrh if( db->mallocFailed ) return; 45717d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 45727d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 45737d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 45747d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 45757d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 45767d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 4577f6bbe022Sdrh } 4578b3bce662Sdanielk1977 4579b3bce662Sdanielk1977 /* 458013449892Sdrh ** Reset the aggregate accumulator. 458113449892Sdrh ** 458213449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 458313449892Sdrh ** intermediate results while calculating an aggregate. This 4584030796dfSdrh ** routine generates code that stores NULLs in all of those memory 4585030796dfSdrh ** cells. 4586b3bce662Sdanielk1977 */ 458713449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 458813449892Sdrh Vdbe *v = pParse->pVdbe; 458913449892Sdrh int i; 4590c99130fdSdrh struct AggInfo_func *pFunc; 45917e61d18eSdrh int nReg = pAggInfo->nFunc + pAggInfo->nColumn; 45927e61d18eSdrh if( nReg==0 ) return; 45937e61d18eSdrh #ifdef SQLITE_DEBUG 45947e61d18eSdrh /* Verify that all AggInfo registers are within the range specified by 45957e61d18eSdrh ** AggInfo.mnReg..AggInfo.mxReg */ 45967e61d18eSdrh assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); 459713449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 45987e61d18eSdrh assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg 45997e61d18eSdrh && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); 460013449892Sdrh } 46017e61d18eSdrh for(i=0; i<pAggInfo->nFunc; i++){ 46027e61d18eSdrh assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg 46037e61d18eSdrh && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); 46047e61d18eSdrh } 46057e61d18eSdrh #endif 46067e61d18eSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); 4607c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 4608c99130fdSdrh if( pFunc->iDistinct>=0 ){ 4609c99130fdSdrh Expr *pE = pFunc->pExpr; 46106ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 46116ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 46120daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 46130daa002cSdrh "argument"); 4614c99130fdSdrh pFunc->iDistinct = -1; 4615c99130fdSdrh }else{ 4616079a3072Sdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0); 461766a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 46182ec2fb22Sdrh (char*)pKeyInfo, P4_KEYINFO); 4619c99130fdSdrh } 4620c99130fdSdrh } 462113449892Sdrh } 4622b3bce662Sdanielk1977 } 4623b3bce662Sdanielk1977 4624b3bce662Sdanielk1977 /* 462513449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 462613449892Sdrh ** in the AggInfo structure. 4627b3bce662Sdanielk1977 */ 462813449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 462913449892Sdrh Vdbe *v = pParse->pVdbe; 463013449892Sdrh int i; 463113449892Sdrh struct AggInfo_func *pF; 463213449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 46336ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 46346ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 463566a5167bSdrh sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, 463666a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 4637b3bce662Sdanielk1977 } 463813449892Sdrh } 463913449892Sdrh 464013449892Sdrh /* 464113449892Sdrh ** Update the accumulator memory cells for an aggregate based on 464213449892Sdrh ** the current cursor position. 464313449892Sdrh */ 464413449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 464513449892Sdrh Vdbe *v = pParse->pVdbe; 464613449892Sdrh int i; 46477a95789cSdrh int regHit = 0; 46487a95789cSdrh int addrHitTest = 0; 464913449892Sdrh struct AggInfo_func *pF; 465013449892Sdrh struct AggInfo_col *pC; 465113449892Sdrh 465213449892Sdrh pAggInfo->directMode = 1; 465313449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 465413449892Sdrh int nArg; 4655c99130fdSdrh int addrNext = 0; 465698757157Sdrh int regAgg; 46576ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 46586ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 465913449892Sdrh if( pList ){ 466013449892Sdrh nArg = pList->nExpr; 4661892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 46625579d59fSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); 466313449892Sdrh }else{ 466413449892Sdrh nArg = 0; 466598757157Sdrh regAgg = 0; 466613449892Sdrh } 4667c99130fdSdrh if( pF->iDistinct>=0 ){ 4668c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 46697c052da5Sdrh testcase( nArg==0 ); /* Error condition */ 46707c052da5Sdrh testcase( nArg>1 ); /* Also an error */ 46712dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 4672c99130fdSdrh } 4673d36e1041Sdrh if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 467413449892Sdrh CollSeq *pColl = 0; 467513449892Sdrh struct ExprList_item *pItem; 467613449892Sdrh int j; 4677e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 467843617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 467913449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 468013449892Sdrh } 468113449892Sdrh if( !pColl ){ 468213449892Sdrh pColl = pParse->db->pDfltColl; 468313449892Sdrh } 46847a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 46857a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 468613449892Sdrh } 46879c7c913cSdrh sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem, 468866a5167bSdrh (void*)pF->pFunc, P4_FUNCDEF); 4689ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 4690da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 4691f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 4692c99130fdSdrh if( addrNext ){ 4693c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 4694ceea3321Sdrh sqlite3ExprCacheClear(pParse); 4695c99130fdSdrh } 469613449892Sdrh } 469767a6a40cSdan 469867a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 469967a6a40cSdan ** Otherwise, if any of the required column values are already present 470067a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 470167a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 470267a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 470367a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 470467a6a40cSdan ** 470567a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 470667a6a40cSdan ** values to an OP_Copy. 470767a6a40cSdan */ 47087a95789cSdrh if( regHit ){ 4709688852abSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); 47107a95789cSdrh } 471167a6a40cSdan sqlite3ExprCacheClear(pParse); 471213449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 4713389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 471413449892Sdrh } 471513449892Sdrh pAggInfo->directMode = 0; 4716ceea3321Sdrh sqlite3ExprCacheClear(pParse); 47177a95789cSdrh if( addrHitTest ){ 47187a95789cSdrh sqlite3VdbeJumpHere(v, addrHitTest); 47197a95789cSdrh } 472013449892Sdrh } 472113449892Sdrh 4722b3bce662Sdanielk1977 /* 4723ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 4724ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 4725ef7075deSdan */ 4726ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 4727ef7075deSdan static void explainSimpleCount( 4728ef7075deSdan Parse *pParse, /* Parse context */ 4729ef7075deSdan Table *pTab, /* Table being queried */ 4730ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 4731ef7075deSdan ){ 4732ef7075deSdan if( pParse->explain==2 ){ 473348dd1d8eSdrh int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); 47348a4380d7Sdrh char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", 4735ef7075deSdan pTab->zName, 4736e96f2df3Sdan bCover ? " USING COVERING INDEX " : "", 4737e96f2df3Sdan bCover ? pIdx->zName : "" 4738ef7075deSdan ); 4739ef7075deSdan sqlite3VdbeAddOp4( 4740ef7075deSdan pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC 4741ef7075deSdan ); 4742ef7075deSdan } 4743ef7075deSdan } 4744ef7075deSdan #else 4745ef7075deSdan # define explainSimpleCount(a,b,c) 4746ef7075deSdan #endif 4747ef7075deSdan 4748ef7075deSdan /* 47497d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 47509bb61fe7Sdrh ** 4751340309fdSdrh ** The results are returned according to the SelectDest structure. 4752340309fdSdrh ** See comments in sqliteInt.h for further information. 4753e78e8284Sdrh ** 47549bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 47559bb61fe7Sdrh ** encountered, then an appropriate error message is left in 47569bb61fe7Sdrh ** pParse->zErrMsg. 47579bb61fe7Sdrh ** 47589bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 47599bb61fe7Sdrh ** calling function needs to do that. 47609bb61fe7Sdrh */ 47614adee20fSdanielk1977 int sqlite3Select( 4762cce7d176Sdrh Parse *pParse, /* The parser context */ 47639bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 47647d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 4765cce7d176Sdrh ){ 476613449892Sdrh int i, j; /* Loop counters */ 476713449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 476813449892Sdrh Vdbe *v; /* The virtual machine under construction */ 4769b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 4770c29cbb0bSmistachkin ExprList *pEList = 0; /* List of columns to extract. */ 4771ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 47729bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 47732282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 47742282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 47751d83f052Sdrh int rc = 1; /* Value to return from this function */ 4776e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 4777079a3072Sdrh SortCtx sSort; /* Info on how to code the ORDER BY clause */ 477813449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 4779ec7429aeSdrh int iEnd; /* Address of the end of the query */ 478017435752Sdrh sqlite3 *db; /* The database connection */ 47819bb61fe7Sdrh 47822ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 47832ce22453Sdan int iRestoreSelectId = pParse->iSelectId; 47842ce22453Sdan pParse->iSelectId = pParse->iNextSelectId++; 47852ce22453Sdan #endif 47862ce22453Sdan 478717435752Sdrh db = pParse->db; 478817435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 47896f7adc8aSdrh return 1; 47906f7adc8aSdrh } 47914adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 479213449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 4793eb9b884cSdrh #if SELECTTRACE_ENABLED 4794eb9b884cSdrh pParse->nSelectIndent++; 4795c90713d3Sdrh SELECTTRACE(1,pParse,p, ("begin processing:\n")); 4796c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 4797c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 4798c90713d3Sdrh } 4799eb9b884cSdrh #endif 4800daffd0e5Sdrh 48018e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); 48028e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); 48039afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); 48049afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); 48056c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 48069ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 48079afccba2Sdan pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || 48088e1ee88cSdrh pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || 48098e1ee88cSdrh pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); 4810ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 4811ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 4812ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 4813ccfcbceaSdrh p->pOrderBy = 0; 48147d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 48159a99334dSdrh } 48167d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 4817079a3072Sdrh memset(&sSort, 0, sizeof(sSort)); 4818079a3072Sdrh sSort.pOrderBy = p->pOrderBy; 4819b27b7f5dSdrh pTabList = p->pSrc; 4820956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 48219a99334dSdrh goto select_end; 48229a99334dSdrh } 4823adc57f68Sdrh assert( p->pEList!=0 ); 48247d10d5a6Sdrh isAgg = (p->selFlags & SF_Aggregate)!=0; 482517645f5eSdrh #if SELECTTRACE_ENABLED 482617645f5eSdrh if( sqlite3SelectTrace & 0x100 ){ 482717645f5eSdrh SELECTTRACE(0x100,pParse,p, ("after name resolution:\n")); 482817645f5eSdrh sqlite3TreeViewSelect(0, p, 0); 482917645f5eSdrh } 483017645f5eSdrh #endif 483117645f5eSdrh 4832cce7d176Sdrh 483374b617b2Sdan /* If writing to memory or generating a set 483474b617b2Sdan ** only a single column may be output. 483574b617b2Sdan */ 483674b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY 4837adc57f68Sdrh if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){ 483874b617b2Sdan goto select_end; 483974b617b2Sdan } 484074b617b2Sdan #endif 484174b617b2Sdan 4842adc57f68Sdrh /* Try to flatten subqueries in the FROM clause up into the main query 4843d820cb1bSdrh */ 484451522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 4845f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 484613449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 4847daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 4848f23329a2Sdanielk1977 int isAggSub; 48492679f14fSdrh Table *pTab = pItem->pTab; 48504490c40bSdrh if( pSub==0 ) continue; 48512679f14fSdrh 48522679f14fSdrh /* Catch mismatch in the declared columns of a view and the number of 48532679f14fSdrh ** columns in the SELECT on the RHS */ 48542679f14fSdrh if( pTab->nCol!=pSub->pEList->nExpr ){ 48552679f14fSdrh sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", 48562679f14fSdrh pTab->nCol, pTab->zName, pSub->pEList->nExpr); 48572679f14fSdrh goto select_end; 48582679f14fSdrh } 48592679f14fSdrh 48604490c40bSdrh isAggSub = (pSub->selFlags & SF_Aggregate)!=0; 48614490c40bSdrh if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ 48624490c40bSdrh /* This subquery can be absorbed into its parent. */ 48634490c40bSdrh if( isAggSub ){ 48644490c40bSdrh isAgg = 1; 48654490c40bSdrh p->selFlags |= SF_Aggregate; 48664490c40bSdrh } 48674490c40bSdrh i = -1; 48684490c40bSdrh } 48694490c40bSdrh pTabList = p->pSrc; 48704490c40bSdrh if( db->mallocFailed ) goto select_end; 48714490c40bSdrh if( !IgnorableOrderby(pDest) ){ 48724490c40bSdrh sSort.pOrderBy = p->pOrderBy; 48734490c40bSdrh } 48744490c40bSdrh } 48754490c40bSdrh #endif 48764490c40bSdrh 4877adc57f68Sdrh /* Get a pointer the VDBE under construction, allocating a new VDBE if one 4878adc57f68Sdrh ** does not already exist */ 4879adc57f68Sdrh v = sqlite3GetVdbe(pParse); 4880adc57f68Sdrh if( v==0 ) goto select_end; 48814490c40bSdrh 48824490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 48834490c40bSdrh /* Handle compound SELECT statements using the separate multiSelect() 48844490c40bSdrh ** procedure. 48854490c40bSdrh */ 48864490c40bSdrh if( p->pPrior ){ 48874490c40bSdrh rc = multiSelect(pParse, p, pDest); 48884490c40bSdrh explainSetInteger(pParse->iSelectId, iRestoreSelectId); 48894490c40bSdrh #if SELECTTRACE_ENABLED 48904490c40bSdrh SELECTTRACE(1,pParse,p,("end compound-select processing\n")); 48914490c40bSdrh pParse->nSelectIndent--; 48924490c40bSdrh #endif 48934490c40bSdrh return rc; 48944490c40bSdrh } 48954490c40bSdrh #endif 48964490c40bSdrh 48974490c40bSdrh /* Generate code for all sub-queries in the FROM clause 48984490c40bSdrh */ 48994490c40bSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 49004490c40bSdrh for(i=0; i<pTabList->nSrc; i++){ 49014490c40bSdrh struct SrcList_item *pItem = &pTabList->a[i]; 49024490c40bSdrh SelectDest dest; 49034490c40bSdrh Select *pSub = pItem->pSelect; 49045b6a9ed4Sdrh if( pSub==0 ) continue; 490521172c4cSdrh 490621172c4cSdrh /* Sometimes the code for a subquery will be generated more than 490721172c4cSdrh ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, 490821172c4cSdrh ** for example. In that case, do not regenerate the code to manifest 490921172c4cSdrh ** a view or the co-routine to implement a view. The first instance 491021172c4cSdrh ** is sufficient, though the subroutine to manifest the view does need 491121172c4cSdrh ** to be invoked again. */ 49125b6a9ed4Sdrh if( pItem->addrFillSub ){ 49138a48b9c0Sdrh if( pItem->fg.viaCoroutine==0 ){ 49145b6a9ed4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 491521172c4cSdrh } 49165b6a9ed4Sdrh continue; 49175b6a9ed4Sdrh } 4918daf79acbSdanielk1977 4919fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 4920f7b5496eSdrh ** tree referred to by this, the parent select. The child select 4921fc976065Sdanielk1977 ** may contain expression trees of at most 4922fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 4923fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 4924fc976065Sdanielk1977 ** an exact limit. 4925fc976065Sdanielk1977 */ 4926fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 4927daf79acbSdanielk1977 4928adc57f68Sdrh /* Make copies of constant WHERE-clause terms in the outer query down 4929adc57f68Sdrh ** inside the subquery. This can help the subquery to run more efficiently. 4930adc57f68Sdrh */ 49318a48b9c0Sdrh if( (pItem->fg.jointype & JT_OUTER)==0 493269b72d5aSdrh && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor) 493369b72d5aSdrh ){ 493469b72d5aSdrh #if SELECTTRACE_ENABLED 493569b72d5aSdrh if( sqlite3SelectTrace & 0x100 ){ 4936bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n")); 493769b72d5aSdrh sqlite3TreeViewSelect(0, p, 0); 493869b72d5aSdrh } 493969b72d5aSdrh #endif 494069b72d5aSdrh } 4941adc57f68Sdrh 4942adc57f68Sdrh /* Generate code to implement the subquery 4943adc57f68Sdrh */ 494469b72d5aSdrh if( pTabList->nSrc==1 49457cea7f95Sdrh && (p->selFlags & SF_All)==0 4946a5759677Sdrh && OptimizationEnabled(db, SQLITE_SubqCoroutine) 4947a5759677Sdrh ){ 494821172c4cSdrh /* Implement a co-routine that will return a single row of the result 494921172c4cSdrh ** set on each invocation. 495021172c4cSdrh */ 4951725de29aSdrh int addrTop = sqlite3VdbeCurrentAddr(v)+1; 495221172c4cSdrh pItem->regReturn = ++pParse->nMem; 4953725de29aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 4954725de29aSdrh VdbeComment((v, "%s", pItem->pTab->zName)); 495521172c4cSdrh pItem->addrFillSub = addrTop; 495621172c4cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 495721172c4cSdrh explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 495821172c4cSdrh sqlite3Select(pParse, pSub, &dest); 4959cfc9df76Sdan pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow); 49608a48b9c0Sdrh pItem->fg.viaCoroutine = 1; 49615f612295Sdrh pItem->regResult = dest.iSdst; 496281cf13ecSdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn); 496321172c4cSdrh sqlite3VdbeJumpHere(v, addrTop-1); 496421172c4cSdrh sqlite3ClearTempRegCache(pParse); 4965daf79acbSdanielk1977 }else{ 49665b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 49675b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 49685b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 49695b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 49705b6a9ed4Sdrh */ 49717157e8eaSdrh int topAddr; 497248f2d3b1Sdrh int onceAddr = 0; 49737157e8eaSdrh int retAddr; 49745b6a9ed4Sdrh assert( pItem->addrFillSub==0 ); 49755b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 49767157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 49777157e8eaSdrh pItem->addrFillSub = topAddr+1; 49788a48b9c0Sdrh if( pItem->fg.isCorrelated==0 ){ 4979ed17167eSdrh /* If the subquery is not correlated and if we are not inside of 49805b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 49815b6a9ed4Sdrh ** once. */ 49827d176105Sdrh onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v); 4983725de29aSdrh VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); 4984725de29aSdrh }else{ 4985725de29aSdrh VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); 49865b6a9ed4Sdrh } 49871013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 4988ce7e189dSdan explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 49897d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 4990cfc9df76Sdan pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow); 499148f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 49927157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 49937157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 49947157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 4995cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 4996daf79acbSdanielk1977 } 4997adc57f68Sdrh if( db->mallocFailed ) goto select_end; 4998fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 4999daf79acbSdanielk1977 } 5000daf79acbSdanielk1977 #endif 5001adc57f68Sdrh 500238b4149cSdrh /* Various elements of the SELECT copied into local variables for 500338b4149cSdrh ** convenience */ 5004adc57f68Sdrh pEList = p->pEList; 5005daf79acbSdanielk1977 pWhere = p->pWhere; 5006832508b7Sdrh pGroupBy = p->pGroupBy; 5007832508b7Sdrh pHaving = p->pHaving; 5008e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 5009832508b7Sdrh 5010bc8edba1Sdrh #if SELECTTRACE_ENABLED 5011bc8edba1Sdrh if( sqlite3SelectTrace & 0x400 ){ 5012bc8edba1Sdrh SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); 5013bc8edba1Sdrh sqlite3TreeViewSelect(0, p, 0); 5014bc8edba1Sdrh } 5015bc8edba1Sdrh #endif 5016bc8edba1Sdrh 501750118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 501850118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 501950118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 502050118cdfSdan ** 502150118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 502250118cdfSdan ** 502350118cdfSdan ** is transformed to: 502450118cdfSdan ** 5025dea7d70dSdrh ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz 502650118cdfSdan ** 502750118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 502850118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 502950118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 503050118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 503150118cdfSdan */ 503250118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 5033adc57f68Sdrh && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 503450118cdfSdan ){ 503550118cdfSdan p->selFlags &= ~SF_Distinct; 5036adc57f68Sdrh pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); 5037e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 5038e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 5039e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 5040e8e4af76Sdrh assert( sDistinct.isTnct ); 504150118cdfSdan } 504250118cdfSdan 5043adc57f68Sdrh /* If there is an ORDER BY clause, then create an ephemeral index to 5044adc57f68Sdrh ** do the sorting. But this sorting ephemeral index might end up 5045adc57f68Sdrh ** being unused if the data can be extracted in pre-sorted order. 5046adc57f68Sdrh ** If that is the case, then the OP_OpenEphemeral instruction will be 5047adc57f68Sdrh ** changed to an OP_Noop once we figure out that the sorting index is 5048adc57f68Sdrh ** not needed. The sSort.addrSortIndex variable is used to facilitate 5049adc57f68Sdrh ** that change. 50507cedc8d4Sdanielk1977 */ 5051079a3072Sdrh if( sSort.pOrderBy ){ 50520342b1f5Sdrh KeyInfo *pKeyInfo; 50533f39bcf5Sdrh pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr); 5054079a3072Sdrh sSort.iECursor = pParse->nTab++; 5055079a3072Sdrh sSort.addrSortIndex = 505666a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 5057f45f2326Sdrh sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 5058f45f2326Sdrh (char*)pKeyInfo, P4_KEYINFO 5059f45f2326Sdrh ); 50609d2985c7Sdrh }else{ 5061079a3072Sdrh sSort.addrSortIndex = -1; 50627cedc8d4Sdanielk1977 } 50637cedc8d4Sdanielk1977 50642d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 50652d0794e3Sdrh */ 50666c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 50672b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 50682d0794e3Sdrh } 50692d0794e3Sdrh 5070f42bacc2Sdrh /* Set the limiter. 5071f42bacc2Sdrh */ 5072f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 5073c63367efSdrh p->nSelectRow = LARGEST_INT64; 5074f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 5075079a3072Sdrh if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 50760ff287fbSdrh sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); 5077079a3072Sdrh sSort.sortFlags |= SORTFLAG_UseSorter; 5078c6aff30cSdrh } 5079f42bacc2Sdrh 5080adc57f68Sdrh /* Open an ephemeral index to use for the distinct set. 5081cce7d176Sdrh */ 50822ce22453Sdan if( p->selFlags & SF_Distinct ){ 5083e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 5084e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 5085e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 5086079a3072Sdrh (char*)keyInfoFromExprList(pParse, p->pEList,0,0), 50872ec2fb22Sdrh P4_KEYINFO); 5088d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 5089e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 5090832508b7Sdrh }else{ 5091e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 5092efb7251dSdrh } 5093832508b7Sdrh 509413449892Sdrh if( !isAgg && pGroupBy==0 ){ 5095e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 50966457a353Sdrh u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); 509738cc40c2Sdan 509838cc40c2Sdan /* Begin the database scan. */ 5099079a3072Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, 5100079a3072Sdrh p->pEList, wctrlFlags, 0); 51011d83f052Sdrh if( pWInfo==0 ) goto select_end; 51026f32848dSdrh if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ 51036f32848dSdrh p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); 51046f32848dSdrh } 51056457a353Sdrh if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ 51066f32848dSdrh sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); 51076f32848dSdrh } 5108079a3072Sdrh if( sSort.pOrderBy ){ 5109079a3072Sdrh sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); 5110079a3072Sdrh if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ 5111079a3072Sdrh sSort.pOrderBy = 0; 5112079a3072Sdrh } 5113079a3072Sdrh } 5114cce7d176Sdrh 5115b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 5116b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 51179d2985c7Sdrh ** into an OP_Noop. 51189d2985c7Sdrh */ 5119079a3072Sdrh if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ 5120079a3072Sdrh sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 51219d2985c7Sdrh } 51229d2985c7Sdrh 512338cc40c2Sdan /* Use the standard inner loop. */ 5124079a3072Sdrh selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest, 51256f32848dSdrh sqlite3WhereContinueLabel(pWInfo), 51266f32848dSdrh sqlite3WhereBreakLabel(pWInfo)); 51272282792aSdrh 5128cce7d176Sdrh /* End the database scan loop. 5129cce7d176Sdrh */ 51304adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 513113449892Sdrh }else{ 5132e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 5133e8e4af76Sdrh ** or both */ 513413449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 513513449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 513613449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 513713449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 513813449892Sdrh ** one row of the input to the aggregator has been 513913449892Sdrh ** processed */ 514013449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 514113449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 5142d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 51431c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 51441c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 5145374cd78cSdan int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ 5146d176611bSdrh 5147d176611bSdrh /* Remove any and all aliases between the result set and the 5148d176611bSdrh ** GROUP BY clause. 5149d176611bSdrh */ 5150d176611bSdrh if( pGroupBy ){ 5151dc5ea5c7Sdrh int k; /* Loop counter */ 5152d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 5153d176611bSdrh 5154dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 5155c2acc4e4Sdrh pItem->u.x.iAlias = 0; 5156d176611bSdrh } 5157dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 5158c2acc4e4Sdrh pItem->u.x.iAlias = 0; 5159d176611bSdrh } 5160c63367efSdrh if( p->nSelectRow>100 ) p->nSelectRow = 100; 516195aa47b1Sdrh }else{ 5162c63367efSdrh p->nSelectRow = 1; 5163d176611bSdrh } 5164cce7d176Sdrh 5165374cd78cSdan /* If there is both a GROUP BY and an ORDER BY clause and they are 5166374cd78cSdan ** identical, then it may be possible to disable the ORDER BY clause 5167374cd78cSdan ** on the grounds that the GROUP BY will cause elements to come out 5168adc57f68Sdrh ** in the correct order. It also may not - the GROUP BY might use a 5169374cd78cSdan ** database index that causes rows to be grouped together as required 5170374cd78cSdan ** but not actually sorted. Either way, record the fact that the 5171374cd78cSdan ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 5172374cd78cSdan ** variable. */ 5173374cd78cSdan if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 5174374cd78cSdan orderByGrp = 1; 5175374cd78cSdan } 5176374cd78cSdan 5177d176611bSdrh /* Create a label to jump to when we want to abort the query */ 517813449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 517913449892Sdrh 518013449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 518113449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 518213449892Sdrh ** SELECT statement. 51832282792aSdrh */ 518413449892Sdrh memset(&sNC, 0, sizeof(sNC)); 518513449892Sdrh sNC.pParse = pParse; 518613449892Sdrh sNC.pSrcList = pTabList; 518713449892Sdrh sNC.pAggInfo = &sAggInfo; 51887e61d18eSdrh sAggInfo.mnReg = pParse->nMem+1; 5189dd23c6bfSdan sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; 51909d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 5191d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 5192079a3072Sdrh sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); 5193d2b3e23bSdrh if( pHaving ){ 5194d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 519513449892Sdrh } 519613449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 519713449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 51986ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 51993a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 52006ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 52013a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 520213449892Sdrh } 52037e61d18eSdrh sAggInfo.mxReg = pParse->nMem; 520417435752Sdrh if( db->mallocFailed ) goto select_end; 520513449892Sdrh 520613449892Sdrh /* Processing for aggregates with GROUP BY is very different and 52073c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 520813449892Sdrh */ 520913449892Sdrh if( pGroupBy ){ 521013449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 5211728e0f91Sdrh int addr1; /* A-vs-B comparision jump */ 5212d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 5213d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 5214d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 5215d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 5216d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 5217d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 5218d176611bSdrh int regReset; /* Return address register for reset subroutine */ 521913449892Sdrh 522013449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 522113449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 52221c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 522313449892Sdrh ** will be converted into a Noop. 522413449892Sdrh */ 522513449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 52263f39bcf5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn); 52271c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 5228cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 52292ec2fb22Sdrh 0, (char*)pKeyInfo, P4_KEYINFO); 523013449892Sdrh 523113449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 523213449892Sdrh */ 52330a07c107Sdrh iUseFlag = ++pParse->nMem; 52340a07c107Sdrh iAbortFlag = ++pParse->nMem; 5235d176611bSdrh regOutputRow = ++pParse->nMem; 5236d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 5237d176611bSdrh regReset = ++pParse->nMem; 5238d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 52390a07c107Sdrh iAMem = pParse->nMem + 1; 524013449892Sdrh pParse->nMem += pGroupBy->nExpr; 52410a07c107Sdrh iBMem = pParse->nMem + 1; 524213449892Sdrh pParse->nMem += pGroupBy->nExpr; 52434c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 5244d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 52454c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 5246d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 5247b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 5248e313382eSdrh 524913449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 525013449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 525113449892Sdrh ** it might be a single loop that uses an index to extract information 525213449892Sdrh ** in the right order to begin with. 525313449892Sdrh */ 52542eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 525593ec45d5Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 5256374cd78cSdan WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 5257374cd78cSdan ); 52585360ad34Sdrh if( pWInfo==0 ) goto select_end; 5259ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ 526013449892Sdrh /* The optimizer is able to deliver rows in group by order so 5261b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 526213449892Sdrh ** cancelled later because we still need to use the pKeyInfo 526313449892Sdrh */ 526413449892Sdrh groupBySort = 0; 526513449892Sdrh }else{ 526613449892Sdrh /* Rows are coming out in undetermined order. We have to push 526713449892Sdrh ** each row into a sorting index, terminate the first loop, 526813449892Sdrh ** then loop over the sorting index in order to get the output 526913449892Sdrh ** in sorted order 527013449892Sdrh */ 5271892d3179Sdrh int regBase; 5272892d3179Sdrh int regRecord; 5273892d3179Sdrh int nCol; 5274892d3179Sdrh int nGroupBy; 5275892d3179Sdrh 52762ce22453Sdan explainTempTable(pParse, 5277e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 5278e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 52792ce22453Sdan 528013449892Sdrh groupBySort = 1; 5281892d3179Sdrh nGroupBy = pGroupBy->nExpr; 5282dd23c6bfSdan nCol = nGroupBy; 5283dd23c6bfSdan j = nGroupBy; 528413449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 5285892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 5286892d3179Sdrh nCol++; 528713449892Sdrh j++; 528813449892Sdrh } 5289892d3179Sdrh } 5290892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 5291ceea3321Sdrh sqlite3ExprCacheClear(pParse); 52925579d59fSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); 5293dd23c6bfSdan j = nGroupBy; 5294892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 5295892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 5296892d3179Sdrh if( pCol->iSorterColumn>=j ){ 5297e55cbd72Sdrh int r1 = j + regBase; 5298*ce78bc6eSdrh sqlite3ExprCodeGetColumnToReg(pParse, 5299*ce78bc6eSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1); 53006a012f04Sdrh j++; 5301892d3179Sdrh } 5302892d3179Sdrh } 5303892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 53041db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 53051c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 5306892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 5307892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 530813449892Sdrh sqlite3WhereEnd(pWInfo); 53095134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 53101c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 53111c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 53121c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 5313688852abSdrh VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); 531413449892Sdrh sAggInfo.useSortingIdx = 1; 5315ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5316374cd78cSdan 5317374cd78cSdan } 5318374cd78cSdan 5319374cd78cSdan /* If the index or temporary table used by the GROUP BY sort 5320374cd78cSdan ** will naturally deliver rows in the order required by the ORDER BY 5321374cd78cSdan ** clause, cancel the ephemeral table open coded earlier. 5322374cd78cSdan ** 5323374cd78cSdan ** This is an optimization - the correct answer should result regardless. 5324374cd78cSdan ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 5325374cd78cSdan ** disable this optimization for testing purposes. */ 5326374cd78cSdan if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 5327374cd78cSdan && (groupBySort || sqlite3WhereIsSorted(pWInfo)) 5328374cd78cSdan ){ 5329374cd78cSdan sSort.pOrderBy = 0; 5330374cd78cSdan sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 533113449892Sdrh } 533213449892Sdrh 533313449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 533413449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 533513449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 533613449892Sdrh ** from the previous row currently stored in a0, a1, a2... 533713449892Sdrh */ 533813449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 5339ceea3321Sdrh sqlite3ExprCacheClear(pParse); 53401c9d835dSdrh if( groupBySort ){ 534138b4149cSdrh sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, 534238b4149cSdrh sortOut, sortPTab); 53431c9d835dSdrh } 534413449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 534513449892Sdrh if( groupBySort ){ 53461c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 534713449892Sdrh }else{ 534813449892Sdrh sAggInfo.directMode = 1; 53492dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 535013449892Sdrh } 535113449892Sdrh } 535216ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 53532ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 5354728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 5355728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); 535613449892Sdrh 535713449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 5358e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 535913449892Sdrh ** block. If there were no changes, this block is skipped. 536013449892Sdrh ** 536113449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 536213449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 536313449892Sdrh ** and resets the aggregate accumulator registers in preparation 536413449892Sdrh ** for the next GROUP BY batch. 536513449892Sdrh */ 5366b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 53672eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 5368d4e70ebdSdrh VdbeComment((v, "output one row")); 5369688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 5370d4e70ebdSdrh VdbeComment((v, "check abort flag")); 53712eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 5372d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 537313449892Sdrh 537413449892Sdrh /* Update the aggregate accumulators based on the content of 537513449892Sdrh ** the current row 537613449892Sdrh */ 5377728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 537813449892Sdrh updateAccumulator(pParse, &sAggInfo); 53794c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 5380d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 538113449892Sdrh 538213449892Sdrh /* End of the loop 538313449892Sdrh */ 538413449892Sdrh if( groupBySort ){ 53851c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 5386688852abSdrh VdbeCoverage(v); 538713449892Sdrh }else{ 538813449892Sdrh sqlite3WhereEnd(pWInfo); 538948f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 539013449892Sdrh } 539113449892Sdrh 539213449892Sdrh /* Output the final row of result 539313449892Sdrh */ 53942eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 5395d4e70ebdSdrh VdbeComment((v, "output final row")); 539613449892Sdrh 5397d176611bSdrh /* Jump over the subroutines 5398d176611bSdrh */ 5399076e85f5Sdrh sqlite3VdbeGoto(v, addrEnd); 5400d176611bSdrh 5401d176611bSdrh /* Generate a subroutine that outputs a single row of the result 5402d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 5403d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 5404d176611bSdrh ** the processing calls for the query to abort, this subroutine 5405d176611bSdrh ** increments the iAbortFlag memory location before returning in 5406d176611bSdrh ** order to signal the caller to abort. 5407d176611bSdrh */ 5408d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 5409d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 5410d176611bSdrh VdbeComment((v, "set abort flag")); 5411d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5412d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 5413d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 541438b4149cSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 541538b4149cSdrh VdbeCoverage(v); 5416d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 5417d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5418d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 5419d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 5420079a3072Sdrh selectInnerLoop(pParse, p, p->pEList, -1, &sSort, 5421e8e4af76Sdrh &sDistinct, pDest, 5422d176611bSdrh addrOutputRow+1, addrSetAbort); 5423d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5424d176611bSdrh VdbeComment((v, "end groupby result generator")); 5425d176611bSdrh 5426d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 5427d176611bSdrh */ 5428d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 5429d176611bSdrh resetAccumulator(pParse, &sAggInfo); 5430d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 5431d176611bSdrh 543243152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 543313449892Sdrh else { 5434dba0137eSdanielk1977 ExprList *pDel = 0; 5435a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 5436a5533162Sdanielk1977 Table *pTab; 5437a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 5438a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 5439a5533162Sdanielk1977 ** the SQL statement is of the form: 5440a5533162Sdanielk1977 ** 5441a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 5442a5533162Sdanielk1977 ** 5443a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 5444a5533162Sdanielk1977 ** 5445a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 5446a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 5447a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 5448a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 5449a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 5450a5533162Sdanielk1977 */ 5451a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 5452a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 5453a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 5454a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 5455a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 5456a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 5457a9d1ccb9Sdanielk1977 5458a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 5459a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 5460a5533162Sdanielk1977 5461d9e3cad2Sdrh /* Search for the index that has the lowest scan cost. 5462a5533162Sdanielk1977 ** 54633e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 54643e9548b3Sdrh ** 5465abcc1941Sdrh ** (2013-10-03) Do not count the entries in a partial index. 54665f33f375Sdrh ** 5467a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 5468a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 5469a5533162Sdanielk1977 */ 54705c7917e4Sdrh if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); 5471a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 5472d9e3cad2Sdrh if( pIdx->bUnordered==0 5473e13e9f54Sdrh && pIdx->szIdxRow<pTab->szTabRow 5474d3037a41Sdrh && pIdx->pPartIdxWhere==0 5475e13e9f54Sdrh && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) 5476d9e3cad2Sdrh ){ 5477a5533162Sdanielk1977 pBest = pIdx; 5478a5533162Sdanielk1977 } 5479a5533162Sdanielk1977 } 5480d9e3cad2Sdrh if( pBest ){ 5481a5533162Sdanielk1977 iRoot = pBest->tnum; 54822ec2fb22Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); 5483a5533162Sdanielk1977 } 5484a5533162Sdanielk1977 5485a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 5486261c02d9Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); 5487a5533162Sdanielk1977 if( pKeyInfo ){ 54882ec2fb22Sdrh sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); 5489a5533162Sdanielk1977 } 5490a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 5491a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 5492ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 5493a5533162Sdanielk1977 }else 5494a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 5495a5533162Sdanielk1977 { 5496738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 5497738bdcfbSdanielk1977 ** 5498738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 5499738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 5500738bdcfbSdanielk1977 ** 5501738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 5502738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 5503738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 5504738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 5505738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 5506738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 5507738bdcfbSdanielk1977 ** value of x, the only row required). 5508738bdcfbSdanielk1977 ** 5509738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 551048864df9Smistachkin ** modify behavior as follows: 5511738bdcfbSdanielk1977 ** 5512738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 5513738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 5514738bdcfbSdanielk1977 ** for x. 5515738bdcfbSdanielk1977 ** 5516738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 5517738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 5518738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 5519738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 5520738bdcfbSdanielk1977 */ 5521a5533162Sdanielk1977 ExprList *pMinMax = 0; 55224ac391fcSdan u8 flag = WHERE_ORDERBY_NORMAL; 55234ac391fcSdan 55244ac391fcSdan assert( p->pGroupBy==0 ); 55254ac391fcSdan assert( flag==0 ); 55264ac391fcSdan if( p->pHaving==0 ){ 55274ac391fcSdan flag = minMaxQuery(&sAggInfo, &pMinMax); 55284ac391fcSdan } 55294ac391fcSdan assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); 55304ac391fcSdan 5531a9d1ccb9Sdanielk1977 if( flag ){ 55324ac391fcSdan pMinMax = sqlite3ExprListDup(db, pMinMax, 0); 55336ab3a2ecSdanielk1977 pDel = pMinMax; 55340e359b30Sdrh if( pMinMax && !db->mallocFailed ){ 5535ea678832Sdrh pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; 5536a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 5537a9d1ccb9Sdanielk1977 } 55381013c932Sdrh } 5539a9d1ccb9Sdanielk1977 554013449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 554113449892Sdrh ** processing is much simpler since there is only a single row 554213449892Sdrh ** of output. 554313449892Sdrh */ 554413449892Sdrh resetAccumulator(pParse, &sAggInfo); 554546ec5b63Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0); 5546dba0137eSdanielk1977 if( pWInfo==0 ){ 5547633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 5548dba0137eSdanielk1977 goto select_end; 5549dba0137eSdanielk1977 } 555013449892Sdrh updateAccumulator(pParse, &sAggInfo); 555146c35f9bSdrh assert( pMinMax==0 || pMinMax->nExpr==1 ); 5552ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)>0 ){ 5553076e85f5Sdrh sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); 5554a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 5555a5533162Sdanielk1977 (flag==WHERE_ORDERBY_MIN?"min":"max"))); 5556a9d1ccb9Sdanielk1977 } 555713449892Sdrh sqlite3WhereEnd(pWInfo); 555813449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 55597a895a80Sdanielk1977 } 55607a895a80Sdanielk1977 5561079a3072Sdrh sSort.pOrderBy = 0; 556235573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 5563079a3072Sdrh selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, 5564a9671a22Sdrh pDest, addrEnd, addrEnd); 5565633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 556613449892Sdrh } 556713449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 556813449892Sdrh 556913449892Sdrh } /* endif aggregate query */ 55702282792aSdrh 5571e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 55722ce22453Sdan explainTempTable(pParse, "DISTINCT"); 55732ce22453Sdan } 55742ce22453Sdan 5575cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 5576cce7d176Sdrh ** and send them to the callback one by one. 5577cce7d176Sdrh */ 5578079a3072Sdrh if( sSort.pOrderBy ){ 557938b4149cSdrh explainTempTable(pParse, 558038b4149cSdrh sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); 5581079a3072Sdrh generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 5582cce7d176Sdrh } 55836a535340Sdrh 5584ec7429aeSdrh /* Jump here to skip this query 5585ec7429aeSdrh */ 5586ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 5587ec7429aeSdrh 55885b1c07e7Sdan /* The SELECT has been coded. If there is an error in the Parse structure, 55895b1c07e7Sdan ** set the return code to 1. Otherwise 0. */ 55905b1c07e7Sdan rc = (pParse->nErr>0); 55911d83f052Sdrh 55921d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 55931d83f052Sdrh ** successful coding of the SELECT. 55941d83f052Sdrh */ 55951d83f052Sdrh select_end: 559617c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 5597955de52cSdanielk1977 55987d10d5a6Sdrh /* Identify column names if results of the SELECT are to be output. 5599955de52cSdanielk1977 */ 56007d10d5a6Sdrh if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ 5601955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 5602955de52cSdanielk1977 } 5603955de52cSdanielk1977 5604633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 5605633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 5606eb9b884cSdrh #if SELECTTRACE_ENABLED 5607eb9b884cSdrh SELECTTRACE(1,pParse,p,("end processing\n")); 5608eb9b884cSdrh pParse->nSelectIndent--; 5609eb9b884cSdrh #endif 56101d83f052Sdrh return rc; 5611cce7d176Sdrh } 5612