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 ** 15*309be024Sdrh ** $Id: select.c,v 1.354 2007/07/18 18:17:12 drh Exp $ 16cce7d176Sdrh */ 17cce7d176Sdrh #include "sqliteInt.h" 18cce7d176Sdrh 19315555caSdrh 20cce7d176Sdrh /* 21eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate 22eda639e1Sdrh ** the select structure itself. 23eda639e1Sdrh */ 24f0113000Sdanielk1977 static void clearSelect(Select *p){ 25eda639e1Sdrh sqlite3ExprListDelete(p->pEList); 26eda639e1Sdrh sqlite3SrcListDelete(p->pSrc); 27eda639e1Sdrh sqlite3ExprDelete(p->pWhere); 28eda639e1Sdrh sqlite3ExprListDelete(p->pGroupBy); 29eda639e1Sdrh sqlite3ExprDelete(p->pHaving); 30eda639e1Sdrh sqlite3ExprListDelete(p->pOrderBy); 31eda639e1Sdrh sqlite3SelectDelete(p->pPrior); 32eda639e1Sdrh sqlite3ExprDelete(p->pLimit); 33eda639e1Sdrh sqlite3ExprDelete(p->pOffset); 34eda639e1Sdrh } 35eda639e1Sdrh 36eda639e1Sdrh 37eda639e1Sdrh /* 389bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 399bb61fe7Sdrh ** structure. 40cce7d176Sdrh */ 414adee20fSdanielk1977 Select *sqlite3SelectNew( 42daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 43ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 44daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 45daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 46daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 47daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 489bbca4c1Sdrh int isDistinct, /* true if the DISTINCT keyword is present */ 49a2dc3b1aSdanielk1977 Expr *pLimit, /* LIMIT value. NULL means not used */ 50a2dc3b1aSdanielk1977 Expr *pOffset /* OFFSET value. NULL means no offset */ 519bb61fe7Sdrh ){ 529bb61fe7Sdrh Select *pNew; 53eda639e1Sdrh Select standin; 549bb61fe7Sdrh pNew = sqliteMalloc( sizeof(*pNew) ); 55a2dc3b1aSdanielk1977 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */ 56daffd0e5Sdrh if( pNew==0 ){ 57eda639e1Sdrh pNew = &standin; 58eda639e1Sdrh memset(pNew, 0, sizeof(*pNew)); 59eda639e1Sdrh } 60b733d037Sdrh if( pEList==0 ){ 614adee20fSdanielk1977 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0); 62b733d037Sdrh } 639bb61fe7Sdrh pNew->pEList = pEList; 649bb61fe7Sdrh pNew->pSrc = pSrc; 659bb61fe7Sdrh pNew->pWhere = pWhere; 669bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 679bb61fe7Sdrh pNew->pHaving = pHaving; 689bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 699bb61fe7Sdrh pNew->isDistinct = isDistinct; 7082c3d636Sdrh pNew->op = TK_SELECT; 718103b7d2Sdrh assert( pOffset==0 || pLimit!=0 ); 72a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 73a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 747b58daeaSdrh pNew->iLimit = -1; 757b58daeaSdrh pNew->iOffset = -1; 76b9bb7c18Sdrh pNew->addrOpenEphm[0] = -1; 77b9bb7c18Sdrh pNew->addrOpenEphm[1] = -1; 78b9bb7c18Sdrh pNew->addrOpenEphm[2] = -1; 79eda639e1Sdrh if( pNew==&standin) { 80eda639e1Sdrh clearSelect(pNew); 81eda639e1Sdrh pNew = 0; 82daffd0e5Sdrh } 839bb61fe7Sdrh return pNew; 849bb61fe7Sdrh } 859bb61fe7Sdrh 869bb61fe7Sdrh /* 87eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 88eda639e1Sdrh */ 89eda639e1Sdrh void sqlite3SelectDelete(Select *p){ 90eda639e1Sdrh if( p ){ 91eda639e1Sdrh clearSelect(p); 92eda639e1Sdrh sqliteFree(p); 93eda639e1Sdrh } 94eda639e1Sdrh } 95eda639e1Sdrh 96eda639e1Sdrh /* 9701f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 9801f3f253Sdrh ** type of join. Return an integer constant that expresses that type 9901f3f253Sdrh ** in terms of the following bit values: 10001f3f253Sdrh ** 10101f3f253Sdrh ** JT_INNER 1023dec223cSdrh ** JT_CROSS 10301f3f253Sdrh ** JT_OUTER 10401f3f253Sdrh ** JT_NATURAL 10501f3f253Sdrh ** JT_LEFT 10601f3f253Sdrh ** JT_RIGHT 10701f3f253Sdrh ** 10801f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 10901f3f253Sdrh ** 11001f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 11101f3f253Sdrh ** a join type, but put an error in the pParse structure. 11201f3f253Sdrh */ 1134adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 11401f3f253Sdrh int jointype = 0; 11501f3f253Sdrh Token *apAll[3]; 11601f3f253Sdrh Token *p; 1175719628aSdrh static const struct { 118c182d163Sdrh const char zKeyword[8]; 119290c1948Sdrh u8 nChar; 120290c1948Sdrh u8 code; 12101f3f253Sdrh } keywords[] = { 12201f3f253Sdrh { "natural", 7, JT_NATURAL }, 123195e6967Sdrh { "left", 4, JT_LEFT|JT_OUTER }, 124195e6967Sdrh { "right", 5, JT_RIGHT|JT_OUTER }, 125195e6967Sdrh { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 12601f3f253Sdrh { "outer", 5, JT_OUTER }, 12701f3f253Sdrh { "inner", 5, JT_INNER }, 1283dec223cSdrh { "cross", 5, JT_INNER|JT_CROSS }, 12901f3f253Sdrh }; 13001f3f253Sdrh int i, j; 13101f3f253Sdrh apAll[0] = pA; 13201f3f253Sdrh apAll[1] = pB; 13301f3f253Sdrh apAll[2] = pC; 134195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 13501f3f253Sdrh p = apAll[i]; 13601f3f253Sdrh for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){ 13701f3f253Sdrh if( p->n==keywords[j].nChar 1382646da7eSdrh && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){ 13901f3f253Sdrh jointype |= keywords[j].code; 14001f3f253Sdrh break; 14101f3f253Sdrh } 14201f3f253Sdrh } 14301f3f253Sdrh if( j>=sizeof(keywords)/sizeof(keywords[0]) ){ 14401f3f253Sdrh jointype |= JT_ERROR; 14501f3f253Sdrh break; 14601f3f253Sdrh } 14701f3f253Sdrh } 148ad2d8307Sdrh if( 149ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 150195e6967Sdrh (jointype & JT_ERROR)!=0 151ad2d8307Sdrh ){ 152ae29ffbeSdrh const char *zSp1 = " "; 153ae29ffbeSdrh const char *zSp2 = " "; 154ae29ffbeSdrh if( pB==0 ){ zSp1++; } 155ae29ffbeSdrh if( pC==0 ){ zSp2++; } 156ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 157ae29ffbeSdrh "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); 15801f3f253Sdrh jointype = JT_INNER; 159195e6967Sdrh }else if( jointype & JT_RIGHT ){ 1604adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 161da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 162195e6967Sdrh jointype = JT_INNER; 16301f3f253Sdrh } 16401f3f253Sdrh return jointype; 16501f3f253Sdrh } 16601f3f253Sdrh 16701f3f253Sdrh /* 168ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 169ad2d8307Sdrh ** is not contained in the table. 170ad2d8307Sdrh */ 171ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 172ad2d8307Sdrh int i; 173ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1744adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 175ad2d8307Sdrh } 176ad2d8307Sdrh return -1; 177ad2d8307Sdrh } 178ad2d8307Sdrh 179ad2d8307Sdrh /* 18091bb0eedSdrh ** Set the value of a token to a '\000'-terminated string. 18191bb0eedSdrh */ 18291bb0eedSdrh static void setToken(Token *p, const char *z){ 1832646da7eSdrh p->z = (u8*)z; 184261919ccSdanielk1977 p->n = z ? strlen(z) : 0; 18591bb0eedSdrh p->dyn = 0; 18691bb0eedSdrh } 18791bb0eedSdrh 188c182d163Sdrh /* 189f3b863edSdanielk1977 ** Set the token to the double-quoted and escaped version of the string pointed 190f3b863edSdanielk1977 ** to by z. For example; 191f3b863edSdanielk1977 ** 192f3b863edSdanielk1977 ** {a"bc} -> {"a""bc"} 193f3b863edSdanielk1977 */ 194f3b863edSdanielk1977 static void setQuotedToken(Token *p, const char *z){ 195f3b863edSdanielk1977 p->z = (u8 *)sqlite3MPrintf("\"%w\"", z); 196f3b863edSdanielk1977 p->dyn = 1; 197f3b863edSdanielk1977 if( p->z ){ 198f3b863edSdanielk1977 p->n = strlen((char *)p->z); 199f3b863edSdanielk1977 } 200f3b863edSdanielk1977 } 201f3b863edSdanielk1977 202f3b863edSdanielk1977 /* 203c182d163Sdrh ** Create an expression node for an identifier with the name of zName 204c182d163Sdrh */ 2059c41938fSdrh Expr *sqlite3CreateIdExpr(const char *zName){ 206c182d163Sdrh Token dummy; 207c182d163Sdrh setToken(&dummy, zName); 208c182d163Sdrh return sqlite3Expr(TK_ID, 0, 0, &dummy); 209c182d163Sdrh } 210c182d163Sdrh 21191bb0eedSdrh 21291bb0eedSdrh /* 213ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the 214ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2. 215ad2d8307Sdrh */ 216ad2d8307Sdrh static void addWhereTerm( 217ad2d8307Sdrh const char *zCol, /* Name of the column */ 218ad2d8307Sdrh const Table *pTab1, /* First table */ 219030530deSdrh const char *zAlias1, /* Alias for first table. May be NULL */ 220ad2d8307Sdrh const Table *pTab2, /* Second table */ 221030530deSdrh const char *zAlias2, /* Alias for second table. May be NULL */ 22222d6a53aSdrh int iRightJoinTable, /* VDBE cursor for the right table */ 223ad2d8307Sdrh Expr **ppExpr /* Add the equality term to this expression */ 224ad2d8307Sdrh ){ 225ad2d8307Sdrh Expr *pE1a, *pE1b, *pE1c; 226ad2d8307Sdrh Expr *pE2a, *pE2b, *pE2c; 227ad2d8307Sdrh Expr *pE; 228ad2d8307Sdrh 2299c41938fSdrh pE1a = sqlite3CreateIdExpr(zCol); 2309c41938fSdrh pE2a = sqlite3CreateIdExpr(zCol); 231030530deSdrh if( zAlias1==0 ){ 232030530deSdrh zAlias1 = pTab1->zName; 233030530deSdrh } 2349c41938fSdrh pE1b = sqlite3CreateIdExpr(zAlias1); 235030530deSdrh if( zAlias2==0 ){ 236030530deSdrh zAlias2 = pTab2->zName; 237030530deSdrh } 2389c41938fSdrh pE2b = sqlite3CreateIdExpr(zAlias2); 239206f3d96Sdrh pE1c = sqlite3ExprOrFree(TK_DOT, pE1b, pE1a, 0); 240206f3d96Sdrh pE2c = sqlite3ExprOrFree(TK_DOT, pE2b, pE2a, 0); 241206f3d96Sdrh pE = sqlite3ExprOrFree(TK_EQ, pE1c, pE2c, 0); 242206f3d96Sdrh if( pE ){ 2431f16230bSdrh ExprSetProperty(pE, EP_FromJoin); 24422d6a53aSdrh pE->iRightJoinTable = iRightJoinTable; 245206f3d96Sdrh } 246206f3d96Sdrh pE = sqlite3ExprAnd(*ppExpr, pE); 247206f3d96Sdrh if( pE ){ 248206f3d96Sdrh *ppExpr = pE; 249206f3d96Sdrh } 250ad2d8307Sdrh } 251ad2d8307Sdrh 252ad2d8307Sdrh /* 2531f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 25422d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 25522d6a53aSdrh ** expression. 2561cc093c2Sdrh ** 257e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 2581cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 2591f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 2601f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 2611f16230bSdrh ** WHERE clause during join processing but we need to remember that they 2621f16230bSdrh ** originated in the ON or USING clause. 26322d6a53aSdrh ** 26422d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 26522d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 26622d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 26722d6a53aSdrh ** for cases like this: 26822d6a53aSdrh ** 26922d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 27022d6a53aSdrh ** 27122d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 27222d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 27322d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 27422d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 27522d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 27622d6a53aSdrh ** the output, which is incorrect. 2771cc093c2Sdrh */ 27822d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 2791cc093c2Sdrh while( p ){ 2801f16230bSdrh ExprSetProperty(p, EP_FromJoin); 28122d6a53aSdrh p->iRightJoinTable = iTable; 28222d6a53aSdrh setJoinExpr(p->pLeft, iTable); 2831cc093c2Sdrh p = p->pRight; 2841cc093c2Sdrh } 2851cc093c2Sdrh } 2861cc093c2Sdrh 2871cc093c2Sdrh /* 288ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 289ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 290ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 291ad2d8307Sdrh ** 29291bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 29391bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 29491bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 29591bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 29691bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 29791bb0eedSdrh ** also attached to the left entry. 29891bb0eedSdrh ** 299ad2d8307Sdrh ** This routine returns the number of errors encountered. 300ad2d8307Sdrh */ 301ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 30291bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 30391bb0eedSdrh int i, j; /* Loop counters */ 30491bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 30591bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 306ad2d8307Sdrh 30791bb0eedSdrh pSrc = p->pSrc; 30891bb0eedSdrh pLeft = &pSrc->a[0]; 30991bb0eedSdrh pRight = &pLeft[1]; 31091bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 31191bb0eedSdrh Table *pLeftTab = pLeft->pTab; 31291bb0eedSdrh Table *pRightTab = pRight->pTab; 31391bb0eedSdrh 31491bb0eedSdrh if( pLeftTab==0 || pRightTab==0 ) continue; 315ad2d8307Sdrh 316ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 317ad2d8307Sdrh ** every column that the two tables have in common. 318ad2d8307Sdrh */ 31961dfc31dSdrh if( pRight->jointype & JT_NATURAL ){ 32061dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 3214adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 322ad2d8307Sdrh "an ON or USING clause", 0); 323ad2d8307Sdrh return 1; 324ad2d8307Sdrh } 32591bb0eedSdrh for(j=0; j<pLeftTab->nCol; j++){ 32691bb0eedSdrh char *zName = pLeftTab->aCol[j].zName; 32791bb0eedSdrh if( columnIndex(pRightTab, zName)>=0 ){ 328030530deSdrh addWhereTerm(zName, pLeftTab, pLeft->zAlias, 32922d6a53aSdrh pRightTab, pRight->zAlias, 33022d6a53aSdrh pRight->iCursor, &p->pWhere); 33122d6a53aSdrh 332ad2d8307Sdrh } 333ad2d8307Sdrh } 334ad2d8307Sdrh } 335ad2d8307Sdrh 336ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 337ad2d8307Sdrh */ 33861dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 3394adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 340da93d238Sdrh "clauses in the same join"); 341ad2d8307Sdrh return 1; 342ad2d8307Sdrh } 343ad2d8307Sdrh 344ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 34591bb0eedSdrh ** an AND operator. 346ad2d8307Sdrh */ 34761dfc31dSdrh if( pRight->pOn ){ 34861dfc31dSdrh setJoinExpr(pRight->pOn, pRight->iCursor); 34961dfc31dSdrh p->pWhere = sqlite3ExprAnd(p->pWhere, pRight->pOn); 35061dfc31dSdrh pRight->pOn = 0; 351ad2d8307Sdrh } 352ad2d8307Sdrh 353ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 354ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 355ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 356ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 357ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 358ad2d8307Sdrh ** not contained in both tables to be joined. 359ad2d8307Sdrh */ 36061dfc31dSdrh if( pRight->pUsing ){ 36161dfc31dSdrh IdList *pList = pRight->pUsing; 362ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 36391bb0eedSdrh char *zName = pList->a[j].zName; 36491bb0eedSdrh if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){ 3654adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 36691bb0eedSdrh "not present in both tables", zName); 367ad2d8307Sdrh return 1; 368ad2d8307Sdrh } 369030530deSdrh addWhereTerm(zName, pLeftTab, pLeft->zAlias, 37022d6a53aSdrh pRightTab, pRight->zAlias, 37122d6a53aSdrh pRight->iCursor, &p->pWhere); 372ad2d8307Sdrh } 373ad2d8307Sdrh } 374ad2d8307Sdrh } 375ad2d8307Sdrh return 0; 376ad2d8307Sdrh } 377ad2d8307Sdrh 378ad2d8307Sdrh /* 379c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 380c926afbcSdrh ** stack into the sorter. 381c926afbcSdrh */ 382d59ba6ceSdrh static void pushOntoSorter( 383d59ba6ceSdrh Parse *pParse, /* Parser context */ 384d59ba6ceSdrh ExprList *pOrderBy, /* The ORDER BY clause */ 385d59ba6ceSdrh Select *pSelect /* The whole SELECT statement */ 386d59ba6ceSdrh ){ 387d59ba6ceSdrh Vdbe *v = pParse->pVdbe; 388c182d163Sdrh sqlite3ExprCodeExprList(pParse, pOrderBy); 3899d2985c7Sdrh sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0); 3904db38a70Sdrh sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0); 3914db38a70Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0); 3929d2985c7Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0); 393d59ba6ceSdrh if( pSelect->iLimit>=0 ){ 39415007a99Sdrh int addr1, addr2; 39515007a99Sdrh addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0); 39615007a99Sdrh sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1); 39715007a99Sdrh addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 398d59ba6ceSdrh sqlite3VdbeJumpHere(v, addr1); 399d59ba6ceSdrh sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0); 400d59ba6ceSdrh sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0); 40115007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 402d59ba6ceSdrh pSelect->iLimit = -1; 403d59ba6ceSdrh } 404c926afbcSdrh } 405c926afbcSdrh 406c926afbcSdrh /* 407ec7429aeSdrh ** Add code to implement the OFFSET 408ea48eb2eSdrh */ 409ec7429aeSdrh static void codeOffset( 410bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 411ea48eb2eSdrh Select *p, /* The SELECT statement being coded */ 412ea48eb2eSdrh int iContinue, /* Jump here to skip the current record */ 413ea48eb2eSdrh int nPop /* Number of times to pop stack when jumping */ 414ea48eb2eSdrh ){ 41513449892Sdrh if( p->iOffset>=0 && iContinue!=0 ){ 41615007a99Sdrh int addr; 41715007a99Sdrh sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset); 4183a129247Sdrh addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0); 419ea48eb2eSdrh if( nPop>0 ){ 420ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_Pop, nPop, 0); 421ea48eb2eSdrh } 422ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); 423ad6d9460Sdrh VdbeComment((v, "# skip OFFSET records")); 42415007a99Sdrh sqlite3VdbeJumpHere(v, addr); 425ea48eb2eSdrh } 426ea48eb2eSdrh } 427ea48eb2eSdrh 428ea48eb2eSdrh /* 429c99130fdSdrh ** Add code that will check to make sure the top N elements of the 430c99130fdSdrh ** stack are distinct. iTab is a sorting index that holds previously 431c99130fdSdrh ** seen combinations of the N values. A new entry is made in iTab 432c99130fdSdrh ** if the current N values are new. 433c99130fdSdrh ** 434f8875400Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 435c99130fdSdrh ** stack if the top N elements are not distinct. 436c99130fdSdrh */ 437c99130fdSdrh static void codeDistinct( 438c99130fdSdrh Vdbe *v, /* Generate code into this VM */ 439c99130fdSdrh int iTab, /* A sorting index used to test for distinctness */ 440c99130fdSdrh int addrRepeat, /* Jump to here if not distinct */ 441f8875400Sdrh int N /* The top N elements of the stack must be distinct */ 442c99130fdSdrh ){ 443c99130fdSdrh sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0); 444c99130fdSdrh sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3); 445f8875400Sdrh sqlite3VdbeAddOp(v, OP_Pop, N+1, 0); 446c99130fdSdrh sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat); 447c99130fdSdrh VdbeComment((v, "# skip indistinct records")); 448c99130fdSdrh sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0); 449c99130fdSdrh } 450c99130fdSdrh 451e305f43fSdrh /* 452e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression 453e305f43fSdrh ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result 454e305f43fSdrh ** column. We do this in a subroutine because the error occurs in multiple 455e305f43fSdrh ** places. 456e305f43fSdrh */ 457e305f43fSdrh static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){ 458e305f43fSdrh if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ 459e305f43fSdrh sqlite3ErrorMsg(pParse, "only a single result allowed for " 460e305f43fSdrh "a SELECT that is part of an expression"); 461e305f43fSdrh return 1; 462e305f43fSdrh }else{ 463e305f43fSdrh return 0; 464e305f43fSdrh } 465e305f43fSdrh } 466c99130fdSdrh 467c99130fdSdrh /* 4682282792aSdrh ** This routine generates the code for the inside of the inner loop 4692282792aSdrh ** of a SELECT. 47082c3d636Sdrh ** 47138640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 47238640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 47338640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 47438640e15Sdrh ** datatypes for each column. 4752282792aSdrh */ 4762282792aSdrh static int selectInnerLoop( 4772282792aSdrh Parse *pParse, /* The parser context */ 478df199a25Sdrh Select *p, /* The complete select statement being coded */ 4792282792aSdrh ExprList *pEList, /* List of values being extracted */ 48082c3d636Sdrh int srcTab, /* Pull data from this table */ 481967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 4822282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 4832282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 4842282792aSdrh int eDest, /* How to dispose of the results */ 4852282792aSdrh int iParm, /* An argument to the disposal method */ 4862282792aSdrh int iContinue, /* Jump here to continue with next row */ 48784ac9d02Sdanielk1977 int iBreak, /* Jump here to break out of the inner loop */ 48884ac9d02Sdanielk1977 char *aff /* affinity string if eDest is SRT_Union */ 4892282792aSdrh ){ 4902282792aSdrh Vdbe *v = pParse->pVdbe; 4912282792aSdrh int i; 492ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 49338640e15Sdrh 494daffd0e5Sdrh if( v==0 ) return 0; 49538640e15Sdrh assert( pEList!=0 ); 4962282792aSdrh 497df199a25Sdrh /* If there was a LIMIT clause on the SELECT statement, then do the check 498df199a25Sdrh ** to see if this row should be output. 499df199a25Sdrh */ 500eda639e1Sdrh hasDistinct = distinct>=0 && pEList->nExpr>0; 501ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 502ec7429aeSdrh codeOffset(v, p, iContinue, 0); 503df199a25Sdrh } 504df199a25Sdrh 505967e8b73Sdrh /* Pull the requested columns. 5062282792aSdrh */ 50738640e15Sdrh if( nColumn>0 ){ 508967e8b73Sdrh for(i=0; i<nColumn; i++){ 5094adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Column, srcTab, i); 51082c3d636Sdrh } 51138640e15Sdrh }else{ 51238640e15Sdrh nColumn = pEList->nExpr; 513c182d163Sdrh sqlite3ExprCodeExprList(pParse, pEList); 51482c3d636Sdrh } 5152282792aSdrh 516daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 517daffd0e5Sdrh ** and this row has been seen before, then do not make this row 518daffd0e5Sdrh ** part of the result. 5192282792aSdrh */ 520ea48eb2eSdrh if( hasDistinct ){ 521f8875400Sdrh assert( pEList!=0 ); 522f8875400Sdrh assert( pEList->nExpr==nColumn ); 523f8875400Sdrh codeDistinct(v, distinct, iContinue, nColumn); 524ea48eb2eSdrh if( pOrderBy==0 ){ 525ec7429aeSdrh codeOffset(v, p, iContinue, nColumn); 526ea48eb2eSdrh } 5272282792aSdrh } 52882c3d636Sdrh 529e305f43fSdrh if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ 530e305f43fSdrh return 0; 531e305f43fSdrh } 532e305f43fSdrh 533c926afbcSdrh switch( eDest ){ 53482c3d636Sdrh /* In this mode, write each query result to the key of the temporary 53582c3d636Sdrh ** table iParm. 5362282792aSdrh */ 53713449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 538c926afbcSdrh case SRT_Union: { 539f8875400Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 54013449892Sdrh if( aff ){ 54184ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 54213449892Sdrh } 543f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0); 544c926afbcSdrh break; 545c926afbcSdrh } 54682c3d636Sdrh 54782c3d636Sdrh /* Construct a record from the query result, but instead of 54882c3d636Sdrh ** saving that record, use it as a key to delete elements from 54982c3d636Sdrh ** the temporary table iParm. 55082c3d636Sdrh */ 551c926afbcSdrh case SRT_Except: { 5520bd1f4eaSdrh int addr; 553f8875400Sdrh addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 55484ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 5554adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3); 5564adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0); 557c926afbcSdrh break; 558c926afbcSdrh } 5595338a5f7Sdanielk1977 #endif 5605338a5f7Sdanielk1977 5615338a5f7Sdanielk1977 /* Store the result as data using a unique key. 5625338a5f7Sdanielk1977 */ 5635338a5f7Sdanielk1977 case SRT_Table: 564b9bb7c18Sdrh case SRT_EphemTab: { 5655338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 5665338a5f7Sdanielk1977 if( pOrderBy ){ 567d59ba6ceSdrh pushOntoSorter(pParse, pOrderBy, p); 5685338a5f7Sdanielk1977 }else{ 569f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); 5705338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 571e4d90813Sdrh sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); 5725338a5f7Sdanielk1977 } 5735338a5f7Sdanielk1977 break; 5745338a5f7Sdanielk1977 } 5752282792aSdrh 57693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 5772282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 5782282792aSdrh ** then there should be a single item on the stack. Write this 5792282792aSdrh ** item into the set table with bogus data. 5802282792aSdrh */ 581c926afbcSdrh case SRT_Set: { 5824adee20fSdanielk1977 int addr1 = sqlite3VdbeCurrentAddr(v); 58352b36cabSdrh int addr2; 584e014a838Sdanielk1977 585967e8b73Sdrh assert( nColumn==1 ); 5864adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3); 5874adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 5884adee20fSdanielk1977 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 5896c1426fdSdrh p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff); 590c926afbcSdrh if( pOrderBy ){ 591de941c60Sdrh /* At first glance you would think we could optimize out the 592de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 593de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 594de941c60Sdrh ** case the order does matter */ 595d59ba6ceSdrh pushOntoSorter(pParse, pOrderBy, p); 596c926afbcSdrh }else{ 5976c1426fdSdrh sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); 598f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); 599c926afbcSdrh } 600d654be80Sdrh sqlite3VdbeJumpHere(v, addr2); 601c926afbcSdrh break; 602c926afbcSdrh } 60382c3d636Sdrh 604504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 605ec7429aeSdrh */ 606ec7429aeSdrh case SRT_Exists: { 607ec7429aeSdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm); 608ec7429aeSdrh sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 609ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 610ec7429aeSdrh break; 611ec7429aeSdrh } 612ec7429aeSdrh 6132282792aSdrh /* If this is a scalar select that is part of an expression, then 6142282792aSdrh ** store the results in the appropriate memory cell and break out 6152282792aSdrh ** of the scan loop. 6162282792aSdrh */ 617c926afbcSdrh case SRT_Mem: { 618967e8b73Sdrh assert( nColumn==1 ); 619c926afbcSdrh if( pOrderBy ){ 620d59ba6ceSdrh pushOntoSorter(pParse, pOrderBy, p); 621c926afbcSdrh }else{ 6224adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 623ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 624c926afbcSdrh } 625c926afbcSdrh break; 626c926afbcSdrh } 62793758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 6282282792aSdrh 629c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 630c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 631c182d163Sdrh ** popping the data from the stack. 632f46f905aSdrh */ 633c182d163Sdrh case SRT_Subroutine: 6349d2985c7Sdrh case SRT_Callback: { 635f46f905aSdrh if( pOrderBy ){ 636ce665cf6Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 637d59ba6ceSdrh pushOntoSorter(pParse, pOrderBy, p); 638c182d163Sdrh }else if( eDest==SRT_Subroutine ){ 6394adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 640c182d163Sdrh }else{ 641c182d163Sdrh sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 642ac82fcf5Sdrh } 643142e30dfSdrh break; 644142e30dfSdrh } 645142e30dfSdrh 6466a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 647d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 648d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 649d7489c39Sdrh ** user-defined functions that have side effects. We do not care 650d7489c39Sdrh ** about the actual results of the select. 651d7489c39Sdrh */ 652c926afbcSdrh default: { 653f46f905aSdrh assert( eDest==SRT_Discard ); 6544adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 655c926afbcSdrh break; 656c926afbcSdrh } 65793758c8dSdanielk1977 #endif 658c926afbcSdrh } 659ec7429aeSdrh 660ec7429aeSdrh /* Jump to the end of the loop if the LIMIT is reached. 661ec7429aeSdrh */ 662ec7429aeSdrh if( p->iLimit>=0 && pOrderBy==0 ){ 66315007a99Sdrh sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); 664ec7429aeSdrh sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak); 665ec7429aeSdrh } 66682c3d636Sdrh return 0; 66782c3d636Sdrh } 66882c3d636Sdrh 66982c3d636Sdrh /* 670dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 671dece1a84Sdrh ** the collating sequence for each expression in that expression list. 672dece1a84Sdrh ** 6730342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 6740342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 6750342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 6760342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 6770342b1f5Sdrh ** index to implement a DISTINCT test. 6780342b1f5Sdrh ** 679dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 680dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 681dece1a84Sdrh ** freed. Add the KeyInfo structure to the P3 field of an opcode using 682dece1a84Sdrh ** P3_KEYINFO_HANDOFF is the usual way of dealing with this. 683dece1a84Sdrh */ 684dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 685dece1a84Sdrh sqlite3 *db = pParse->db; 686dece1a84Sdrh int nExpr; 687dece1a84Sdrh KeyInfo *pInfo; 688dece1a84Sdrh struct ExprList_item *pItem; 689dece1a84Sdrh int i; 690dece1a84Sdrh 691dece1a84Sdrh nExpr = pList->nExpr; 692dece1a84Sdrh pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 693dece1a84Sdrh if( pInfo ){ 6942646da7eSdrh pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr]; 695dece1a84Sdrh pInfo->nField = nExpr; 69614db2665Sdanielk1977 pInfo->enc = ENC(db); 697dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 698dece1a84Sdrh CollSeq *pColl; 699dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 700dece1a84Sdrh if( !pColl ){ 701dece1a84Sdrh pColl = db->pDfltColl; 702dece1a84Sdrh } 703dece1a84Sdrh pInfo->aColl[i] = pColl; 704dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 705dece1a84Sdrh } 706dece1a84Sdrh } 707dece1a84Sdrh return pInfo; 708dece1a84Sdrh } 709dece1a84Sdrh 710dece1a84Sdrh 711dece1a84Sdrh /* 712d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 713d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 714d8bc7086Sdrh ** we need to run the sorter and output the results. The following 715d8bc7086Sdrh ** routine generates the code needed to do that. 716d8bc7086Sdrh */ 717c926afbcSdrh static void generateSortTail( 718cdd536f0Sdrh Parse *pParse, /* Parsing context */ 719c926afbcSdrh Select *p, /* The SELECT statement */ 720c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 721c926afbcSdrh int nColumn, /* Number of columns of data */ 722c926afbcSdrh int eDest, /* Write the sorted results here */ 723c926afbcSdrh int iParm /* Optional parameter associated with eDest */ 724c926afbcSdrh ){ 7250342b1f5Sdrh int brk = sqlite3VdbeMakeLabel(v); 7260342b1f5Sdrh int cont = sqlite3VdbeMakeLabel(v); 727d8bc7086Sdrh int addr; 7280342b1f5Sdrh int iTab; 72961fc595fSdrh int pseudoTab = 0; 7300342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 731ffbc3088Sdrh 7329d2985c7Sdrh iTab = pOrderBy->iECursor; 733cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 734cdd536f0Sdrh pseudoTab = pParse->nTab++; 735cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0); 736cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn); 737cdd536f0Sdrh } 7380342b1f5Sdrh addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk); 739ec7429aeSdrh codeOffset(v, p, cont, 0); 740cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 741cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_Integer, 1, 0); 742cdd536f0Sdrh } 7434db38a70Sdrh sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1); 744c926afbcSdrh switch( eDest ){ 745c926afbcSdrh case SRT_Table: 746b9bb7c18Sdrh case SRT_EphemTab: { 747f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); 7484adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 749e4d90813Sdrh sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); 750c926afbcSdrh break; 751c926afbcSdrh } 75293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 753c926afbcSdrh case SRT_Set: { 754c926afbcSdrh assert( nColumn==1 ); 7554adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); 7564adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 7574adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); 7586c1426fdSdrh sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); 759f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); 760c926afbcSdrh break; 761c926afbcSdrh } 762c926afbcSdrh case SRT_Mem: { 763c926afbcSdrh assert( nColumn==1 ); 7644adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 765ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 766c926afbcSdrh break; 767c926afbcSdrh } 76893758c8dSdanielk1977 #endif 769ce665cf6Sdrh case SRT_Callback: 770ac82fcf5Sdrh case SRT_Subroutine: { 771ac82fcf5Sdrh int i; 772cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0); 773ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 774cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i); 775ac82fcf5Sdrh } 776ce665cf6Sdrh if( eDest==SRT_Callback ){ 777ce665cf6Sdrh sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 778ce665cf6Sdrh }else{ 7794adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 780ce665cf6Sdrh } 781ac82fcf5Sdrh break; 782ac82fcf5Sdrh } 783c926afbcSdrh default: { 784f46f905aSdrh /* Do nothing */ 785c926afbcSdrh break; 786c926afbcSdrh } 787c926afbcSdrh } 788ec7429aeSdrh 789ec7429aeSdrh /* Jump to the end of the loop when the LIMIT is reached 790ec7429aeSdrh */ 791ec7429aeSdrh if( p->iLimit>=0 ){ 79215007a99Sdrh sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); 793ec7429aeSdrh sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk); 794ec7429aeSdrh } 795ec7429aeSdrh 796ec7429aeSdrh /* The bottom of the loop 797ec7429aeSdrh */ 7980342b1f5Sdrh sqlite3VdbeResolveLabel(v, cont); 7990342b1f5Sdrh sqlite3VdbeAddOp(v, OP_Next, iTab, addr); 8000342b1f5Sdrh sqlite3VdbeResolveLabel(v, brk); 801cdd536f0Sdrh if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ 802cdd536f0Sdrh sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0); 803cdd536f0Sdrh } 804cdd536f0Sdrh 805d8bc7086Sdrh } 806d8bc7086Sdrh 807d8bc7086Sdrh /* 808517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 809517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 810e78e8284Sdrh ** 811955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 812955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 813955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 814955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 815955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 816955de52cSdanielk1977 ** considered a column by this function. 817e78e8284Sdrh ** 818955de52cSdanielk1977 ** SELECT col FROM tbl; 819955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 820955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 821955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 822955de52cSdanielk1977 ** 823955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 824fcb78a49Sdrh */ 825955de52cSdanielk1977 static const char *columnType( 826955de52cSdanielk1977 NameContext *pNC, 827955de52cSdanielk1977 Expr *pExpr, 828955de52cSdanielk1977 const char **pzOriginDb, 829955de52cSdanielk1977 const char **pzOriginTab, 830955de52cSdanielk1977 const char **pzOriginCol 831955de52cSdanielk1977 ){ 832955de52cSdanielk1977 char const *zType = 0; 833955de52cSdanielk1977 char const *zOriginDb = 0; 834955de52cSdanielk1977 char const *zOriginTab = 0; 835955de52cSdanielk1977 char const *zOriginCol = 0; 836517eb646Sdanielk1977 int j; 837b3bce662Sdanielk1977 if( pExpr==0 || pNC->pSrcList==0 ) return 0; 8385338a5f7Sdanielk1977 83900e279d9Sdanielk1977 switch( pExpr->op ){ 84030bcf5dbSdrh case TK_AGG_COLUMN: 84100e279d9Sdanielk1977 case TK_COLUMN: { 842955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 843955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 844955de52cSdanielk1977 ** database table or a subquery. 845955de52cSdanielk1977 */ 846955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 847955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 848955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 849b3bce662Sdanielk1977 while( pNC && !pTab ){ 850b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 851b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 852b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 8536a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 854955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 855b3bce662Sdanielk1977 }else{ 856b3bce662Sdanielk1977 pNC = pNC->pNext; 857b3bce662Sdanielk1977 } 858b3bce662Sdanielk1977 } 859955de52cSdanielk1977 8607e62779aSdrh if( pTab==0 ){ 8617e62779aSdrh /* FIX ME: 8627e62779aSdrh ** This can occurs if you have something like "SELECT new.x;" inside 8637e62779aSdrh ** a trigger. In other words, if you reference the special "new" 8647e62779aSdrh ** table in the result set of a select. We do not have a good way 8657e62779aSdrh ** to find the actual table type, so call it "TEXT". This is really 8667e62779aSdrh ** something of a bug, but I do not know how to fix it. 8677e62779aSdrh ** 8687e62779aSdrh ** This code does not produce the correct answer - it just prevents 8697e62779aSdrh ** a segfault. See ticket #1229. 8707e62779aSdrh */ 8717e62779aSdrh zType = "TEXT"; 8727e62779aSdrh break; 8737e62779aSdrh } 874955de52cSdanielk1977 875b3bce662Sdanielk1977 assert( pTab ); 876955de52cSdanielk1977 if( pS ){ 877955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 878955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 879955de52cSdanielk1977 ** data for the result-set column of the sub-select. 880955de52cSdanielk1977 */ 881955de52cSdanielk1977 if( iCol>=0 && iCol<pS->pEList->nExpr ){ 882955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 883955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 884955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 885955de52cSdanielk1977 */ 886955de52cSdanielk1977 NameContext sNC; 887955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 888955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 889955de52cSdanielk1977 sNC.pNext = 0; 890955de52cSdanielk1977 sNC.pParse = pNC->pParse; 891955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 892955de52cSdanielk1977 } 8934b2688abSdanielk1977 }else if( pTab->pSchema ){ 894955de52cSdanielk1977 /* A real table */ 895955de52cSdanielk1977 assert( !pS ); 896fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 897fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 898fcb78a49Sdrh if( iCol<0 ){ 899fcb78a49Sdrh zType = "INTEGER"; 900955de52cSdanielk1977 zOriginCol = "rowid"; 901fcb78a49Sdrh }else{ 902fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 903955de52cSdanielk1977 zOriginCol = pTab->aCol[iCol].zName; 904955de52cSdanielk1977 } 905955de52cSdanielk1977 zOriginTab = pTab->zName; 906955de52cSdanielk1977 if( pNC->pParse ){ 907955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 908955de52cSdanielk1977 zOriginDb = pNC->pParse->db->aDb[iDb].zName; 909955de52cSdanielk1977 } 910fcb78a49Sdrh } 91100e279d9Sdanielk1977 break; 912736c22b8Sdrh } 91393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 91400e279d9Sdanielk1977 case TK_SELECT: { 915955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 916955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 917955de52cSdanielk1977 ** statement. 918955de52cSdanielk1977 */ 919b3bce662Sdanielk1977 NameContext sNC; 92000e279d9Sdanielk1977 Select *pS = pExpr->pSelect; 921955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 922955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 923b3bce662Sdanielk1977 sNC.pNext = pNC; 924955de52cSdanielk1977 sNC.pParse = pNC->pParse; 925955de52cSdanielk1977 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 92600e279d9Sdanielk1977 break; 927fcb78a49Sdrh } 92893758c8dSdanielk1977 #endif 92900e279d9Sdanielk1977 } 93000e279d9Sdanielk1977 931955de52cSdanielk1977 if( pzOriginDb ){ 932955de52cSdanielk1977 assert( pzOriginTab && pzOriginCol ); 933955de52cSdanielk1977 *pzOriginDb = zOriginDb; 934955de52cSdanielk1977 *pzOriginTab = zOriginTab; 935955de52cSdanielk1977 *pzOriginCol = zOriginCol; 936955de52cSdanielk1977 } 937517eb646Sdanielk1977 return zType; 938517eb646Sdanielk1977 } 939517eb646Sdanielk1977 940517eb646Sdanielk1977 /* 941517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 942517eb646Sdanielk1977 ** in the result set. 943517eb646Sdanielk1977 */ 944517eb646Sdanielk1977 static void generateColumnTypes( 945517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 946517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 947517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 948517eb646Sdanielk1977 ){ 949517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 950517eb646Sdanielk1977 int i; 951b3bce662Sdanielk1977 NameContext sNC; 952b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 953955de52cSdanielk1977 sNC.pParse = pParse; 954517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 955517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 956955de52cSdanielk1977 const char *zOrigDb = 0; 957955de52cSdanielk1977 const char *zOrigTab = 0; 958955de52cSdanielk1977 const char *zOrigCol = 0; 959955de52cSdanielk1977 const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 960955de52cSdanielk1977 9614b1ae99dSdanielk1977 /* The vdbe must make it's own copy of the column-type and other 9624b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 9634b1ae99dSdanielk1977 ** virtual machine is deleted. 964fbcd585fSdanielk1977 */ 9654b1ae99dSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT); 9664b1ae99dSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT); 9674b1ae99dSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT); 9684b1ae99dSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT); 969fcb78a49Sdrh } 970fcb78a49Sdrh } 971fcb78a49Sdrh 972fcb78a49Sdrh /* 973fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 974fcb78a49Sdrh ** in the result set. This information is used to provide the 975fcabd464Sdrh ** azCol[] values in the callback. 97682c3d636Sdrh */ 977832508b7Sdrh static void generateColumnNames( 978832508b7Sdrh Parse *pParse, /* Parser context */ 979ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 980832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 981832508b7Sdrh ){ 982d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 9836a3ea0e6Sdrh int i, j; 9849bb575fdSdrh sqlite3 *db = pParse->db; 985fcabd464Sdrh int fullNames, shortNames; 986fcabd464Sdrh 987fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 9883cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 9893cf86063Sdanielk1977 if( pParse->explain ){ 99061de0d1bSdanielk1977 return; 9913cf86063Sdanielk1977 } 9925338a5f7Sdanielk1977 #endif 9933cf86063Sdanielk1977 994d6502758Sdrh assert( v!=0 ); 9959e12800dSdanielk1977 if( pParse->colNamesSet || v==0 || sqlite3MallocFailed() ) return; 996d8bc7086Sdrh pParse->colNamesSet = 1; 997fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 998fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 99922322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 100082c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 100182c3d636Sdrh Expr *p; 10025a38705eSdrh p = pEList->a[i].pExpr; 10035a38705eSdrh if( p==0 ) continue; 100482c3d636Sdrh if( pEList->a[i].zName ){ 100582c3d636Sdrh char *zName = pEList->a[i].zName; 1006955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName)); 100782c3d636Sdrh continue; 100882c3d636Sdrh } 1009fa173a76Sdrh if( p->op==TK_COLUMN && pTabList ){ 10106a3ea0e6Sdrh Table *pTab; 101197665873Sdrh char *zCol; 10128aff1015Sdrh int iCol = p->iColumn; 10136a3ea0e6Sdrh for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 10146a3ea0e6Sdrh assert( j<pTabList->nSrc ); 10156a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 10168aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 101797665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1018b1363206Sdrh if( iCol<0 ){ 101947a6db2bSdrh zCol = "rowid"; 1020b1363206Sdrh }else{ 1021b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1022b1363206Sdrh } 1023fcabd464Sdrh if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ 1024955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 1025fcabd464Sdrh }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ 102682c3d636Sdrh char *zName = 0; 102782c3d636Sdrh char *zTab; 102882c3d636Sdrh 10296a3ea0e6Sdrh zTab = pTabList->a[j].zAlias; 1030fcabd464Sdrh if( fullNames || zTab==0 ) zTab = pTab->zName; 1031f93339deSdrh sqlite3SetString(&zName, zTab, ".", zCol, (char*)0); 1032955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC); 103382c3d636Sdrh }else{ 1034955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol)); 103582c3d636Sdrh } 10366977fea8Sdrh }else if( p->span.z && p->span.z[0] ){ 1037955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); 10383cf86063Sdanielk1977 /* sqlite3VdbeCompressSpace(v, addr); */ 10391bee3d7bSdrh }else{ 10401bee3d7bSdrh char zName[30]; 10411bee3d7bSdrh assert( p->op!=TK_COLUMN || pTabList==0 ); 10425bb3eb9bSdrh sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1); 1043955de52cSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0); 104482c3d636Sdrh } 104582c3d636Sdrh } 104676d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 10475080aaa7Sdrh } 104882c3d636Sdrh 104993758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 105082c3d636Sdrh /* 1051d8bc7086Sdrh ** Name of the connection operator, used for error messages. 1052d8bc7086Sdrh */ 1053d8bc7086Sdrh static const char *selectOpName(int id){ 1054d8bc7086Sdrh char *z; 1055d8bc7086Sdrh switch( id ){ 1056d8bc7086Sdrh case TK_ALL: z = "UNION ALL"; break; 1057d8bc7086Sdrh case TK_INTERSECT: z = "INTERSECT"; break; 1058d8bc7086Sdrh case TK_EXCEPT: z = "EXCEPT"; break; 1059d8bc7086Sdrh default: z = "UNION"; break; 1060d8bc7086Sdrh } 1061d8bc7086Sdrh return z; 1062d8bc7086Sdrh } 106393758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1064d8bc7086Sdrh 1065d8bc7086Sdrh /* 1066315555caSdrh ** Forward declaration 1067315555caSdrh */ 10689b3187e1Sdrh static int prepSelectStmt(Parse*, Select*); 1069315555caSdrh 1070315555caSdrh /* 107122f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes 107222f70c32Sdrh ** the result set of that SELECT. 107322f70c32Sdrh */ 10744adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 107522f70c32Sdrh Table *pTab; 1076b733d037Sdrh int i, j; 107722f70c32Sdrh ExprList *pEList; 1078290c1948Sdrh Column *aCol, *pCol; 107922f70c32Sdrh 108092378253Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 10819b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 108222f70c32Sdrh return 0; 108322f70c32Sdrh } 1084142bdf40Sdanielk1977 if( sqlite3SelectResolve(pParse, pSelect, 0) ){ 1085142bdf40Sdanielk1977 return 0; 1086142bdf40Sdanielk1977 } 108722f70c32Sdrh pTab = sqliteMalloc( sizeof(Table) ); 108822f70c32Sdrh if( pTab==0 ){ 108922f70c32Sdrh return 0; 109022f70c32Sdrh } 1091ed8a3bb1Sdrh pTab->nRef = 1; 109222f70c32Sdrh pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0; 109322f70c32Sdrh pEList = pSelect->pEList; 109422f70c32Sdrh pTab->nCol = pEList->nExpr; 1095417be79cSdrh assert( pTab->nCol>0 ); 1096b733d037Sdrh pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol ); 1097290c1948Sdrh for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){ 109879d5f63fSdrh Expr *p, *pR; 1099517eb646Sdanielk1977 char *zType; 110091bb0eedSdrh char *zName; 11012564ef97Sdrh int nName; 1102b3bf556eSdanielk1977 CollSeq *pColl; 110379d5f63fSdrh int cnt; 1104b3bce662Sdanielk1977 NameContext sNC; 110579d5f63fSdrh 110679d5f63fSdrh /* Get an appropriate name for the column 110779d5f63fSdrh */ 110879d5f63fSdrh p = pEList->a[i].pExpr; 1109290c1948Sdrh assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 ); 111091bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 111179d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 111291bb0eedSdrh zName = sqliteStrDup(zName); 1113517eb646Sdanielk1977 }else if( p->op==TK_DOT 1114b733d037Sdrh && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ 111579d5f63fSdrh /* For columns of the from A.B use B as the name */ 111691bb0eedSdrh zName = sqlite3MPrintf("%T", &pR->token); 1117b733d037Sdrh }else if( p->span.z && p->span.z[0] ){ 111879d5f63fSdrh /* Use the original text of the column expression as its name */ 111991bb0eedSdrh zName = sqlite3MPrintf("%T", &p->span); 112022f70c32Sdrh }else{ 112179d5f63fSdrh /* If all else fails, make up a name */ 112291bb0eedSdrh zName = sqlite3MPrintf("column%d", i+1); 112322f70c32Sdrh } 112491bb0eedSdrh sqlite3Dequote(zName); 11259e12800dSdanielk1977 if( sqlite3MallocFailed() ){ 1126dd5b2fa5Sdrh sqliteFree(zName); 1127a04a34ffSdanielk1977 sqlite3DeleteTable(pTab); 1128dd5b2fa5Sdrh return 0; 1129dd5b2fa5Sdrh } 113079d5f63fSdrh 113179d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 113279d5f63fSdrh ** append a integer to the name so that it becomes unique. 113379d5f63fSdrh */ 11342564ef97Sdrh nName = strlen(zName); 113579d5f63fSdrh for(j=cnt=0; j<i; j++){ 113679d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 11372564ef97Sdrh zName[nName] = 0; 11382564ef97Sdrh zName = sqlite3MPrintf("%z:%d", zName, ++cnt); 113979d5f63fSdrh j = -1; 1140dd5b2fa5Sdrh if( zName==0 ) break; 114179d5f63fSdrh } 114279d5f63fSdrh } 114391bb0eedSdrh pCol->zName = zName; 1144e014a838Sdanielk1977 114579d5f63fSdrh /* Get the typename, type affinity, and collating sequence for the 114679d5f63fSdrh ** column. 114779d5f63fSdrh */ 1148c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1149b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 1150955de52cSdanielk1977 zType = sqliteStrDup(columnType(&sNC, p, 0, 0, 0)); 1151290c1948Sdrh pCol->zType = zType; 1152c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1153b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 1154b3bf556eSdanielk1977 if( pColl ){ 1155e7259296Sdanielk1977 pCol->zColl = sqliteStrDup(pColl->zName); 11560202b29eSdanielk1977 } 115722f70c32Sdrh } 115822f70c32Sdrh pTab->iPKey = -1; 115922f70c32Sdrh return pTab; 116022f70c32Sdrh } 116122f70c32Sdrh 116222f70c32Sdrh /* 11639b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following 11649b3187e1Sdrh ** things: 1165d8bc7086Sdrh ** 11669b3187e1Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 11679b3187e1Sdrh ** element of the FROM clause. 11689b3187e1Sdrh ** 11699b3187e1Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 11709b3187e1Sdrh ** defines FROM clause. When views appear in the FROM clause, 117163eb5f29Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 117263eb5f29Sdrh ** that implements the view. A copy is made of the view's SELECT 117363eb5f29Sdrh ** statement so that we can freely modify or delete that statement 117463eb5f29Sdrh ** without worrying about messing up the presistent representation 117563eb5f29Sdrh ** of the view. 1176d8bc7086Sdrh ** 11779b3187e1Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 1178ad2d8307Sdrh ** on joins and the ON and USING clause of joins. 1179ad2d8307Sdrh ** 11809b3187e1Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 118154473229Sdrh ** for instances of the "*" operator or the TABLE.* operator. 118254473229Sdrh ** If found, expand each "*" to be every column in every table 118354473229Sdrh ** and TABLE.* to be every column in TABLE. 1184d8bc7086Sdrh ** 1185d8bc7086Sdrh ** Return 0 on success. If there are problems, leave an error message 1186d8bc7086Sdrh ** in pParse and return non-zero. 1187d8bc7086Sdrh */ 11889b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){ 118954473229Sdrh int i, j, k, rc; 1190ad3cab52Sdrh SrcList *pTabList; 1191daffd0e5Sdrh ExprList *pEList; 1192290c1948Sdrh struct SrcList_item *pFrom; 1193daffd0e5Sdrh 11949e12800dSdanielk1977 if( p==0 || p->pSrc==0 || sqlite3MallocFailed() ){ 11956f7adc8aSdrh return 1; 11966f7adc8aSdrh } 1197daffd0e5Sdrh pTabList = p->pSrc; 1198daffd0e5Sdrh pEList = p->pEList; 1199d8bc7086Sdrh 12009b3187e1Sdrh /* Make sure cursor numbers have been assigned to all entries in 12019b3187e1Sdrh ** the FROM clause of the SELECT statement. 12029b3187e1Sdrh */ 12039b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, p->pSrc); 12049b3187e1Sdrh 12059b3187e1Sdrh /* Look up every table named in the FROM clause of the select. If 12069b3187e1Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 12079b3187e1Sdrh ** then create a transient table structure to describe the subquery. 1208d8bc7086Sdrh */ 1209290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1210f0113000Sdanielk1977 Table *pTab; 12119b3187e1Sdrh if( pFrom->pTab!=0 ){ 12129b3187e1Sdrh /* This statement has already been prepared. There is no need 12139b3187e1Sdrh ** to go further. */ 12149b3187e1Sdrh assert( i==0 ); 1215d8bc7086Sdrh return 0; 1216d8bc7086Sdrh } 1217290c1948Sdrh if( pFrom->zName==0 ){ 121893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 121922f70c32Sdrh /* A sub-query in the FROM clause of a SELECT */ 1220290c1948Sdrh assert( pFrom->pSelect!=0 ); 1221290c1948Sdrh if( pFrom->zAlias==0 ){ 122291bb0eedSdrh pFrom->zAlias = 122391bb0eedSdrh sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect); 1224ad2d8307Sdrh } 1225ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1226290c1948Sdrh pFrom->pTab = pTab = 1227290c1948Sdrh sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect); 122822f70c32Sdrh if( pTab==0 ){ 1229daffd0e5Sdrh return 1; 1230daffd0e5Sdrh } 1231b9bb7c18Sdrh /* The isEphem flag indicates that the Table structure has been 12325cf590c1Sdrh ** dynamically allocated and may be freed at any time. In other words, 12335cf590c1Sdrh ** pTab is not pointing to a persistent table structure that defines 12345cf590c1Sdrh ** part of the schema. */ 1235b9bb7c18Sdrh pTab->isEphem = 1; 123693758c8dSdanielk1977 #endif 123722f70c32Sdrh }else{ 1238a76b5dfcSdrh /* An ordinary table or view name in the FROM clause */ 1239ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1240290c1948Sdrh pFrom->pTab = pTab = 1241290c1948Sdrh sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase); 1242a76b5dfcSdrh if( pTab==0 ){ 1243d8bc7086Sdrh return 1; 1244d8bc7086Sdrh } 1245ed8a3bb1Sdrh pTab->nRef++; 124693626f48Sdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 124793626f48Sdanielk1977 if( pTab->pSelect || IsVirtual(pTab) ){ 124863eb5f29Sdrh /* We reach here if the named table is a really a view */ 12494adee20fSdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 1250417be79cSdrh return 1; 1251417be79cSdrh } 1252290c1948Sdrh /* If pFrom->pSelect!=0 it means we are dealing with a 125363eb5f29Sdrh ** view within a view. The SELECT structure has already been 125463eb5f29Sdrh ** copied by the outer view so we can skip the copy step here 125563eb5f29Sdrh ** in the inner view. 125663eb5f29Sdrh */ 1257290c1948Sdrh if( pFrom->pSelect==0 ){ 1258290c1948Sdrh pFrom->pSelect = sqlite3SelectDup(pTab->pSelect); 1259a76b5dfcSdrh } 1260d8bc7086Sdrh } 126193758c8dSdanielk1977 #endif 126222f70c32Sdrh } 126363eb5f29Sdrh } 1264d8bc7086Sdrh 1265ad2d8307Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 1266ad2d8307Sdrh */ 1267ad2d8307Sdrh if( sqliteProcessJoin(pParse, p) ) return 1; 1268ad2d8307Sdrh 12697c917d19Sdrh /* For every "*" that occurs in the column list, insert the names of 127054473229Sdrh ** all columns in all tables. And for every TABLE.* insert the names 127154473229Sdrh ** of all columns in TABLE. The parser inserted a special expression 12727c917d19Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 12737c917d19Sdrh ** The following code just has to locate the TK_ALL expressions and expand 12747c917d19Sdrh ** each one to the list of all columns in all tables. 127554473229Sdrh ** 127654473229Sdrh ** The first loop just checks to see if there are any "*" operators 127754473229Sdrh ** that need expanding. 1278d8bc7086Sdrh */ 12797c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 128054473229Sdrh Expr *pE = pEList->a[k].pExpr; 128154473229Sdrh if( pE->op==TK_ALL ) break; 128254473229Sdrh if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 128354473229Sdrh && pE->pLeft && pE->pLeft->op==TK_ID ) break; 12847c917d19Sdrh } 128554473229Sdrh rc = 0; 12867c917d19Sdrh if( k<pEList->nExpr ){ 128754473229Sdrh /* 128854473229Sdrh ** If we get here it means the result set contains one or more "*" 128954473229Sdrh ** operators that need to be expanded. Loop through each expression 129054473229Sdrh ** in the result set and expand them one by one. 129154473229Sdrh */ 12927c917d19Sdrh struct ExprList_item *a = pEList->a; 12937c917d19Sdrh ExprList *pNew = 0; 1294d70dc52dSdrh int flags = pParse->db->flags; 1295d70dc52dSdrh int longNames = (flags & SQLITE_FullColNames)!=0 && 1296d70dc52dSdrh (flags & SQLITE_ShortColNames)==0; 1297d70dc52dSdrh 12987c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 129954473229Sdrh Expr *pE = a[k].pExpr; 130054473229Sdrh if( pE->op!=TK_ALL && 130154473229Sdrh (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 130254473229Sdrh /* This particular expression does not need to be expanded. 130354473229Sdrh */ 13044adee20fSdanielk1977 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0); 1305261919ccSdanielk1977 if( pNew ){ 13067c917d19Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 1307261919ccSdanielk1977 }else{ 1308261919ccSdanielk1977 rc = 1; 1309261919ccSdanielk1977 } 13107c917d19Sdrh a[k].pExpr = 0; 13117c917d19Sdrh a[k].zName = 0; 13127c917d19Sdrh }else{ 131354473229Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 131454473229Sdrh ** expanded. */ 131554473229Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 1316cf55b7aeSdrh char *zTName; /* text of name of TABLE */ 131754473229Sdrh if( pE->op==TK_DOT && pE->pLeft ){ 1318cf55b7aeSdrh zTName = sqlite3NameFromToken(&pE->pLeft->token); 131954473229Sdrh }else{ 1320cf55b7aeSdrh zTName = 0; 132154473229Sdrh } 1322290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1323290c1948Sdrh Table *pTab = pFrom->pTab; 1324290c1948Sdrh char *zTabName = pFrom->zAlias; 132554473229Sdrh if( zTabName==0 || zTabName[0]==0 ){ 132654473229Sdrh zTabName = pTab->zName; 132754473229Sdrh } 1328cf55b7aeSdrh if( zTName && (zTabName==0 || zTabName[0]==0 || 1329cf55b7aeSdrh sqlite3StrICmp(zTName, zTabName)!=0) ){ 133054473229Sdrh continue; 133154473229Sdrh } 133254473229Sdrh tableSeen = 1; 1333d8bc7086Sdrh for(j=0; j<pTab->nCol; j++){ 1334f0113000Sdanielk1977 Expr *pExpr, *pRight; 1335ad2d8307Sdrh char *zName = pTab->aCol[j].zName; 1336ad2d8307Sdrh 1337034ca14fSdanielk1977 /* If a column is marked as 'hidden' (currently only possible 1338034ca14fSdanielk1977 ** for virtual tables), do not include it in the expanded 1339034ca14fSdanielk1977 ** result-set list. 1340034ca14fSdanielk1977 */ 1341034ca14fSdanielk1977 if( IsHiddenColumn(&pTab->aCol[j]) ){ 1342034ca14fSdanielk1977 assert(IsVirtual(pTab)); 1343034ca14fSdanielk1977 continue; 1344034ca14fSdanielk1977 } 1345034ca14fSdanielk1977 134691bb0eedSdrh if( i>0 ){ 134791bb0eedSdrh struct SrcList_item *pLeft = &pTabList->a[i-1]; 134861dfc31dSdrh if( (pLeft[1].jointype & JT_NATURAL)!=0 && 134991bb0eedSdrh columnIndex(pLeft->pTab, zName)>=0 ){ 1350ad2d8307Sdrh /* In a NATURAL join, omit the join columns from the 1351ad2d8307Sdrh ** table on the right */ 1352ad2d8307Sdrh continue; 1353ad2d8307Sdrh } 135461dfc31dSdrh if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){ 1355ad2d8307Sdrh /* In a join with a USING clause, omit columns in the 1356ad2d8307Sdrh ** using clause from the table on the right. */ 1357ad2d8307Sdrh continue; 1358ad2d8307Sdrh } 135991bb0eedSdrh } 13604adee20fSdanielk1977 pRight = sqlite3Expr(TK_ID, 0, 0, 0); 136122f70c32Sdrh if( pRight==0 ) break; 1362f3b863edSdanielk1977 setQuotedToken(&pRight->token, zName); 1363d70dc52dSdrh if( zTabName && (longNames || pTabList->nSrc>1) ){ 1364f0113000Sdanielk1977 Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, 0); 13654adee20fSdanielk1977 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0); 136622f70c32Sdrh if( pExpr==0 ) break; 1367f3b863edSdanielk1977 setQuotedToken(&pLeft->token, zTabName); 136891bb0eedSdrh setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName)); 13696977fea8Sdrh pExpr->span.dyn = 1; 13706977fea8Sdrh pExpr->token.z = 0; 13716977fea8Sdrh pExpr->token.n = 0; 13726977fea8Sdrh pExpr->token.dyn = 0; 137322f70c32Sdrh }else{ 137422f70c32Sdrh pExpr = pRight; 13756977fea8Sdrh pExpr->span = pExpr->token; 1376f3b863edSdanielk1977 pExpr->span.dyn = 0; 137722f70c32Sdrh } 1378d70dc52dSdrh if( longNames ){ 1379d70dc52dSdrh pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span); 1380d70dc52dSdrh }else{ 138179d5f63fSdrh pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token); 1382d8bc7086Sdrh } 1383d8bc7086Sdrh } 1384d70dc52dSdrh } 138554473229Sdrh if( !tableSeen ){ 1386cf55b7aeSdrh if( zTName ){ 1387cf55b7aeSdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 1388f5db2d3eSdrh }else{ 13894adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no tables specified"); 1390f5db2d3eSdrh } 139154473229Sdrh rc = 1; 139254473229Sdrh } 1393cf55b7aeSdrh sqliteFree(zTName); 13947c917d19Sdrh } 13957c917d19Sdrh } 13964adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 13977c917d19Sdrh p->pEList = pNew; 1398d8bc7086Sdrh } 1399e5c941b8Sdrh if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){ 1400e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 1401e5c941b8Sdrh rc = SQLITE_ERROR; 1402e5c941b8Sdrh } 1403f3b863edSdanielk1977 if( sqlite3MallocFailed() ){ 1404f3b863edSdanielk1977 rc = SQLITE_NOMEM; 1405f3b863edSdanielk1977 } 140654473229Sdrh return rc; 1407d8bc7086Sdrh } 1408d8bc7086Sdrh 140993758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1410ff78bd2fSdrh /* 1411d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with 1412d8bc7086Sdrh ** columns in a result. For each ORDER BY expression, the opcode of 1413967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of 1414d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable 1415d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter. 1416d8bc7086Sdrh ** 1417d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first. A match 1418d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT. 1419d8bc7086Sdrh ** 1420d8bc7086Sdrh ** Any entry that does not match is flagged as an error. The number 1421d8bc7086Sdrh ** of errors is returned. 1422d8bc7086Sdrh */ 1423d8bc7086Sdrh static int matchOrderbyToColumn( 1424d8bc7086Sdrh Parse *pParse, /* A place to leave error messages */ 1425d8bc7086Sdrh Select *pSelect, /* Match to result columns of this SELECT */ 1426d8bc7086Sdrh ExprList *pOrderBy, /* The ORDER BY values to match against columns */ 1427e4de1febSdrh int iTable, /* Insert this value in iTable */ 1428d8bc7086Sdrh int mustComplete /* If TRUE all ORDER BYs must match */ 1429d8bc7086Sdrh ){ 1430d8bc7086Sdrh int nErr = 0; 1431d8bc7086Sdrh int i, j; 1432d8bc7086Sdrh ExprList *pEList; 1433d8bc7086Sdrh 1434daffd0e5Sdrh if( pSelect==0 || pOrderBy==0 ) return 1; 1435d8bc7086Sdrh if( mustComplete ){ 1436d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } 1437d8bc7086Sdrh } 14389b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 1439d8bc7086Sdrh return 1; 1440d8bc7086Sdrh } 1441d8bc7086Sdrh if( pSelect->pPrior ){ 144292cd52f5Sdrh if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ 144392cd52f5Sdrh return 1; 144492cd52f5Sdrh } 1445d8bc7086Sdrh } 1446d8bc7086Sdrh pEList = pSelect->pEList; 1447d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 144894ccde58Sdrh struct ExprList_item *pItem; 1449d8bc7086Sdrh Expr *pE = pOrderBy->a[i].pExpr; 1450e4de1febSdrh int iCol = -1; 145194ccde58Sdrh char *zLabel; 145294ccde58Sdrh 1453d8bc7086Sdrh if( pOrderBy->a[i].done ) continue; 14544adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 1455e4de1febSdrh if( iCol<=0 || iCol>pEList->nExpr ){ 14564adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1457da93d238Sdrh "ORDER BY position %d should be between 1 and %d", 1458e4de1febSdrh iCol, pEList->nExpr); 1459e4de1febSdrh nErr++; 1460e4de1febSdrh break; 1461e4de1febSdrh } 1462fcb78a49Sdrh if( !mustComplete ) continue; 1463e4de1febSdrh iCol--; 1464e4de1febSdrh } 146594ccde58Sdrh if( iCol<0 && (zLabel = sqlite3NameFromToken(&pE->token))!=0 ){ 146694ccde58Sdrh for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){ 146794ccde58Sdrh char *zName; 14685ea2df91Sdrh int isMatch; 146994ccde58Sdrh if( pItem->zName ){ 147094ccde58Sdrh zName = sqlite3StrDup(pItem->zName); 147194ccde58Sdrh }else{ 147294ccde58Sdrh zName = sqlite3NameFromToken(&pItem->pExpr->token); 147394ccde58Sdrh } 14745ea2df91Sdrh isMatch = zName && sqlite3StrICmp(zName, zLabel)==0; 14755ea2df91Sdrh sqliteFree(zName); 14765ea2df91Sdrh if( isMatch ){ 1477e4de1febSdrh iCol = j; 147894ccde58Sdrh break; 147994ccde58Sdrh } 1480d8bc7086Sdrh } 14816e142f54Sdrh sqliteFree(zLabel); 1482d8bc7086Sdrh } 1483e4de1febSdrh if( iCol>=0 ){ 1484967e8b73Sdrh pE->op = TK_COLUMN; 1485e4de1febSdrh pE->iColumn = iCol; 1486d8bc7086Sdrh pE->iTable = iTable; 1487a58fdfb1Sdanielk1977 pE->iAgg = -1; 1488d8bc7086Sdrh pOrderBy->a[i].done = 1; 148994ccde58Sdrh }else if( mustComplete ){ 14904adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1491da93d238Sdrh "ORDER BY term number %d does not match any result column", i+1); 1492d8bc7086Sdrh nErr++; 1493d8bc7086Sdrh break; 1494d8bc7086Sdrh } 1495d8bc7086Sdrh } 1496d8bc7086Sdrh return nErr; 1497d8bc7086Sdrh } 149893758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */ 1499d8bc7086Sdrh 1500d8bc7086Sdrh /* 1501d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1502d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1503d8bc7086Sdrh */ 15044adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1505d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1506d8bc7086Sdrh if( v==0 ){ 15074adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1508d8bc7086Sdrh } 1509d8bc7086Sdrh return v; 1510d8bc7086Sdrh } 1511d8bc7086Sdrh 151215007a99Sdrh 1513d8bc7086Sdrh /* 15147b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1515ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 15167b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1517a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1518a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1519a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1520a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 15217b58daeaSdrh ** 1522d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1523ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 15247b58daeaSdrh ** iOffset should have been preset to appropriate default values 15257b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1526ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 15277b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 15287b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 15297b58daeaSdrh ** SELECT statements. 15307b58daeaSdrh */ 1531ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 153202afc861Sdrh Vdbe *v = 0; 153302afc861Sdrh int iLimit = 0; 153415007a99Sdrh int iOffset; 153515007a99Sdrh int addr1, addr2; 153615007a99Sdrh 15377b58daeaSdrh /* 15387b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 15397b58daeaSdrh ** contraversy about what the correct behavior should be. 15407b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 15417b58daeaSdrh ** no rows. 15427b58daeaSdrh */ 1543a2dc3b1aSdanielk1977 if( p->pLimit ){ 154415007a99Sdrh p->iLimit = iLimit = pParse->nMem; 1545d59ba6ceSdrh pParse->nMem += 2; 154615007a99Sdrh v = sqlite3GetVdbe(pParse); 15477b58daeaSdrh if( v==0 ) return; 1548a2dc3b1aSdanielk1977 sqlite3ExprCode(pParse, p->pLimit); 1549a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 15501e4eaeb5Sdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1); 1551ad6d9460Sdrh VdbeComment((v, "# LIMIT counter")); 155215007a99Sdrh sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak); 15531e4eaeb5Sdanielk1977 sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0); 15547b58daeaSdrh } 1555a2dc3b1aSdanielk1977 if( p->pOffset ){ 155615007a99Sdrh p->iOffset = iOffset = pParse->nMem++; 155715007a99Sdrh v = sqlite3GetVdbe(pParse); 15587b58daeaSdrh if( v==0 ) return; 1559a2dc3b1aSdanielk1977 sqlite3ExprCode(pParse, p->pOffset); 1560a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 156115007a99Sdrh sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0); 1562ad6d9460Sdrh VdbeComment((v, "# OFFSET counter")); 156315007a99Sdrh addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0); 156415007a99Sdrh sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 156515007a99Sdrh sqlite3VdbeAddOp(v, OP_Integer, 0, 0); 156615007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 1567d59ba6ceSdrh if( p->pLimit ){ 1568d59ba6ceSdrh sqlite3VdbeAddOp(v, OP_Add, 0, 0); 1569d59ba6ceSdrh } 15707b58daeaSdrh } 1571d59ba6ceSdrh if( p->pLimit ){ 157215007a99Sdrh addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0); 157315007a99Sdrh sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 157415007a99Sdrh sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1); 157515007a99Sdrh addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 157615007a99Sdrh sqlite3VdbeJumpHere(v, addr1); 157715007a99Sdrh sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1); 1578d59ba6ceSdrh VdbeComment((v, "# LIMIT+OFFSET")); 157915007a99Sdrh sqlite3VdbeJumpHere(v, addr2); 1580d59ba6ceSdrh } 15817b58daeaSdrh } 15827b58daeaSdrh 15837b58daeaSdrh /* 15840342b1f5Sdrh ** Allocate a virtual index to use for sorting. 1585d3d39e93Sdrh */ 15864db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){ 15870342b1f5Sdrh if( pOrderBy ){ 1588dc1bdc4fSdanielk1977 int addr; 15899d2985c7Sdrh assert( pOrderBy->iECursor==0 ); 15909d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 1591b9bb7c18Sdrh addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral, 15929d2985c7Sdrh pOrderBy->iECursor, pOrderBy->nExpr+1); 1593b9bb7c18Sdrh assert( p->addrOpenEphm[2] == -1 ); 1594b9bb7c18Sdrh p->addrOpenEphm[2] = addr; 1595736c22b8Sdrh } 1596dc1bdc4fSdanielk1977 } 1597dc1bdc4fSdanielk1977 1598b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1599fbc4ee7bSdrh /* 1600fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1601fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1602fbc4ee7bSdrh ** the column has no default collating sequence. 1603fbc4ee7bSdrh ** 1604fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1605fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1606fbc4ee7bSdrh */ 1607dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1608fbc4ee7bSdrh CollSeq *pRet; 1609dc1bdc4fSdanielk1977 if( p->pPrior ){ 1610dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1611fbc4ee7bSdrh }else{ 1612fbc4ee7bSdrh pRet = 0; 1613dc1bdc4fSdanielk1977 } 1614fbc4ee7bSdrh if( pRet==0 ){ 1615dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1616dc1bdc4fSdanielk1977 } 1617dc1bdc4fSdanielk1977 return pRet; 1618d3d39e93Sdrh } 1619b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1620d3d39e93Sdrh 1621b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1622d3d39e93Sdrh /* 162382c3d636Sdrh ** This routine is called to process a query that is really the union 162482c3d636Sdrh ** or intersection of two or more separate queries. 1625c926afbcSdrh ** 1626e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1627e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1628e78e8284Sdrh ** in which case this routine will be called recursively. 1629e78e8284Sdrh ** 1630e78e8284Sdrh ** The results of the total query are to be written into a destination 1631e78e8284Sdrh ** of type eDest with parameter iParm. 1632e78e8284Sdrh ** 1633e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1634e78e8284Sdrh ** 1635e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1636e78e8284Sdrh ** 1637e78e8284Sdrh ** This statement is parsed up as follows: 1638e78e8284Sdrh ** 1639e78e8284Sdrh ** SELECT c FROM t3 1640e78e8284Sdrh ** | 1641e78e8284Sdrh ** `-----> SELECT b FROM t2 1642e78e8284Sdrh ** | 16434b11c6d3Sjplyon ** `------> SELECT a FROM t1 1644e78e8284Sdrh ** 1645e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1646e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1647e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1648e78e8284Sdrh ** 1649e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1650e78e8284Sdrh ** individual selects always group from left to right. 165182c3d636Sdrh */ 165284ac9d02Sdanielk1977 static int multiSelect( 1653fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1654fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1655fbc4ee7bSdrh int eDest, /* \___ Store query results as specified */ 1656fbc4ee7bSdrh int iParm, /* / by these two parameters. */ 165784ac9d02Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 165884ac9d02Sdanielk1977 ){ 165984ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 166010e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 166110e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 16628cdbf836Sdrh int nCol; /* Number of columns in the result set */ 16630342b1f5Sdrh ExprList *pOrderBy; /* The ORDER BY clause on p */ 16640342b1f5Sdrh int aSetP2[2]; /* Set P2 value of these op to number of columns */ 16650342b1f5Sdrh int nSetP2 = 0; /* Number of slots in aSetP2[] used */ 166682c3d636Sdrh 16677b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1668fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 166982c3d636Sdrh */ 167084ac9d02Sdanielk1977 if( p==0 || p->pPrior==0 ){ 167184ac9d02Sdanielk1977 rc = 1; 167284ac9d02Sdanielk1977 goto multi_select_end; 167384ac9d02Sdanielk1977 } 1674d8bc7086Sdrh pPrior = p->pPrior; 16750342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 16760342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1677d8bc7086Sdrh if( pPrior->pOrderBy ){ 16784adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1679da93d238Sdrh selectOpName(p->op)); 168084ac9d02Sdanielk1977 rc = 1; 168184ac9d02Sdanielk1977 goto multi_select_end; 168282c3d636Sdrh } 1683a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 16844adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 16857b58daeaSdrh selectOpName(p->op)); 168684ac9d02Sdanielk1977 rc = 1; 168784ac9d02Sdanielk1977 goto multi_select_end; 16887b58daeaSdrh } 168982c3d636Sdrh 1690d8bc7086Sdrh /* Make sure we have a valid query engine. If not, create a new one. 1691d8bc7086Sdrh */ 16924adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 169384ac9d02Sdanielk1977 if( v==0 ){ 169484ac9d02Sdanielk1977 rc = 1; 169584ac9d02Sdanielk1977 goto multi_select_end; 169684ac9d02Sdanielk1977 } 1697d8bc7086Sdrh 16981cc3d75fSdrh /* Create the destination temporary table if necessary 16991cc3d75fSdrh */ 1700b9bb7c18Sdrh if( eDest==SRT_EphemTab ){ 1701b4964b72Sdanielk1977 assert( p->pEList ); 17020342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 1703b9bb7c18Sdrh aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0); 17041cc3d75fSdrh eDest = SRT_Table; 17051cc3d75fSdrh } 17061cc3d75fSdrh 1707f46f905aSdrh /* Generate code for the left and right SELECT statements. 1708d8bc7086Sdrh */ 17090342b1f5Sdrh pOrderBy = p->pOrderBy; 171082c3d636Sdrh switch( p->op ){ 1711f46f905aSdrh case TK_ALL: { 17120342b1f5Sdrh if( pOrderBy==0 ){ 1713ec7429aeSdrh int addr = 0; 1714a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1715a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1716a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 1717b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff); 1718ad68cb6bSdanielk1977 p->pLimit = 0; 1719ad68cb6bSdanielk1977 p->pOffset = 0; 172084ac9d02Sdanielk1977 if( rc ){ 172184ac9d02Sdanielk1977 goto multi_select_end; 172284ac9d02Sdanielk1977 } 1723f46f905aSdrh p->pPrior = 0; 17247b58daeaSdrh p->iLimit = pPrior->iLimit; 17257b58daeaSdrh p->iOffset = pPrior->iOffset; 1726ec7429aeSdrh if( p->iLimit>=0 ){ 1727ec7429aeSdrh addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0); 1728ec7429aeSdrh VdbeComment((v, "# Jump ahead if LIMIT reached")); 1729ec7429aeSdrh } 1730b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff); 1731f46f905aSdrh p->pPrior = pPrior; 173284ac9d02Sdanielk1977 if( rc ){ 173384ac9d02Sdanielk1977 goto multi_select_end; 173484ac9d02Sdanielk1977 } 1735ec7429aeSdrh if( addr ){ 1736ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1737ec7429aeSdrh } 1738f46f905aSdrh break; 1739f46f905aSdrh } 1740f46f905aSdrh /* For UNION ALL ... ORDER BY fall through to the next case */ 1741f46f905aSdrh } 174282c3d636Sdrh case TK_EXCEPT: 174382c3d636Sdrh case TK_UNION: { 1744d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1745742f947bSdanielk1977 int op = 0; /* One of the SRT_ operations to apply to self */ 1746d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1747a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1748dc1bdc4fSdanielk1977 int addr; 174982c3d636Sdrh 1750d8bc7086Sdrh priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 17510342b1f5Sdrh if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ 1752d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1753c926afbcSdrh ** right. 1754d8bc7086Sdrh */ 175582c3d636Sdrh unionTab = iParm; 175682c3d636Sdrh }else{ 1757d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1758d8bc7086Sdrh ** intermediate results. 1759d8bc7086Sdrh */ 176082c3d636Sdrh unionTab = pParse->nTab++; 17610342b1f5Sdrh if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){ 176284ac9d02Sdanielk1977 rc = 1; 176384ac9d02Sdanielk1977 goto multi_select_end; 1764d8bc7086Sdrh } 1765b9bb7c18Sdrh addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0); 17660342b1f5Sdrh if( priorOp==SRT_Table ){ 17670342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 17680342b1f5Sdrh aSetP2[nSetP2++] = addr; 17690342b1f5Sdrh }else{ 1770b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1771b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 1772b9bb7c18Sdrh p->pRightmost->usesEphm = 1; 1773dc1bdc4fSdanielk1977 } 17740342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 177584ac9d02Sdanielk1977 assert( p->pEList ); 1776d8bc7086Sdrh } 1777d8bc7086Sdrh 1778d8bc7086Sdrh /* Code the SELECT statements to our left 1779d8bc7086Sdrh */ 1780b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 1781b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); 178284ac9d02Sdanielk1977 if( rc ){ 178384ac9d02Sdanielk1977 goto multi_select_end; 178484ac9d02Sdanielk1977 } 1785d8bc7086Sdrh 1786d8bc7086Sdrh /* Code the current SELECT statement 1787d8bc7086Sdrh */ 1788d8bc7086Sdrh switch( p->op ){ 1789d8bc7086Sdrh case TK_EXCEPT: op = SRT_Except; break; 1790d8bc7086Sdrh case TK_UNION: op = SRT_Union; break; 1791d8bc7086Sdrh case TK_ALL: op = SRT_Table; break; 1792d8bc7086Sdrh } 179382c3d636Sdrh p->pPrior = 0; 1794c926afbcSdrh p->pOrderBy = 0; 17954b14b4d7Sdrh p->disallowOrderBy = pOrderBy!=0; 1796a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1797a2dc3b1aSdanielk1977 p->pLimit = 0; 1798a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1799a2dc3b1aSdanielk1977 p->pOffset = 0; 1800b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff); 18015bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 18025bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 18035bd1bf2eSdrh sqlite3ExprListDelete(p->pOrderBy); 180482c3d636Sdrh p->pPrior = pPrior; 1805c926afbcSdrh p->pOrderBy = pOrderBy; 1806a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 1807a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1808a2dc3b1aSdanielk1977 p->pOffset = pOffset; 1809be5fd490Sdrh p->iLimit = -1; 1810be5fd490Sdrh p->iOffset = -1; 181184ac9d02Sdanielk1977 if( rc ){ 181284ac9d02Sdanielk1977 goto multi_select_end; 181384ac9d02Sdanielk1977 } 181484ac9d02Sdanielk1977 1815d8bc7086Sdrh 1816d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1817d8bc7086Sdrh ** it is that we currently need. 1818d8bc7086Sdrh */ 1819c926afbcSdrh if( eDest!=priorOp || unionTab!=iParm ){ 18206b56344dSdrh int iCont, iBreak, iStart; 182182c3d636Sdrh assert( p->pEList ); 182241202ccaSdrh if( eDest==SRT_Callback ){ 182392378253Sdrh Select *pFirst = p; 182492378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 182592378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 182641202ccaSdrh } 18274adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 18284adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1829ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 18304adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); 18314adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 183238640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 18330342b1f5Sdrh pOrderBy, -1, eDest, iParm, 183484ac9d02Sdanielk1977 iCont, iBreak, 0); 183584ac9d02Sdanielk1977 if( rc ){ 183684ac9d02Sdanielk1977 rc = 1; 183784ac9d02Sdanielk1977 goto multi_select_end; 183884ac9d02Sdanielk1977 } 18394adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 18404adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); 18414adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 18424adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); 184382c3d636Sdrh } 184482c3d636Sdrh break; 184582c3d636Sdrh } 184682c3d636Sdrh case TK_INTERSECT: { 184782c3d636Sdrh int tab1, tab2; 18486b56344dSdrh int iCont, iBreak, iStart; 1849a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 1850dc1bdc4fSdanielk1977 int addr; 185182c3d636Sdrh 1852d8bc7086Sdrh /* INTERSECT is different from the others since it requires 18536206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1854d8bc7086Sdrh ** by allocating the tables we will need. 1855d8bc7086Sdrh */ 185682c3d636Sdrh tab1 = pParse->nTab++; 185782c3d636Sdrh tab2 = pParse->nTab++; 18580342b1f5Sdrh if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){ 185984ac9d02Sdanielk1977 rc = 1; 186084ac9d02Sdanielk1977 goto multi_select_end; 1861d8bc7086Sdrh } 18620342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 1863dc1bdc4fSdanielk1977 1864b9bb7c18Sdrh addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0); 1865b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 1866b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 1867b9bb7c18Sdrh p->pRightmost->usesEphm = 1; 186884ac9d02Sdanielk1977 assert( p->pEList ); 1869d8bc7086Sdrh 1870d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1871d8bc7086Sdrh */ 1872b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); 187384ac9d02Sdanielk1977 if( rc ){ 187484ac9d02Sdanielk1977 goto multi_select_end; 187584ac9d02Sdanielk1977 } 1876d8bc7086Sdrh 1877d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1878d8bc7086Sdrh */ 1879b9bb7c18Sdrh addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0); 1880b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 1881b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 188282c3d636Sdrh p->pPrior = 0; 1883a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1884a2dc3b1aSdanielk1977 p->pLimit = 0; 1885a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1886a2dc3b1aSdanielk1977 p->pOffset = 0; 1887b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); 188882c3d636Sdrh p->pPrior = pPrior; 1889a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 1890a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1891a2dc3b1aSdanielk1977 p->pOffset = pOffset; 189284ac9d02Sdanielk1977 if( rc ){ 189384ac9d02Sdanielk1977 goto multi_select_end; 189484ac9d02Sdanielk1977 } 1895d8bc7086Sdrh 1896d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1897d8bc7086Sdrh ** tables. 1898d8bc7086Sdrh */ 189982c3d636Sdrh assert( p->pEList ); 190041202ccaSdrh if( eDest==SRT_Callback ){ 190192378253Sdrh Select *pFirst = p; 190292378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 190392378253Sdrh generateColumnNames(pParse, 0, pFirst->pEList); 190441202ccaSdrh } 19054adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 19064adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1907ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 19084adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak); 19094a9f241cSdrh iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0); 19104adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont); 191138640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 19120342b1f5Sdrh pOrderBy, -1, eDest, iParm, 191384ac9d02Sdanielk1977 iCont, iBreak, 0); 191484ac9d02Sdanielk1977 if( rc ){ 191584ac9d02Sdanielk1977 rc = 1; 191684ac9d02Sdanielk1977 goto multi_select_end; 191784ac9d02Sdanielk1977 } 19184adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 19194adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); 19204adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 19214adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab2, 0); 19224adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab1, 0); 192382c3d636Sdrh break; 192482c3d636Sdrh } 192582c3d636Sdrh } 19268cdbf836Sdrh 19278cdbf836Sdrh /* Make sure all SELECTs in the statement have the same number of elements 19288cdbf836Sdrh ** in their result sets. 19298cdbf836Sdrh */ 193082c3d636Sdrh assert( p->pEList && pPrior->pEList ); 193182c3d636Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 19324adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1933da93d238Sdrh " do not have the same number of result columns", selectOpName(p->op)); 193484ac9d02Sdanielk1977 rc = 1; 193584ac9d02Sdanielk1977 goto multi_select_end; 19362282792aSdrh } 193784ac9d02Sdanielk1977 19388cdbf836Sdrh /* Set the number of columns in temporary tables 19398cdbf836Sdrh */ 19408cdbf836Sdrh nCol = p->pEList->nExpr; 19410342b1f5Sdrh while( nSetP2 ){ 19420342b1f5Sdrh sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol); 19438cdbf836Sdrh } 19448cdbf836Sdrh 1945fbc4ee7bSdrh /* Compute collating sequences used by either the ORDER BY clause or 1946fbc4ee7bSdrh ** by any temporary tables needed to implement the compound select. 1947fbc4ee7bSdrh ** Attach the KeyInfo structure to all temporary tables. Invoke the 1948fbc4ee7bSdrh ** ORDER BY processing if there is an ORDER BY clause. 19498cdbf836Sdrh ** 19508cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 19518cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 19528cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 19538cdbf836Sdrh ** no temp tables are required. 1954fbc4ee7bSdrh */ 1955b9bb7c18Sdrh if( pOrderBy || p->usesEphm ){ 1956fbc4ee7bSdrh int i; /* Loop counter */ 1957fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 19580342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 19591e31e0b2Sdrh int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */ 1960f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 1961f68d7d17Sdrh CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */ 1962fbc4ee7bSdrh 19630342b1f5Sdrh assert( p->pRightmost==p ); 19641e31e0b2Sdrh nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0); 19651e31e0b2Sdrh pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1)); 1966dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1967dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1968dc1bdc4fSdanielk1977 goto multi_select_end; 1969dc1bdc4fSdanielk1977 } 1970dc1bdc4fSdanielk1977 197114db2665Sdanielk1977 pKeyInfo->enc = ENC(pParse->db); 1972dc1bdc4fSdanielk1977 pKeyInfo->nField = nCol; 1973dc1bdc4fSdanielk1977 19740342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 19750342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 19760342b1f5Sdrh if( 0==*apColl ){ 19770342b1f5Sdrh *apColl = pParse->db->pDfltColl; 1978dc1bdc4fSdanielk1977 } 1979dc1bdc4fSdanielk1977 } 1980dc1bdc4fSdanielk1977 19810342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 19820342b1f5Sdrh for(i=0; i<2; i++){ 1983b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 19840342b1f5Sdrh if( addr<0 ){ 19850342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 19860342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 1987b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 19880342b1f5Sdrh break; 19890342b1f5Sdrh } 19900342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 19910342b1f5Sdrh sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO); 19920ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 19930342b1f5Sdrh } 1994dc1bdc4fSdanielk1977 } 1995dc1bdc4fSdanielk1977 19960342b1f5Sdrh if( pOrderBy ){ 19970342b1f5Sdrh struct ExprList_item *pOTerm = pOrderBy->a; 19984efc083fSdrh int nOrderByExpr = pOrderBy->nExpr; 19990342b1f5Sdrh int addr; 20004db38a70Sdrh u8 *pSortOrder; 20010342b1f5Sdrh 2002f68d7d17Sdrh /* Reuse the same pKeyInfo for the ORDER BY as was used above for 2003f68d7d17Sdrh ** the compound select statements. Except we have to change out the 2004f68d7d17Sdrh ** pKeyInfo->aColl[] values. Some of the aColl[] values will be 2005f68d7d17Sdrh ** reused when constructing the pKeyInfo for the ORDER BY, so make 2006f68d7d17Sdrh ** a copy. Sufficient space to hold both the nCol entries for 2007f68d7d17Sdrh ** the compound select and the nOrderbyExpr entries for the ORDER BY 2008f68d7d17Sdrh ** was allocated above. But we need to move the compound select 2009f68d7d17Sdrh ** entries out of the way before constructing the ORDER BY entries. 2010f68d7d17Sdrh ** Move the compound select entries into aCopy[] where they can be 2011f68d7d17Sdrh ** accessed and reused when constructing the ORDER BY entries. 2012f68d7d17Sdrh ** Because nCol might be greater than or less than nOrderByExpr 2013f68d7d17Sdrh ** we have to use memmove() when doing the copy. 2014f68d7d17Sdrh */ 20151e31e0b2Sdrh aCopy = &pKeyInfo->aColl[nOrderByExpr]; 20164efc083fSdrh pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol]; 2017f68d7d17Sdrh memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*)); 2018f68d7d17Sdrh 20190342b1f5Sdrh apColl = pKeyInfo->aColl; 20204efc083fSdrh for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){ 20210342b1f5Sdrh Expr *pExpr = pOTerm->pExpr; 20228b4c40d8Sdrh if( (pExpr->flags & EP_ExpCollate) ){ 20238b4c40d8Sdrh assert( pExpr->pColl!=0 ); 20248b4c40d8Sdrh *apColl = pExpr->pColl; 202584ac9d02Sdanielk1977 }else{ 20260342b1f5Sdrh *apColl = aCopy[pExpr->iColumn]; 202784ac9d02Sdanielk1977 } 20284db38a70Sdrh *pSortOrder = pOTerm->sortOrder; 202984ac9d02Sdanielk1977 } 20300342b1f5Sdrh assert( p->pRightmost==p ); 2031b9bb7c18Sdrh assert( p->addrOpenEphm[2]>=0 ); 2032b9bb7c18Sdrh addr = p->addrOpenEphm[2]; 2033a670b226Sdanielk1977 sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2); 20344efc083fSdrh pKeyInfo->nField = nOrderByExpr; 20354db38a70Sdrh sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 20364db38a70Sdrh pKeyInfo = 0; 2037cdd536f0Sdrh generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm); 2038dc1bdc4fSdanielk1977 } 2039dc1bdc4fSdanielk1977 2040dc1bdc4fSdanielk1977 sqliteFree(pKeyInfo); 2041dc1bdc4fSdanielk1977 } 2042dc1bdc4fSdanielk1977 2043dc1bdc4fSdanielk1977 multi_select_end: 204484ac9d02Sdanielk1977 return rc; 20452282792aSdrh } 2046b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 20472282792aSdrh 2048b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 20492282792aSdrh /* 2050832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 20516a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 205284e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 20536a3ea0e6Sdrh ** unchanged.) 2054832508b7Sdrh ** 2055832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 2056832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 2057832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 2058832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 2059832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 2060832508b7Sdrh ** of the subquery rather the result set of the subquery. 2061832508b7Sdrh */ 20626a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */ 2063b3bce662Sdanielk1977 static void substSelect(Select *, int, ExprList *); /* Forward Decl */ 20646a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){ 2065832508b7Sdrh if( pExpr==0 ) return; 206650350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 206750350a15Sdrh if( pExpr->iColumn<0 ){ 206850350a15Sdrh pExpr->op = TK_NULL; 206950350a15Sdrh }else{ 2070832508b7Sdrh Expr *pNew; 207184e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 2072832508b7Sdrh assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 2073832508b7Sdrh pNew = pEList->a[pExpr->iColumn].pExpr; 2074832508b7Sdrh assert( pNew!=0 ); 2075832508b7Sdrh pExpr->op = pNew->op; 2076d94a6698Sdrh assert( pExpr->pLeft==0 ); 20774adee20fSdanielk1977 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft); 2078d94a6698Sdrh assert( pExpr->pRight==0 ); 20794adee20fSdanielk1977 pExpr->pRight = sqlite3ExprDup(pNew->pRight); 2080d94a6698Sdrh assert( pExpr->pList==0 ); 20814adee20fSdanielk1977 pExpr->pList = sqlite3ExprListDup(pNew->pList); 2082832508b7Sdrh pExpr->iTable = pNew->iTable; 2083fbbe005aSdanielk1977 pExpr->pTab = pNew->pTab; 2084832508b7Sdrh pExpr->iColumn = pNew->iColumn; 2085832508b7Sdrh pExpr->iAgg = pNew->iAgg; 20864adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->token, &pNew->token); 20874adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->span, &pNew->span); 2088a1cb183dSdanielk1977 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect); 2089a1cb183dSdanielk1977 pExpr->flags = pNew->flags; 209050350a15Sdrh } 2091832508b7Sdrh }else{ 20926a3ea0e6Sdrh substExpr(pExpr->pLeft, iTable, pEList); 20936a3ea0e6Sdrh substExpr(pExpr->pRight, iTable, pEList); 2094b3bce662Sdanielk1977 substSelect(pExpr->pSelect, iTable, pEList); 20956a3ea0e6Sdrh substExprList(pExpr->pList, iTable, pEList); 2096832508b7Sdrh } 2097832508b7Sdrh } 2098b3bce662Sdanielk1977 static void substExprList(ExprList *pList, int iTable, ExprList *pEList){ 2099832508b7Sdrh int i; 2100832508b7Sdrh if( pList==0 ) return; 2101832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 21026a3ea0e6Sdrh substExpr(pList->a[i].pExpr, iTable, pEList); 2103832508b7Sdrh } 2104832508b7Sdrh } 2105b3bce662Sdanielk1977 static void substSelect(Select *p, int iTable, ExprList *pEList){ 2106b3bce662Sdanielk1977 if( !p ) return; 2107b3bce662Sdanielk1977 substExprList(p->pEList, iTable, pEList); 2108b3bce662Sdanielk1977 substExprList(p->pGroupBy, iTable, pEList); 2109b3bce662Sdanielk1977 substExprList(p->pOrderBy, iTable, pEList); 2110b3bce662Sdanielk1977 substExpr(p->pHaving, iTable, pEList); 2111b3bce662Sdanielk1977 substExpr(p->pWhere, iTable, pEList); 2112fa2bb6daSdanielk1977 substSelect(p->pPrior, iTable, pEList); 2113b3bce662Sdanielk1977 } 2114b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */ 2115832508b7Sdrh 2116b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 2117832508b7Sdrh /* 21181350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 21191350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 21201350b030Sdrh ** occurs. 21211350b030Sdrh ** 21221350b030Sdrh ** To understand the concept of flattening, consider the following 21231350b030Sdrh ** query: 21241350b030Sdrh ** 21251350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 21261350b030Sdrh ** 21271350b030Sdrh ** The default way of implementing this query is to execute the 21281350b030Sdrh ** subquery first and store the results in a temporary table, then 21291350b030Sdrh ** run the outer query on that temporary table. This requires two 21301350b030Sdrh ** passes over the data. Furthermore, because the temporary table 21311350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 2132832508b7Sdrh ** optimized. 21331350b030Sdrh ** 2134832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 21351350b030Sdrh ** a single flat select, like this: 21361350b030Sdrh ** 21371350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 21381350b030Sdrh ** 21391350b030Sdrh ** The code generated for this simpification gives the same result 2140832508b7Sdrh ** but only has to scan the data once. And because indices might 2141832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 2142832508b7Sdrh ** avoided. 21431350b030Sdrh ** 2144832508b7Sdrh ** Flattening is only attempted if all of the following are true: 21451350b030Sdrh ** 2146832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 21471350b030Sdrh ** 2148832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 2149832508b7Sdrh ** 21508af4d3acSdrh ** (3) The subquery is not the right operand of a left outer join, or 21518af4d3acSdrh ** the subquery is not itself a join. (Ticket #306) 2152832508b7Sdrh ** 2153832508b7Sdrh ** (4) The subquery is not DISTINCT or the outer query is not a join. 2154832508b7Sdrh ** 2155832508b7Sdrh ** (5) The subquery is not DISTINCT or the outer query does not use 2156832508b7Sdrh ** aggregates. 2157832508b7Sdrh ** 2158832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 2159832508b7Sdrh ** DISTINCT. 2160832508b7Sdrh ** 216108192d5fSdrh ** (7) The subquery has a FROM clause. 216208192d5fSdrh ** 2163df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 2164df199a25Sdrh ** 2165df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 2166df199a25Sdrh ** aggregates. 2167df199a25Sdrh ** 2168df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 2169df199a25Sdrh ** use LIMIT. 2170df199a25Sdrh ** 2171174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 2172174b6195Sdrh ** 21733fc673e6Sdrh ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 21743fc673e6Sdrh ** subquery has no WHERE clause. (added by ticket #350) 21753fc673e6Sdrh ** 2176ac83963aSdrh ** (13) The subquery and outer query do not both use LIMIT 2177ac83963aSdrh ** 2178ac83963aSdrh ** (14) The subquery does not use OFFSET 2179ac83963aSdrh ** 2180ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 2181ad91c6cdSdrh ** subquery does not have both an ORDER BY and a LIMIT clause. 2182ad91c6cdSdrh ** (See ticket #2339) 2183ad91c6cdSdrh ** 2184832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 2185832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 2186832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 2187832508b7Sdrh ** 2188665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 2189832508b7Sdrh ** If flattening is attempted this routine returns 1. 2190832508b7Sdrh ** 2191832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 2192832508b7Sdrh ** the subquery before this routine runs. 21931350b030Sdrh */ 21948c74a8caSdrh static int flattenSubquery( 21958c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 21968c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 21978c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 21988c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 21998c74a8caSdrh ){ 22000bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2201ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2202ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 22030bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 22046a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 220591bb0eedSdrh int i; /* Loop counter */ 220691bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 220791bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 22081350b030Sdrh 2209832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2210832508b7Sdrh */ 2211832508b7Sdrh if( p==0 ) return 0; 2212832508b7Sdrh pSrc = p->pSrc; 2213ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 221491bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 221591bb0eedSdrh pSub = pSubitem->pSelect; 2216832508b7Sdrh assert( pSub!=0 ); 2217ac83963aSdrh if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ 2218ac83963aSdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ 2219832508b7Sdrh pSubSrc = pSub->pSrc; 2220832508b7Sdrh assert( pSubSrc ); 2221ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 2222ac83963aSdrh ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET 2223ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 2224ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 2225ac83963aSdrh ** and (14). */ 2226ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 2227ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 2228ad91c6cdSdrh if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){ 2229ad91c6cdSdrh return 0; /* Restriction (15) */ 2230ad91c6cdSdrh } 2231ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 2232ac83963aSdrh if( (pSub->isDistinct || pSub->pLimit) 2233ac83963aSdrh && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */ 2234df199a25Sdrh return 0; 2235df199a25Sdrh } 2236ac83963aSdrh if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */ 2237ac83963aSdrh if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){ 2238ac83963aSdrh return 0; /* Restriction (11) */ 2239ac83963aSdrh } 2240832508b7Sdrh 22418af4d3acSdrh /* Restriction 3: If the subquery is a join, make sure the subquery is 22428af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 22438af4d3acSdrh ** is not allowed: 22448af4d3acSdrh ** 22458af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 22468af4d3acSdrh ** 22478af4d3acSdrh ** If we flatten the above, we would get 22488af4d3acSdrh ** 22498af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 22508af4d3acSdrh ** 22518af4d3acSdrh ** which is not at all the same thing. 22528af4d3acSdrh */ 225361dfc31dSdrh if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){ 22548af4d3acSdrh return 0; 22558af4d3acSdrh } 22568af4d3acSdrh 22573fc673e6Sdrh /* Restriction 12: If the subquery is the right operand of a left outer 22583fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 22593fc673e6Sdrh ** An examples of why this is not allowed: 22603fc673e6Sdrh ** 22613fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 22623fc673e6Sdrh ** 22633fc673e6Sdrh ** If we flatten the above, we would get 22643fc673e6Sdrh ** 22653fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 22663fc673e6Sdrh ** 22673fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 22683fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 22693fc673e6Sdrh */ 227061dfc31dSdrh if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){ 22713fc673e6Sdrh return 0; 22723fc673e6Sdrh } 22733fc673e6Sdrh 22740bb28106Sdrh /* If we reach this point, it means flattening is permitted for the 227563eb5f29Sdrh ** iFrom-th entry of the FROM clause in the outer query. 2276832508b7Sdrh */ 2277c31c2eb8Sdrh 2278c31c2eb8Sdrh /* Move all of the FROM elements of the subquery into the 2279c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2280c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2281c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2282c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2283c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2284c31c2eb8Sdrh ** elements we are now copying in. 2285c31c2eb8Sdrh */ 228691bb0eedSdrh iParent = pSubitem->iCursor; 2287c31c2eb8Sdrh { 2288c31c2eb8Sdrh int nSubSrc = pSubSrc->nSrc; 228991bb0eedSdrh int jointype = pSubitem->jointype; 2290c31c2eb8Sdrh 2291a04a34ffSdanielk1977 sqlite3DeleteTable(pSubitem->pTab); 229291bb0eedSdrh sqliteFree(pSubitem->zDatabase); 229391bb0eedSdrh sqliteFree(pSubitem->zName); 229491bb0eedSdrh sqliteFree(pSubitem->zAlias); 2295c31c2eb8Sdrh if( nSubSrc>1 ){ 2296c31c2eb8Sdrh int extra = nSubSrc - 1; 2297c31c2eb8Sdrh for(i=1; i<nSubSrc; i++){ 22984adee20fSdanielk1977 pSrc = sqlite3SrcListAppend(pSrc, 0, 0); 2299c31c2eb8Sdrh } 2300c31c2eb8Sdrh p->pSrc = pSrc; 2301c31c2eb8Sdrh for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 2302c31c2eb8Sdrh pSrc->a[i] = pSrc->a[i-extra]; 2303c31c2eb8Sdrh } 2304c31c2eb8Sdrh } 2305c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2306c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2307c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2308c31c2eb8Sdrh } 230961dfc31dSdrh pSrc->a[iFrom].jointype = jointype; 2310c31c2eb8Sdrh } 2311c31c2eb8Sdrh 2312c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2313c31c2eb8Sdrh ** references to the iParent in the outer query. 2314c31c2eb8Sdrh ** 2315c31c2eb8Sdrh ** Example: 2316c31c2eb8Sdrh ** 2317c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2318c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 2319c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 2320c31c2eb8Sdrh ** 2321c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 2322c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2323c31c2eb8Sdrh */ 2324832508b7Sdrh pList = p->pEList; 2325832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 23266977fea8Sdrh Expr *pExpr; 23276977fea8Sdrh if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 23282646da7eSdrh pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n); 2329832508b7Sdrh } 2330832508b7Sdrh } 2331643054c1Sdrh substExprList(p->pEList, iParent, pSub->pEList); 23321b2e0329Sdrh if( isAgg ){ 23336a3ea0e6Sdrh substExprList(p->pGroupBy, iParent, pSub->pEList); 23346a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 23351b2e0329Sdrh } 2336174b6195Sdrh if( pSub->pOrderBy ){ 2337174b6195Sdrh assert( p->pOrderBy==0 ); 2338174b6195Sdrh p->pOrderBy = pSub->pOrderBy; 2339174b6195Sdrh pSub->pOrderBy = 0; 2340174b6195Sdrh }else if( p->pOrderBy ){ 23416a3ea0e6Sdrh substExprList(p->pOrderBy, iParent, pSub->pEList); 2342174b6195Sdrh } 2343832508b7Sdrh if( pSub->pWhere ){ 23444adee20fSdanielk1977 pWhere = sqlite3ExprDup(pSub->pWhere); 2345832508b7Sdrh }else{ 2346832508b7Sdrh pWhere = 0; 2347832508b7Sdrh } 2348832508b7Sdrh if( subqueryIsAgg ){ 2349832508b7Sdrh assert( p->pHaving==0 ); 23501b2e0329Sdrh p->pHaving = p->pWhere; 23511b2e0329Sdrh p->pWhere = pWhere; 23526a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 235391bb0eedSdrh p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving)); 23541b2e0329Sdrh assert( p->pGroupBy==0 ); 23554adee20fSdanielk1977 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy); 2356832508b7Sdrh }else{ 23576a3ea0e6Sdrh substExpr(p->pWhere, iParent, pSub->pEList); 235891bb0eedSdrh p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere); 2359832508b7Sdrh } 2360c31c2eb8Sdrh 2361c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 2362c31c2eb8Sdrh ** outer query is distinct. 2363c31c2eb8Sdrh */ 2364832508b7Sdrh p->isDistinct = p->isDistinct || pSub->isDistinct; 23658c74a8caSdrh 2366a58fdfb1Sdanielk1977 /* 2367a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 2368ac83963aSdrh ** 2369ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 2370ac83963aSdrh ** does not work if either limit is negative. 2371a58fdfb1Sdanielk1977 */ 2372a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 2373a2dc3b1aSdanielk1977 p->pLimit = pSub->pLimit; 2374a2dc3b1aSdanielk1977 pSub->pLimit = 0; 2375df199a25Sdrh } 23768c74a8caSdrh 2377c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 2378c31c2eb8Sdrh ** success. 2379c31c2eb8Sdrh */ 23804adee20fSdanielk1977 sqlite3SelectDelete(pSub); 2381832508b7Sdrh return 1; 23821350b030Sdrh } 2383b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 23841350b030Sdrh 23851350b030Sdrh /* 23869562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it 23879562b551Sdrh ** is a simple min() or max() query. If it is and this query can be 23889562b551Sdrh ** satisfied using a single seek to the beginning or end of an index, 2389e78e8284Sdrh ** then generate the code for this SELECT and return 1. If this is not a 23909562b551Sdrh ** simple min() or max() query, then return 0; 23919562b551Sdrh ** 23929562b551Sdrh ** A simply min() or max() query looks like this: 23939562b551Sdrh ** 23949562b551Sdrh ** SELECT min(a) FROM table; 23959562b551Sdrh ** SELECT max(a) FROM table; 23969562b551Sdrh ** 23979562b551Sdrh ** The query may have only a single table in its FROM argument. There 23989562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses. The result set must 23999562b551Sdrh ** be the min() or max() of a single column of the table. The column 24009562b551Sdrh ** in the min() or max() function must be indexed. 24019562b551Sdrh ** 24024adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select(). 24039562b551Sdrh ** See the header comment on that routine for additional information. 24049562b551Sdrh */ 24059562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ 24069562b551Sdrh Expr *pExpr; 24079562b551Sdrh int iCol; 24089562b551Sdrh Table *pTab; 24099562b551Sdrh Index *pIdx; 24109562b551Sdrh int base; 24119562b551Sdrh Vdbe *v; 24129562b551Sdrh int seekOp; 24136e17529eSdrh ExprList *pEList, *pList, eList; 24149562b551Sdrh struct ExprList_item eListItem; 24156e17529eSdrh SrcList *pSrc; 2416ec7429aeSdrh int brk; 2417da184236Sdanielk1977 int iDb; 24186e17529eSdrh 24199562b551Sdrh /* Check to see if this query is a simple min() or max() query. Return 24209562b551Sdrh ** zero if it is not. 24219562b551Sdrh */ 24229562b551Sdrh if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; 24236e17529eSdrh pSrc = p->pSrc; 24246e17529eSdrh if( pSrc->nSrc!=1 ) return 0; 24256e17529eSdrh pEList = p->pEList; 24266e17529eSdrh if( pEList->nExpr!=1 ) return 0; 24276e17529eSdrh pExpr = pEList->a[0].pExpr; 24289562b551Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 24296e17529eSdrh pList = pExpr->pList; 24306e17529eSdrh if( pList==0 || pList->nExpr!=1 ) return 0; 24316977fea8Sdrh if( pExpr->token.n!=3 ) return 0; 24322646da7eSdrh if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ 24330bce8354Sdrh seekOp = OP_Rewind; 24342646da7eSdrh }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ 24350bce8354Sdrh seekOp = OP_Last; 24360bce8354Sdrh }else{ 24370bce8354Sdrh return 0; 24380bce8354Sdrh } 24396e17529eSdrh pExpr = pList->a[0].pExpr; 24409562b551Sdrh if( pExpr->op!=TK_COLUMN ) return 0; 24419562b551Sdrh iCol = pExpr->iColumn; 24426e17529eSdrh pTab = pSrc->a[0].pTab; 24439562b551Sdrh 2444a41c7497Sdanielk1977 /* This optimization cannot be used with virtual tables. */ 2445a41c7497Sdanielk1977 if( IsVirtual(pTab) ) return 0; 2446c00da105Sdanielk1977 24479562b551Sdrh /* If we get to here, it means the query is of the correct form. 244817f71934Sdrh ** Check to make sure we have an index and make pIdx point to the 244917f71934Sdrh ** appropriate index. If the min() or max() is on an INTEGER PRIMARY 245017f71934Sdrh ** key column, no index is necessary so set pIdx to NULL. If no 245117f71934Sdrh ** usable index is found, return 0. 24529562b551Sdrh */ 24539562b551Sdrh if( iCol<0 ){ 24549562b551Sdrh pIdx = 0; 24559562b551Sdrh }else{ 2456dc1bdc4fSdanielk1977 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr); 2457206f3d96Sdrh if( pColl==0 ) return 0; 24589562b551Sdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 24599562b551Sdrh assert( pIdx->nColumn>=1 ); 2460b3bf556eSdanielk1977 if( pIdx->aiColumn[0]==iCol && 2461b3bf556eSdanielk1977 0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){ 2462b3bf556eSdanielk1977 break; 2463b3bf556eSdanielk1977 } 24649562b551Sdrh } 24659562b551Sdrh if( pIdx==0 ) return 0; 24669562b551Sdrh } 24679562b551Sdrh 2468e5f50722Sdrh /* Identify column types if we will be using the callback. This 24699562b551Sdrh ** step is skipped if the output is going to a table or a memory cell. 2470e5f50722Sdrh ** The column names have already been generated in the calling function. 24719562b551Sdrh */ 24724adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 24739562b551Sdrh if( v==0 ) return 0; 24749562b551Sdrh 24750c37e630Sdrh /* If the output is destined for a temporary table, open that table. 24760c37e630Sdrh */ 2477b9bb7c18Sdrh if( eDest==SRT_EphemTab ){ 2478b9bb7c18Sdrh sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1); 24790c37e630Sdrh } 24800c37e630Sdrh 248117f71934Sdrh /* Generating code to find the min or the max. Basically all we have 248217f71934Sdrh ** to do is find the first or the last entry in the chosen index. If 248317f71934Sdrh ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first 248417f71934Sdrh ** or last entry in the main table. 24859562b551Sdrh */ 2486da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 2487b9bb7c18Sdrh assert( iDb>=0 || pTab->isEphem ); 2488da184236Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 2489c00da105Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 24906e17529eSdrh base = pSrc->a[0].iCursor; 2491ec7429aeSdrh brk = sqlite3VdbeMakeLabel(v); 2492ec7429aeSdrh computeLimitRegisters(pParse, p, brk); 24936e17529eSdrh if( pSrc->a[0].pSelect==0 ){ 2494c00da105Sdanielk1977 sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead); 24956e17529eSdrh } 24969562b551Sdrh if( pIdx==0 ){ 24974adee20fSdanielk1977 sqlite3VdbeAddOp(v, seekOp, base, 0); 24989562b551Sdrh }else{ 24993719d7f9Sdanielk1977 /* Even though the cursor used to open the index here is closed 25003719d7f9Sdanielk1977 ** as soon as a single value has been read from it, allocate it 25013719d7f9Sdanielk1977 ** using (pParse->nTab++) to prevent the cursor id from being 25023719d7f9Sdanielk1977 ** reused. This is important for statements of the form 25033719d7f9Sdanielk1977 ** "INSERT INTO x SELECT max() FROM x". 25043719d7f9Sdanielk1977 */ 25053719d7f9Sdanielk1977 int iIdx; 2506b3bf556eSdanielk1977 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); 25073719d7f9Sdanielk1977 iIdx = pParse->nTab++; 2508da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 2509da184236Sdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); 25103719d7f9Sdanielk1977 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, 2511b3bf556eSdanielk1977 (char*)pKey, P3_KEYINFO_HANDOFF); 25129eb516c0Sdrh if( seekOp==OP_Rewind ){ 2513f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_Null, 0, 0); 25141af3fdb4Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0); 25151af3fdb4Sdrh seekOp = OP_MoveGt; 25169eb516c0Sdrh } 2517*309be024Sdrh if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){ 2518*309be024Sdrh /* Ticket #2514: invert the seek operator if we are using 2519*309be024Sdrh ** a descending index. */ 2520*309be024Sdrh if( seekOp==OP_Last ){ 2521*309be024Sdrh seekOp = OP_Rewind; 2522*309be024Sdrh }else{ 2523*309be024Sdrh assert( seekOp==OP_MoveGt ); 2524*309be024Sdrh seekOp = OP_MoveLt; 2525*309be024Sdrh } 2526*309be024Sdrh } 25273719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, seekOp, iIdx, 0); 2528f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0); 25293719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); 25307cf6e4deSdrh sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 25319562b551Sdrh } 25325cf8e8c7Sdrh eList.nExpr = 1; 25335cf8e8c7Sdrh memset(&eListItem, 0, sizeof(eListItem)); 25345cf8e8c7Sdrh eList.a = &eListItem; 25355cf8e8c7Sdrh eList.a[0].pExpr = pExpr; 2536ec7429aeSdrh selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0); 2537ec7429aeSdrh sqlite3VdbeResolveLabel(v, brk); 25384adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, base, 0); 25396e17529eSdrh 25409562b551Sdrh return 1; 25419562b551Sdrh } 25429562b551Sdrh 25439562b551Sdrh /* 2544290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return 2545290c1948Sdrh ** the number of errors seen. 2546290c1948Sdrh ** 2547290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions. If any expression 2548290c1948Sdrh ** is an integer constant, then that expression is replaced by the 2549290c1948Sdrh ** corresponding entry in the result set. 2550290c1948Sdrh */ 2551290c1948Sdrh static int processOrderGroupBy( 2552b3bce662Sdanielk1977 NameContext *pNC, /* Name context of the SELECT statement. */ 2553290c1948Sdrh ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 2554290c1948Sdrh const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 2555290c1948Sdrh ){ 2556290c1948Sdrh int i; 2557b3bce662Sdanielk1977 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */ 2558b3bce662Sdanielk1977 Parse *pParse = pNC->pParse; /* The result set of the SELECT */ 2559b3bce662Sdanielk1977 assert( pEList ); 2560b3bce662Sdanielk1977 2561290c1948Sdrh if( pOrderBy==0 ) return 0; 2562e5c941b8Sdrh if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ 2563e5c941b8Sdrh sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 2564e5c941b8Sdrh return 1; 2565e5c941b8Sdrh } 2566290c1948Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 2567290c1948Sdrh int iCol; 2568290c1948Sdrh Expr *pE = pOrderBy->a[i].pExpr; 2569b3bce662Sdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 2570b3bce662Sdanielk1977 if( iCol>0 && iCol<=pEList->nExpr ){ 25718b4c40d8Sdrh CollSeq *pColl = pE->pColl; 25728b4c40d8Sdrh int flags = pE->flags & EP_ExpCollate; 2573290c1948Sdrh sqlite3ExprDelete(pE); 2574290c1948Sdrh pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr); 25758b4c40d8Sdrh if( pColl && flags ){ 25768b4c40d8Sdrh pE->pColl = pColl; 25778b4c40d8Sdrh pE->flags |= flags; 25788b4c40d8Sdrh } 2579b3bce662Sdanielk1977 }else{ 2580290c1948Sdrh sqlite3ErrorMsg(pParse, 2581290c1948Sdrh "%s BY column number %d out of range - should be " 2582290c1948Sdrh "between 1 and %d", zType, iCol, pEList->nExpr); 2583290c1948Sdrh return 1; 2584290c1948Sdrh } 2585290c1948Sdrh } 2586b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(pNC, pE) ){ 2587b3bce662Sdanielk1977 return 1; 2588b3bce662Sdanielk1977 } 2589290c1948Sdrh } 2590290c1948Sdrh return 0; 2591290c1948Sdrh } 2592290c1948Sdrh 2593290c1948Sdrh /* 2594b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the 2595b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved 2596b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext 2597b3bce662Sdanielk1977 ** of the parent SELECT. 2598b3bce662Sdanielk1977 */ 2599b3bce662Sdanielk1977 int sqlite3SelectResolve( 2600b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 2601b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 2602b3bce662Sdanielk1977 NameContext *pOuterNC /* The outer name context. May be NULL. */ 2603b3bce662Sdanielk1977 ){ 2604b3bce662Sdanielk1977 ExprList *pEList; /* Result set. */ 2605b3bce662Sdanielk1977 int i; /* For-loop variable used in multiple places */ 2606b3bce662Sdanielk1977 NameContext sNC; /* Local name-context */ 260713449892Sdrh ExprList *pGroupBy; /* The group by clause */ 2608b3bce662Sdanielk1977 2609b3bce662Sdanielk1977 /* If this routine has run before, return immediately. */ 2610b3bce662Sdanielk1977 if( p->isResolved ){ 2611b3bce662Sdanielk1977 assert( !pOuterNC ); 2612b3bce662Sdanielk1977 return SQLITE_OK; 2613b3bce662Sdanielk1977 } 2614b3bce662Sdanielk1977 p->isResolved = 1; 2615b3bce662Sdanielk1977 2616b3bce662Sdanielk1977 /* If there have already been errors, do nothing. */ 2617b3bce662Sdanielk1977 if( pParse->nErr>0 ){ 2618b3bce662Sdanielk1977 return SQLITE_ERROR; 2619b3bce662Sdanielk1977 } 2620b3bce662Sdanielk1977 2621b3bce662Sdanielk1977 /* Prepare the select statement. This call will allocate all cursors 2622b3bce662Sdanielk1977 ** required to handle the tables and subqueries in the FROM clause. 2623b3bce662Sdanielk1977 */ 2624b3bce662Sdanielk1977 if( prepSelectStmt(pParse, p) ){ 2625b3bce662Sdanielk1977 return SQLITE_ERROR; 2626b3bce662Sdanielk1977 } 2627b3bce662Sdanielk1977 2628a2dc3b1aSdanielk1977 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 2629a2dc3b1aSdanielk1977 ** are not allowed to refer to any names, so pass an empty NameContext. 2630a2dc3b1aSdanielk1977 */ 2631ffe07b2dSdrh memset(&sNC, 0, sizeof(sNC)); 2632b3bce662Sdanielk1977 sNC.pParse = pParse; 2633a2dc3b1aSdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pLimit) || 2634a2dc3b1aSdanielk1977 sqlite3ExprResolveNames(&sNC, p->pOffset) ){ 2635a2dc3b1aSdanielk1977 return SQLITE_ERROR; 2636a2dc3b1aSdanielk1977 } 2637a2dc3b1aSdanielk1977 2638a2dc3b1aSdanielk1977 /* Set up the local name-context to pass to ExprResolveNames() to 2639a2dc3b1aSdanielk1977 ** resolve the expression-list. 2640a2dc3b1aSdanielk1977 */ 2641a2dc3b1aSdanielk1977 sNC.allowAgg = 1; 2642a2dc3b1aSdanielk1977 sNC.pSrcList = p->pSrc; 2643a2dc3b1aSdanielk1977 sNC.pNext = pOuterNC; 2644b3bce662Sdanielk1977 2645b3bce662Sdanielk1977 /* Resolve names in the result set. */ 2646b3bce662Sdanielk1977 pEList = p->pEList; 2647b3bce662Sdanielk1977 if( !pEList ) return SQLITE_ERROR; 2648b3bce662Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 2649b3bce662Sdanielk1977 Expr *pX = pEList->a[i].pExpr; 2650b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pX) ){ 2651b3bce662Sdanielk1977 return SQLITE_ERROR; 2652b3bce662Sdanielk1977 } 2653b3bce662Sdanielk1977 } 2654b3bce662Sdanielk1977 2655b3bce662Sdanielk1977 /* If there are no aggregate functions in the result-set, and no GROUP BY 2656b3bce662Sdanielk1977 ** expression, do not allow aggregates in any of the other expressions. 2657b3bce662Sdanielk1977 */ 2658b3bce662Sdanielk1977 assert( !p->isAgg ); 265913449892Sdrh pGroupBy = p->pGroupBy; 266013449892Sdrh if( pGroupBy || sNC.hasAgg ){ 2661b3bce662Sdanielk1977 p->isAgg = 1; 2662b3bce662Sdanielk1977 }else{ 2663b3bce662Sdanielk1977 sNC.allowAgg = 0; 2664b3bce662Sdanielk1977 } 2665b3bce662Sdanielk1977 2666b3bce662Sdanielk1977 /* If a HAVING clause is present, then there must be a GROUP BY clause. 2667b3bce662Sdanielk1977 */ 266813449892Sdrh if( p->pHaving && !pGroupBy ){ 2669b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2670b3bce662Sdanielk1977 return SQLITE_ERROR; 2671b3bce662Sdanielk1977 } 2672b3bce662Sdanielk1977 2673b3bce662Sdanielk1977 /* Add the expression list to the name-context before parsing the 2674b3bce662Sdanielk1977 ** other expressions in the SELECT statement. This is so that 2675b3bce662Sdanielk1977 ** expressions in the WHERE clause (etc.) can refer to expressions by 2676b3bce662Sdanielk1977 ** aliases in the result set. 2677b3bce662Sdanielk1977 ** 2678b3bce662Sdanielk1977 ** Minor point: If this is the case, then the expression will be 2679b3bce662Sdanielk1977 ** re-evaluated for each reference to it. 2680b3bce662Sdanielk1977 */ 2681b3bce662Sdanielk1977 sNC.pEList = p->pEList; 2682b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pWhere) || 2683994c80afSdrh sqlite3ExprResolveNames(&sNC, p->pHaving) ){ 2684b3bce662Sdanielk1977 return SQLITE_ERROR; 2685b3bce662Sdanielk1977 } 2686994c80afSdrh if( p->pPrior==0 ){ 2687994c80afSdrh if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") || 2688994c80afSdrh processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){ 2689994c80afSdrh return SQLITE_ERROR; 2690994c80afSdrh } 2691994c80afSdrh } 2692b3bce662Sdanielk1977 26939afe689eSdanielk1977 if( sqlite3MallocFailed() ){ 26949afe689eSdanielk1977 return SQLITE_NOMEM; 26959afe689eSdanielk1977 } 26969afe689eSdanielk1977 269713449892Sdrh /* Make sure the GROUP BY clause does not contain aggregate functions. 269813449892Sdrh */ 269913449892Sdrh if( pGroupBy ){ 270013449892Sdrh struct ExprList_item *pItem; 270113449892Sdrh 270213449892Sdrh for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 270313449892Sdrh if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 270413449892Sdrh sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 270513449892Sdrh "the GROUP BY clause"); 270613449892Sdrh return SQLITE_ERROR; 270713449892Sdrh } 270813449892Sdrh } 270913449892Sdrh } 271013449892Sdrh 2711f6bbe022Sdrh /* If this is one SELECT of a compound, be sure to resolve names 2712f6bbe022Sdrh ** in the other SELECTs. 2713f6bbe022Sdrh */ 2714f6bbe022Sdrh if( p->pPrior ){ 2715f6bbe022Sdrh return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC); 2716f6bbe022Sdrh }else{ 2717b3bce662Sdanielk1977 return SQLITE_OK; 2718b3bce662Sdanielk1977 } 2719f6bbe022Sdrh } 2720b3bce662Sdanielk1977 2721b3bce662Sdanielk1977 /* 272213449892Sdrh ** Reset the aggregate accumulator. 272313449892Sdrh ** 272413449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 272513449892Sdrh ** intermediate results while calculating an aggregate. This 272613449892Sdrh ** routine simply stores NULLs in all of those memory cells. 2727b3bce662Sdanielk1977 */ 272813449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 272913449892Sdrh Vdbe *v = pParse->pVdbe; 273013449892Sdrh int i; 2731c99130fdSdrh struct AggInfo_func *pFunc; 273213449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 273313449892Sdrh return; 273413449892Sdrh } 273513449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 2736d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0); 273713449892Sdrh } 2738c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 2739d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0); 2740c99130fdSdrh if( pFunc->iDistinct>=0 ){ 2741c99130fdSdrh Expr *pE = pFunc->pExpr; 2742c99130fdSdrh if( pE->pList==0 || pE->pList->nExpr!=1 ){ 2743c99130fdSdrh sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " 2744c99130fdSdrh "by an expression"); 2745c99130fdSdrh pFunc->iDistinct = -1; 2746c99130fdSdrh }else{ 2747c99130fdSdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); 2748b9bb7c18Sdrh sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 2749c99130fdSdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 2750c99130fdSdrh } 2751c99130fdSdrh } 275213449892Sdrh } 2753b3bce662Sdanielk1977 } 2754b3bce662Sdanielk1977 2755b3bce662Sdanielk1977 /* 275613449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 275713449892Sdrh ** in the AggInfo structure. 2758b3bce662Sdanielk1977 */ 275913449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 276013449892Sdrh Vdbe *v = pParse->pVdbe; 276113449892Sdrh int i; 276213449892Sdrh struct AggInfo_func *pF; 276313449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 2764a10a34b8Sdrh ExprList *pList = pF->pExpr->pList; 2765a10a34b8Sdrh sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 2766a10a34b8Sdrh (void*)pF->pFunc, P3_FUNCDEF); 2767b3bce662Sdanielk1977 } 276813449892Sdrh } 276913449892Sdrh 277013449892Sdrh /* 277113449892Sdrh ** Update the accumulator memory cells for an aggregate based on 277213449892Sdrh ** the current cursor position. 277313449892Sdrh */ 277413449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 277513449892Sdrh Vdbe *v = pParse->pVdbe; 277613449892Sdrh int i; 277713449892Sdrh struct AggInfo_func *pF; 277813449892Sdrh struct AggInfo_col *pC; 277913449892Sdrh 278013449892Sdrh pAggInfo->directMode = 1; 278113449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 278213449892Sdrh int nArg; 2783c99130fdSdrh int addrNext = 0; 278413449892Sdrh ExprList *pList = pF->pExpr->pList; 278513449892Sdrh if( pList ){ 278613449892Sdrh nArg = pList->nExpr; 278713449892Sdrh sqlite3ExprCodeExprList(pParse, pList); 278813449892Sdrh }else{ 278913449892Sdrh nArg = 0; 279013449892Sdrh } 2791c99130fdSdrh if( pF->iDistinct>=0 ){ 2792c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 2793c99130fdSdrh assert( nArg==1 ); 2794f8875400Sdrh codeDistinct(v, pF->iDistinct, addrNext, 1); 2795c99130fdSdrh } 279613449892Sdrh if( pF->pFunc->needCollSeq ){ 279713449892Sdrh CollSeq *pColl = 0; 279813449892Sdrh struct ExprList_item *pItem; 279913449892Sdrh int j; 280043617e9aSdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */ 280143617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 280213449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 280313449892Sdrh } 280413449892Sdrh if( !pColl ){ 280513449892Sdrh pColl = pParse->db->pDfltColl; 280613449892Sdrh } 280713449892Sdrh sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); 280813449892Sdrh } 280913449892Sdrh sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF); 2810c99130fdSdrh if( addrNext ){ 2811c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 2812c99130fdSdrh } 281313449892Sdrh } 281413449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 28155774b806Sdrh sqlite3ExprCode(pParse, pC->pExpr); 281613449892Sdrh sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1); 281713449892Sdrh } 281813449892Sdrh pAggInfo->directMode = 0; 281913449892Sdrh } 282013449892Sdrh 2821b3bce662Sdanielk1977 2822b3bce662Sdanielk1977 /* 28239bb61fe7Sdrh ** Generate code for the given SELECT statement. 28249bb61fe7Sdrh ** 2825fef5208cSdrh ** The results are distributed in various ways depending on the 2826fef5208cSdrh ** value of eDest and iParm. 2827fef5208cSdrh ** 2828fef5208cSdrh ** eDest Value Result 2829fef5208cSdrh ** ------------ ------------------------------------------- 2830fef5208cSdrh ** SRT_Callback Invoke the callback for each row of the result. 2831fef5208cSdrh ** 2832fef5208cSdrh ** SRT_Mem Store first result in memory cell iParm 2833fef5208cSdrh ** 2834e014a838Sdanielk1977 ** SRT_Set Store results as keys of table iParm. 2835fef5208cSdrh ** 283682c3d636Sdrh ** SRT_Union Store results as a key in a temporary table iParm 283782c3d636Sdrh ** 28384b11c6d3Sjplyon ** SRT_Except Remove results from the temporary table iParm. 2839c4a3c779Sdrh ** 2840c4a3c779Sdrh ** SRT_Table Store results in temporary table iParm 28419bb61fe7Sdrh ** 2842e78e8284Sdrh ** The table above is incomplete. Additional eDist value have be added 2843e78e8284Sdrh ** since this comment was written. See the selectInnerLoop() function for 2844e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings. 2845e78e8284Sdrh ** 28469bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 28479bb61fe7Sdrh ** encountered, then an appropriate error message is left in 28489bb61fe7Sdrh ** pParse->zErrMsg. 28499bb61fe7Sdrh ** 28509bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 28519bb61fe7Sdrh ** calling function needs to do that. 28521b2e0329Sdrh ** 28531b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this 28541b2e0329Sdrh ** SELECT is a subquery. This routine may try to combine this SELECT 28551b2e0329Sdrh ** with its parent to form a single flat query. In so doing, it might 28561b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query. 28571b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it 28581b2e0329Sdrh ** can be changed. 2859e78e8284Sdrh ** 2860e78e8284Sdrh ** Example 1: The meaning of the pParent parameter. 2861e78e8284Sdrh ** 2862e78e8284Sdrh ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2863e78e8284Sdrh ** \ \_______ subquery _______/ / 2864e78e8284Sdrh ** \ / 2865e78e8284Sdrh ** \____________________ outer query ___________________/ 2866e78e8284Sdrh ** 2867e78e8284Sdrh ** This routine is called for the outer query first. For that call, 2868e78e8284Sdrh ** pParent will be NULL. During the processing of the outer query, this 2869e78e8284Sdrh ** routine is called recursively to handle the subquery. For the recursive 2870e78e8284Sdrh ** call, pParent will point to the outer query. Because the subquery is 2871e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will 2872e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.) 28739bb61fe7Sdrh */ 28744adee20fSdanielk1977 int sqlite3Select( 2875cce7d176Sdrh Parse *pParse, /* The parser context */ 28769bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 2877e78e8284Sdrh int eDest, /* How to dispose of the results */ 2878e78e8284Sdrh int iParm, /* A parameter used by the eDest disposal method */ 2879832508b7Sdrh Select *pParent, /* Another SELECT for which this is a sub-query */ 2880832508b7Sdrh int parentTab, /* Index in pParent->pSrc of this query */ 288184ac9d02Sdanielk1977 int *pParentAgg, /* True if pParent uses aggregate functions */ 2882b3bce662Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 2883cce7d176Sdrh ){ 288413449892Sdrh int i, j; /* Loop counters */ 288513449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 288613449892Sdrh Vdbe *v; /* The virtual machine under construction */ 2887b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 2888a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 2889ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 28909bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 28919bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 28922282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 28932282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 289419a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 289519a775c2Sdrh int distinct; /* Table to use for the distinct set */ 28961d83f052Sdrh int rc = 1; /* Value to return from this function */ 2897b9bb7c18Sdrh int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ 289813449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 2899ec7429aeSdrh int iEnd; /* Address of the end of the query */ 29009bb61fe7Sdrh 29019e12800dSdanielk1977 if( p==0 || sqlite3MallocFailed() || pParse->nErr ){ 29026f7adc8aSdrh return 1; 29036f7adc8aSdrh } 29044adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 290513449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 2906daffd0e5Sdrh 2907b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 290882c3d636Sdrh /* If there is are a sequence of queries, do the earlier ones first. 290982c3d636Sdrh */ 291082c3d636Sdrh if( p->pPrior ){ 29110342b1f5Sdrh if( p->pRightmost==0 ){ 29120342b1f5Sdrh Select *pLoop; 29130325d873Sdrh int cnt = 0; 29140325d873Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ 29150342b1f5Sdrh pLoop->pRightmost = p; 29160342b1f5Sdrh } 29170325d873Sdrh if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){ 29180325d873Sdrh sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); 29190325d873Sdrh return 1; 29200325d873Sdrh } 29210342b1f5Sdrh } 292284ac9d02Sdanielk1977 return multiSelect(pParse, p, eDest, iParm, aff); 292382c3d636Sdrh } 2924b7f9164eSdrh #endif 292582c3d636Sdrh 2926b3bce662Sdanielk1977 pOrderBy = p->pOrderBy; 292713449892Sdrh if( IgnorableOrderby(eDest) ){ 2928b3bce662Sdanielk1977 p->pOrderBy = 0; 2929b3bce662Sdanielk1977 } 2930b3bce662Sdanielk1977 if( sqlite3SelectResolve(pParse, p, 0) ){ 2931b3bce662Sdanielk1977 goto select_end; 2932b3bce662Sdanielk1977 } 2933b3bce662Sdanielk1977 p->pOrderBy = pOrderBy; 2934b3bce662Sdanielk1977 293582c3d636Sdrh /* Make local copies of the parameters for this query. 293682c3d636Sdrh */ 29379bb61fe7Sdrh pTabList = p->pSrc; 29389bb61fe7Sdrh pWhere = p->pWhere; 29392282792aSdrh pGroupBy = p->pGroupBy; 29402282792aSdrh pHaving = p->pHaving; 2941b3bce662Sdanielk1977 isAgg = p->isAgg; 294219a775c2Sdrh isDistinct = p->isDistinct; 2943b3bce662Sdanielk1977 pEList = p->pEList; 2944b3bce662Sdanielk1977 if( pEList==0 ) goto select_end; 29459bb61fe7Sdrh 29469bb61fe7Sdrh /* 29479bb61fe7Sdrh ** Do not even attempt to generate any code if we have already seen 29489bb61fe7Sdrh ** errors before this routine starts. 29499bb61fe7Sdrh */ 29501d83f052Sdrh if( pParse->nErr>0 ) goto select_end; 2951cce7d176Sdrh 29522282792aSdrh /* If writing to memory or generating a set 29532282792aSdrh ** only a single column may be output. 295419a775c2Sdrh */ 295593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 2956e305f43fSdrh if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ 29571d83f052Sdrh goto select_end; 295819a775c2Sdrh } 295993758c8dSdanielk1977 #endif 296019a775c2Sdrh 2961c926afbcSdrh /* ORDER BY is ignored for some destinations. 29622282792aSdrh */ 296313449892Sdrh if( IgnorableOrderby(eDest) ){ 2964acd4c695Sdrh pOrderBy = 0; 29652282792aSdrh } 29662282792aSdrh 2967d820cb1bSdrh /* Begin generating code. 2968d820cb1bSdrh */ 29694adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2970d820cb1bSdrh if( v==0 ) goto select_end; 2971d820cb1bSdrh 2972d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 2973d820cb1bSdrh */ 297451522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 2975ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 2976742f947bSdanielk1977 const char *zSavedAuthContext = 0; 2977c31c2eb8Sdrh int needRestoreContext; 297813449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 2979c31c2eb8Sdrh 29801787ccabSdanielk1977 if( pItem->pSelect==0 || pItem->isPopulated ) continue; 298113449892Sdrh if( pItem->zName!=0 ){ 29825cf590c1Sdrh zSavedAuthContext = pParse->zAuthContext; 298313449892Sdrh pParse->zAuthContext = pItem->zName; 2984c31c2eb8Sdrh needRestoreContext = 1; 2985c31c2eb8Sdrh }else{ 2986c31c2eb8Sdrh needRestoreContext = 0; 29875cf590c1Sdrh } 2988fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0 2989fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 2990fc976065Sdanielk1977 ** tree refered to by this, the parent select. The child select 2991fc976065Sdanielk1977 ** may contain expression trees of at most 2992fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 2993fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 2994fc976065Sdanielk1977 ** an exact limit. 2995fc976065Sdanielk1977 */ 2996fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 2997fc976065Sdanielk1977 #endif 2998b9bb7c18Sdrh sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab, 299913449892Sdrh pItem->iCursor, p, i, &isAgg, 0); 3000fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0 3001fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 3002fc976065Sdanielk1977 #endif 3003c31c2eb8Sdrh if( needRestoreContext ){ 30045cf590c1Sdrh pParse->zAuthContext = zSavedAuthContext; 30055cf590c1Sdrh } 3006832508b7Sdrh pTabList = p->pSrc; 3007832508b7Sdrh pWhere = p->pWhere; 300813449892Sdrh if( !IgnorableOrderby(eDest) ){ 3009832508b7Sdrh pOrderBy = p->pOrderBy; 3010acd4c695Sdrh } 3011832508b7Sdrh pGroupBy = p->pGroupBy; 3012832508b7Sdrh pHaving = p->pHaving; 3013832508b7Sdrh isDistinct = p->isDistinct; 30141b2e0329Sdrh } 301551522cd3Sdrh #endif 30161b2e0329Sdrh 30176e17529eSdrh /* Check for the special case of a min() or max() function by itself 30186e17529eSdrh ** in the result set. 30196e17529eSdrh */ 30206e17529eSdrh if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ 30216e17529eSdrh rc = 0; 30226e17529eSdrh goto select_end; 30236e17529eSdrh } 30246e17529eSdrh 30251b2e0329Sdrh /* Check to see if this is a subquery that can be "flattened" into its parent. 30261b2e0329Sdrh ** If flattening is a possiblity, do so and return immediately. 30271b2e0329Sdrh */ 3028b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 30291b2e0329Sdrh if( pParent && pParentAgg && 303074161705Sdrh flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){ 30311b2e0329Sdrh if( isAgg ) *pParentAgg = 1; 3032b3bce662Sdanielk1977 goto select_end; 30331b2e0329Sdrh } 3034b7f9164eSdrh #endif 3035832508b7Sdrh 30368b4c40d8Sdrh /* If there is an ORDER BY clause, then this sorting 30378b4c40d8Sdrh ** index might end up being unused if the data can be 30389d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 3039b9bb7c18Sdrh ** OP_OpenEphemeral instruction will be changed to an OP_Noop once 30409d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 30419d2985c7Sdrh ** variable is used to facilitate that change. 30427cedc8d4Sdanielk1977 */ 30437cedc8d4Sdanielk1977 if( pOrderBy ){ 30440342b1f5Sdrh KeyInfo *pKeyInfo; 30457cedc8d4Sdanielk1977 if( pParse->nErr ){ 30467cedc8d4Sdanielk1977 goto select_end; 30477cedc8d4Sdanielk1977 } 30480342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 30499d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 3050b9bb7c18Sdrh p->addrOpenEphm[2] = addrSortIndex = 30511e31e0b2Sdrh sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 30529d2985c7Sdrh }else{ 30539d2985c7Sdrh addrSortIndex = -1; 30547cedc8d4Sdanielk1977 } 30557cedc8d4Sdanielk1977 30562d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 30572d0794e3Sdrh */ 3058b9bb7c18Sdrh if( eDest==SRT_EphemTab ){ 3059b9bb7c18Sdrh sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr); 30602d0794e3Sdrh } 30612d0794e3Sdrh 3062f42bacc2Sdrh /* Set the limiter. 3063f42bacc2Sdrh */ 3064f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 3065f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 3066f42bacc2Sdrh 3067dece1a84Sdrh /* Open a virtual index to use for the distinct set. 3068cce7d176Sdrh */ 306919a775c2Sdrh if( isDistinct ){ 30700342b1f5Sdrh KeyInfo *pKeyInfo; 3071832508b7Sdrh distinct = pParse->nTab++; 30720342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 3073b9bb7c18Sdrh sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0, 30740342b1f5Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 3075832508b7Sdrh }else{ 3076832508b7Sdrh distinct = -1; 3077efb7251dSdrh } 3078832508b7Sdrh 307913449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 308013449892Sdrh if( !isAgg && pGroupBy==0 ){ 308113449892Sdrh /* This case is for non-aggregate queries 308213449892Sdrh ** Begin the database scan 3083832508b7Sdrh */ 308413449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy); 30851d83f052Sdrh if( pWInfo==0 ) goto select_end; 3086cce7d176Sdrh 3087b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 3088b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 30899d2985c7Sdrh ** into an OP_Noop. 30909d2985c7Sdrh */ 30919d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 3092f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortIndex, 1); 3093b9bb7c18Sdrh p->addrOpenEphm[2] = -1; 30949d2985c7Sdrh } 30959d2985c7Sdrh 309613449892Sdrh /* Use the standard inner loop 3097cce7d176Sdrh */ 3098df199a25Sdrh if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 309984ac9d02Sdanielk1977 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ 31001d83f052Sdrh goto select_end; 3101cce7d176Sdrh } 31022282792aSdrh 3103cce7d176Sdrh /* End the database scan loop. 3104cce7d176Sdrh */ 31054adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 310613449892Sdrh }else{ 310713449892Sdrh /* This is the processing for aggregate queries */ 310813449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 310913449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 311013449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 311113449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 311213449892Sdrh ** one row of the input to the aggregator has been 311313449892Sdrh ** processed */ 311413449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 311513449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 3116cce7d176Sdrh 311713449892Sdrh 311813449892Sdrh /* The following variables hold addresses or labels for parts of the 311913449892Sdrh ** virtual machine program we are putting together */ 312013449892Sdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 312113449892Sdrh int addrSetAbort; /* Set the abort flag and return */ 312213449892Sdrh int addrInitializeLoop; /* Start of code that initializes the input loop */ 312313449892Sdrh int addrTopOfLoop; /* Top of the input loop */ 312413449892Sdrh int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ 312513449892Sdrh int addrProcessRow; /* Code to process a single input row */ 312613449892Sdrh int addrEnd; /* End of all processing */ 3127b9bb7c18Sdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 3128e313382eSdrh int addrReset; /* Subroutine for resetting the accumulator */ 312913449892Sdrh 313013449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 313113449892Sdrh 313213449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 313313449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 313413449892Sdrh ** SELECT statement. 31352282792aSdrh */ 313613449892Sdrh memset(&sNC, 0, sizeof(sNC)); 313713449892Sdrh sNC.pParse = pParse; 313813449892Sdrh sNC.pSrcList = pTabList; 313913449892Sdrh sNC.pAggInfo = &sAggInfo; 314013449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 31419d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 314213449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){ 31431d83f052Sdrh goto select_end; 31442282792aSdrh } 314513449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){ 314613449892Sdrh goto select_end; 31472282792aSdrh } 314813449892Sdrh if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){ 314913449892Sdrh goto select_end; 315013449892Sdrh } 315113449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 315213449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 315313449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){ 315413449892Sdrh goto select_end; 315513449892Sdrh } 315613449892Sdrh } 31579e12800dSdanielk1977 if( sqlite3MallocFailed() ) goto select_end; 315813449892Sdrh 315913449892Sdrh /* Processing for aggregates with GROUP BY is very different and 316013449892Sdrh ** much more complex tha aggregates without a GROUP BY. 316113449892Sdrh */ 316213449892Sdrh if( pGroupBy ){ 316313449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 316413449892Sdrh 316513449892Sdrh /* Create labels that we will be needing 316613449892Sdrh */ 316713449892Sdrh 316813449892Sdrh addrInitializeLoop = sqlite3VdbeMakeLabel(v); 316913449892Sdrh addrGroupByChange = sqlite3VdbeMakeLabel(v); 317013449892Sdrh addrProcessRow = sqlite3VdbeMakeLabel(v); 317113449892Sdrh 317213449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 317313449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 3174b9bb7c18Sdrh ** that we do not need it after all, the OpenEphemeral instruction 317513449892Sdrh ** will be converted into a Noop. 317613449892Sdrh */ 317713449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 317813449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 317913449892Sdrh addrSortingIdx = 3180b9bb7c18Sdrh sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx, 318113449892Sdrh sAggInfo.nSortingColumn, 318213449892Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 318313449892Sdrh 318413449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 318513449892Sdrh */ 318613449892Sdrh iUseFlag = pParse->nMem++; 318713449892Sdrh iAbortFlag = pParse->nMem++; 318813449892Sdrh iAMem = pParse->nMem; 318913449892Sdrh pParse->nMem += pGroupBy->nExpr; 319013449892Sdrh iBMem = pParse->nMem; 319113449892Sdrh pParse->nMem += pGroupBy->nExpr; 3192d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag); 3193de29e3e9Sdrh VdbeComment((v, "# clear abort flag")); 3194d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag); 3195de29e3e9Sdrh VdbeComment((v, "# indicate accumulator empty")); 319613449892Sdrh sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop); 319713449892Sdrh 319813449892Sdrh /* Generate a subroutine that outputs a single row of the result 319913449892Sdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 320013449892Sdrh ** is less than or equal to zero, the subroutine is a no-op. If 320113449892Sdrh ** the processing calls for the query to abort, this subroutine 320213449892Sdrh ** increments the iAbortFlag memory location before returning in 320313449892Sdrh ** order to signal the caller to abort. 320413449892Sdrh */ 320513449892Sdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 3206de29e3e9Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag); 3207de29e3e9Sdrh VdbeComment((v, "# set abort flag")); 320813449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 320913449892Sdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 321013449892Sdrh sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2); 3211de29e3e9Sdrh VdbeComment((v, "# Groupby result generator entry point")); 321213449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 321313449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 321413449892Sdrh if( pHaving ){ 321513449892Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1); 321613449892Sdrh } 321713449892Sdrh rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 321813449892Sdrh distinct, eDest, iParm, 321913449892Sdrh addrOutputRow+1, addrSetAbort, aff); 322013449892Sdrh if( rc ){ 322113449892Sdrh goto select_end; 322213449892Sdrh } 322313449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 3224de29e3e9Sdrh VdbeComment((v, "# end groupby result generator")); 322513449892Sdrh 3226e313382eSdrh /* Generate a subroutine that will reset the group-by accumulator 3227e313382eSdrh */ 3228e313382eSdrh addrReset = sqlite3VdbeCurrentAddr(v); 3229e313382eSdrh resetAccumulator(pParse, &sAggInfo); 3230e313382eSdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 3231e313382eSdrh 323213449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 323313449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 323413449892Sdrh ** it might be a single loop that uses an index to extract information 323513449892Sdrh ** in the right order to begin with. 323613449892Sdrh */ 323713449892Sdrh sqlite3VdbeResolveLabel(v, addrInitializeLoop); 3238e313382eSdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); 323913449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy); 32405360ad34Sdrh if( pWInfo==0 ) goto select_end; 324113449892Sdrh if( pGroupBy==0 ){ 324213449892Sdrh /* The optimizer is able to deliver rows in group by order so 3243b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 324413449892Sdrh ** cancelled later because we still need to use the pKeyInfo 324513449892Sdrh */ 324613449892Sdrh pGroupBy = p->pGroupBy; 324713449892Sdrh groupBySort = 0; 324813449892Sdrh }else{ 324913449892Sdrh /* Rows are coming out in undetermined order. We have to push 325013449892Sdrh ** each row into a sorting index, terminate the first loop, 325113449892Sdrh ** then loop over the sorting index in order to get the output 325213449892Sdrh ** in sorted order 325313449892Sdrh */ 325413449892Sdrh groupBySort = 1; 325513449892Sdrh sqlite3ExprCodeExprList(pParse, pGroupBy); 325613449892Sdrh sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0); 325713449892Sdrh j = pGroupBy->nExpr+1; 325813449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 325913449892Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 326013449892Sdrh if( pCol->iSorterColumn<j ) continue; 3261945498f3Sdrh sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable); 326213449892Sdrh j++; 326313449892Sdrh } 326413449892Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0); 326513449892Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0); 326613449892Sdrh sqlite3WhereEnd(pWInfo); 326797571957Sdrh sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); 3268de29e3e9Sdrh VdbeComment((v, "# GROUP BY sort")); 326913449892Sdrh sAggInfo.useSortingIdx = 1; 327013449892Sdrh } 327113449892Sdrh 327213449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 327313449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 327413449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 327513449892Sdrh ** from the previous row currently stored in a0, a1, a2... 327613449892Sdrh */ 327713449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 327813449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 327913449892Sdrh if( groupBySort ){ 328013449892Sdrh sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j); 328113449892Sdrh }else{ 328213449892Sdrh sAggInfo.directMode = 1; 328313449892Sdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr); 328413449892Sdrh } 328513449892Sdrh sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1); 328613449892Sdrh } 328713449892Sdrh for(j=pGroupBy->nExpr-1; j>=0; j--){ 328813449892Sdrh if( j<pGroupBy->nExpr-1 ){ 328913449892Sdrh sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0); 329013449892Sdrh } 329113449892Sdrh sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0); 329213449892Sdrh if( j==0 ){ 3293e313382eSdrh sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow); 329413449892Sdrh }else{ 32954f686238Sdrh sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange); 329613449892Sdrh } 329713449892Sdrh sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ); 329813449892Sdrh } 329913449892Sdrh 330013449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 330113449892Sdrh ** Change in the GROUP BY are detected by the previous code 330213449892Sdrh ** block. If there were no changes, this block is skipped. 330313449892Sdrh ** 330413449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 330513449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 330613449892Sdrh ** and resets the aggregate accumulator registers in preparation 330713449892Sdrh ** for the next GROUP BY batch. 330813449892Sdrh */ 330913449892Sdrh sqlite3VdbeResolveLabel(v, addrGroupByChange); 331013449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 3311d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j); 331213449892Sdrh } 331313449892Sdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); 3314de29e3e9Sdrh VdbeComment((v, "# output one row")); 331513449892Sdrh sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd); 3316de29e3e9Sdrh VdbeComment((v, "# check abort flag")); 3317e313382eSdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); 3318de29e3e9Sdrh VdbeComment((v, "# reset accumulator")); 331913449892Sdrh 332013449892Sdrh /* Update the aggregate accumulators based on the content of 332113449892Sdrh ** the current row 332213449892Sdrh */ 332313449892Sdrh sqlite3VdbeResolveLabel(v, addrProcessRow); 332413449892Sdrh updateAccumulator(pParse, &sAggInfo); 3325de29e3e9Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag); 3326de29e3e9Sdrh VdbeComment((v, "# indicate data in accumulator")); 332713449892Sdrh 332813449892Sdrh /* End of the loop 332913449892Sdrh */ 333013449892Sdrh if( groupBySort ){ 333113449892Sdrh sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); 333213449892Sdrh }else{ 333313449892Sdrh sqlite3WhereEnd(pWInfo); 3334f8875400Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); 333513449892Sdrh } 333613449892Sdrh 333713449892Sdrh /* Output the final row of result 333813449892Sdrh */ 333913449892Sdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); 3340de29e3e9Sdrh VdbeComment((v, "# output final row")); 334113449892Sdrh 334213449892Sdrh } /* endif pGroupBy */ 334313449892Sdrh else { 334413449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 334513449892Sdrh ** processing is much simpler since there is only a single row 334613449892Sdrh ** of output. 334713449892Sdrh */ 334813449892Sdrh resetAccumulator(pParse, &sAggInfo); 334913449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); 33505360ad34Sdrh if( pWInfo==0 ) goto select_end; 335113449892Sdrh updateAccumulator(pParse, &sAggInfo); 335213449892Sdrh sqlite3WhereEnd(pWInfo); 335313449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 335413449892Sdrh pOrderBy = 0; 33555774b806Sdrh if( pHaving ){ 33565774b806Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1); 33575774b806Sdrh } 335813449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 335913449892Sdrh eDest, iParm, addrEnd, addrEnd, aff); 336013449892Sdrh } 336113449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 336213449892Sdrh 336313449892Sdrh } /* endif aggregate query */ 33642282792aSdrh 3365cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 3366cce7d176Sdrh ** and send them to the callback one by one. 3367cce7d176Sdrh */ 3368cce7d176Sdrh if( pOrderBy ){ 3369cdd536f0Sdrh generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm); 3370cce7d176Sdrh } 33716a535340Sdrh 337293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 3373f620b4e2Sdrh /* If this was a subquery, we have now converted the subquery into a 33741787ccabSdanielk1977 ** temporary table. So set the SrcList_item.isPopulated flag to prevent 33751787ccabSdanielk1977 ** this subquery from being evaluated again and to force the use of 33761787ccabSdanielk1977 ** the temporary table. 3377f620b4e2Sdrh */ 3378f620b4e2Sdrh if( pParent ){ 3379f620b4e2Sdrh assert( pParent->pSrc->nSrc>parentTab ); 3380f620b4e2Sdrh assert( pParent->pSrc->a[parentTab].pSelect==p ); 33811787ccabSdanielk1977 pParent->pSrc->a[parentTab].isPopulated = 1; 3382f620b4e2Sdrh } 338393758c8dSdanielk1977 #endif 3384f620b4e2Sdrh 3385ec7429aeSdrh /* Jump here to skip this query 3386ec7429aeSdrh */ 3387ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 3388ec7429aeSdrh 33891d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 33901d83f052Sdrh ** to indicate no errors. 33911d83f052Sdrh */ 33921d83f052Sdrh rc = 0; 33931d83f052Sdrh 33941d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 33951d83f052Sdrh ** successful coding of the SELECT. 33961d83f052Sdrh */ 33971d83f052Sdrh select_end: 3398955de52cSdanielk1977 3399955de52cSdanielk1977 /* Identify column names if we will be using them in a callback. This 3400955de52cSdanielk1977 ** step is skipped if the output is going to some other destination. 3401955de52cSdanielk1977 */ 3402955de52cSdanielk1977 if( rc==SQLITE_OK && eDest==SRT_Callback ){ 3403955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 3404955de52cSdanielk1977 } 3405955de52cSdanielk1977 340613449892Sdrh sqliteFree(sAggInfo.aCol); 340713449892Sdrh sqliteFree(sAggInfo.aFunc); 34081d83f052Sdrh return rc; 3409cce7d176Sdrh } 3410485f0039Sdrh 341177a2a5e7Sdrh #if defined(SQLITE_DEBUG) 3412485f0039Sdrh /* 3413485f0039Sdrh ******************************************************************************* 3414485f0039Sdrh ** The following code is used for testing and debugging only. The code 3415485f0039Sdrh ** that follows does not appear in normal builds. 3416485f0039Sdrh ** 3417485f0039Sdrh ** These routines are used to print out the content of all or part of a 3418485f0039Sdrh ** parse structures such as Select or Expr. Such printouts are useful 3419485f0039Sdrh ** for helping to understand what is happening inside the code generator 3420485f0039Sdrh ** during the execution of complex SELECT statements. 3421485f0039Sdrh ** 3422485f0039Sdrh ** These routine are not called anywhere from within the normal 3423485f0039Sdrh ** code base. Then are intended to be called from within the debugger 3424485f0039Sdrh ** or from temporary "printf" statements inserted for debugging. 3425485f0039Sdrh */ 3426485f0039Sdrh void sqlite3PrintExpr(Expr *p){ 3427485f0039Sdrh if( p->token.z && p->token.n>0 ){ 3428485f0039Sdrh sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z); 3429485f0039Sdrh }else{ 3430485f0039Sdrh sqlite3DebugPrintf("(%d", p->op); 3431485f0039Sdrh } 3432485f0039Sdrh if( p->pLeft ){ 3433485f0039Sdrh sqlite3DebugPrintf(" "); 3434485f0039Sdrh sqlite3PrintExpr(p->pLeft); 3435485f0039Sdrh } 3436485f0039Sdrh if( p->pRight ){ 3437485f0039Sdrh sqlite3DebugPrintf(" "); 3438485f0039Sdrh sqlite3PrintExpr(p->pRight); 3439485f0039Sdrh } 3440485f0039Sdrh sqlite3DebugPrintf(")"); 3441485f0039Sdrh } 3442485f0039Sdrh void sqlite3PrintExprList(ExprList *pList){ 3443485f0039Sdrh int i; 3444485f0039Sdrh for(i=0; i<pList->nExpr; i++){ 3445485f0039Sdrh sqlite3PrintExpr(pList->a[i].pExpr); 3446485f0039Sdrh if( i<pList->nExpr-1 ){ 3447485f0039Sdrh sqlite3DebugPrintf(", "); 3448485f0039Sdrh } 3449485f0039Sdrh } 3450485f0039Sdrh } 3451485f0039Sdrh void sqlite3PrintSelect(Select *p, int indent){ 3452485f0039Sdrh sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p); 3453485f0039Sdrh sqlite3PrintExprList(p->pEList); 3454485f0039Sdrh sqlite3DebugPrintf("\n"); 3455485f0039Sdrh if( p->pSrc ){ 3456485f0039Sdrh char *zPrefix; 3457485f0039Sdrh int i; 3458485f0039Sdrh zPrefix = "FROM"; 3459485f0039Sdrh for(i=0; i<p->pSrc->nSrc; i++){ 3460485f0039Sdrh struct SrcList_item *pItem = &p->pSrc->a[i]; 3461485f0039Sdrh sqlite3DebugPrintf("%*s ", indent+6, zPrefix); 3462485f0039Sdrh zPrefix = ""; 3463485f0039Sdrh if( pItem->pSelect ){ 3464485f0039Sdrh sqlite3DebugPrintf("(\n"); 3465485f0039Sdrh sqlite3PrintSelect(pItem->pSelect, indent+10); 3466485f0039Sdrh sqlite3DebugPrintf("%*s)", indent+8, ""); 3467485f0039Sdrh }else if( pItem->zName ){ 3468485f0039Sdrh sqlite3DebugPrintf("%s", pItem->zName); 3469485f0039Sdrh } 3470485f0039Sdrh if( pItem->pTab ){ 3471485f0039Sdrh sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName); 3472485f0039Sdrh } 3473485f0039Sdrh if( pItem->zAlias ){ 3474485f0039Sdrh sqlite3DebugPrintf(" AS %s", pItem->zAlias); 3475485f0039Sdrh } 3476485f0039Sdrh if( i<p->pSrc->nSrc-1 ){ 3477485f0039Sdrh sqlite3DebugPrintf(","); 3478485f0039Sdrh } 3479485f0039Sdrh sqlite3DebugPrintf("\n"); 3480485f0039Sdrh } 3481485f0039Sdrh } 3482485f0039Sdrh if( p->pWhere ){ 3483485f0039Sdrh sqlite3DebugPrintf("%*s WHERE ", indent, ""); 3484485f0039Sdrh sqlite3PrintExpr(p->pWhere); 3485485f0039Sdrh sqlite3DebugPrintf("\n"); 3486485f0039Sdrh } 3487485f0039Sdrh if( p->pGroupBy ){ 3488485f0039Sdrh sqlite3DebugPrintf("%*s GROUP BY ", indent, ""); 3489485f0039Sdrh sqlite3PrintExprList(p->pGroupBy); 3490485f0039Sdrh sqlite3DebugPrintf("\n"); 3491485f0039Sdrh } 3492485f0039Sdrh if( p->pHaving ){ 3493485f0039Sdrh sqlite3DebugPrintf("%*s HAVING ", indent, ""); 3494485f0039Sdrh sqlite3PrintExpr(p->pHaving); 3495485f0039Sdrh sqlite3DebugPrintf("\n"); 3496485f0039Sdrh } 3497485f0039Sdrh if( p->pOrderBy ){ 3498485f0039Sdrh sqlite3DebugPrintf("%*s ORDER BY ", indent, ""); 3499485f0039Sdrh sqlite3PrintExprList(p->pOrderBy); 3500485f0039Sdrh sqlite3DebugPrintf("\n"); 3501485f0039Sdrh } 3502485f0039Sdrh } 3503485f0039Sdrh /* End of the structure debug printing code 3504485f0039Sdrh *****************************************************************************/ 3505485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ 3506