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*ffe07b2dSdrh ** $Id: select.c,v 1.278 2005/11/03 00:41:17 drh Exp $ 16cce7d176Sdrh */ 17cce7d176Sdrh #include "sqliteInt.h" 18cce7d176Sdrh 19315555caSdrh 20cce7d176Sdrh /* 219bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 229bb61fe7Sdrh ** structure. 23cce7d176Sdrh */ 244adee20fSdanielk1977 Select *sqlite3SelectNew( 25daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 26ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 27daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 28daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 29daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 30daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 319bbca4c1Sdrh int isDistinct, /* true if the DISTINCT keyword is present */ 32a2dc3b1aSdanielk1977 Expr *pLimit, /* LIMIT value. NULL means not used */ 33a2dc3b1aSdanielk1977 Expr *pOffset /* OFFSET value. NULL means no offset */ 349bb61fe7Sdrh ){ 359bb61fe7Sdrh Select *pNew; 369bb61fe7Sdrh pNew = sqliteMalloc( sizeof(*pNew) ); 37a2dc3b1aSdanielk1977 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */ 38daffd0e5Sdrh if( pNew==0 ){ 394adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 404adee20fSdanielk1977 sqlite3SrcListDelete(pSrc); 414adee20fSdanielk1977 sqlite3ExprDelete(pWhere); 424adee20fSdanielk1977 sqlite3ExprListDelete(pGroupBy); 434adee20fSdanielk1977 sqlite3ExprDelete(pHaving); 444adee20fSdanielk1977 sqlite3ExprListDelete(pOrderBy); 45a2dc3b1aSdanielk1977 sqlite3ExprDelete(pLimit); 46a2dc3b1aSdanielk1977 sqlite3ExprDelete(pOffset); 47daffd0e5Sdrh }else{ 48b733d037Sdrh if( pEList==0 ){ 494adee20fSdanielk1977 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0); 50b733d037Sdrh } 519bb61fe7Sdrh pNew->pEList = pEList; 529bb61fe7Sdrh pNew->pSrc = pSrc; 539bb61fe7Sdrh pNew->pWhere = pWhere; 549bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 559bb61fe7Sdrh pNew->pHaving = pHaving; 569bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 579bb61fe7Sdrh pNew->isDistinct = isDistinct; 5882c3d636Sdrh pNew->op = TK_SELECT; 59a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 60a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 617b58daeaSdrh pNew->iLimit = -1; 627b58daeaSdrh pNew->iOffset = -1; 630342b1f5Sdrh pNew->addrOpenVirt[0] = -1; 640342b1f5Sdrh pNew->addrOpenVirt[1] = -1; 650342b1f5Sdrh pNew->addrOpenVirt[2] = -1; 66daffd0e5Sdrh } 679bb61fe7Sdrh return pNew; 689bb61fe7Sdrh } 699bb61fe7Sdrh 709bb61fe7Sdrh /* 7101f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 7201f3f253Sdrh ** type of join. Return an integer constant that expresses that type 7301f3f253Sdrh ** in terms of the following bit values: 7401f3f253Sdrh ** 7501f3f253Sdrh ** JT_INNER 763dec223cSdrh ** JT_CROSS 7701f3f253Sdrh ** JT_OUTER 7801f3f253Sdrh ** JT_NATURAL 7901f3f253Sdrh ** JT_LEFT 8001f3f253Sdrh ** JT_RIGHT 8101f3f253Sdrh ** 8201f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 8301f3f253Sdrh ** 8401f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 8501f3f253Sdrh ** a join type, but put an error in the pParse structure. 8601f3f253Sdrh */ 874adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 8801f3f253Sdrh int jointype = 0; 8901f3f253Sdrh Token *apAll[3]; 9001f3f253Sdrh Token *p; 915719628aSdrh static const struct { 92c182d163Sdrh const char zKeyword[8]; 93290c1948Sdrh u8 nChar; 94290c1948Sdrh u8 code; 9501f3f253Sdrh } keywords[] = { 9601f3f253Sdrh { "natural", 7, JT_NATURAL }, 97195e6967Sdrh { "left", 4, JT_LEFT|JT_OUTER }, 98195e6967Sdrh { "right", 5, JT_RIGHT|JT_OUTER }, 99195e6967Sdrh { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 10001f3f253Sdrh { "outer", 5, JT_OUTER }, 10101f3f253Sdrh { "inner", 5, JT_INNER }, 1023dec223cSdrh { "cross", 5, JT_INNER|JT_CROSS }, 10301f3f253Sdrh }; 10401f3f253Sdrh int i, j; 10501f3f253Sdrh apAll[0] = pA; 10601f3f253Sdrh apAll[1] = pB; 10701f3f253Sdrh apAll[2] = pC; 108195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 10901f3f253Sdrh p = apAll[i]; 11001f3f253Sdrh for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){ 11101f3f253Sdrh if( p->n==keywords[j].nChar 1124adee20fSdanielk1977 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){ 11301f3f253Sdrh jointype |= keywords[j].code; 11401f3f253Sdrh break; 11501f3f253Sdrh } 11601f3f253Sdrh } 11701f3f253Sdrh if( j>=sizeof(keywords)/sizeof(keywords[0]) ){ 11801f3f253Sdrh jointype |= JT_ERROR; 11901f3f253Sdrh break; 12001f3f253Sdrh } 12101f3f253Sdrh } 122ad2d8307Sdrh if( 123ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 124195e6967Sdrh (jointype & JT_ERROR)!=0 125ad2d8307Sdrh ){ 126ae29ffbeSdrh const char *zSp1 = " "; 127ae29ffbeSdrh const char *zSp2 = " "; 128ae29ffbeSdrh if( pB==0 ){ zSp1++; } 129ae29ffbeSdrh if( pC==0 ){ zSp2++; } 130ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 131ae29ffbeSdrh "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); 13201f3f253Sdrh jointype = JT_INNER; 133195e6967Sdrh }else if( jointype & JT_RIGHT ){ 1344adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 135da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 136195e6967Sdrh jointype = JT_INNER; 13701f3f253Sdrh } 13801f3f253Sdrh return jointype; 13901f3f253Sdrh } 14001f3f253Sdrh 14101f3f253Sdrh /* 142ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 143ad2d8307Sdrh ** is not contained in the table. 144ad2d8307Sdrh */ 145ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 146ad2d8307Sdrh int i; 147ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1484adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 149ad2d8307Sdrh } 150ad2d8307Sdrh return -1; 151ad2d8307Sdrh } 152ad2d8307Sdrh 153ad2d8307Sdrh /* 15491bb0eedSdrh ** Set the value of a token to a '\000'-terminated string. 15591bb0eedSdrh */ 15691bb0eedSdrh static void setToken(Token *p, const char *z){ 15791bb0eedSdrh p->z = z; 15891bb0eedSdrh p->n = strlen(z); 15991bb0eedSdrh p->dyn = 0; 16091bb0eedSdrh } 16191bb0eedSdrh 162c182d163Sdrh /* 163c182d163Sdrh ** Create an expression node for an identifier with the name of zName 164c182d163Sdrh */ 165c182d163Sdrh static Expr *createIdExpr(const char *zName){ 166c182d163Sdrh Token dummy; 167c182d163Sdrh setToken(&dummy, zName); 168c182d163Sdrh return sqlite3Expr(TK_ID, 0, 0, &dummy); 169c182d163Sdrh } 170c182d163Sdrh 17191bb0eedSdrh 17291bb0eedSdrh /* 173ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the 174ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2. 175ad2d8307Sdrh */ 176ad2d8307Sdrh static void addWhereTerm( 177ad2d8307Sdrh const char *zCol, /* Name of the column */ 178ad2d8307Sdrh const Table *pTab1, /* First table */ 179030530deSdrh const char *zAlias1, /* Alias for first table. May be NULL */ 180ad2d8307Sdrh const Table *pTab2, /* Second table */ 181030530deSdrh const char *zAlias2, /* Alias for second table. May be NULL */ 18222d6a53aSdrh int iRightJoinTable, /* VDBE cursor for the right table */ 183ad2d8307Sdrh Expr **ppExpr /* Add the equality term to this expression */ 184ad2d8307Sdrh ){ 185ad2d8307Sdrh Expr *pE1a, *pE1b, *pE1c; 186ad2d8307Sdrh Expr *pE2a, *pE2b, *pE2c; 187ad2d8307Sdrh Expr *pE; 188ad2d8307Sdrh 189c182d163Sdrh pE1a = createIdExpr(zCol); 190c182d163Sdrh pE2a = createIdExpr(zCol); 191030530deSdrh if( zAlias1==0 ){ 192030530deSdrh zAlias1 = pTab1->zName; 193030530deSdrh } 194c182d163Sdrh pE1b = createIdExpr(zAlias1); 195030530deSdrh if( zAlias2==0 ){ 196030530deSdrh zAlias2 = pTab2->zName; 197030530deSdrh } 198c182d163Sdrh pE2b = createIdExpr(zAlias2); 1994adee20fSdanielk1977 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0); 2004adee20fSdanielk1977 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0); 2014adee20fSdanielk1977 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0); 2021f16230bSdrh ExprSetProperty(pE, EP_FromJoin); 20322d6a53aSdrh pE->iRightJoinTable = iRightJoinTable; 20491bb0eedSdrh *ppExpr = sqlite3ExprAnd(*ppExpr, pE); 205ad2d8307Sdrh } 206ad2d8307Sdrh 207ad2d8307Sdrh /* 2081f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 20922d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 21022d6a53aSdrh ** expression. 2111cc093c2Sdrh ** 212e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 2131cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 2141f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 2151f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 2161f16230bSdrh ** WHERE clause during join processing but we need to remember that they 2171f16230bSdrh ** originated in the ON or USING clause. 21822d6a53aSdrh ** 21922d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 22022d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 22122d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 22222d6a53aSdrh ** for cases like this: 22322d6a53aSdrh ** 22422d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 22522d6a53aSdrh ** 22622d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 22722d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 22822d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 22922d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 23022d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 23122d6a53aSdrh ** the output, which is incorrect. 2321cc093c2Sdrh */ 23322d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 2341cc093c2Sdrh while( p ){ 2351f16230bSdrh ExprSetProperty(p, EP_FromJoin); 23622d6a53aSdrh p->iRightJoinTable = iTable; 23722d6a53aSdrh setJoinExpr(p->pLeft, iTable); 2381cc093c2Sdrh p = p->pRight; 2391cc093c2Sdrh } 2401cc093c2Sdrh } 2411cc093c2Sdrh 2421cc093c2Sdrh /* 243ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 244ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 245ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 246ad2d8307Sdrh ** 24791bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 24891bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 24991bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 25091bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 25191bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 25291bb0eedSdrh ** also attached to the left entry. 25391bb0eedSdrh ** 254ad2d8307Sdrh ** This routine returns the number of errors encountered. 255ad2d8307Sdrh */ 256ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 25791bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 25891bb0eedSdrh int i, j; /* Loop counters */ 25991bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 26091bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 261ad2d8307Sdrh 26291bb0eedSdrh pSrc = p->pSrc; 26391bb0eedSdrh pLeft = &pSrc->a[0]; 26491bb0eedSdrh pRight = &pLeft[1]; 26591bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 26691bb0eedSdrh Table *pLeftTab = pLeft->pTab; 26791bb0eedSdrh Table *pRightTab = pRight->pTab; 26891bb0eedSdrh 26991bb0eedSdrh if( pLeftTab==0 || pRightTab==0 ) continue; 270ad2d8307Sdrh 271ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 272ad2d8307Sdrh ** every column that the two tables have in common. 273ad2d8307Sdrh */ 27491bb0eedSdrh if( pLeft->jointype & JT_NATURAL ){ 27591bb0eedSdrh if( pLeft->pOn || pLeft->pUsing ){ 2764adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 277ad2d8307Sdrh "an ON or USING clause", 0); 278ad2d8307Sdrh return 1; 279ad2d8307Sdrh } 28091bb0eedSdrh for(j=0; j<pLeftTab->nCol; j++){ 28191bb0eedSdrh char *zName = pLeftTab->aCol[j].zName; 28291bb0eedSdrh if( columnIndex(pRightTab, zName)>=0 ){ 283030530deSdrh addWhereTerm(zName, pLeftTab, pLeft->zAlias, 28422d6a53aSdrh pRightTab, pRight->zAlias, 28522d6a53aSdrh pRight->iCursor, &p->pWhere); 28622d6a53aSdrh 287ad2d8307Sdrh } 288ad2d8307Sdrh } 289ad2d8307Sdrh } 290ad2d8307Sdrh 291ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 292ad2d8307Sdrh */ 29391bb0eedSdrh if( pLeft->pOn && pLeft->pUsing ){ 2944adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 295da93d238Sdrh "clauses in the same join"); 296ad2d8307Sdrh return 1; 297ad2d8307Sdrh } 298ad2d8307Sdrh 299ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 30091bb0eedSdrh ** an AND operator. 301ad2d8307Sdrh */ 30291bb0eedSdrh if( pLeft->pOn ){ 30322d6a53aSdrh setJoinExpr(pLeft->pOn, pRight->iCursor); 30491bb0eedSdrh p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn); 30591bb0eedSdrh pLeft->pOn = 0; 306ad2d8307Sdrh } 307ad2d8307Sdrh 308ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 309ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 310ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 311ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 312ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 313ad2d8307Sdrh ** not contained in both tables to be joined. 314ad2d8307Sdrh */ 31591bb0eedSdrh if( pLeft->pUsing ){ 31691bb0eedSdrh IdList *pList = pLeft->pUsing; 317ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 31891bb0eedSdrh char *zName = pList->a[j].zName; 31991bb0eedSdrh if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){ 3204adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 32191bb0eedSdrh "not present in both tables", zName); 322ad2d8307Sdrh return 1; 323ad2d8307Sdrh } 324030530deSdrh addWhereTerm(zName, pLeftTab, pLeft->zAlias, 32522d6a53aSdrh pRightTab, pRight->zAlias, 32622d6a53aSdrh pRight->iCursor, &p->pWhere); 327ad2d8307Sdrh } 328ad2d8307Sdrh } 329ad2d8307Sdrh } 330ad2d8307Sdrh return 0; 331ad2d8307Sdrh } 332ad2d8307Sdrh 333ad2d8307Sdrh /* 3349bb61fe7Sdrh ** Delete the given Select structure and all of its substructures. 3359bb61fe7Sdrh */ 3364adee20fSdanielk1977 void sqlite3SelectDelete(Select *p){ 33782c3d636Sdrh if( p==0 ) return; 3384adee20fSdanielk1977 sqlite3ExprListDelete(p->pEList); 3394adee20fSdanielk1977 sqlite3SrcListDelete(p->pSrc); 3404adee20fSdanielk1977 sqlite3ExprDelete(p->pWhere); 3414adee20fSdanielk1977 sqlite3ExprListDelete(p->pGroupBy); 3424adee20fSdanielk1977 sqlite3ExprDelete(p->pHaving); 3434adee20fSdanielk1977 sqlite3ExprListDelete(p->pOrderBy); 3444adee20fSdanielk1977 sqlite3SelectDelete(p->pPrior); 345a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 346a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pOffset); 3479bb61fe7Sdrh sqliteFree(p); 3489bb61fe7Sdrh } 3499bb61fe7Sdrh 3509bb61fe7Sdrh /* 351c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 352c926afbcSdrh ** stack into the sorter. 353c926afbcSdrh */ 354c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){ 355c182d163Sdrh sqlite3ExprCodeExprList(pParse, pOrderBy); 3569d2985c7Sdrh sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0); 3574db38a70Sdrh sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0); 3584db38a70Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0); 3599d2985c7Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0); 360c926afbcSdrh } 361c926afbcSdrh 362c926afbcSdrh /* 363ec7429aeSdrh ** Add code to implement the OFFSET 364ea48eb2eSdrh */ 365ec7429aeSdrh static void codeOffset( 366bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 367ea48eb2eSdrh Select *p, /* The SELECT statement being coded */ 368ea48eb2eSdrh int iContinue, /* Jump here to skip the current record */ 369ea48eb2eSdrh int nPop /* Number of times to pop stack when jumping */ 370ea48eb2eSdrh ){ 37113449892Sdrh if( p->iOffset>=0 && iContinue!=0 ){ 372a2dc3b1aSdanielk1977 int addr = sqlite3VdbeCurrentAddr(v) + 3; 373ea48eb2eSdrh if( nPop>0 ) addr++; 374a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, 0); 375a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_IfMemPos, p->iOffset, addr); 376ea48eb2eSdrh if( nPop>0 ){ 377ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_Pop, nPop, 0); 378ea48eb2eSdrh } 379ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); 380ad6d9460Sdrh VdbeComment((v, "# skip OFFSET records")); 381ea48eb2eSdrh } 382ea48eb2eSdrh } 383ea48eb2eSdrh 384ea48eb2eSdrh /* 385c99130fdSdrh ** Add code that will check to make sure the top N elements of the 386c99130fdSdrh ** stack are distinct. iTab is a sorting index that holds previously 387c99130fdSdrh ** seen combinations of the N values. A new entry is made in iTab 388c99130fdSdrh ** if the current N values are new. 389c99130fdSdrh ** 390c99130fdSdrh ** A jump to addrRepeat is made and the K values are popped from the 391c99130fdSdrh ** stack if the top N elements are not distinct. 392c99130fdSdrh */ 393c99130fdSdrh static void codeDistinct( 394c99130fdSdrh Vdbe *v, /* Generate code into this VM */ 395c99130fdSdrh int iTab, /* A sorting index used to test for distinctness */ 396c99130fdSdrh int addrRepeat, /* Jump to here if not distinct */ 397c99130fdSdrh int N, /* The top N elements of the stack must be distinct */ 398c99130fdSdrh int K /* Pop K elements from the stack if indistinct */ 399c99130fdSdrh ){ 400c99130fdSdrh #if NULL_ALWAYS_DISTINCT 401c99130fdSdrh sqlite3VdbeAddOp(v, OP_IsNull, -N, sqlite3VdbeCurrentAddr(v)+6); 402c99130fdSdrh #endif 403c99130fdSdrh sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0); 404c99130fdSdrh sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3); 405c99130fdSdrh sqlite3VdbeAddOp(v, OP_Pop, K, 0); 406c99130fdSdrh sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat); 407c99130fdSdrh VdbeComment((v, "# skip indistinct records")); 408c99130fdSdrh sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0); 409c99130fdSdrh } 410c99130fdSdrh 411c99130fdSdrh 412c99130fdSdrh /* 4132282792aSdrh ** This routine generates the code for the inside of the inner loop 4142282792aSdrh ** of a SELECT. 41582c3d636Sdrh ** 41638640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 41738640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 41838640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 41938640e15Sdrh ** datatypes for each column. 4202282792aSdrh */ 4212282792aSdrh static int selectInnerLoop( 4222282792aSdrh Parse *pParse, /* The parser context */ 423df199a25Sdrh Select *p, /* The complete select statement being coded */ 4242282792aSdrh ExprList *pEList, /* List of values being extracted */ 42582c3d636Sdrh int srcTab, /* Pull data from this table */ 426967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 4272282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 4282282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 4292282792aSdrh int eDest, /* How to dispose of the results */ 4302282792aSdrh int iParm, /* An argument to the disposal method */ 4312282792aSdrh int iContinue, /* Jump here to continue with next row */ 43284ac9d02Sdanielk1977 int iBreak, /* Jump here to break out of the inner loop */ 43384ac9d02Sdanielk1977 char *aff /* affinity string if eDest is SRT_Union */ 4342282792aSdrh ){ 4352282792aSdrh Vdbe *v = pParse->pVdbe; 4362282792aSdrh int i; 437ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 43838640e15Sdrh 439daffd0e5Sdrh if( v==0 ) return 0; 44038640e15Sdrh assert( pEList!=0 ); 4412282792aSdrh 442df199a25Sdrh /* If there was a LIMIT clause on the SELECT statement, then do the check 443df199a25Sdrh ** to see if this row should be output. 444df199a25Sdrh */ 445ea48eb2eSdrh hasDistinct = distinct>=0 && pEList && pEList->nExpr>0; 446ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 447ec7429aeSdrh codeOffset(v, p, iContinue, 0); 448df199a25Sdrh } 449df199a25Sdrh 450967e8b73Sdrh /* Pull the requested columns. 4512282792aSdrh */ 45238640e15Sdrh if( nColumn>0 ){ 453967e8b73Sdrh for(i=0; i<nColumn; i++){ 4544adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Column, srcTab, i); 45582c3d636Sdrh } 45638640e15Sdrh }else{ 45738640e15Sdrh nColumn = pEList->nExpr; 458c182d163Sdrh sqlite3ExprCodeExprList(pParse, pEList); 45982c3d636Sdrh } 4602282792aSdrh 461daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 462daffd0e5Sdrh ** and this row has been seen before, then do not make this row 463daffd0e5Sdrh ** part of the result. 4642282792aSdrh */ 465ea48eb2eSdrh if( hasDistinct ){ 466c182d163Sdrh int n = pEList->nExpr; 467c99130fdSdrh codeDistinct(v, distinct, iContinue, n, n+1); 468ea48eb2eSdrh if( pOrderBy==0 ){ 469ec7429aeSdrh codeOffset(v, p, iContinue, nColumn); 470ea48eb2eSdrh } 4712282792aSdrh } 47282c3d636Sdrh 473c926afbcSdrh switch( eDest ){ 47482c3d636Sdrh /* In this mode, write each query result to the key of the temporary 47582c3d636Sdrh ** table iParm. 4762282792aSdrh */ 47713449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 478c926afbcSdrh case SRT_Union: { 4794adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT); 48013449892Sdrh if( aff ){ 48184ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 48213449892Sdrh } 483f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0); 484c926afbcSdrh break; 485c926afbcSdrh } 48682c3d636Sdrh 48782c3d636Sdrh /* Construct a record from the query result, but instead of 48882c3d636Sdrh ** saving that record, use it as a key to delete elements from 48982c3d636Sdrh ** the temporary table iParm. 49082c3d636Sdrh */ 491c926afbcSdrh case SRT_Except: { 4920bd1f4eaSdrh int addr; 4934adee20fSdanielk1977 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT); 49484ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 4954adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3); 4964adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0); 497c926afbcSdrh break; 498c926afbcSdrh } 4995338a5f7Sdanielk1977 #endif 5005338a5f7Sdanielk1977 5015338a5f7Sdanielk1977 /* Store the result as data using a unique key. 5025338a5f7Sdanielk1977 */ 5035338a5f7Sdanielk1977 case SRT_Table: 5049d2985c7Sdrh case SRT_VirtualTab: { 5055338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 5065338a5f7Sdanielk1977 if( pOrderBy ){ 5075338a5f7Sdanielk1977 pushOntoSorter(pParse, v, pOrderBy); 5085338a5f7Sdanielk1977 }else{ 509f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); 5105338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 511f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_Insert, iParm, 0); 5125338a5f7Sdanielk1977 } 5135338a5f7Sdanielk1977 break; 5145338a5f7Sdanielk1977 } 5152282792aSdrh 51693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 5172282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 5182282792aSdrh ** then there should be a single item on the stack. Write this 5192282792aSdrh ** item into the set table with bogus data. 5202282792aSdrh */ 521c926afbcSdrh case SRT_Set: { 5224adee20fSdanielk1977 int addr1 = sqlite3VdbeCurrentAddr(v); 52352b36cabSdrh int addr2; 524e014a838Sdanielk1977 525967e8b73Sdrh assert( nColumn==1 ); 5264adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3); 5274adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 5284adee20fSdanielk1977 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 529c926afbcSdrh if( pOrderBy ){ 530de941c60Sdrh /* At first glance you would think we could optimize out the 531de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 532de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 533de941c60Sdrh ** case the order does matter */ 534c926afbcSdrh pushOntoSorter(pParse, v, pOrderBy); 535c926afbcSdrh }else{ 536e014a838Sdanielk1977 char aff = (iParm>>16)&0xFF; 537e014a838Sdanielk1977 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff); 53894a11211Sdrh sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1); 539f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); 540c926afbcSdrh } 541d654be80Sdrh sqlite3VdbeJumpHere(v, addr2); 542c926afbcSdrh break; 543c926afbcSdrh } 54482c3d636Sdrh 545ec7429aeSdrh /* If any row exists in the result set, record that fact and abort. 546ec7429aeSdrh */ 547ec7429aeSdrh case SRT_Exists: { 548ec7429aeSdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm); 549ec7429aeSdrh sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 550ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 551ec7429aeSdrh break; 552ec7429aeSdrh } 553ec7429aeSdrh 5542282792aSdrh /* If this is a scalar select that is part of an expression, then 5552282792aSdrh ** store the results in the appropriate memory cell and break out 5562282792aSdrh ** of the scan loop. 5572282792aSdrh */ 558c926afbcSdrh case SRT_Mem: { 559967e8b73Sdrh assert( nColumn==1 ); 560c926afbcSdrh if( pOrderBy ){ 561c926afbcSdrh pushOntoSorter(pParse, v, pOrderBy); 562c926afbcSdrh }else{ 5634adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 564ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 565c926afbcSdrh } 566c926afbcSdrh break; 567c926afbcSdrh } 56893758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 5692282792aSdrh 570c182d163Sdrh /* Send the data to the callback function or to a subroutine. In the 571c182d163Sdrh ** case of a subroutine, the subroutine itself is responsible for 572c182d163Sdrh ** popping the data from the stack. 573f46f905aSdrh */ 574c182d163Sdrh case SRT_Subroutine: 5759d2985c7Sdrh case SRT_Callback: { 576f46f905aSdrh if( pOrderBy ){ 577ce665cf6Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 578f46f905aSdrh pushOntoSorter(pParse, v, pOrderBy); 579c182d163Sdrh }else if( eDest==SRT_Subroutine ){ 5804adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 581c182d163Sdrh }else{ 582c182d163Sdrh sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 583ac82fcf5Sdrh } 584142e30dfSdrh break; 585142e30dfSdrh } 586142e30dfSdrh 5876a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 588d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 589d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 590d7489c39Sdrh ** user-defined functions that have side effects. We do not care 591d7489c39Sdrh ** about the actual results of the select. 592d7489c39Sdrh */ 593c926afbcSdrh default: { 594f46f905aSdrh assert( eDest==SRT_Discard ); 5954adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 596c926afbcSdrh break; 597c926afbcSdrh } 59893758c8dSdanielk1977 #endif 599c926afbcSdrh } 600ec7429aeSdrh 601ec7429aeSdrh /* Jump to the end of the loop if the LIMIT is reached. 602ec7429aeSdrh */ 603ec7429aeSdrh if( p->iLimit>=0 && pOrderBy==0 ){ 604ec7429aeSdrh sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, 0); 605ec7429aeSdrh sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak); 606ec7429aeSdrh } 60782c3d636Sdrh return 0; 60882c3d636Sdrh } 60982c3d636Sdrh 61082c3d636Sdrh /* 611dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 612dece1a84Sdrh ** the collating sequence for each expression in that expression list. 613dece1a84Sdrh ** 6140342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 6150342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 6160342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 6170342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 6180342b1f5Sdrh ** index to implement a DISTINCT test. 6190342b1f5Sdrh ** 620dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc. The calling 621dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 622dece1a84Sdrh ** freed. Add the KeyInfo structure to the P3 field of an opcode using 623dece1a84Sdrh ** P3_KEYINFO_HANDOFF is the usual way of dealing with this. 624dece1a84Sdrh */ 625dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ 626dece1a84Sdrh sqlite3 *db = pParse->db; 627dece1a84Sdrh int nExpr; 628dece1a84Sdrh KeyInfo *pInfo; 629dece1a84Sdrh struct ExprList_item *pItem; 630dece1a84Sdrh int i; 631dece1a84Sdrh 632dece1a84Sdrh nExpr = pList->nExpr; 633dece1a84Sdrh pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) ); 634dece1a84Sdrh if( pInfo ){ 635dece1a84Sdrh pInfo->aSortOrder = (char*)&pInfo->aColl[nExpr]; 636dece1a84Sdrh pInfo->nField = nExpr; 637dece1a84Sdrh pInfo->enc = db->enc; 638dece1a84Sdrh for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){ 639dece1a84Sdrh CollSeq *pColl; 640dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 641dece1a84Sdrh if( !pColl ){ 642dece1a84Sdrh pColl = db->pDfltColl; 643dece1a84Sdrh } 644dece1a84Sdrh pInfo->aColl[i] = pColl; 645dece1a84Sdrh pInfo->aSortOrder[i] = pItem->sortOrder; 646dece1a84Sdrh } 647dece1a84Sdrh } 648dece1a84Sdrh return pInfo; 649dece1a84Sdrh } 650dece1a84Sdrh 651dece1a84Sdrh 652dece1a84Sdrh /* 653d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 654d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 655d8bc7086Sdrh ** we need to run the sorter and output the results. The following 656d8bc7086Sdrh ** routine generates the code needed to do that. 657d8bc7086Sdrh */ 658c926afbcSdrh static void generateSortTail( 659ffbc3088Sdrh Parse *pParse, /* The parsing context */ 660c926afbcSdrh Select *p, /* The SELECT statement */ 661c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 662c926afbcSdrh int nColumn, /* Number of columns of data */ 663c926afbcSdrh int eDest, /* Write the sorted results here */ 664c926afbcSdrh int iParm /* Optional parameter associated with eDest */ 665c926afbcSdrh ){ 6660342b1f5Sdrh int brk = sqlite3VdbeMakeLabel(v); 6670342b1f5Sdrh int cont = sqlite3VdbeMakeLabel(v); 668d8bc7086Sdrh int addr; 6690342b1f5Sdrh int iTab; 6700342b1f5Sdrh ExprList *pOrderBy = p->pOrderBy; 671ffbc3088Sdrh 6729d2985c7Sdrh iTab = pOrderBy->iECursor; 6730342b1f5Sdrh addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk); 674ec7429aeSdrh codeOffset(v, p, cont, 0); 6754db38a70Sdrh sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1); 676c926afbcSdrh switch( eDest ){ 677c926afbcSdrh case SRT_Table: 6789d2985c7Sdrh case SRT_VirtualTab: { 679f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); 6804adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 681f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_Insert, iParm, 0); 682c926afbcSdrh break; 683c926afbcSdrh } 68493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 685c926afbcSdrh case SRT_Set: { 686c926afbcSdrh assert( nColumn==1 ); 6874adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); 6884adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 6894adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); 690ededfd5eSdanielk1977 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC); 691f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); 692c926afbcSdrh break; 693c926afbcSdrh } 694c926afbcSdrh case SRT_Mem: { 695c926afbcSdrh assert( nColumn==1 ); 6964adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 697ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 698c926afbcSdrh break; 699c926afbcSdrh } 70093758c8dSdanielk1977 #endif 701ce665cf6Sdrh case SRT_Callback: 702ac82fcf5Sdrh case SRT_Subroutine: { 703ac82fcf5Sdrh int i; 70484ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0); 70584ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 706ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 7074adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Column, -1-i, i); 708ac82fcf5Sdrh } 709ce665cf6Sdrh if( eDest==SRT_Callback ){ 710ce665cf6Sdrh sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 711ce665cf6Sdrh }else{ 7124adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 713ce665cf6Sdrh } 71484ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 2, 0); 715ac82fcf5Sdrh break; 716ac82fcf5Sdrh } 717c926afbcSdrh default: { 718f46f905aSdrh /* Do nothing */ 719c926afbcSdrh break; 720c926afbcSdrh } 721c926afbcSdrh } 722ec7429aeSdrh 723ec7429aeSdrh /* Jump to the end of the loop when the LIMIT is reached 724ec7429aeSdrh */ 725ec7429aeSdrh if( p->iLimit>=0 ){ 726ec7429aeSdrh sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, 0); 727ec7429aeSdrh sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk); 728ec7429aeSdrh } 729ec7429aeSdrh 730ec7429aeSdrh /* The bottom of the loop 731ec7429aeSdrh */ 7320342b1f5Sdrh sqlite3VdbeResolveLabel(v, cont); 7330342b1f5Sdrh sqlite3VdbeAddOp(v, OP_Next, iTab, addr); 7340342b1f5Sdrh sqlite3VdbeResolveLabel(v, brk); 735d8bc7086Sdrh } 736d8bc7086Sdrh 737d8bc7086Sdrh /* 738517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 739517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 740e78e8284Sdrh ** 741517eb646Sdanielk1977 ** If the declaration type is the exact datatype definition extracted from 742517eb646Sdanielk1977 ** the original CREATE TABLE statement if the expression is a column. 743e78e8284Sdrh ** 744517eb646Sdanielk1977 ** The declaration type for an expression is either TEXT, NUMERIC or ANY. 745517eb646Sdanielk1977 ** The declaration type for a ROWID field is INTEGER. 746fcb78a49Sdrh */ 747b3bce662Sdanielk1977 static const char *columnType(NameContext *pNC, Expr *pExpr){ 74800e279d9Sdanielk1977 char const *zType; 749517eb646Sdanielk1977 int j; 750b3bce662Sdanielk1977 if( pExpr==0 || pNC->pSrcList==0 ) return 0; 7515338a5f7Sdanielk1977 7525338a5f7Sdanielk1977 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING, 7535338a5f7Sdanielk1977 ** and LIMIT clauses. But pExpr originates in the result set of a 7545338a5f7Sdanielk1977 ** SELECT. So pExpr can never contain an AS operator. 7555338a5f7Sdanielk1977 */ 7565338a5f7Sdanielk1977 assert( pExpr->op!=TK_AS ); 7575338a5f7Sdanielk1977 75800e279d9Sdanielk1977 switch( pExpr->op ){ 75900e279d9Sdanielk1977 case TK_COLUMN: { 760b3bce662Sdanielk1977 Table *pTab = 0; 761517eb646Sdanielk1977 int iCol = pExpr->iColumn; 762b3bce662Sdanielk1977 while( pNC && !pTab ){ 763b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 764b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 765b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 7666a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 767b3bce662Sdanielk1977 }else{ 768b3bce662Sdanielk1977 pNC = pNC->pNext; 769b3bce662Sdanielk1977 } 770b3bce662Sdanielk1977 } 7717e62779aSdrh if( pTab==0 ){ 7727e62779aSdrh /* FIX ME: 7737e62779aSdrh ** This can occurs if you have something like "SELECT new.x;" inside 7747e62779aSdrh ** a trigger. In other words, if you reference the special "new" 7757e62779aSdrh ** table in the result set of a select. We do not have a good way 7767e62779aSdrh ** to find the actual table type, so call it "TEXT". This is really 7777e62779aSdrh ** something of a bug, but I do not know how to fix it. 7787e62779aSdrh ** 7797e62779aSdrh ** This code does not produce the correct answer - it just prevents 7807e62779aSdrh ** a segfault. See ticket #1229. 7817e62779aSdrh */ 7827e62779aSdrh zType = "TEXT"; 7837e62779aSdrh break; 7847e62779aSdrh } 785b3bce662Sdanielk1977 assert( pTab ); 786fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 787fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 788fcb78a49Sdrh if( iCol<0 ){ 789fcb78a49Sdrh zType = "INTEGER"; 790fcb78a49Sdrh }else{ 791fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 792fcb78a49Sdrh } 79300e279d9Sdanielk1977 break; 794736c22b8Sdrh } 79593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 79600e279d9Sdanielk1977 case TK_SELECT: { 797b3bce662Sdanielk1977 NameContext sNC; 79800e279d9Sdanielk1977 Select *pS = pExpr->pSelect; 799b3bce662Sdanielk1977 sNC.pSrcList = pExpr->pSelect->pSrc; 800b3bce662Sdanielk1977 sNC.pNext = pNC; 801b3bce662Sdanielk1977 zType = columnType(&sNC, pS->pEList->a[0].pExpr); 80200e279d9Sdanielk1977 break; 803fcb78a49Sdrh } 80493758c8dSdanielk1977 #endif 80500e279d9Sdanielk1977 default: 80600e279d9Sdanielk1977 zType = 0; 80700e279d9Sdanielk1977 } 80800e279d9Sdanielk1977 809517eb646Sdanielk1977 return zType; 810517eb646Sdanielk1977 } 811517eb646Sdanielk1977 812517eb646Sdanielk1977 /* 813517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 814517eb646Sdanielk1977 ** in the result set. 815517eb646Sdanielk1977 */ 816517eb646Sdanielk1977 static void generateColumnTypes( 817517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 818517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 819517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 820517eb646Sdanielk1977 ){ 821517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 822517eb646Sdanielk1977 int i; 823b3bce662Sdanielk1977 NameContext sNC; 824b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 825517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 826517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 827b3bce662Sdanielk1977 const char *zType = columnType(&sNC, p); 82800e279d9Sdanielk1977 if( zType==0 ) continue; 829fbcd585fSdanielk1977 /* The vdbe must make it's own copy of the column-type, in case the 830fbcd585fSdanielk1977 ** schema is reset before this virtual machine is deleted. 831fbcd585fSdanielk1977 */ 832fbcd585fSdanielk1977 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType)); 833fcb78a49Sdrh } 834fcb78a49Sdrh } 835fcb78a49Sdrh 836fcb78a49Sdrh /* 837fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 838fcb78a49Sdrh ** in the result set. This information is used to provide the 839fcabd464Sdrh ** azCol[] values in the callback. 84082c3d636Sdrh */ 841832508b7Sdrh static void generateColumnNames( 842832508b7Sdrh Parse *pParse, /* Parser context */ 843ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 844832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 845832508b7Sdrh ){ 846d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 8476a3ea0e6Sdrh int i, j; 8489bb575fdSdrh sqlite3 *db = pParse->db; 849fcabd464Sdrh int fullNames, shortNames; 850fcabd464Sdrh 851fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 8523cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 8533cf86063Sdanielk1977 if( pParse->explain ){ 85461de0d1bSdanielk1977 return; 8553cf86063Sdanielk1977 } 8565338a5f7Sdanielk1977 #endif 8573cf86063Sdanielk1977 858d6502758Sdrh assert( v!=0 ); 8596f8a503dSdanielk1977 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return; 860d8bc7086Sdrh pParse->colNamesSet = 1; 861fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 862fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 86322322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 86482c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 86582c3d636Sdrh Expr *p; 8665a38705eSdrh p = pEList->a[i].pExpr; 8675a38705eSdrh if( p==0 ) continue; 86882c3d636Sdrh if( pEList->a[i].zName ){ 86982c3d636Sdrh char *zName = pEList->a[i].zName; 870d8123366Sdanielk1977 sqlite3VdbeSetColName(v, i, zName, strlen(zName)); 87182c3d636Sdrh continue; 87282c3d636Sdrh } 873fa173a76Sdrh if( p->op==TK_COLUMN && pTabList ){ 8746a3ea0e6Sdrh Table *pTab; 87597665873Sdrh char *zCol; 8768aff1015Sdrh int iCol = p->iColumn; 8776a3ea0e6Sdrh for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 8786a3ea0e6Sdrh assert( j<pTabList->nSrc ); 8796a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 8808aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 88197665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 882b1363206Sdrh if( iCol<0 ){ 88347a6db2bSdrh zCol = "rowid"; 884b1363206Sdrh }else{ 885b1363206Sdrh zCol = pTab->aCol[iCol].zName; 886b1363206Sdrh } 887fcabd464Sdrh if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ 8883cf86063Sdanielk1977 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n); 889fcabd464Sdrh }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ 89082c3d636Sdrh char *zName = 0; 89182c3d636Sdrh char *zTab; 89282c3d636Sdrh 8936a3ea0e6Sdrh zTab = pTabList->a[j].zAlias; 894fcabd464Sdrh if( fullNames || zTab==0 ) zTab = pTab->zName; 8954adee20fSdanielk1977 sqlite3SetString(&zName, zTab, ".", zCol, 0); 8963cf86063Sdanielk1977 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC); 89782c3d636Sdrh }else{ 89847a6db2bSdrh sqlite3VdbeSetColName(v, i, zCol, strlen(zCol)); 89982c3d636Sdrh } 9006977fea8Sdrh }else if( p->span.z && p->span.z[0] ){ 9013cf86063Sdanielk1977 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n); 9023cf86063Sdanielk1977 /* sqlite3VdbeCompressSpace(v, addr); */ 9031bee3d7bSdrh }else{ 9041bee3d7bSdrh char zName[30]; 9051bee3d7bSdrh assert( p->op!=TK_COLUMN || pTabList==0 ); 9061bee3d7bSdrh sprintf(zName, "column%d", i+1); 9073cf86063Sdanielk1977 sqlite3VdbeSetColName(v, i, zName, 0); 90882c3d636Sdrh } 90982c3d636Sdrh } 91076d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 9115080aaa7Sdrh } 91282c3d636Sdrh 91393758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 91482c3d636Sdrh /* 915d8bc7086Sdrh ** Name of the connection operator, used for error messages. 916d8bc7086Sdrh */ 917d8bc7086Sdrh static const char *selectOpName(int id){ 918d8bc7086Sdrh char *z; 919d8bc7086Sdrh switch( id ){ 920d8bc7086Sdrh case TK_ALL: z = "UNION ALL"; break; 921d8bc7086Sdrh case TK_INTERSECT: z = "INTERSECT"; break; 922d8bc7086Sdrh case TK_EXCEPT: z = "EXCEPT"; break; 923d8bc7086Sdrh default: z = "UNION"; break; 924d8bc7086Sdrh } 925d8bc7086Sdrh return z; 926d8bc7086Sdrh } 92793758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 928d8bc7086Sdrh 929d8bc7086Sdrh /* 930315555caSdrh ** Forward declaration 931315555caSdrh */ 9329b3187e1Sdrh static int prepSelectStmt(Parse*, Select*); 933315555caSdrh 934315555caSdrh /* 93522f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes 93622f70c32Sdrh ** the result set of that SELECT. 93722f70c32Sdrh */ 9384adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 93922f70c32Sdrh Table *pTab; 940b733d037Sdrh int i, j; 94122f70c32Sdrh ExprList *pEList; 942290c1948Sdrh Column *aCol, *pCol; 94322f70c32Sdrh 9449b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 94522f70c32Sdrh return 0; 94622f70c32Sdrh } 947142bdf40Sdanielk1977 if( sqlite3SelectResolve(pParse, pSelect, 0) ){ 948142bdf40Sdanielk1977 return 0; 949142bdf40Sdanielk1977 } 95022f70c32Sdrh pTab = sqliteMalloc( sizeof(Table) ); 95122f70c32Sdrh if( pTab==0 ){ 95222f70c32Sdrh return 0; 95322f70c32Sdrh } 954ed8a3bb1Sdrh pTab->nRef = 1; 95522f70c32Sdrh pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0; 95622f70c32Sdrh pEList = pSelect->pEList; 95722f70c32Sdrh pTab->nCol = pEList->nExpr; 958417be79cSdrh assert( pTab->nCol>0 ); 959b733d037Sdrh pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol ); 960290c1948Sdrh for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){ 96179d5f63fSdrh Expr *p, *pR; 962517eb646Sdanielk1977 char *zType; 96391bb0eedSdrh char *zName; 96479d5f63fSdrh char *zBasename; 96579d5f63fSdrh int cnt; 966b3bce662Sdanielk1977 NameContext sNC; 96779d5f63fSdrh 96879d5f63fSdrh /* Get an appropriate name for the column 96979d5f63fSdrh */ 97079d5f63fSdrh p = pEList->a[i].pExpr; 971290c1948Sdrh assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 ); 97291bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 97379d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 97491bb0eedSdrh zName = sqliteStrDup(zName); 975517eb646Sdanielk1977 }else if( p->op==TK_DOT 976b733d037Sdrh && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ 97779d5f63fSdrh /* For columns of the from A.B use B as the name */ 97891bb0eedSdrh zName = sqlite3MPrintf("%T", &pR->token); 979b733d037Sdrh }else if( p->span.z && p->span.z[0] ){ 98079d5f63fSdrh /* Use the original text of the column expression as its name */ 98191bb0eedSdrh zName = sqlite3MPrintf("%T", &p->span); 98222f70c32Sdrh }else{ 98379d5f63fSdrh /* If all else fails, make up a name */ 98491bb0eedSdrh zName = sqlite3MPrintf("column%d", i+1); 98522f70c32Sdrh } 98691bb0eedSdrh sqlite3Dequote(zName); 987dd5b2fa5Sdrh if( sqlite3_malloc_failed ){ 988dd5b2fa5Sdrh sqliteFree(zName); 989dd5b2fa5Sdrh sqlite3DeleteTable(0, pTab); 990dd5b2fa5Sdrh return 0; 991dd5b2fa5Sdrh } 99279d5f63fSdrh 99379d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 99479d5f63fSdrh ** append a integer to the name so that it becomes unique. 99579d5f63fSdrh */ 99679d5f63fSdrh zBasename = zName; 99779d5f63fSdrh for(j=cnt=0; j<i; j++){ 99879d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 99979d5f63fSdrh zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt); 100079d5f63fSdrh j = -1; 1001dd5b2fa5Sdrh if( zName==0 ) break; 100279d5f63fSdrh } 100379d5f63fSdrh } 100479d5f63fSdrh if( zBasename!=zName ){ 100579d5f63fSdrh sqliteFree(zBasename); 100679d5f63fSdrh } 100791bb0eedSdrh pCol->zName = zName; 1008e014a838Sdanielk1977 100979d5f63fSdrh /* Get the typename, type affinity, and collating sequence for the 101079d5f63fSdrh ** column. 101179d5f63fSdrh */ 1012c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1013b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 1014b3bce662Sdanielk1977 zType = sqliteStrDup(columnType(&sNC, p)); 1015290c1948Sdrh pCol->zType = zType; 1016c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1017290c1948Sdrh pCol->pColl = sqlite3ExprCollSeq(pParse, p); 1018290c1948Sdrh if( !pCol->pColl ){ 1019290c1948Sdrh pCol->pColl = pParse->db->pDfltColl; 10200202b29eSdanielk1977 } 102122f70c32Sdrh } 102222f70c32Sdrh pTab->iPKey = -1; 102322f70c32Sdrh return pTab; 102422f70c32Sdrh } 102522f70c32Sdrh 102622f70c32Sdrh /* 10279b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following 10289b3187e1Sdrh ** things: 1029d8bc7086Sdrh ** 10309b3187e1Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 10319b3187e1Sdrh ** element of the FROM clause. 10329b3187e1Sdrh ** 10339b3187e1Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 10349b3187e1Sdrh ** defines FROM clause. When views appear in the FROM clause, 103563eb5f29Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 103663eb5f29Sdrh ** that implements the view. A copy is made of the view's SELECT 103763eb5f29Sdrh ** statement so that we can freely modify or delete that statement 103863eb5f29Sdrh ** without worrying about messing up the presistent representation 103963eb5f29Sdrh ** of the view. 1040d8bc7086Sdrh ** 10419b3187e1Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 1042ad2d8307Sdrh ** on joins and the ON and USING clause of joins. 1043ad2d8307Sdrh ** 10449b3187e1Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 104554473229Sdrh ** for instances of the "*" operator or the TABLE.* operator. 104654473229Sdrh ** If found, expand each "*" to be every column in every table 104754473229Sdrh ** and TABLE.* to be every column in TABLE. 1048d8bc7086Sdrh ** 1049d8bc7086Sdrh ** Return 0 on success. If there are problems, leave an error message 1050d8bc7086Sdrh ** in pParse and return non-zero. 1051d8bc7086Sdrh */ 10529b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){ 105354473229Sdrh int i, j, k, rc; 1054ad3cab52Sdrh SrcList *pTabList; 1055daffd0e5Sdrh ExprList *pEList; 1056a76b5dfcSdrh Table *pTab; 1057290c1948Sdrh struct SrcList_item *pFrom; 1058daffd0e5Sdrh 1059e94ddc9eSdanielk1977 if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1; 1060daffd0e5Sdrh pTabList = p->pSrc; 1061daffd0e5Sdrh pEList = p->pEList; 1062d8bc7086Sdrh 10639b3187e1Sdrh /* Make sure cursor numbers have been assigned to all entries in 10649b3187e1Sdrh ** the FROM clause of the SELECT statement. 10659b3187e1Sdrh */ 10669b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, p->pSrc); 10679b3187e1Sdrh 10689b3187e1Sdrh /* Look up every table named in the FROM clause of the select. If 10699b3187e1Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 10709b3187e1Sdrh ** then create a transient table structure to describe the subquery. 1071d8bc7086Sdrh */ 1072290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 10739b3187e1Sdrh if( pFrom->pTab!=0 ){ 10749b3187e1Sdrh /* This statement has already been prepared. There is no need 10759b3187e1Sdrh ** to go further. */ 10769b3187e1Sdrh assert( i==0 ); 1077d8bc7086Sdrh return 0; 1078d8bc7086Sdrh } 1079290c1948Sdrh if( pFrom->zName==0 ){ 108093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 108122f70c32Sdrh /* A sub-query in the FROM clause of a SELECT */ 1082290c1948Sdrh assert( pFrom->pSelect!=0 ); 1083290c1948Sdrh if( pFrom->zAlias==0 ){ 108491bb0eedSdrh pFrom->zAlias = 108591bb0eedSdrh sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect); 1086ad2d8307Sdrh } 1087ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1088290c1948Sdrh pFrom->pTab = pTab = 1089290c1948Sdrh sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect); 109022f70c32Sdrh if( pTab==0 ){ 1091daffd0e5Sdrh return 1; 1092daffd0e5Sdrh } 10935cf590c1Sdrh /* The isTransient flag indicates that the Table structure has been 10945cf590c1Sdrh ** dynamically allocated and may be freed at any time. In other words, 10955cf590c1Sdrh ** pTab is not pointing to a persistent table structure that defines 10965cf590c1Sdrh ** part of the schema. */ 109722f70c32Sdrh pTab->isTransient = 1; 109893758c8dSdanielk1977 #endif 109922f70c32Sdrh }else{ 1100a76b5dfcSdrh /* An ordinary table or view name in the FROM clause */ 1101ed8a3bb1Sdrh assert( pFrom->pTab==0 ); 1102290c1948Sdrh pFrom->pTab = pTab = 1103290c1948Sdrh sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase); 1104a76b5dfcSdrh if( pTab==0 ){ 1105d8bc7086Sdrh return 1; 1106d8bc7086Sdrh } 1107ed8a3bb1Sdrh pTab->nRef++; 110893758c8dSdanielk1977 #ifndef SQLITE_OMIT_VIEW 1109a76b5dfcSdrh if( pTab->pSelect ){ 111063eb5f29Sdrh /* We reach here if the named table is a really a view */ 11114adee20fSdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 1112417be79cSdrh return 1; 1113417be79cSdrh } 1114290c1948Sdrh /* If pFrom->pSelect!=0 it means we are dealing with a 111563eb5f29Sdrh ** view within a view. The SELECT structure has already been 111663eb5f29Sdrh ** copied by the outer view so we can skip the copy step here 111763eb5f29Sdrh ** in the inner view. 111863eb5f29Sdrh */ 1119290c1948Sdrh if( pFrom->pSelect==0 ){ 1120290c1948Sdrh pFrom->pSelect = sqlite3SelectDup(pTab->pSelect); 1121a76b5dfcSdrh } 1122d8bc7086Sdrh } 112393758c8dSdanielk1977 #endif 112422f70c32Sdrh } 112563eb5f29Sdrh } 1126d8bc7086Sdrh 1127ad2d8307Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 1128ad2d8307Sdrh */ 1129ad2d8307Sdrh if( sqliteProcessJoin(pParse, p) ) return 1; 1130ad2d8307Sdrh 11317c917d19Sdrh /* For every "*" that occurs in the column list, insert the names of 113254473229Sdrh ** all columns in all tables. And for every TABLE.* insert the names 113354473229Sdrh ** of all columns in TABLE. The parser inserted a special expression 11347c917d19Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 11357c917d19Sdrh ** The following code just has to locate the TK_ALL expressions and expand 11367c917d19Sdrh ** each one to the list of all columns in all tables. 113754473229Sdrh ** 113854473229Sdrh ** The first loop just checks to see if there are any "*" operators 113954473229Sdrh ** that need expanding. 1140d8bc7086Sdrh */ 11417c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 114254473229Sdrh Expr *pE = pEList->a[k].pExpr; 114354473229Sdrh if( pE->op==TK_ALL ) break; 114454473229Sdrh if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 114554473229Sdrh && pE->pLeft && pE->pLeft->op==TK_ID ) break; 11467c917d19Sdrh } 114754473229Sdrh rc = 0; 11487c917d19Sdrh if( k<pEList->nExpr ){ 114954473229Sdrh /* 115054473229Sdrh ** If we get here it means the result set contains one or more "*" 115154473229Sdrh ** operators that need to be expanded. Loop through each expression 115254473229Sdrh ** in the result set and expand them one by one. 115354473229Sdrh */ 11547c917d19Sdrh struct ExprList_item *a = pEList->a; 11557c917d19Sdrh ExprList *pNew = 0; 1156d70dc52dSdrh int flags = pParse->db->flags; 1157d70dc52dSdrh int longNames = (flags & SQLITE_FullColNames)!=0 && 1158d70dc52dSdrh (flags & SQLITE_ShortColNames)==0; 1159d70dc52dSdrh 11607c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 116154473229Sdrh Expr *pE = a[k].pExpr; 116254473229Sdrh if( pE->op!=TK_ALL && 116354473229Sdrh (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 116454473229Sdrh /* This particular expression does not need to be expanded. 116554473229Sdrh */ 11664adee20fSdanielk1977 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0); 11677c917d19Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 11687c917d19Sdrh a[k].pExpr = 0; 11697c917d19Sdrh a[k].zName = 0; 11707c917d19Sdrh }else{ 117154473229Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 117254473229Sdrh ** expanded. */ 117354473229Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 1174cf55b7aeSdrh char *zTName; /* text of name of TABLE */ 117554473229Sdrh if( pE->op==TK_DOT && pE->pLeft ){ 1176cf55b7aeSdrh zTName = sqlite3NameFromToken(&pE->pLeft->token); 117754473229Sdrh }else{ 1178cf55b7aeSdrh zTName = 0; 117954473229Sdrh } 1180290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1181290c1948Sdrh Table *pTab = pFrom->pTab; 1182290c1948Sdrh char *zTabName = pFrom->zAlias; 118354473229Sdrh if( zTabName==0 || zTabName[0]==0 ){ 118454473229Sdrh zTabName = pTab->zName; 118554473229Sdrh } 1186cf55b7aeSdrh if( zTName && (zTabName==0 || zTabName[0]==0 || 1187cf55b7aeSdrh sqlite3StrICmp(zTName, zTabName)!=0) ){ 118854473229Sdrh continue; 118954473229Sdrh } 119054473229Sdrh tableSeen = 1; 1191d8bc7086Sdrh for(j=0; j<pTab->nCol; j++){ 119222f70c32Sdrh Expr *pExpr, *pLeft, *pRight; 1193ad2d8307Sdrh char *zName = pTab->aCol[j].zName; 1194ad2d8307Sdrh 119591bb0eedSdrh if( i>0 ){ 119691bb0eedSdrh struct SrcList_item *pLeft = &pTabList->a[i-1]; 119791bb0eedSdrh if( (pLeft->jointype & JT_NATURAL)!=0 && 119891bb0eedSdrh columnIndex(pLeft->pTab, zName)>=0 ){ 1199ad2d8307Sdrh /* In a NATURAL join, omit the join columns from the 1200ad2d8307Sdrh ** table on the right */ 1201ad2d8307Sdrh continue; 1202ad2d8307Sdrh } 120391bb0eedSdrh if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){ 1204ad2d8307Sdrh /* In a join with a USING clause, omit columns in the 1205ad2d8307Sdrh ** using clause from the table on the right. */ 1206ad2d8307Sdrh continue; 1207ad2d8307Sdrh } 120891bb0eedSdrh } 12094adee20fSdanielk1977 pRight = sqlite3Expr(TK_ID, 0, 0, 0); 121022f70c32Sdrh if( pRight==0 ) break; 121191bb0eedSdrh setToken(&pRight->token, zName); 1212d70dc52dSdrh if( zTabName && (longNames || pTabList->nSrc>1) ){ 12134adee20fSdanielk1977 pLeft = sqlite3Expr(TK_ID, 0, 0, 0); 12144adee20fSdanielk1977 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0); 121522f70c32Sdrh if( pExpr==0 ) break; 121691bb0eedSdrh setToken(&pLeft->token, zTabName); 121791bb0eedSdrh setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName)); 12186977fea8Sdrh pExpr->span.dyn = 1; 12196977fea8Sdrh pExpr->token.z = 0; 12206977fea8Sdrh pExpr->token.n = 0; 12216977fea8Sdrh pExpr->token.dyn = 0; 122222f70c32Sdrh }else{ 122322f70c32Sdrh pExpr = pRight; 12246977fea8Sdrh pExpr->span = pExpr->token; 122522f70c32Sdrh } 1226d70dc52dSdrh if( longNames ){ 1227d70dc52dSdrh pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span); 1228d70dc52dSdrh }else{ 122979d5f63fSdrh pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token); 1230d8bc7086Sdrh } 1231d8bc7086Sdrh } 1232d70dc52dSdrh } 123354473229Sdrh if( !tableSeen ){ 1234cf55b7aeSdrh if( zTName ){ 1235cf55b7aeSdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 1236f5db2d3eSdrh }else{ 12374adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no tables specified"); 1238f5db2d3eSdrh } 123954473229Sdrh rc = 1; 124054473229Sdrh } 1241cf55b7aeSdrh sqliteFree(zTName); 12427c917d19Sdrh } 12437c917d19Sdrh } 12444adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 12457c917d19Sdrh p->pEList = pNew; 1246d8bc7086Sdrh } 124754473229Sdrh return rc; 1248d8bc7086Sdrh } 1249d8bc7086Sdrh 125093758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1251ff78bd2fSdrh /* 1252d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with 1253d8bc7086Sdrh ** columns in a result. For each ORDER BY expression, the opcode of 1254967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of 1255d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable 1256d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter. 1257d8bc7086Sdrh ** 1258d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first. A match 1259d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT. 1260d8bc7086Sdrh ** 1261d8bc7086Sdrh ** Any entry that does not match is flagged as an error. The number 1262d8bc7086Sdrh ** of errors is returned. 1263d8bc7086Sdrh */ 1264d8bc7086Sdrh static int matchOrderbyToColumn( 1265d8bc7086Sdrh Parse *pParse, /* A place to leave error messages */ 1266d8bc7086Sdrh Select *pSelect, /* Match to result columns of this SELECT */ 1267d8bc7086Sdrh ExprList *pOrderBy, /* The ORDER BY values to match against columns */ 1268e4de1febSdrh int iTable, /* Insert this value in iTable */ 1269d8bc7086Sdrh int mustComplete /* If TRUE all ORDER BYs must match */ 1270d8bc7086Sdrh ){ 1271d8bc7086Sdrh int nErr = 0; 1272d8bc7086Sdrh int i, j; 1273d8bc7086Sdrh ExprList *pEList; 1274d8bc7086Sdrh 1275daffd0e5Sdrh if( pSelect==0 || pOrderBy==0 ) return 1; 1276d8bc7086Sdrh if( mustComplete ){ 1277d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } 1278d8bc7086Sdrh } 12799b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 1280d8bc7086Sdrh return 1; 1281d8bc7086Sdrh } 1282d8bc7086Sdrh if( pSelect->pPrior ){ 128392cd52f5Sdrh if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ 128492cd52f5Sdrh return 1; 128592cd52f5Sdrh } 1286d8bc7086Sdrh } 1287d8bc7086Sdrh pEList = pSelect->pEList; 1288d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 1289d8bc7086Sdrh Expr *pE = pOrderBy->a[i].pExpr; 1290e4de1febSdrh int iCol = -1; 1291d8bc7086Sdrh if( pOrderBy->a[i].done ) continue; 12924adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 1293e4de1febSdrh if( iCol<=0 || iCol>pEList->nExpr ){ 12944adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1295da93d238Sdrh "ORDER BY position %d should be between 1 and %d", 1296e4de1febSdrh iCol, pEList->nExpr); 1297e4de1febSdrh nErr++; 1298e4de1febSdrh break; 1299e4de1febSdrh } 1300fcb78a49Sdrh if( !mustComplete ) continue; 1301e4de1febSdrh iCol--; 1302e4de1febSdrh } 1303e4de1febSdrh for(j=0; iCol<0 && j<pEList->nExpr; j++){ 13044cfa7934Sdrh if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){ 1305a76b5dfcSdrh char *zName, *zLabel; 1306a76b5dfcSdrh zName = pEList->a[j].zName; 1307a99db3b6Sdrh zLabel = sqlite3NameFromToken(&pE->token); 1308a99db3b6Sdrh assert( zLabel!=0 ); 13094adee20fSdanielk1977 if( sqlite3StrICmp(zName, zLabel)==0 ){ 1310e4de1febSdrh iCol = j; 1311d8bc7086Sdrh } 13126e142f54Sdrh sqliteFree(zLabel); 1313d8bc7086Sdrh } 13144adee20fSdanielk1977 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){ 1315e4de1febSdrh iCol = j; 1316d8bc7086Sdrh } 1317e4de1febSdrh } 1318e4de1febSdrh if( iCol>=0 ){ 1319967e8b73Sdrh pE->op = TK_COLUMN; 1320e4de1febSdrh pE->iColumn = iCol; 1321d8bc7086Sdrh pE->iTable = iTable; 1322a58fdfb1Sdanielk1977 pE->iAgg = -1; 1323d8bc7086Sdrh pOrderBy->a[i].done = 1; 1324d8bc7086Sdrh } 1325e4de1febSdrh if( iCol<0 && mustComplete ){ 13264adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1327da93d238Sdrh "ORDER BY term number %d does not match any result column", i+1); 1328d8bc7086Sdrh nErr++; 1329d8bc7086Sdrh break; 1330d8bc7086Sdrh } 1331d8bc7086Sdrh } 1332d8bc7086Sdrh return nErr; 1333d8bc7086Sdrh } 133493758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */ 1335d8bc7086Sdrh 1336d8bc7086Sdrh /* 1337d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1338d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1339d8bc7086Sdrh */ 13404adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1341d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1342d8bc7086Sdrh if( v==0 ){ 13434adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1344d8bc7086Sdrh } 1345d8bc7086Sdrh return v; 1346d8bc7086Sdrh } 1347d8bc7086Sdrh 1348d8bc7086Sdrh /* 13497b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1350ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 13517b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1352a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1353a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1354a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1355a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 13567b58daeaSdrh ** 13577b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if 1358ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 13597b58daeaSdrh ** iOffset should have been preset to appropriate default values 13607b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1361ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 13627b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 13637b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 13647b58daeaSdrh ** SELECT statements. 13657b58daeaSdrh */ 1366ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 13677b58daeaSdrh /* 13687b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 13697b58daeaSdrh ** contraversy about what the correct behavior should be. 13707b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 13717b58daeaSdrh ** no rows. 13727b58daeaSdrh */ 1373a2dc3b1aSdanielk1977 if( p->pLimit ){ 13747b58daeaSdrh int iMem = pParse->nMem++; 13754adee20fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 13767b58daeaSdrh if( v==0 ) return; 1377a2dc3b1aSdanielk1977 sqlite3ExprCode(pParse, p->pLimit); 1378a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 1379a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_Negative, 0, 0); 13804adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1); 1381ad6d9460Sdrh VdbeComment((v, "# LIMIT counter")); 1382ec7429aeSdrh sqlite3VdbeAddOp(v, OP_IfMemZero, iMem, iBreak); 13837b58daeaSdrh p->iLimit = iMem; 13847b58daeaSdrh } 1385a2dc3b1aSdanielk1977 if( p->pOffset ){ 13867b58daeaSdrh int iMem = pParse->nMem++; 13874adee20fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 13887b58daeaSdrh if( v==0 ) return; 1389a2dc3b1aSdanielk1977 sqlite3ExprCode(pParse, p->pOffset); 1390a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 1391a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_Negative, 0, 0); 13924adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1); 1393ad6d9460Sdrh VdbeComment((v, "# OFFSET counter")); 13947b58daeaSdrh p->iOffset = iMem; 13957b58daeaSdrh } 13967b58daeaSdrh } 13977b58daeaSdrh 13987b58daeaSdrh /* 13990342b1f5Sdrh ** Allocate a virtual index to use for sorting. 1400d3d39e93Sdrh */ 14014db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){ 14020342b1f5Sdrh if( pOrderBy ){ 1403dc1bdc4fSdanielk1977 int addr; 14049d2985c7Sdrh assert( pOrderBy->iECursor==0 ); 14059d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 14060342b1f5Sdrh addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual, 14079d2985c7Sdrh pOrderBy->iECursor, pOrderBy->nExpr+1); 14080342b1f5Sdrh assert( p->addrOpenVirt[2] == -1 ); 14090342b1f5Sdrh p->addrOpenVirt[2] = addr; 1410736c22b8Sdrh } 1411dc1bdc4fSdanielk1977 } 1412dc1bdc4fSdanielk1977 141313449892Sdrh /* 141413449892Sdrh ** The opcode at addr is an OP_OpenVirtual that created a sorting 141513449892Sdrh ** index tha we ended up not needing. This routine changes that 141613449892Sdrh ** opcode to OP_Noop. 141713449892Sdrh */ 141813449892Sdrh static void uncreateSortingIndex(Parse *pParse, int addr){ 141913449892Sdrh Vdbe *v = pParse->pVdbe; 142013449892Sdrh VdbeOp *pOp = sqlite3VdbeGetOp(v, addr); 142113449892Sdrh sqlite3VdbeChangeP3(v, addr, 0, 0); 142213449892Sdrh pOp->opcode = OP_Noop; 142313449892Sdrh pOp->p1 = 0; 142413449892Sdrh pOp->p2 = 0; 142513449892Sdrh } 142613449892Sdrh 1427b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1428fbc4ee7bSdrh /* 1429fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1430fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1431fbc4ee7bSdrh ** the column has no default collating sequence. 1432fbc4ee7bSdrh ** 1433fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1434fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1435fbc4ee7bSdrh */ 1436dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1437fbc4ee7bSdrh CollSeq *pRet; 1438dc1bdc4fSdanielk1977 if( p->pPrior ){ 1439dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1440fbc4ee7bSdrh }else{ 1441fbc4ee7bSdrh pRet = 0; 1442dc1bdc4fSdanielk1977 } 1443fbc4ee7bSdrh if( pRet==0 ){ 1444dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1445dc1bdc4fSdanielk1977 } 1446dc1bdc4fSdanielk1977 return pRet; 1447d3d39e93Sdrh } 1448b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1449d3d39e93Sdrh 1450b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1451d3d39e93Sdrh /* 145282c3d636Sdrh ** This routine is called to process a query that is really the union 145382c3d636Sdrh ** or intersection of two or more separate queries. 1454c926afbcSdrh ** 1455e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1456e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1457e78e8284Sdrh ** in which case this routine will be called recursively. 1458e78e8284Sdrh ** 1459e78e8284Sdrh ** The results of the total query are to be written into a destination 1460e78e8284Sdrh ** of type eDest with parameter iParm. 1461e78e8284Sdrh ** 1462e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1463e78e8284Sdrh ** 1464e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1465e78e8284Sdrh ** 1466e78e8284Sdrh ** This statement is parsed up as follows: 1467e78e8284Sdrh ** 1468e78e8284Sdrh ** SELECT c FROM t3 1469e78e8284Sdrh ** | 1470e78e8284Sdrh ** `-----> SELECT b FROM t2 1471e78e8284Sdrh ** | 14724b11c6d3Sjplyon ** `------> SELECT a FROM t1 1473e78e8284Sdrh ** 1474e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1475e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1476e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1477e78e8284Sdrh ** 1478e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1479e78e8284Sdrh ** individual selects always group from left to right. 148082c3d636Sdrh */ 148184ac9d02Sdanielk1977 static int multiSelect( 1482fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1483fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1484fbc4ee7bSdrh int eDest, /* \___ Store query results as specified */ 1485fbc4ee7bSdrh int iParm, /* / by these two parameters. */ 148684ac9d02Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 148784ac9d02Sdanielk1977 ){ 148884ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 148910e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 149010e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 14918cdbf836Sdrh int nCol; /* Number of columns in the result set */ 14920342b1f5Sdrh ExprList *pOrderBy; /* The ORDER BY clause on p */ 14930342b1f5Sdrh int aSetP2[2]; /* Set P2 value of these op to number of columns */ 14940342b1f5Sdrh int nSetP2 = 0; /* Number of slots in aSetP2[] used */ 149582c3d636Sdrh 14967b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1497fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 149882c3d636Sdrh */ 149984ac9d02Sdanielk1977 if( p==0 || p->pPrior==0 ){ 150084ac9d02Sdanielk1977 rc = 1; 150184ac9d02Sdanielk1977 goto multi_select_end; 150284ac9d02Sdanielk1977 } 1503d8bc7086Sdrh pPrior = p->pPrior; 15040342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 15050342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1506d8bc7086Sdrh if( pPrior->pOrderBy ){ 15074adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1508da93d238Sdrh selectOpName(p->op)); 150984ac9d02Sdanielk1977 rc = 1; 151084ac9d02Sdanielk1977 goto multi_select_end; 151182c3d636Sdrh } 1512a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 15134adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 15147b58daeaSdrh selectOpName(p->op)); 151584ac9d02Sdanielk1977 rc = 1; 151684ac9d02Sdanielk1977 goto multi_select_end; 15177b58daeaSdrh } 151882c3d636Sdrh 1519d8bc7086Sdrh /* Make sure we have a valid query engine. If not, create a new one. 1520d8bc7086Sdrh */ 15214adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 152284ac9d02Sdanielk1977 if( v==0 ){ 152384ac9d02Sdanielk1977 rc = 1; 152484ac9d02Sdanielk1977 goto multi_select_end; 152584ac9d02Sdanielk1977 } 1526d8bc7086Sdrh 15271cc3d75fSdrh /* Create the destination temporary table if necessary 15281cc3d75fSdrh */ 15299d2985c7Sdrh if( eDest==SRT_VirtualTab ){ 1530b4964b72Sdanielk1977 assert( p->pEList ); 15310342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 15320342b1f5Sdrh aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0); 15331cc3d75fSdrh eDest = SRT_Table; 15341cc3d75fSdrh } 15351cc3d75fSdrh 1536f46f905aSdrh /* Generate code for the left and right SELECT statements. 1537d8bc7086Sdrh */ 15380342b1f5Sdrh pOrderBy = p->pOrderBy; 153982c3d636Sdrh switch( p->op ){ 1540f46f905aSdrh case TK_ALL: { 15410342b1f5Sdrh if( pOrderBy==0 ){ 1542ec7429aeSdrh int addr = 0; 1543a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1544a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1545a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 1546b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff); 154784ac9d02Sdanielk1977 if( rc ){ 154884ac9d02Sdanielk1977 goto multi_select_end; 154984ac9d02Sdanielk1977 } 1550f46f905aSdrh p->pPrior = 0; 15517b58daeaSdrh p->iLimit = pPrior->iLimit; 15527b58daeaSdrh p->iOffset = pPrior->iOffset; 1553a2dc3b1aSdanielk1977 p->pLimit = 0; 1554a2dc3b1aSdanielk1977 p->pOffset = 0; 1555ec7429aeSdrh if( p->iLimit>=0 ){ 1556ec7429aeSdrh addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0); 1557ec7429aeSdrh VdbeComment((v, "# Jump ahead if LIMIT reached")); 1558ec7429aeSdrh } 1559b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff); 1560f46f905aSdrh p->pPrior = pPrior; 156184ac9d02Sdanielk1977 if( rc ){ 156284ac9d02Sdanielk1977 goto multi_select_end; 156384ac9d02Sdanielk1977 } 1564ec7429aeSdrh if( addr ){ 1565ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1566ec7429aeSdrh } 1567f46f905aSdrh break; 1568f46f905aSdrh } 1569f46f905aSdrh /* For UNION ALL ... ORDER BY fall through to the next case */ 1570f46f905aSdrh } 157182c3d636Sdrh case TK_EXCEPT: 157282c3d636Sdrh case TK_UNION: { 1573d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1574742f947bSdanielk1977 int op = 0; /* One of the SRT_ operations to apply to self */ 1575d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1576a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1577dc1bdc4fSdanielk1977 int addr; 157882c3d636Sdrh 1579d8bc7086Sdrh priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 15800342b1f5Sdrh if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ 1581d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1582c926afbcSdrh ** right. 1583d8bc7086Sdrh */ 158482c3d636Sdrh unionTab = iParm; 158582c3d636Sdrh }else{ 1586d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1587d8bc7086Sdrh ** intermediate results. 1588d8bc7086Sdrh */ 158982c3d636Sdrh unionTab = pParse->nTab++; 15900342b1f5Sdrh if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){ 159184ac9d02Sdanielk1977 rc = 1; 159284ac9d02Sdanielk1977 goto multi_select_end; 1593d8bc7086Sdrh } 15949170dd7eSdrh addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0); 15950342b1f5Sdrh if( priorOp==SRT_Table ){ 15960342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 15970342b1f5Sdrh aSetP2[nSetP2++] = addr; 15980342b1f5Sdrh }else{ 15990342b1f5Sdrh assert( p->addrOpenVirt[0] == -1 ); 16000342b1f5Sdrh p->addrOpenVirt[0] = addr; 16010342b1f5Sdrh p->pRightmost->usesVirt = 1; 1602dc1bdc4fSdanielk1977 } 16030342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 160484ac9d02Sdanielk1977 assert( p->pEList ); 1605d8bc7086Sdrh } 1606d8bc7086Sdrh 1607d8bc7086Sdrh /* Code the SELECT statements to our left 1608d8bc7086Sdrh */ 1609b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 1610b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); 161184ac9d02Sdanielk1977 if( rc ){ 161284ac9d02Sdanielk1977 goto multi_select_end; 161384ac9d02Sdanielk1977 } 1614d8bc7086Sdrh 1615d8bc7086Sdrh /* Code the current SELECT statement 1616d8bc7086Sdrh */ 1617d8bc7086Sdrh switch( p->op ){ 1618d8bc7086Sdrh case TK_EXCEPT: op = SRT_Except; break; 1619d8bc7086Sdrh case TK_UNION: op = SRT_Union; break; 1620d8bc7086Sdrh case TK_ALL: op = SRT_Table; break; 1621d8bc7086Sdrh } 162282c3d636Sdrh p->pPrior = 0; 1623c926afbcSdrh p->pOrderBy = 0; 16244b14b4d7Sdrh p->disallowOrderBy = pOrderBy!=0; 1625a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1626a2dc3b1aSdanielk1977 p->pLimit = 0; 1627a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1628a2dc3b1aSdanielk1977 p->pOffset = 0; 1629b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff); 163082c3d636Sdrh p->pPrior = pPrior; 1631c926afbcSdrh p->pOrderBy = pOrderBy; 1632a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 1633a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1634a2dc3b1aSdanielk1977 p->pOffset = pOffset; 1635be5fd490Sdrh p->iLimit = -1; 1636be5fd490Sdrh p->iOffset = -1; 163784ac9d02Sdanielk1977 if( rc ){ 163884ac9d02Sdanielk1977 goto multi_select_end; 163984ac9d02Sdanielk1977 } 164084ac9d02Sdanielk1977 1641d8bc7086Sdrh 1642d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1643d8bc7086Sdrh ** it is that we currently need. 1644d8bc7086Sdrh */ 1645c926afbcSdrh if( eDest!=priorOp || unionTab!=iParm ){ 16466b56344dSdrh int iCont, iBreak, iStart; 164782c3d636Sdrh assert( p->pEList ); 164841202ccaSdrh if( eDest==SRT_Callback ){ 16496a3ea0e6Sdrh generateColumnNames(pParse, 0, p->pEList); 165041202ccaSdrh } 16514adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 16524adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1653ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 16544adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); 16554adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 165638640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 16570342b1f5Sdrh pOrderBy, -1, eDest, iParm, 165884ac9d02Sdanielk1977 iCont, iBreak, 0); 165984ac9d02Sdanielk1977 if( rc ){ 166084ac9d02Sdanielk1977 rc = 1; 166184ac9d02Sdanielk1977 goto multi_select_end; 166284ac9d02Sdanielk1977 } 16634adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 16644adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); 16654adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 16664adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); 166782c3d636Sdrh } 166882c3d636Sdrh break; 166982c3d636Sdrh } 167082c3d636Sdrh case TK_INTERSECT: { 167182c3d636Sdrh int tab1, tab2; 16726b56344dSdrh int iCont, iBreak, iStart; 1673a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 1674dc1bdc4fSdanielk1977 int addr; 167582c3d636Sdrh 1676d8bc7086Sdrh /* INTERSECT is different from the others since it requires 16776206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1678d8bc7086Sdrh ** by allocating the tables we will need. 1679d8bc7086Sdrh */ 168082c3d636Sdrh tab1 = pParse->nTab++; 168182c3d636Sdrh tab2 = pParse->nTab++; 16820342b1f5Sdrh if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){ 168384ac9d02Sdanielk1977 rc = 1; 168484ac9d02Sdanielk1977 goto multi_select_end; 1685d8bc7086Sdrh } 16860342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 1687dc1bdc4fSdanielk1977 16889170dd7eSdrh addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0); 16890342b1f5Sdrh assert( p->addrOpenVirt[0] == -1 ); 16900342b1f5Sdrh p->addrOpenVirt[0] = addr; 16910342b1f5Sdrh p->pRightmost->usesVirt = 1; 169284ac9d02Sdanielk1977 assert( p->pEList ); 1693d8bc7086Sdrh 1694d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1695d8bc7086Sdrh */ 1696b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); 169784ac9d02Sdanielk1977 if( rc ){ 169884ac9d02Sdanielk1977 goto multi_select_end; 169984ac9d02Sdanielk1977 } 1700d8bc7086Sdrh 1701d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1702d8bc7086Sdrh */ 17039170dd7eSdrh addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0); 17040342b1f5Sdrh assert( p->addrOpenVirt[1] == -1 ); 17050342b1f5Sdrh p->addrOpenVirt[1] = addr; 170682c3d636Sdrh p->pPrior = 0; 1707a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1708a2dc3b1aSdanielk1977 p->pLimit = 0; 1709a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1710a2dc3b1aSdanielk1977 p->pOffset = 0; 1711b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); 171282c3d636Sdrh p->pPrior = pPrior; 1713a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 1714a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1715a2dc3b1aSdanielk1977 p->pOffset = pOffset; 171684ac9d02Sdanielk1977 if( rc ){ 171784ac9d02Sdanielk1977 goto multi_select_end; 171884ac9d02Sdanielk1977 } 1719d8bc7086Sdrh 1720d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1721d8bc7086Sdrh ** tables. 1722d8bc7086Sdrh */ 172382c3d636Sdrh assert( p->pEList ); 172441202ccaSdrh if( eDest==SRT_Callback ){ 17256a3ea0e6Sdrh generateColumnNames(pParse, 0, p->pEList); 172641202ccaSdrh } 17274adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 17284adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1729ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 17304adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak); 17314a9f241cSdrh iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0); 17324adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont); 173338640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 17340342b1f5Sdrh pOrderBy, -1, eDest, iParm, 173584ac9d02Sdanielk1977 iCont, iBreak, 0); 173684ac9d02Sdanielk1977 if( rc ){ 173784ac9d02Sdanielk1977 rc = 1; 173884ac9d02Sdanielk1977 goto multi_select_end; 173984ac9d02Sdanielk1977 } 17404adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 17414adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); 17424adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 17434adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab2, 0); 17444adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab1, 0); 174582c3d636Sdrh break; 174682c3d636Sdrh } 174782c3d636Sdrh } 17488cdbf836Sdrh 17498cdbf836Sdrh /* Make sure all SELECTs in the statement have the same number of elements 17508cdbf836Sdrh ** in their result sets. 17518cdbf836Sdrh */ 175282c3d636Sdrh assert( p->pEList && pPrior->pEList ); 175382c3d636Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 17544adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1755da93d238Sdrh " do not have the same number of result columns", selectOpName(p->op)); 175684ac9d02Sdanielk1977 rc = 1; 175784ac9d02Sdanielk1977 goto multi_select_end; 17582282792aSdrh } 175984ac9d02Sdanielk1977 17608cdbf836Sdrh /* Set the number of columns in temporary tables 17618cdbf836Sdrh */ 17628cdbf836Sdrh nCol = p->pEList->nExpr; 17630342b1f5Sdrh while( nSetP2 ){ 17640342b1f5Sdrh sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol); 17658cdbf836Sdrh } 17668cdbf836Sdrh 1767fbc4ee7bSdrh /* Compute collating sequences used by either the ORDER BY clause or 1768fbc4ee7bSdrh ** by any temporary tables needed to implement the compound select. 1769fbc4ee7bSdrh ** Attach the KeyInfo structure to all temporary tables. Invoke the 1770fbc4ee7bSdrh ** ORDER BY processing if there is an ORDER BY clause. 17718cdbf836Sdrh ** 17728cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 17738cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 17748cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 17758cdbf836Sdrh ** no temp tables are required. 1776fbc4ee7bSdrh */ 17770342b1f5Sdrh if( pOrderBy || p->usesVirt ){ 1778fbc4ee7bSdrh int i; /* Loop counter */ 1779fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 17800342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 17810342b1f5Sdrh CollSeq **apColl; 17820342b1f5Sdrh CollSeq **aCopy; 1783fbc4ee7bSdrh 17840342b1f5Sdrh assert( p->pRightmost==p ); 17854db38a70Sdrh pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*) + nCol); 1786dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1787dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1788dc1bdc4fSdanielk1977 goto multi_select_end; 1789dc1bdc4fSdanielk1977 } 1790dc1bdc4fSdanielk1977 1791dc1bdc4fSdanielk1977 pKeyInfo->enc = pParse->db->enc; 1792dc1bdc4fSdanielk1977 pKeyInfo->nField = nCol; 1793dc1bdc4fSdanielk1977 17940342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 17950342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 17960342b1f5Sdrh if( 0==*apColl ){ 17970342b1f5Sdrh *apColl = pParse->db->pDfltColl; 1798dc1bdc4fSdanielk1977 } 1799dc1bdc4fSdanielk1977 } 1800dc1bdc4fSdanielk1977 18010342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 18020342b1f5Sdrh for(i=0; i<2; i++){ 18030342b1f5Sdrh int addr = pLoop->addrOpenVirt[i]; 18040342b1f5Sdrh if( addr<0 ){ 18050342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 18060342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 18070342b1f5Sdrh assert( pLoop->addrOpenVirt[1]<0 ); 18080342b1f5Sdrh break; 18090342b1f5Sdrh } 18100342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 18110342b1f5Sdrh sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO); 18120342b1f5Sdrh } 1813dc1bdc4fSdanielk1977 } 1814dc1bdc4fSdanielk1977 18150342b1f5Sdrh if( pOrderBy ){ 18160342b1f5Sdrh struct ExprList_item *pOTerm = pOrderBy->a; 18170342b1f5Sdrh int nExpr = pOrderBy->nExpr; 18180342b1f5Sdrh int addr; 18194db38a70Sdrh u8 *pSortOrder; 18200342b1f5Sdrh 18210342b1f5Sdrh aCopy = (CollSeq**)&pKeyInfo[1]; 18224db38a70Sdrh pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nExpr]; 18230342b1f5Sdrh memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*)); 18240342b1f5Sdrh apColl = pKeyInfo->aColl; 18254db38a70Sdrh for(i=0; i<pOrderBy->nExpr; i++, pOTerm++, apColl++, pSortOrder++){ 18260342b1f5Sdrh Expr *pExpr = pOTerm->pExpr; 18270342b1f5Sdrh char *zName = pOTerm->zName; 1828dc1bdc4fSdanielk1977 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol ); 1829dc1bdc4fSdanielk1977 if( zName ){ 18300342b1f5Sdrh *apColl = sqlite3LocateCollSeq(pParse, zName, -1); 183184ac9d02Sdanielk1977 }else{ 18320342b1f5Sdrh *apColl = aCopy[pExpr->iColumn]; 183384ac9d02Sdanielk1977 } 18344db38a70Sdrh *pSortOrder = pOTerm->sortOrder; 183584ac9d02Sdanielk1977 } 18360342b1f5Sdrh assert( p->pRightmost==p ); 18370342b1f5Sdrh assert( p->addrOpenVirt[2]>=0 ); 18380342b1f5Sdrh addr = p->addrOpenVirt[2]; 18394db38a70Sdrh sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2); 1840a7aa59e0Sdrh pKeyInfo->nField = pOrderBy->nExpr; 18414db38a70Sdrh sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 18424db38a70Sdrh pKeyInfo = 0; 1843dc1bdc4fSdanielk1977 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm); 1844dc1bdc4fSdanielk1977 } 1845dc1bdc4fSdanielk1977 1846dc1bdc4fSdanielk1977 sqliteFree(pKeyInfo); 1847dc1bdc4fSdanielk1977 } 1848dc1bdc4fSdanielk1977 1849dc1bdc4fSdanielk1977 multi_select_end: 185084ac9d02Sdanielk1977 return rc; 18512282792aSdrh } 1852b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 18532282792aSdrh 1854b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 18552282792aSdrh /* 1856832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 18576a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 185884e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 18596a3ea0e6Sdrh ** unchanged.) 1860832508b7Sdrh ** 1861832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 1862832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 1863832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 1864832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 1865832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 1866832508b7Sdrh ** of the subquery rather the result set of the subquery. 1867832508b7Sdrh */ 18686a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */ 1869b3bce662Sdanielk1977 static void substSelect(Select *, int, ExprList *); /* Forward Decl */ 18706a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){ 1871832508b7Sdrh if( pExpr==0 ) return; 187250350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 187350350a15Sdrh if( pExpr->iColumn<0 ){ 187450350a15Sdrh pExpr->op = TK_NULL; 187550350a15Sdrh }else{ 1876832508b7Sdrh Expr *pNew; 187784e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 1878832508b7Sdrh assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 1879832508b7Sdrh pNew = pEList->a[pExpr->iColumn].pExpr; 1880832508b7Sdrh assert( pNew!=0 ); 1881832508b7Sdrh pExpr->op = pNew->op; 1882d94a6698Sdrh assert( pExpr->pLeft==0 ); 18834adee20fSdanielk1977 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft); 1884d94a6698Sdrh assert( pExpr->pRight==0 ); 18854adee20fSdanielk1977 pExpr->pRight = sqlite3ExprDup(pNew->pRight); 1886d94a6698Sdrh assert( pExpr->pList==0 ); 18874adee20fSdanielk1977 pExpr->pList = sqlite3ExprListDup(pNew->pList); 1888832508b7Sdrh pExpr->iTable = pNew->iTable; 1889832508b7Sdrh pExpr->iColumn = pNew->iColumn; 1890832508b7Sdrh pExpr->iAgg = pNew->iAgg; 18914adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->token, &pNew->token); 18924adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->span, &pNew->span); 1893a1cb183dSdanielk1977 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect); 1894a1cb183dSdanielk1977 pExpr->flags = pNew->flags; 189550350a15Sdrh } 1896832508b7Sdrh }else{ 18976a3ea0e6Sdrh substExpr(pExpr->pLeft, iTable, pEList); 18986a3ea0e6Sdrh substExpr(pExpr->pRight, iTable, pEList); 1899b3bce662Sdanielk1977 substSelect(pExpr->pSelect, iTable, pEList); 19006a3ea0e6Sdrh substExprList(pExpr->pList, iTable, pEList); 1901832508b7Sdrh } 1902832508b7Sdrh } 1903b3bce662Sdanielk1977 static void substExprList(ExprList *pList, int iTable, ExprList *pEList){ 1904832508b7Sdrh int i; 1905832508b7Sdrh if( pList==0 ) return; 1906832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 19076a3ea0e6Sdrh substExpr(pList->a[i].pExpr, iTable, pEList); 1908832508b7Sdrh } 1909832508b7Sdrh } 1910b3bce662Sdanielk1977 static void substSelect(Select *p, int iTable, ExprList *pEList){ 1911b3bce662Sdanielk1977 if( !p ) return; 1912b3bce662Sdanielk1977 substExprList(p->pEList, iTable, pEList); 1913b3bce662Sdanielk1977 substExprList(p->pGroupBy, iTable, pEList); 1914b3bce662Sdanielk1977 substExprList(p->pOrderBy, iTable, pEList); 1915b3bce662Sdanielk1977 substExpr(p->pHaving, iTable, pEList); 1916b3bce662Sdanielk1977 substExpr(p->pWhere, iTable, pEList); 1917b3bce662Sdanielk1977 } 1918b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */ 1919832508b7Sdrh 1920b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 1921832508b7Sdrh /* 19221350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 19231350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 19241350b030Sdrh ** occurs. 19251350b030Sdrh ** 19261350b030Sdrh ** To understand the concept of flattening, consider the following 19271350b030Sdrh ** query: 19281350b030Sdrh ** 19291350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 19301350b030Sdrh ** 19311350b030Sdrh ** The default way of implementing this query is to execute the 19321350b030Sdrh ** subquery first and store the results in a temporary table, then 19331350b030Sdrh ** run the outer query on that temporary table. This requires two 19341350b030Sdrh ** passes over the data. Furthermore, because the temporary table 19351350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 1936832508b7Sdrh ** optimized. 19371350b030Sdrh ** 1938832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 19391350b030Sdrh ** a single flat select, like this: 19401350b030Sdrh ** 19411350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 19421350b030Sdrh ** 19431350b030Sdrh ** The code generated for this simpification gives the same result 1944832508b7Sdrh ** but only has to scan the data once. And because indices might 1945832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 1946832508b7Sdrh ** avoided. 19471350b030Sdrh ** 1948832508b7Sdrh ** Flattening is only attempted if all of the following are true: 19491350b030Sdrh ** 1950832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 19511350b030Sdrh ** 1952832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 1953832508b7Sdrh ** 19548af4d3acSdrh ** (3) The subquery is not the right operand of a left outer join, or 19558af4d3acSdrh ** the subquery is not itself a join. (Ticket #306) 1956832508b7Sdrh ** 1957832508b7Sdrh ** (4) The subquery is not DISTINCT or the outer query is not a join. 1958832508b7Sdrh ** 1959832508b7Sdrh ** (5) The subquery is not DISTINCT or the outer query does not use 1960832508b7Sdrh ** aggregates. 1961832508b7Sdrh ** 1962832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 1963832508b7Sdrh ** DISTINCT. 1964832508b7Sdrh ** 196508192d5fSdrh ** (7) The subquery has a FROM clause. 196608192d5fSdrh ** 1967df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 1968df199a25Sdrh ** 1969df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 1970df199a25Sdrh ** aggregates. 1971df199a25Sdrh ** 1972df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 1973df199a25Sdrh ** use LIMIT. 1974df199a25Sdrh ** 1975174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 1976174b6195Sdrh ** 19773fc673e6Sdrh ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 19783fc673e6Sdrh ** subquery has no WHERE clause. (added by ticket #350) 19793fc673e6Sdrh ** 1980832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 1981832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 1982832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 1983832508b7Sdrh ** 1984665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 1985832508b7Sdrh ** If flattening is attempted this routine returns 1. 1986832508b7Sdrh ** 1987832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 1988832508b7Sdrh ** the subquery before this routine runs. 19891350b030Sdrh */ 19908c74a8caSdrh static int flattenSubquery( 19918c74a8caSdrh Parse *pParse, /* The parsing context */ 19928c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 19938c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 19948c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 19958c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 19968c74a8caSdrh ){ 19970bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 1998ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 1999ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 20000bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 20016a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 200291bb0eedSdrh int i; /* Loop counter */ 200391bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 200491bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 20051350b030Sdrh 2006832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2007832508b7Sdrh */ 2008832508b7Sdrh if( p==0 ) return 0; 2009832508b7Sdrh pSrc = p->pSrc; 2010ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 201191bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 201291bb0eedSdrh pSub = pSubitem->pSelect; 2013832508b7Sdrh assert( pSub!=0 ); 2014832508b7Sdrh if( isAgg && subqueryIsAgg ) return 0; 2015ad3cab52Sdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; 2016832508b7Sdrh pSubSrc = pSub->pSrc; 2017832508b7Sdrh assert( pSubSrc ); 2018a2dc3b1aSdanielk1977 if( (pSub->pLimit && p->pLimit) || pSub->pOffset || 2019a2dc3b1aSdanielk1977 (pSub->pLimit && isAgg) ) return 0; 2020c31c2eb8Sdrh if( pSubSrc->nSrc==0 ) return 0; 2021a2dc3b1aSdanielk1977 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){ 2022df199a25Sdrh return 0; 2023df199a25Sdrh } 2024a2dc3b1aSdanielk1977 if( p->isDistinct && subqueryIsAgg ) return 0; 20254b14b4d7Sdrh if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ) return 0; 2026832508b7Sdrh 20278af4d3acSdrh /* Restriction 3: If the subquery is a join, make sure the subquery is 20288af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 20298af4d3acSdrh ** is not allowed: 20308af4d3acSdrh ** 20318af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 20328af4d3acSdrh ** 20338af4d3acSdrh ** If we flatten the above, we would get 20348af4d3acSdrh ** 20358af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 20368af4d3acSdrh ** 20378af4d3acSdrh ** which is not at all the same thing. 20388af4d3acSdrh */ 20398af4d3acSdrh if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){ 20408af4d3acSdrh return 0; 20418af4d3acSdrh } 20428af4d3acSdrh 20433fc673e6Sdrh /* Restriction 12: If the subquery is the right operand of a left outer 20443fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 20453fc673e6Sdrh ** An examples of why this is not allowed: 20463fc673e6Sdrh ** 20473fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 20483fc673e6Sdrh ** 20493fc673e6Sdrh ** If we flatten the above, we would get 20503fc673e6Sdrh ** 20513fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 20523fc673e6Sdrh ** 20533fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 20543fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 20553fc673e6Sdrh */ 20563fc673e6Sdrh if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 20573fc673e6Sdrh && pSub->pWhere!=0 ){ 20583fc673e6Sdrh return 0; 20593fc673e6Sdrh } 20603fc673e6Sdrh 20610bb28106Sdrh /* If we reach this point, it means flattening is permitted for the 206263eb5f29Sdrh ** iFrom-th entry of the FROM clause in the outer query. 2063832508b7Sdrh */ 2064c31c2eb8Sdrh 2065c31c2eb8Sdrh /* Move all of the FROM elements of the subquery into the 2066c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2067c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2068c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2069c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2070c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2071c31c2eb8Sdrh ** elements we are now copying in. 2072c31c2eb8Sdrh */ 207391bb0eedSdrh iParent = pSubitem->iCursor; 2074c31c2eb8Sdrh { 2075c31c2eb8Sdrh int nSubSrc = pSubSrc->nSrc; 207691bb0eedSdrh int jointype = pSubitem->jointype; 2077c31c2eb8Sdrh 207891bb0eedSdrh sqlite3DeleteTable(0, pSubitem->pTab); 207991bb0eedSdrh sqliteFree(pSubitem->zDatabase); 208091bb0eedSdrh sqliteFree(pSubitem->zName); 208191bb0eedSdrh sqliteFree(pSubitem->zAlias); 2082c31c2eb8Sdrh if( nSubSrc>1 ){ 2083c31c2eb8Sdrh int extra = nSubSrc - 1; 2084c31c2eb8Sdrh for(i=1; i<nSubSrc; i++){ 20854adee20fSdanielk1977 pSrc = sqlite3SrcListAppend(pSrc, 0, 0); 2086c31c2eb8Sdrh } 2087c31c2eb8Sdrh p->pSrc = pSrc; 2088c31c2eb8Sdrh for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 2089c31c2eb8Sdrh pSrc->a[i] = pSrc->a[i-extra]; 2090c31c2eb8Sdrh } 2091c31c2eb8Sdrh } 2092c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2093c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2094c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2095c31c2eb8Sdrh } 20968af4d3acSdrh pSrc->a[iFrom+nSubSrc-1].jointype = jointype; 2097c31c2eb8Sdrh } 2098c31c2eb8Sdrh 2099c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2100c31c2eb8Sdrh ** references to the iParent in the outer query. 2101c31c2eb8Sdrh ** 2102c31c2eb8Sdrh ** Example: 2103c31c2eb8Sdrh ** 2104c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2105c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 2106c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 2107c31c2eb8Sdrh ** 2108c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 2109c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2110c31c2eb8Sdrh */ 21116a3ea0e6Sdrh substExprList(p->pEList, iParent, pSub->pEList); 2112832508b7Sdrh pList = p->pEList; 2113832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 21146977fea8Sdrh Expr *pExpr; 21156977fea8Sdrh if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 21166977fea8Sdrh pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n); 2117832508b7Sdrh } 2118832508b7Sdrh } 21191b2e0329Sdrh if( isAgg ){ 21206a3ea0e6Sdrh substExprList(p->pGroupBy, iParent, pSub->pEList); 21216a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 21221b2e0329Sdrh } 2123174b6195Sdrh if( pSub->pOrderBy ){ 2124174b6195Sdrh assert( p->pOrderBy==0 ); 2125174b6195Sdrh p->pOrderBy = pSub->pOrderBy; 2126174b6195Sdrh pSub->pOrderBy = 0; 2127174b6195Sdrh }else if( p->pOrderBy ){ 21286a3ea0e6Sdrh substExprList(p->pOrderBy, iParent, pSub->pEList); 2129174b6195Sdrh } 2130832508b7Sdrh if( pSub->pWhere ){ 21314adee20fSdanielk1977 pWhere = sqlite3ExprDup(pSub->pWhere); 2132832508b7Sdrh }else{ 2133832508b7Sdrh pWhere = 0; 2134832508b7Sdrh } 2135832508b7Sdrh if( subqueryIsAgg ){ 2136832508b7Sdrh assert( p->pHaving==0 ); 21371b2e0329Sdrh p->pHaving = p->pWhere; 21381b2e0329Sdrh p->pWhere = pWhere; 21396a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 214091bb0eedSdrh p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving)); 21411b2e0329Sdrh assert( p->pGroupBy==0 ); 21424adee20fSdanielk1977 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy); 2143832508b7Sdrh }else{ 21446a3ea0e6Sdrh substExpr(p->pWhere, iParent, pSub->pEList); 214591bb0eedSdrh p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere); 2146832508b7Sdrh } 2147c31c2eb8Sdrh 2148c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 2149c31c2eb8Sdrh ** outer query is distinct. 2150c31c2eb8Sdrh */ 2151832508b7Sdrh p->isDistinct = p->isDistinct || pSub->isDistinct; 21528c74a8caSdrh 2153a58fdfb1Sdanielk1977 /* 2154a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 2155a58fdfb1Sdanielk1977 */ 2156a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 2157a2dc3b1aSdanielk1977 p->pLimit = pSub->pLimit; 2158a2dc3b1aSdanielk1977 pSub->pLimit = 0; 2159df199a25Sdrh } 21608c74a8caSdrh 2161c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 2162c31c2eb8Sdrh ** success. 2163c31c2eb8Sdrh */ 21644adee20fSdanielk1977 sqlite3SelectDelete(pSub); 2165832508b7Sdrh return 1; 21661350b030Sdrh } 2167b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 21681350b030Sdrh 21691350b030Sdrh /* 21709562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it 21719562b551Sdrh ** is a simple min() or max() query. If it is and this query can be 21729562b551Sdrh ** satisfied using a single seek to the beginning or end of an index, 2173e78e8284Sdrh ** then generate the code for this SELECT and return 1. If this is not a 21749562b551Sdrh ** simple min() or max() query, then return 0; 21759562b551Sdrh ** 21769562b551Sdrh ** A simply min() or max() query looks like this: 21779562b551Sdrh ** 21789562b551Sdrh ** SELECT min(a) FROM table; 21799562b551Sdrh ** SELECT max(a) FROM table; 21809562b551Sdrh ** 21819562b551Sdrh ** The query may have only a single table in its FROM argument. There 21829562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses. The result set must 21839562b551Sdrh ** be the min() or max() of a single column of the table. The column 21849562b551Sdrh ** in the min() or max() function must be indexed. 21859562b551Sdrh ** 21864adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select(). 21879562b551Sdrh ** See the header comment on that routine for additional information. 21889562b551Sdrh */ 21899562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ 21909562b551Sdrh Expr *pExpr; 21919562b551Sdrh int iCol; 21929562b551Sdrh Table *pTab; 21939562b551Sdrh Index *pIdx; 21949562b551Sdrh int base; 21959562b551Sdrh Vdbe *v; 21969562b551Sdrh int seekOp; 21976e17529eSdrh ExprList *pEList, *pList, eList; 21989562b551Sdrh struct ExprList_item eListItem; 21996e17529eSdrh SrcList *pSrc; 2200ec7429aeSdrh int brk; 22016e17529eSdrh 22029562b551Sdrh /* Check to see if this query is a simple min() or max() query. Return 22039562b551Sdrh ** zero if it is not. 22049562b551Sdrh */ 22059562b551Sdrh if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; 22066e17529eSdrh pSrc = p->pSrc; 22076e17529eSdrh if( pSrc->nSrc!=1 ) return 0; 22086e17529eSdrh pEList = p->pEList; 22096e17529eSdrh if( pEList->nExpr!=1 ) return 0; 22106e17529eSdrh pExpr = pEList->a[0].pExpr; 22119562b551Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 22126e17529eSdrh pList = pExpr->pList; 22136e17529eSdrh if( pList==0 || pList->nExpr!=1 ) return 0; 22146977fea8Sdrh if( pExpr->token.n!=3 ) return 0; 22154adee20fSdanielk1977 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){ 22160bce8354Sdrh seekOp = OP_Rewind; 22174adee20fSdanielk1977 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){ 22180bce8354Sdrh seekOp = OP_Last; 22190bce8354Sdrh }else{ 22200bce8354Sdrh return 0; 22210bce8354Sdrh } 22226e17529eSdrh pExpr = pList->a[0].pExpr; 22239562b551Sdrh if( pExpr->op!=TK_COLUMN ) return 0; 22249562b551Sdrh iCol = pExpr->iColumn; 22256e17529eSdrh pTab = pSrc->a[0].pTab; 22269562b551Sdrh 22279562b551Sdrh /* If we get to here, it means the query is of the correct form. 222817f71934Sdrh ** Check to make sure we have an index and make pIdx point to the 222917f71934Sdrh ** appropriate index. If the min() or max() is on an INTEGER PRIMARY 223017f71934Sdrh ** key column, no index is necessary so set pIdx to NULL. If no 223117f71934Sdrh ** usable index is found, return 0. 22329562b551Sdrh */ 22339562b551Sdrh if( iCol<0 ){ 22349562b551Sdrh pIdx = 0; 22359562b551Sdrh }else{ 2236dc1bdc4fSdanielk1977 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr); 22379562b551Sdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 22389562b551Sdrh assert( pIdx->nColumn>=1 ); 2239dc1bdc4fSdanielk1977 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break; 22409562b551Sdrh } 22419562b551Sdrh if( pIdx==0 ) return 0; 22429562b551Sdrh } 22439562b551Sdrh 2244e5f50722Sdrh /* Identify column types if we will be using the callback. This 22459562b551Sdrh ** step is skipped if the output is going to a table or a memory cell. 2246e5f50722Sdrh ** The column names have already been generated in the calling function. 22479562b551Sdrh */ 22484adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 22499562b551Sdrh if( v==0 ) return 0; 22509562b551Sdrh 22510c37e630Sdrh /* If the output is destined for a temporary table, open that table. 22520c37e630Sdrh */ 22539d2985c7Sdrh if( eDest==SRT_VirtualTab ){ 2254d81bd4e2Sdrh sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 1); 22550c37e630Sdrh } 22560c37e630Sdrh 225717f71934Sdrh /* Generating code to find the min or the max. Basically all we have 225817f71934Sdrh ** to do is find the first or the last entry in the chosen index. If 225917f71934Sdrh ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first 226017f71934Sdrh ** or last entry in the main table. 22619562b551Sdrh */ 22624adee20fSdanielk1977 sqlite3CodeVerifySchema(pParse, pTab->iDb); 22636e17529eSdrh base = pSrc->a[0].iCursor; 2264ec7429aeSdrh brk = sqlite3VdbeMakeLabel(v); 2265ec7429aeSdrh computeLimitRegisters(pParse, p, brk); 22666e17529eSdrh if( pSrc->a[0].pSelect==0 ){ 2267ad6d9460Sdrh sqlite3OpenTableForReading(v, base, pTab); 22686e17529eSdrh } 22699562b551Sdrh if( pIdx==0 ){ 22704adee20fSdanielk1977 sqlite3VdbeAddOp(v, seekOp, base, 0); 22719562b551Sdrh }else{ 22723719d7f9Sdanielk1977 /* Even though the cursor used to open the index here is closed 22733719d7f9Sdanielk1977 ** as soon as a single value has been read from it, allocate it 22743719d7f9Sdanielk1977 ** using (pParse->nTab++) to prevent the cursor id from being 22753719d7f9Sdanielk1977 ** reused. This is important for statements of the form 22763719d7f9Sdanielk1977 ** "INSERT INTO x SELECT max() FROM x". 22773719d7f9Sdanielk1977 */ 22783719d7f9Sdanielk1977 int iIdx; 22793719d7f9Sdanielk1977 iIdx = pParse->nTab++; 22804adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0); 22813719d7f9Sdanielk1977 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, 2282d3d39e93Sdrh (char*)&pIdx->keyInfo, P3_KEYINFO); 22839eb516c0Sdrh if( seekOp==OP_Rewind ){ 2284f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_Null, 0, 0); 22851af3fdb4Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0); 22861af3fdb4Sdrh seekOp = OP_MoveGt; 22879eb516c0Sdrh } 22883719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, seekOp, iIdx, 0); 2289f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0); 22903719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); 22917cf6e4deSdrh sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 22929562b551Sdrh } 22935cf8e8c7Sdrh eList.nExpr = 1; 22945cf8e8c7Sdrh memset(&eListItem, 0, sizeof(eListItem)); 22955cf8e8c7Sdrh eList.a = &eListItem; 22965cf8e8c7Sdrh eList.a[0].pExpr = pExpr; 2297ec7429aeSdrh selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0); 2298ec7429aeSdrh sqlite3VdbeResolveLabel(v, brk); 22994adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, base, 0); 23006e17529eSdrh 23019562b551Sdrh return 1; 23029562b551Sdrh } 23039562b551Sdrh 23049562b551Sdrh /* 2305290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return 2306290c1948Sdrh ** the number of errors seen. 2307290c1948Sdrh ** 2308290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions. If any expression 2309290c1948Sdrh ** is an integer constant, then that expression is replaced by the 2310290c1948Sdrh ** corresponding entry in the result set. 2311290c1948Sdrh */ 2312290c1948Sdrh static int processOrderGroupBy( 2313b3bce662Sdanielk1977 NameContext *pNC, /* Name context of the SELECT statement. */ 2314290c1948Sdrh ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 2315290c1948Sdrh const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 2316290c1948Sdrh ){ 2317290c1948Sdrh int i; 2318b3bce662Sdanielk1977 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */ 2319b3bce662Sdanielk1977 Parse *pParse = pNC->pParse; /* The result set of the SELECT */ 2320b3bce662Sdanielk1977 assert( pEList ); 2321b3bce662Sdanielk1977 2322290c1948Sdrh if( pOrderBy==0 ) return 0; 2323290c1948Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 2324290c1948Sdrh int iCol; 2325290c1948Sdrh Expr *pE = pOrderBy->a[i].pExpr; 2326b3bce662Sdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 2327b3bce662Sdanielk1977 if( iCol>0 && iCol<=pEList->nExpr ){ 2328290c1948Sdrh sqlite3ExprDelete(pE); 2329290c1948Sdrh pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr); 2330b3bce662Sdanielk1977 }else{ 2331290c1948Sdrh sqlite3ErrorMsg(pParse, 2332290c1948Sdrh "%s BY column number %d out of range - should be " 2333290c1948Sdrh "between 1 and %d", zType, iCol, pEList->nExpr); 2334290c1948Sdrh return 1; 2335290c1948Sdrh } 2336290c1948Sdrh } 2337b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(pNC, pE) ){ 2338b3bce662Sdanielk1977 return 1; 2339b3bce662Sdanielk1977 } 2340b3bce662Sdanielk1977 if( sqlite3ExprIsConstant(pE) ){ 2341b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, 2342b3bce662Sdanielk1977 "%s BY terms must not be non-integer constants", zType); 2343b3bce662Sdanielk1977 return 1; 2344b3bce662Sdanielk1977 } 2345290c1948Sdrh } 2346290c1948Sdrh return 0; 2347290c1948Sdrh } 2348290c1948Sdrh 2349290c1948Sdrh /* 2350b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the 2351b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved 2352b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext 2353b3bce662Sdanielk1977 ** of the parent SELECT. 2354b3bce662Sdanielk1977 */ 2355b3bce662Sdanielk1977 int sqlite3SelectResolve( 2356b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 2357b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 2358b3bce662Sdanielk1977 NameContext *pOuterNC /* The outer name context. May be NULL. */ 2359b3bce662Sdanielk1977 ){ 2360b3bce662Sdanielk1977 ExprList *pEList; /* Result set. */ 2361b3bce662Sdanielk1977 int i; /* For-loop variable used in multiple places */ 2362b3bce662Sdanielk1977 NameContext sNC; /* Local name-context */ 236313449892Sdrh ExprList *pGroupBy; /* The group by clause */ 2364b3bce662Sdanielk1977 2365b3bce662Sdanielk1977 /* If this routine has run before, return immediately. */ 2366b3bce662Sdanielk1977 if( p->isResolved ){ 2367b3bce662Sdanielk1977 assert( !pOuterNC ); 2368b3bce662Sdanielk1977 return SQLITE_OK; 2369b3bce662Sdanielk1977 } 2370b3bce662Sdanielk1977 p->isResolved = 1; 2371b3bce662Sdanielk1977 2372b3bce662Sdanielk1977 /* If there have already been errors, do nothing. */ 2373b3bce662Sdanielk1977 if( pParse->nErr>0 ){ 2374b3bce662Sdanielk1977 return SQLITE_ERROR; 2375b3bce662Sdanielk1977 } 2376b3bce662Sdanielk1977 2377b3bce662Sdanielk1977 /* Prepare the select statement. This call will allocate all cursors 2378b3bce662Sdanielk1977 ** required to handle the tables and subqueries in the FROM clause. 2379b3bce662Sdanielk1977 */ 2380b3bce662Sdanielk1977 if( prepSelectStmt(pParse, p) ){ 2381b3bce662Sdanielk1977 return SQLITE_ERROR; 2382b3bce662Sdanielk1977 } 2383b3bce662Sdanielk1977 2384a2dc3b1aSdanielk1977 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 2385a2dc3b1aSdanielk1977 ** are not allowed to refer to any names, so pass an empty NameContext. 2386a2dc3b1aSdanielk1977 */ 2387*ffe07b2dSdrh memset(&sNC, 0, sizeof(sNC)); 2388b3bce662Sdanielk1977 sNC.pParse = pParse; 2389a2dc3b1aSdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pLimit) || 2390a2dc3b1aSdanielk1977 sqlite3ExprResolveNames(&sNC, p->pOffset) ){ 2391a2dc3b1aSdanielk1977 return SQLITE_ERROR; 2392a2dc3b1aSdanielk1977 } 2393a2dc3b1aSdanielk1977 2394a2dc3b1aSdanielk1977 /* Set up the local name-context to pass to ExprResolveNames() to 2395a2dc3b1aSdanielk1977 ** resolve the expression-list. 2396a2dc3b1aSdanielk1977 */ 2397a2dc3b1aSdanielk1977 sNC.allowAgg = 1; 2398a2dc3b1aSdanielk1977 sNC.pSrcList = p->pSrc; 2399a2dc3b1aSdanielk1977 sNC.pNext = pOuterNC; 2400b3bce662Sdanielk1977 2401b3bce662Sdanielk1977 /* Resolve names in the result set. */ 2402b3bce662Sdanielk1977 pEList = p->pEList; 2403b3bce662Sdanielk1977 if( !pEList ) return SQLITE_ERROR; 2404b3bce662Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 2405b3bce662Sdanielk1977 Expr *pX = pEList->a[i].pExpr; 2406b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pX) ){ 2407b3bce662Sdanielk1977 return SQLITE_ERROR; 2408b3bce662Sdanielk1977 } 2409b3bce662Sdanielk1977 } 2410b3bce662Sdanielk1977 2411b3bce662Sdanielk1977 /* If there are no aggregate functions in the result-set, and no GROUP BY 2412b3bce662Sdanielk1977 ** expression, do not allow aggregates in any of the other expressions. 2413b3bce662Sdanielk1977 */ 2414b3bce662Sdanielk1977 assert( !p->isAgg ); 241513449892Sdrh pGroupBy = p->pGroupBy; 241613449892Sdrh if( pGroupBy || sNC.hasAgg ){ 2417b3bce662Sdanielk1977 p->isAgg = 1; 2418b3bce662Sdanielk1977 }else{ 2419b3bce662Sdanielk1977 sNC.allowAgg = 0; 2420b3bce662Sdanielk1977 } 2421b3bce662Sdanielk1977 2422b3bce662Sdanielk1977 /* If a HAVING clause is present, then there must be a GROUP BY clause. 2423b3bce662Sdanielk1977 */ 242413449892Sdrh if( p->pHaving && !pGroupBy ){ 2425b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2426b3bce662Sdanielk1977 return SQLITE_ERROR; 2427b3bce662Sdanielk1977 } 2428b3bce662Sdanielk1977 2429b3bce662Sdanielk1977 /* Add the expression list to the name-context before parsing the 2430b3bce662Sdanielk1977 ** other expressions in the SELECT statement. This is so that 2431b3bce662Sdanielk1977 ** expressions in the WHERE clause (etc.) can refer to expressions by 2432b3bce662Sdanielk1977 ** aliases in the result set. 2433b3bce662Sdanielk1977 ** 2434b3bce662Sdanielk1977 ** Minor point: If this is the case, then the expression will be 2435b3bce662Sdanielk1977 ** re-evaluated for each reference to it. 2436b3bce662Sdanielk1977 */ 2437b3bce662Sdanielk1977 sNC.pEList = p->pEList; 2438b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pWhere) || 2439b3bce662Sdanielk1977 sqlite3ExprResolveNames(&sNC, p->pHaving) || 2440b3bce662Sdanielk1977 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") || 244113449892Sdrh processOrderGroupBy(&sNC, pGroupBy, "GROUP") 2442b3bce662Sdanielk1977 ){ 2443b3bce662Sdanielk1977 return SQLITE_ERROR; 2444b3bce662Sdanielk1977 } 2445b3bce662Sdanielk1977 244613449892Sdrh /* Make sure the GROUP BY clause does not contain aggregate functions. 244713449892Sdrh */ 244813449892Sdrh if( pGroupBy ){ 244913449892Sdrh struct ExprList_item *pItem; 245013449892Sdrh 245113449892Sdrh for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 245213449892Sdrh if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 245313449892Sdrh sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 245413449892Sdrh "the GROUP BY clause"); 245513449892Sdrh return SQLITE_ERROR; 245613449892Sdrh } 245713449892Sdrh } 245813449892Sdrh } 245913449892Sdrh 2460b3bce662Sdanielk1977 return SQLITE_OK; 2461b3bce662Sdanielk1977 } 2462b3bce662Sdanielk1977 2463b3bce662Sdanielk1977 /* 246413449892Sdrh ** Reset the aggregate accumulator. 246513449892Sdrh ** 246613449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 246713449892Sdrh ** intermediate results while calculating an aggregate. This 246813449892Sdrh ** routine simply stores NULLs in all of those memory cells. 2469b3bce662Sdanielk1977 */ 247013449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 247113449892Sdrh Vdbe *v = pParse->pVdbe; 247213449892Sdrh int i; 2473c99130fdSdrh struct AggInfo_func *pFunc; 247413449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 247513449892Sdrh return; 247613449892Sdrh } 247713449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 2478d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0); 247913449892Sdrh } 2480c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 2481d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0); 2482c99130fdSdrh if( pFunc->iDistinct>=0 ){ 2483c99130fdSdrh Expr *pE = pFunc->pExpr; 2484c99130fdSdrh if( pE->pList==0 || pE->pList->nExpr!=1 ){ 2485c99130fdSdrh sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " 2486c99130fdSdrh "by an expression"); 2487c99130fdSdrh pFunc->iDistinct = -1; 2488c99130fdSdrh }else{ 2489c99130fdSdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); 2490c99130fdSdrh sqlite3VdbeOp3(v, OP_OpenVirtual, pFunc->iDistinct, 0, 2491c99130fdSdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 2492c99130fdSdrh } 2493c99130fdSdrh } 249413449892Sdrh } 2495b3bce662Sdanielk1977 } 2496b3bce662Sdanielk1977 2497b3bce662Sdanielk1977 /* 249813449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 249913449892Sdrh ** in the AggInfo structure. 2500b3bce662Sdanielk1977 */ 250113449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 250213449892Sdrh Vdbe *v = pParse->pVdbe; 250313449892Sdrh int i; 250413449892Sdrh struct AggInfo_func *pF; 250513449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 2506a10a34b8Sdrh ExprList *pList = pF->pExpr->pList; 2507a10a34b8Sdrh sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 2508a10a34b8Sdrh (void*)pF->pFunc, P3_FUNCDEF); 2509b3bce662Sdanielk1977 } 251013449892Sdrh } 251113449892Sdrh 251213449892Sdrh /* 251313449892Sdrh ** Update the accumulator memory cells for an aggregate based on 251413449892Sdrh ** the current cursor position. 251513449892Sdrh */ 251613449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 251713449892Sdrh Vdbe *v = pParse->pVdbe; 251813449892Sdrh int i; 251913449892Sdrh struct AggInfo_func *pF; 252013449892Sdrh struct AggInfo_col *pC; 252113449892Sdrh 252213449892Sdrh pAggInfo->directMode = 1; 252313449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 252413449892Sdrh int nArg; 2525c99130fdSdrh int addrNext = 0; 252613449892Sdrh ExprList *pList = pF->pExpr->pList; 252713449892Sdrh if( pList ){ 252813449892Sdrh nArg = pList->nExpr; 252913449892Sdrh sqlite3ExprCodeExprList(pParse, pList); 253013449892Sdrh }else{ 253113449892Sdrh nArg = 0; 253213449892Sdrh } 2533c99130fdSdrh if( pF->iDistinct>=0 ){ 2534c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 2535c99130fdSdrh assert( nArg==1 ); 25369d4673a9Sdrh codeDistinct(v, pF->iDistinct, addrNext, 1, 2); 2537c99130fdSdrh } 253813449892Sdrh if( pF->pFunc->needCollSeq ){ 253913449892Sdrh CollSeq *pColl = 0; 254013449892Sdrh struct ExprList_item *pItem; 254113449892Sdrh int j; 254213449892Sdrh for(j=0, pItem=pList->a; !pColl && j<pList->nExpr; j++, pItem++){ 254313449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 254413449892Sdrh } 254513449892Sdrh if( !pColl ){ 254613449892Sdrh pColl = pParse->db->pDfltColl; 254713449892Sdrh } 254813449892Sdrh sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); 254913449892Sdrh } 255013449892Sdrh sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF); 2551c99130fdSdrh if( addrNext ){ 2552c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 2553c99130fdSdrh } 255413449892Sdrh } 255513449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 25565774b806Sdrh sqlite3ExprCode(pParse, pC->pExpr); 255713449892Sdrh sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1); 255813449892Sdrh } 255913449892Sdrh pAggInfo->directMode = 0; 256013449892Sdrh } 256113449892Sdrh 2562b3bce662Sdanielk1977 2563b3bce662Sdanielk1977 /* 25649bb61fe7Sdrh ** Generate code for the given SELECT statement. 25659bb61fe7Sdrh ** 2566fef5208cSdrh ** The results are distributed in various ways depending on the 2567fef5208cSdrh ** value of eDest and iParm. 2568fef5208cSdrh ** 2569fef5208cSdrh ** eDest Value Result 2570fef5208cSdrh ** ------------ ------------------------------------------- 2571fef5208cSdrh ** SRT_Callback Invoke the callback for each row of the result. 2572fef5208cSdrh ** 2573fef5208cSdrh ** SRT_Mem Store first result in memory cell iParm 2574fef5208cSdrh ** 2575e014a838Sdanielk1977 ** SRT_Set Store results as keys of table iParm. 2576fef5208cSdrh ** 257782c3d636Sdrh ** SRT_Union Store results as a key in a temporary table iParm 257882c3d636Sdrh ** 25794b11c6d3Sjplyon ** SRT_Except Remove results from the temporary table iParm. 2580c4a3c779Sdrh ** 2581c4a3c779Sdrh ** SRT_Table Store results in temporary table iParm 25829bb61fe7Sdrh ** 2583e78e8284Sdrh ** The table above is incomplete. Additional eDist value have be added 2584e78e8284Sdrh ** since this comment was written. See the selectInnerLoop() function for 2585e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings. 2586e78e8284Sdrh ** 25879bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 25889bb61fe7Sdrh ** encountered, then an appropriate error message is left in 25899bb61fe7Sdrh ** pParse->zErrMsg. 25909bb61fe7Sdrh ** 25919bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 25929bb61fe7Sdrh ** calling function needs to do that. 25931b2e0329Sdrh ** 25941b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this 25951b2e0329Sdrh ** SELECT is a subquery. This routine may try to combine this SELECT 25961b2e0329Sdrh ** with its parent to form a single flat query. In so doing, it might 25971b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query. 25981b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it 25991b2e0329Sdrh ** can be changed. 2600e78e8284Sdrh ** 2601e78e8284Sdrh ** Example 1: The meaning of the pParent parameter. 2602e78e8284Sdrh ** 2603e78e8284Sdrh ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2604e78e8284Sdrh ** \ \_______ subquery _______/ / 2605e78e8284Sdrh ** \ / 2606e78e8284Sdrh ** \____________________ outer query ___________________/ 2607e78e8284Sdrh ** 2608e78e8284Sdrh ** This routine is called for the outer query first. For that call, 2609e78e8284Sdrh ** pParent will be NULL. During the processing of the outer query, this 2610e78e8284Sdrh ** routine is called recursively to handle the subquery. For the recursive 2611e78e8284Sdrh ** call, pParent will point to the outer query. Because the subquery is 2612e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will 2613e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.) 26149bb61fe7Sdrh */ 26154adee20fSdanielk1977 int sqlite3Select( 2616cce7d176Sdrh Parse *pParse, /* The parser context */ 26179bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 2618e78e8284Sdrh int eDest, /* How to dispose of the results */ 2619e78e8284Sdrh int iParm, /* A parameter used by the eDest disposal method */ 2620832508b7Sdrh Select *pParent, /* Another SELECT for which this is a sub-query */ 2621832508b7Sdrh int parentTab, /* Index in pParent->pSrc of this query */ 262284ac9d02Sdanielk1977 int *pParentAgg, /* True if pParent uses aggregate functions */ 2623b3bce662Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 2624cce7d176Sdrh ){ 262513449892Sdrh int i, j; /* Loop counters */ 262613449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 262713449892Sdrh Vdbe *v; /* The virtual machine under construction */ 2628b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 2629a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 2630ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 26319bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 26329bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 26332282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 26342282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 263519a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 263619a775c2Sdrh int distinct; /* Table to use for the distinct set */ 26371d83f052Sdrh int rc = 1; /* Value to return from this function */ 26389d2985c7Sdrh int addrSortIndex; /* Address of an OP_OpenVirtual instruction */ 263913449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 2640ec7429aeSdrh int iEnd; /* Address of the end of the query */ 26419bb61fe7Sdrh 26426f8a503dSdanielk1977 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1; 26434adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 264413449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 2645daffd0e5Sdrh 2646b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 264782c3d636Sdrh /* If there is are a sequence of queries, do the earlier ones first. 264882c3d636Sdrh */ 264982c3d636Sdrh if( p->pPrior ){ 26500342b1f5Sdrh if( p->pRightmost==0 ){ 26510342b1f5Sdrh Select *pLoop; 26520342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 26530342b1f5Sdrh pLoop->pRightmost = p; 26540342b1f5Sdrh } 26550342b1f5Sdrh } 265684ac9d02Sdanielk1977 return multiSelect(pParse, p, eDest, iParm, aff); 265782c3d636Sdrh } 2658b7f9164eSdrh #endif 265982c3d636Sdrh 2660b3bce662Sdanielk1977 pOrderBy = p->pOrderBy; 266113449892Sdrh if( IgnorableOrderby(eDest) ){ 2662b3bce662Sdanielk1977 p->pOrderBy = 0; 2663b3bce662Sdanielk1977 } 2664b3bce662Sdanielk1977 if( sqlite3SelectResolve(pParse, p, 0) ){ 2665b3bce662Sdanielk1977 goto select_end; 2666b3bce662Sdanielk1977 } 2667b3bce662Sdanielk1977 p->pOrderBy = pOrderBy; 2668b3bce662Sdanielk1977 266982c3d636Sdrh /* Make local copies of the parameters for this query. 267082c3d636Sdrh */ 26719bb61fe7Sdrh pTabList = p->pSrc; 26729bb61fe7Sdrh pWhere = p->pWhere; 26732282792aSdrh pGroupBy = p->pGroupBy; 26742282792aSdrh pHaving = p->pHaving; 2675b3bce662Sdanielk1977 isAgg = p->isAgg; 267619a775c2Sdrh isDistinct = p->isDistinct; 2677b3bce662Sdanielk1977 pEList = p->pEList; 2678b3bce662Sdanielk1977 if( pEList==0 ) goto select_end; 26799bb61fe7Sdrh 26809bb61fe7Sdrh /* 26819bb61fe7Sdrh ** Do not even attempt to generate any code if we have already seen 26829bb61fe7Sdrh ** errors before this routine starts. 26839bb61fe7Sdrh */ 26841d83f052Sdrh if( pParse->nErr>0 ) goto select_end; 2685cce7d176Sdrh 26862282792aSdrh /* If writing to memory or generating a set 26872282792aSdrh ** only a single column may be output. 268819a775c2Sdrh */ 268993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 2690fef5208cSdrh if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){ 26914adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "only a single result allowed for " 2692da93d238Sdrh "a SELECT that is part of an expression"); 26931d83f052Sdrh goto select_end; 269419a775c2Sdrh } 269593758c8dSdanielk1977 #endif 269619a775c2Sdrh 2697c926afbcSdrh /* ORDER BY is ignored for some destinations. 26982282792aSdrh */ 269913449892Sdrh if( IgnorableOrderby(eDest) ){ 2700acd4c695Sdrh pOrderBy = 0; 27012282792aSdrh } 27022282792aSdrh 2703d820cb1bSdrh /* Begin generating code. 2704d820cb1bSdrh */ 27054adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2706d820cb1bSdrh if( v==0 ) goto select_end; 2707d820cb1bSdrh 2708e78e8284Sdrh /* Identify column names if we will be using them in a callback. This 2709e78e8284Sdrh ** step is skipped if the output is going to some other destination. 27100bb28106Sdrh */ 27110bb28106Sdrh if( eDest==SRT_Callback ){ 27126a3ea0e6Sdrh generateColumnNames(pParse, pTabList, pEList); 27130bb28106Sdrh } 27140bb28106Sdrh 2715d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 2716d820cb1bSdrh */ 271751522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 2718ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 2719742f947bSdanielk1977 const char *zSavedAuthContext = 0; 2720c31c2eb8Sdrh int needRestoreContext; 272113449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 2722c31c2eb8Sdrh 272313449892Sdrh if( pItem->pSelect==0 ) continue; 272413449892Sdrh if( pItem->zName!=0 ){ 27255cf590c1Sdrh zSavedAuthContext = pParse->zAuthContext; 272613449892Sdrh pParse->zAuthContext = pItem->zName; 2727c31c2eb8Sdrh needRestoreContext = 1; 2728c31c2eb8Sdrh }else{ 2729c31c2eb8Sdrh needRestoreContext = 0; 27305cf590c1Sdrh } 27319d2985c7Sdrh sqlite3Select(pParse, pItem->pSelect, SRT_VirtualTab, 273213449892Sdrh pItem->iCursor, p, i, &isAgg, 0); 2733c31c2eb8Sdrh if( needRestoreContext ){ 27345cf590c1Sdrh pParse->zAuthContext = zSavedAuthContext; 27355cf590c1Sdrh } 2736832508b7Sdrh pTabList = p->pSrc; 2737832508b7Sdrh pWhere = p->pWhere; 273813449892Sdrh if( !IgnorableOrderby(eDest) ){ 2739832508b7Sdrh pOrderBy = p->pOrderBy; 2740acd4c695Sdrh } 2741832508b7Sdrh pGroupBy = p->pGroupBy; 2742832508b7Sdrh pHaving = p->pHaving; 2743832508b7Sdrh isDistinct = p->isDistinct; 27441b2e0329Sdrh } 274551522cd3Sdrh #endif 27461b2e0329Sdrh 27476e17529eSdrh /* Check for the special case of a min() or max() function by itself 27486e17529eSdrh ** in the result set. 27496e17529eSdrh */ 27506e17529eSdrh if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ 27516e17529eSdrh rc = 0; 27526e17529eSdrh goto select_end; 27536e17529eSdrh } 27546e17529eSdrh 27551b2e0329Sdrh /* Check to see if this is a subquery that can be "flattened" into its parent. 27561b2e0329Sdrh ** If flattening is a possiblity, do so and return immediately. 27571b2e0329Sdrh */ 2758b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 27591b2e0329Sdrh if( pParent && pParentAgg && 27608c74a8caSdrh flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){ 27611b2e0329Sdrh if( isAgg ) *pParentAgg = 1; 2762b3bce662Sdanielk1977 goto select_end; 27631b2e0329Sdrh } 2764b7f9164eSdrh #endif 2765832508b7Sdrh 27667cedc8d4Sdanielk1977 /* If there is an ORDER BY clause, resolve any collation sequences 27679d2985c7Sdrh ** names that have been explicitly specified and create a sorting index. 27689d2985c7Sdrh ** 27699d2985c7Sdrh ** This sorting index might end up being unused if the data can be 27709d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 27719d2985c7Sdrh ** OP_OpenVirtual instruction will be changed to an OP_Noop once 27729d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 27739d2985c7Sdrh ** variable is used to facilitate that change. 27747cedc8d4Sdanielk1977 */ 27757cedc8d4Sdanielk1977 if( pOrderBy ){ 27765d9a4af9Sdrh struct ExprList_item *pTerm; 27770342b1f5Sdrh KeyInfo *pKeyInfo; 27785d9a4af9Sdrh for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){ 27795d9a4af9Sdrh if( pTerm->zName ){ 27805d9a4af9Sdrh pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1); 27817cedc8d4Sdanielk1977 } 27827cedc8d4Sdanielk1977 } 27837cedc8d4Sdanielk1977 if( pParse->nErr ){ 27847cedc8d4Sdanielk1977 goto select_end; 27857cedc8d4Sdanielk1977 } 27860342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 27879d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 27889d2985c7Sdrh p->addrOpenVirt[2] = addrSortIndex = 27899d2985c7Sdrh sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iECursor, pOrderBy->nExpr+2, 27900342b1f5Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 27919d2985c7Sdrh }else{ 27929d2985c7Sdrh addrSortIndex = -1; 27937cedc8d4Sdanielk1977 } 27947cedc8d4Sdanielk1977 27957b58daeaSdrh /* Set the limiter. 27967b58daeaSdrh */ 2797ec7429aeSdrh iEnd = sqlite3VdbeMakeLabel(v); 2798ec7429aeSdrh computeLimitRegisters(pParse, p, iEnd); 27997b58daeaSdrh 28002d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 28012d0794e3Sdrh */ 28029d2985c7Sdrh if( eDest==SRT_VirtualTab ){ 28030342b1f5Sdrh sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr); 28042d0794e3Sdrh } 28052d0794e3Sdrh 2806dece1a84Sdrh /* Open a virtual index to use for the distinct set. 2807cce7d176Sdrh */ 280819a775c2Sdrh if( isDistinct ){ 28090342b1f5Sdrh KeyInfo *pKeyInfo; 2810832508b7Sdrh distinct = pParse->nTab++; 28110342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 28120342b1f5Sdrh sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0, 28130342b1f5Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 2814832508b7Sdrh }else{ 2815832508b7Sdrh distinct = -1; 2816efb7251dSdrh } 2817832508b7Sdrh 281813449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 281913449892Sdrh if( !isAgg && pGroupBy==0 ){ 282013449892Sdrh /* This case is for non-aggregate queries 282113449892Sdrh ** Begin the database scan 2822832508b7Sdrh */ 282313449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy); 28241d83f052Sdrh if( pWInfo==0 ) goto select_end; 2825cce7d176Sdrh 28269d2985c7Sdrh /* If sorting index that was created by a prior OP_OpenVirtual 28279d2985c7Sdrh ** instruction ended up not being needed, then change the OP_OpenVirtual 28289d2985c7Sdrh ** into an OP_Noop. 28299d2985c7Sdrh */ 28309d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 28319d2985c7Sdrh uncreateSortingIndex(pParse, addrSortIndex); 28329d2985c7Sdrh p->addrOpenVirt[2] = -1; 28339d2985c7Sdrh } 28349d2985c7Sdrh 283513449892Sdrh /* Use the standard inner loop 2836cce7d176Sdrh */ 2837df199a25Sdrh if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 283884ac9d02Sdanielk1977 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ 28391d83f052Sdrh goto select_end; 2840cce7d176Sdrh } 28412282792aSdrh 2842cce7d176Sdrh /* End the database scan loop. 2843cce7d176Sdrh */ 28444adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 284513449892Sdrh }else{ 284613449892Sdrh /* This is the processing for aggregate queries */ 284713449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 284813449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 284913449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 285013449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 285113449892Sdrh ** one row of the input to the aggregator has been 285213449892Sdrh ** processed */ 285313449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 285413449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 2855cce7d176Sdrh 285613449892Sdrh 285713449892Sdrh /* The following variables hold addresses or labels for parts of the 285813449892Sdrh ** virtual machine program we are putting together */ 285913449892Sdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 286013449892Sdrh int addrSetAbort; /* Set the abort flag and return */ 286113449892Sdrh int addrInitializeLoop; /* Start of code that initializes the input loop */ 286213449892Sdrh int addrTopOfLoop; /* Top of the input loop */ 286313449892Sdrh int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ 286413449892Sdrh int addrProcessRow; /* Code to process a single input row */ 286513449892Sdrh int addrEnd; /* End of all processing */ 286613449892Sdrh int addrSortingIdx; /* The OP_OpenVirtual for the sorting index */ 2867e313382eSdrh int addrReset; /* Subroutine for resetting the accumulator */ 286813449892Sdrh 286913449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 287013449892Sdrh 287113449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 287213449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 287313449892Sdrh ** SELECT statement. 28742282792aSdrh */ 287513449892Sdrh memset(&sNC, 0, sizeof(sNC)); 287613449892Sdrh sNC.pParse = pParse; 287713449892Sdrh sNC.pSrcList = pTabList; 287813449892Sdrh sNC.pAggInfo = &sAggInfo; 287913449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 28809d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 288113449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){ 28821d83f052Sdrh goto select_end; 28832282792aSdrh } 288413449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){ 288513449892Sdrh goto select_end; 28862282792aSdrh } 288713449892Sdrh if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){ 288813449892Sdrh goto select_end; 288913449892Sdrh } 289013449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 289113449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 289213449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){ 289313449892Sdrh goto select_end; 289413449892Sdrh } 289513449892Sdrh } 28965360ad34Sdrh if( sqlite3_malloc_failed ) goto select_end; 289713449892Sdrh 289813449892Sdrh /* Processing for aggregates with GROUP BY is very different and 289913449892Sdrh ** much more complex tha aggregates without a GROUP BY. 290013449892Sdrh */ 290113449892Sdrh if( pGroupBy ){ 290213449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 290313449892Sdrh 290413449892Sdrh /* Create labels that we will be needing 290513449892Sdrh */ 290613449892Sdrh 290713449892Sdrh addrInitializeLoop = sqlite3VdbeMakeLabel(v); 290813449892Sdrh addrGroupByChange = sqlite3VdbeMakeLabel(v); 290913449892Sdrh addrProcessRow = sqlite3VdbeMakeLabel(v); 291013449892Sdrh 291113449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 291213449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 291313449892Sdrh ** that we do not need it after all, the OpenVirtual instruction 291413449892Sdrh ** will be converted into a Noop. 291513449892Sdrh */ 291613449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 291713449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 291813449892Sdrh addrSortingIdx = 291913449892Sdrh sqlite3VdbeOp3(v, OP_OpenVirtual, sAggInfo.sortingIdx, 292013449892Sdrh sAggInfo.nSortingColumn, 292113449892Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 292213449892Sdrh 292313449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 292413449892Sdrh */ 292513449892Sdrh iUseFlag = pParse->nMem++; 292613449892Sdrh iAbortFlag = pParse->nMem++; 292713449892Sdrh iAMem = pParse->nMem; 292813449892Sdrh pParse->nMem += pGroupBy->nExpr; 292913449892Sdrh iBMem = pParse->nMem; 293013449892Sdrh pParse->nMem += pGroupBy->nExpr; 2931d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag); 2932de29e3e9Sdrh VdbeComment((v, "# clear abort flag")); 2933d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag); 2934de29e3e9Sdrh VdbeComment((v, "# indicate accumulator empty")); 293513449892Sdrh sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop); 293613449892Sdrh 293713449892Sdrh /* Generate a subroutine that outputs a single row of the result 293813449892Sdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 293913449892Sdrh ** is less than or equal to zero, the subroutine is a no-op. If 294013449892Sdrh ** the processing calls for the query to abort, this subroutine 294113449892Sdrh ** increments the iAbortFlag memory location before returning in 294213449892Sdrh ** order to signal the caller to abort. 294313449892Sdrh */ 294413449892Sdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 2945de29e3e9Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag); 2946de29e3e9Sdrh VdbeComment((v, "# set abort flag")); 294713449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 294813449892Sdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 294913449892Sdrh sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2); 2950de29e3e9Sdrh VdbeComment((v, "# Groupby result generator entry point")); 295113449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 295213449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 295313449892Sdrh if( pHaving ){ 295413449892Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1); 295513449892Sdrh } 295613449892Sdrh rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 295713449892Sdrh distinct, eDest, iParm, 295813449892Sdrh addrOutputRow+1, addrSetAbort, aff); 295913449892Sdrh if( rc ){ 296013449892Sdrh goto select_end; 296113449892Sdrh } 296213449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 2963de29e3e9Sdrh VdbeComment((v, "# end groupby result generator")); 296413449892Sdrh 2965e313382eSdrh /* Generate a subroutine that will reset the group-by accumulator 2966e313382eSdrh */ 2967e313382eSdrh addrReset = sqlite3VdbeCurrentAddr(v); 2968e313382eSdrh resetAccumulator(pParse, &sAggInfo); 2969e313382eSdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 2970e313382eSdrh 297113449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 297213449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 297313449892Sdrh ** it might be a single loop that uses an index to extract information 297413449892Sdrh ** in the right order to begin with. 297513449892Sdrh */ 297613449892Sdrh sqlite3VdbeResolveLabel(v, addrInitializeLoop); 2977e313382eSdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); 297813449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy); 29795360ad34Sdrh if( pWInfo==0 ) goto select_end; 298013449892Sdrh if( pGroupBy==0 ){ 298113449892Sdrh /* The optimizer is able to deliver rows in group by order so 298213449892Sdrh ** we do not have to sort. The OP_OpenVirtual table will be 298313449892Sdrh ** cancelled later because we still need to use the pKeyInfo 298413449892Sdrh */ 298513449892Sdrh pGroupBy = p->pGroupBy; 298613449892Sdrh groupBySort = 0; 298713449892Sdrh }else{ 298813449892Sdrh /* Rows are coming out in undetermined order. We have to push 298913449892Sdrh ** each row into a sorting index, terminate the first loop, 299013449892Sdrh ** then loop over the sorting index in order to get the output 299113449892Sdrh ** in sorted order 299213449892Sdrh */ 299313449892Sdrh groupBySort = 1; 299413449892Sdrh sqlite3ExprCodeExprList(pParse, pGroupBy); 299513449892Sdrh sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0); 299613449892Sdrh j = pGroupBy->nExpr+1; 299713449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 299813449892Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 299913449892Sdrh if( pCol->iSorterColumn<j ) continue; 300013449892Sdrh if( pCol->iColumn<0 ){ 300113449892Sdrh sqlite3VdbeAddOp(v, OP_Rowid, pCol->iTable, 0); 300213449892Sdrh }else{ 300313449892Sdrh sqlite3VdbeAddOp(v, OP_Column, pCol->iTable, pCol->iColumn); 300413449892Sdrh } 300513449892Sdrh j++; 300613449892Sdrh } 300713449892Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0); 300813449892Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0); 300913449892Sdrh sqlite3WhereEnd(pWInfo); 301097571957Sdrh sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); 3011de29e3e9Sdrh VdbeComment((v, "# GROUP BY sort")); 301213449892Sdrh sAggInfo.useSortingIdx = 1; 301313449892Sdrh } 301413449892Sdrh 301513449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 301613449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 301713449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 301813449892Sdrh ** from the previous row currently stored in a0, a1, a2... 301913449892Sdrh */ 302013449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 302113449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 302213449892Sdrh if( groupBySort ){ 302313449892Sdrh sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j); 302413449892Sdrh }else{ 302513449892Sdrh sAggInfo.directMode = 1; 302613449892Sdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr); 302713449892Sdrh } 302813449892Sdrh sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1); 302913449892Sdrh } 303013449892Sdrh for(j=pGroupBy->nExpr-1; j>=0; j--){ 303113449892Sdrh if( j<pGroupBy->nExpr-1 ){ 303213449892Sdrh sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0); 303313449892Sdrh } 303413449892Sdrh sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0); 303513449892Sdrh if( j==0 ){ 3036e313382eSdrh sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow); 303713449892Sdrh }else{ 30384f686238Sdrh sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange); 303913449892Sdrh } 304013449892Sdrh sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ); 304113449892Sdrh } 304213449892Sdrh 304313449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 304413449892Sdrh ** Change in the GROUP BY are detected by the previous code 304513449892Sdrh ** block. If there were no changes, this block is skipped. 304613449892Sdrh ** 304713449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 304813449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 304913449892Sdrh ** and resets the aggregate accumulator registers in preparation 305013449892Sdrh ** for the next GROUP BY batch. 305113449892Sdrh */ 305213449892Sdrh sqlite3VdbeResolveLabel(v, addrGroupByChange); 305313449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 3054d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j); 305513449892Sdrh } 305613449892Sdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); 3057de29e3e9Sdrh VdbeComment((v, "# output one row")); 305813449892Sdrh sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd); 3059de29e3e9Sdrh VdbeComment((v, "# check abort flag")); 3060e313382eSdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); 3061de29e3e9Sdrh VdbeComment((v, "# reset accumulator")); 306213449892Sdrh 306313449892Sdrh /* Update the aggregate accumulators based on the content of 306413449892Sdrh ** the current row 306513449892Sdrh */ 306613449892Sdrh sqlite3VdbeResolveLabel(v, addrProcessRow); 306713449892Sdrh updateAccumulator(pParse, &sAggInfo); 3068de29e3e9Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag); 3069de29e3e9Sdrh VdbeComment((v, "# indicate data in accumulator")); 307013449892Sdrh 307113449892Sdrh /* End of the loop 307213449892Sdrh */ 307313449892Sdrh if( groupBySort ){ 307413449892Sdrh sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); 307513449892Sdrh }else{ 307613449892Sdrh sqlite3WhereEnd(pWInfo); 307713449892Sdrh uncreateSortingIndex(pParse, addrSortingIdx); 307813449892Sdrh } 307913449892Sdrh 308013449892Sdrh /* Output the final row of result 308113449892Sdrh */ 308213449892Sdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); 3083de29e3e9Sdrh VdbeComment((v, "# output final row")); 308413449892Sdrh 308513449892Sdrh } /* endif pGroupBy */ 308613449892Sdrh else { 308713449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 308813449892Sdrh ** processing is much simpler since there is only a single row 308913449892Sdrh ** of output. 309013449892Sdrh */ 309113449892Sdrh resetAccumulator(pParse, &sAggInfo); 309213449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); 30935360ad34Sdrh if( pWInfo==0 ) goto select_end; 309413449892Sdrh updateAccumulator(pParse, &sAggInfo); 309513449892Sdrh sqlite3WhereEnd(pWInfo); 309613449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 309713449892Sdrh pOrderBy = 0; 30985774b806Sdrh if( pHaving ){ 30995774b806Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1); 31005774b806Sdrh } 310113449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 310213449892Sdrh eDest, iParm, addrEnd, addrEnd, aff); 310313449892Sdrh } 310413449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 310513449892Sdrh 310613449892Sdrh } /* endif aggregate query */ 31072282792aSdrh 3108cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 3109cce7d176Sdrh ** and send them to the callback one by one. 3110cce7d176Sdrh */ 3111cce7d176Sdrh if( pOrderBy ){ 3112ffbc3088Sdrh generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm); 3113cce7d176Sdrh } 31146a535340Sdrh 311593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 3116f620b4e2Sdrh /* If this was a subquery, we have now converted the subquery into a 3117f620b4e2Sdrh ** temporary table. So delete the subquery structure from the parent 3118f620b4e2Sdrh ** to prevent this subquery from being evaluated again and to force the 3119f620b4e2Sdrh ** the use of the temporary table. 3120f620b4e2Sdrh */ 3121f620b4e2Sdrh if( pParent ){ 3122f620b4e2Sdrh assert( pParent->pSrc->nSrc>parentTab ); 3123f620b4e2Sdrh assert( pParent->pSrc->a[parentTab].pSelect==p ); 31244adee20fSdanielk1977 sqlite3SelectDelete(p); 3125f620b4e2Sdrh pParent->pSrc->a[parentTab].pSelect = 0; 3126f620b4e2Sdrh } 312793758c8dSdanielk1977 #endif 3128f620b4e2Sdrh 3129ec7429aeSdrh /* Jump here to skip this query 3130ec7429aeSdrh */ 3131ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 3132ec7429aeSdrh 31331d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 31341d83f052Sdrh ** to indicate no errors. 31351d83f052Sdrh */ 31361d83f052Sdrh rc = 0; 31371d83f052Sdrh 31381d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 31391d83f052Sdrh ** successful coding of the SELECT. 31401d83f052Sdrh */ 31411d83f052Sdrh select_end: 314213449892Sdrh sqliteFree(sAggInfo.aCol); 314313449892Sdrh sqliteFree(sAggInfo.aFunc); 31441d83f052Sdrh return rc; 3145cce7d176Sdrh } 3146