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*2646da7eSdrh ** $Id: select.c,v 1.282 2005/12/09 20:02:05 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 112*2646da7eSdrh && sqlite3StrNICmp((char*)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){ 157*2646da7eSdrh p->z = (u8*)z; 158261919ccSdanielk1977 p->n = z ? strlen(z) : 0; 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 ){ 635*2646da7eSdrh pInfo->aSortOrder = (u8*)&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); 6908a51256cSdrh sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "c", 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 ); 859261919ccSdanielk1977 if( pParse->colNamesSet || v==0 || sqlite3Tsd()->mallocFailed ) 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] ){ 888*2646da7eSdrh sqlite3VdbeSetColName(v, i, (char*)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] ){ 901*2646da7eSdrh sqlite3VdbeSetColName(v, i, (char*)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); 987261919ccSdanielk1977 if( sqlite3Tsd()->mallocFailed ){ 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 1059261919ccSdanielk1977 if( p==0 || p->pSrc==0 || sqlite3Tsd()->mallocFailed ) 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); 1167261919ccSdanielk1977 if( pNew ){ 11687c917d19Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 1169261919ccSdanielk1977 }else{ 1170261919ccSdanielk1977 rc = 1; 1171261919ccSdanielk1977 } 11727c917d19Sdrh a[k].pExpr = 0; 11737c917d19Sdrh a[k].zName = 0; 11747c917d19Sdrh }else{ 117554473229Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 117654473229Sdrh ** expanded. */ 117754473229Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 1178cf55b7aeSdrh char *zTName; /* text of name of TABLE */ 117954473229Sdrh if( pE->op==TK_DOT && pE->pLeft ){ 1180cf55b7aeSdrh zTName = sqlite3NameFromToken(&pE->pLeft->token); 118154473229Sdrh }else{ 1182cf55b7aeSdrh zTName = 0; 118354473229Sdrh } 1184290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1185290c1948Sdrh Table *pTab = pFrom->pTab; 1186290c1948Sdrh char *zTabName = pFrom->zAlias; 118754473229Sdrh if( zTabName==0 || zTabName[0]==0 ){ 118854473229Sdrh zTabName = pTab->zName; 118954473229Sdrh } 1190cf55b7aeSdrh if( zTName && (zTabName==0 || zTabName[0]==0 || 1191cf55b7aeSdrh sqlite3StrICmp(zTName, zTabName)!=0) ){ 119254473229Sdrh continue; 119354473229Sdrh } 119454473229Sdrh tableSeen = 1; 1195d8bc7086Sdrh for(j=0; j<pTab->nCol; j++){ 119622f70c32Sdrh Expr *pExpr, *pLeft, *pRight; 1197ad2d8307Sdrh char *zName = pTab->aCol[j].zName; 1198ad2d8307Sdrh 119991bb0eedSdrh if( i>0 ){ 120091bb0eedSdrh struct SrcList_item *pLeft = &pTabList->a[i-1]; 120191bb0eedSdrh if( (pLeft->jointype & JT_NATURAL)!=0 && 120291bb0eedSdrh columnIndex(pLeft->pTab, zName)>=0 ){ 1203ad2d8307Sdrh /* In a NATURAL join, omit the join columns from the 1204ad2d8307Sdrh ** table on the right */ 1205ad2d8307Sdrh continue; 1206ad2d8307Sdrh } 120791bb0eedSdrh if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){ 1208ad2d8307Sdrh /* In a join with a USING clause, omit columns in the 1209ad2d8307Sdrh ** using clause from the table on the right. */ 1210ad2d8307Sdrh continue; 1211ad2d8307Sdrh } 121291bb0eedSdrh } 12134adee20fSdanielk1977 pRight = sqlite3Expr(TK_ID, 0, 0, 0); 121422f70c32Sdrh if( pRight==0 ) break; 121591bb0eedSdrh setToken(&pRight->token, zName); 1216d70dc52dSdrh if( zTabName && (longNames || pTabList->nSrc>1) ){ 12174adee20fSdanielk1977 pLeft = sqlite3Expr(TK_ID, 0, 0, 0); 12184adee20fSdanielk1977 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0); 121922f70c32Sdrh if( pExpr==0 ) break; 122091bb0eedSdrh setToken(&pLeft->token, zTabName); 122191bb0eedSdrh setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName)); 12226977fea8Sdrh pExpr->span.dyn = 1; 12236977fea8Sdrh pExpr->token.z = 0; 12246977fea8Sdrh pExpr->token.n = 0; 12256977fea8Sdrh pExpr->token.dyn = 0; 122622f70c32Sdrh }else{ 122722f70c32Sdrh pExpr = pRight; 12286977fea8Sdrh pExpr->span = pExpr->token; 122922f70c32Sdrh } 1230d70dc52dSdrh if( longNames ){ 1231d70dc52dSdrh pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span); 1232d70dc52dSdrh }else{ 123379d5f63fSdrh pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token); 1234d8bc7086Sdrh } 1235d8bc7086Sdrh } 1236d70dc52dSdrh } 123754473229Sdrh if( !tableSeen ){ 1238cf55b7aeSdrh if( zTName ){ 1239cf55b7aeSdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 1240f5db2d3eSdrh }else{ 12414adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no tables specified"); 1242f5db2d3eSdrh } 124354473229Sdrh rc = 1; 124454473229Sdrh } 1245cf55b7aeSdrh sqliteFree(zTName); 12467c917d19Sdrh } 12477c917d19Sdrh } 12484adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 12497c917d19Sdrh p->pEList = pNew; 1250d8bc7086Sdrh } 125154473229Sdrh return rc; 1252d8bc7086Sdrh } 1253d8bc7086Sdrh 125493758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1255ff78bd2fSdrh /* 1256d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with 1257d8bc7086Sdrh ** columns in a result. For each ORDER BY expression, the opcode of 1258967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of 1259d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable 1260d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter. 1261d8bc7086Sdrh ** 1262d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first. A match 1263d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT. 1264d8bc7086Sdrh ** 1265d8bc7086Sdrh ** Any entry that does not match is flagged as an error. The number 1266d8bc7086Sdrh ** of errors is returned. 1267d8bc7086Sdrh */ 1268d8bc7086Sdrh static int matchOrderbyToColumn( 1269d8bc7086Sdrh Parse *pParse, /* A place to leave error messages */ 1270d8bc7086Sdrh Select *pSelect, /* Match to result columns of this SELECT */ 1271d8bc7086Sdrh ExprList *pOrderBy, /* The ORDER BY values to match against columns */ 1272e4de1febSdrh int iTable, /* Insert this value in iTable */ 1273d8bc7086Sdrh int mustComplete /* If TRUE all ORDER BYs must match */ 1274d8bc7086Sdrh ){ 1275d8bc7086Sdrh int nErr = 0; 1276d8bc7086Sdrh int i, j; 1277d8bc7086Sdrh ExprList *pEList; 1278d8bc7086Sdrh 1279daffd0e5Sdrh if( pSelect==0 || pOrderBy==0 ) return 1; 1280d8bc7086Sdrh if( mustComplete ){ 1281d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } 1282d8bc7086Sdrh } 12839b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 1284d8bc7086Sdrh return 1; 1285d8bc7086Sdrh } 1286d8bc7086Sdrh if( pSelect->pPrior ){ 128792cd52f5Sdrh if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ 128892cd52f5Sdrh return 1; 128992cd52f5Sdrh } 1290d8bc7086Sdrh } 1291d8bc7086Sdrh pEList = pSelect->pEList; 1292d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 1293d8bc7086Sdrh Expr *pE = pOrderBy->a[i].pExpr; 1294e4de1febSdrh int iCol = -1; 1295d8bc7086Sdrh if( pOrderBy->a[i].done ) continue; 12964adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 1297e4de1febSdrh if( iCol<=0 || iCol>pEList->nExpr ){ 12984adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1299da93d238Sdrh "ORDER BY position %d should be between 1 and %d", 1300e4de1febSdrh iCol, pEList->nExpr); 1301e4de1febSdrh nErr++; 1302e4de1febSdrh break; 1303e4de1febSdrh } 1304fcb78a49Sdrh if( !mustComplete ) continue; 1305e4de1febSdrh iCol--; 1306e4de1febSdrh } 1307e4de1febSdrh for(j=0; iCol<0 && j<pEList->nExpr; j++){ 13084cfa7934Sdrh if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){ 1309a76b5dfcSdrh char *zName, *zLabel; 1310a76b5dfcSdrh zName = pEList->a[j].zName; 1311a99db3b6Sdrh zLabel = sqlite3NameFromToken(&pE->token); 1312a99db3b6Sdrh assert( zLabel!=0 ); 13134adee20fSdanielk1977 if( sqlite3StrICmp(zName, zLabel)==0 ){ 1314e4de1febSdrh iCol = j; 1315d8bc7086Sdrh } 13166e142f54Sdrh sqliteFree(zLabel); 1317d8bc7086Sdrh } 13184adee20fSdanielk1977 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){ 1319e4de1febSdrh iCol = j; 1320d8bc7086Sdrh } 1321e4de1febSdrh } 1322e4de1febSdrh if( iCol>=0 ){ 1323967e8b73Sdrh pE->op = TK_COLUMN; 1324e4de1febSdrh pE->iColumn = iCol; 1325d8bc7086Sdrh pE->iTable = iTable; 1326a58fdfb1Sdanielk1977 pE->iAgg = -1; 1327d8bc7086Sdrh pOrderBy->a[i].done = 1; 1328d8bc7086Sdrh } 1329e4de1febSdrh if( iCol<0 && mustComplete ){ 13304adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1331da93d238Sdrh "ORDER BY term number %d does not match any result column", i+1); 1332d8bc7086Sdrh nErr++; 1333d8bc7086Sdrh break; 1334d8bc7086Sdrh } 1335d8bc7086Sdrh } 1336d8bc7086Sdrh return nErr; 1337d8bc7086Sdrh } 133893758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */ 1339d8bc7086Sdrh 1340d8bc7086Sdrh /* 1341d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1342d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1343d8bc7086Sdrh */ 13444adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1345d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1346d8bc7086Sdrh if( v==0 ){ 13474adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1348d8bc7086Sdrh } 1349d8bc7086Sdrh return v; 1350d8bc7086Sdrh } 1351d8bc7086Sdrh 1352d8bc7086Sdrh /* 13537b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1354ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 13557b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1356a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1357a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1358a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1359a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 13607b58daeaSdrh ** 13617b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if 1362ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 13637b58daeaSdrh ** iOffset should have been preset to appropriate default values 13647b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 1365ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 13667b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 13677b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 13687b58daeaSdrh ** SELECT statements. 13697b58daeaSdrh */ 1370ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 13717b58daeaSdrh /* 13727b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 13737b58daeaSdrh ** contraversy about what the correct behavior should be. 13747b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 13757b58daeaSdrh ** no rows. 13767b58daeaSdrh */ 1377a2dc3b1aSdanielk1977 if( p->pLimit ){ 13787b58daeaSdrh int iMem = pParse->nMem++; 13794adee20fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 13807b58daeaSdrh if( v==0 ) return; 1381a2dc3b1aSdanielk1977 sqlite3ExprCode(pParse, p->pLimit); 1382a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 1383a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_Negative, 0, 0); 13844adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1); 1385ad6d9460Sdrh VdbeComment((v, "# LIMIT counter")); 1386ec7429aeSdrh sqlite3VdbeAddOp(v, OP_IfMemZero, iMem, iBreak); 13877b58daeaSdrh p->iLimit = iMem; 13887b58daeaSdrh } 1389a2dc3b1aSdanielk1977 if( p->pOffset ){ 13907b58daeaSdrh int iMem = pParse->nMem++; 13914adee20fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 13927b58daeaSdrh if( v==0 ) return; 1393a2dc3b1aSdanielk1977 sqlite3ExprCode(pParse, p->pOffset); 1394a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); 1395a2dc3b1aSdanielk1977 sqlite3VdbeAddOp(v, OP_Negative, 0, 0); 13964adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1); 1397ad6d9460Sdrh VdbeComment((v, "# OFFSET counter")); 13987b58daeaSdrh p->iOffset = iMem; 13997b58daeaSdrh } 14007b58daeaSdrh } 14017b58daeaSdrh 14027b58daeaSdrh /* 14030342b1f5Sdrh ** Allocate a virtual index to use for sorting. 1404d3d39e93Sdrh */ 14054db38a70Sdrh static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){ 14060342b1f5Sdrh if( pOrderBy ){ 1407dc1bdc4fSdanielk1977 int addr; 14089d2985c7Sdrh assert( pOrderBy->iECursor==0 ); 14099d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 14100342b1f5Sdrh addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenVirtual, 14119d2985c7Sdrh pOrderBy->iECursor, pOrderBy->nExpr+1); 14120342b1f5Sdrh assert( p->addrOpenVirt[2] == -1 ); 14130342b1f5Sdrh p->addrOpenVirt[2] = addr; 1414736c22b8Sdrh } 1415dc1bdc4fSdanielk1977 } 1416dc1bdc4fSdanielk1977 141713449892Sdrh /* 141813449892Sdrh ** The opcode at addr is an OP_OpenVirtual that created a sorting 141913449892Sdrh ** index tha we ended up not needing. This routine changes that 142013449892Sdrh ** opcode to OP_Noop. 142113449892Sdrh */ 142213449892Sdrh static void uncreateSortingIndex(Parse *pParse, int addr){ 142313449892Sdrh Vdbe *v = pParse->pVdbe; 142413449892Sdrh VdbeOp *pOp = sqlite3VdbeGetOp(v, addr); 142513449892Sdrh sqlite3VdbeChangeP3(v, addr, 0, 0); 142613449892Sdrh pOp->opcode = OP_Noop; 142713449892Sdrh pOp->p1 = 0; 142813449892Sdrh pOp->p2 = 0; 142913449892Sdrh } 143013449892Sdrh 1431b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1432fbc4ee7bSdrh /* 1433fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1434fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1435fbc4ee7bSdrh ** the column has no default collating sequence. 1436fbc4ee7bSdrh ** 1437fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1438fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1439fbc4ee7bSdrh */ 1440dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1441fbc4ee7bSdrh CollSeq *pRet; 1442dc1bdc4fSdanielk1977 if( p->pPrior ){ 1443dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1444fbc4ee7bSdrh }else{ 1445fbc4ee7bSdrh pRet = 0; 1446dc1bdc4fSdanielk1977 } 1447fbc4ee7bSdrh if( pRet==0 ){ 1448dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1449dc1bdc4fSdanielk1977 } 1450dc1bdc4fSdanielk1977 return pRet; 1451d3d39e93Sdrh } 1452b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1453d3d39e93Sdrh 1454b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1455d3d39e93Sdrh /* 145682c3d636Sdrh ** This routine is called to process a query that is really the union 145782c3d636Sdrh ** or intersection of two or more separate queries. 1458c926afbcSdrh ** 1459e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1460e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1461e78e8284Sdrh ** in which case this routine will be called recursively. 1462e78e8284Sdrh ** 1463e78e8284Sdrh ** The results of the total query are to be written into a destination 1464e78e8284Sdrh ** of type eDest with parameter iParm. 1465e78e8284Sdrh ** 1466e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1467e78e8284Sdrh ** 1468e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1469e78e8284Sdrh ** 1470e78e8284Sdrh ** This statement is parsed up as follows: 1471e78e8284Sdrh ** 1472e78e8284Sdrh ** SELECT c FROM t3 1473e78e8284Sdrh ** | 1474e78e8284Sdrh ** `-----> SELECT b FROM t2 1475e78e8284Sdrh ** | 14764b11c6d3Sjplyon ** `------> SELECT a FROM t1 1477e78e8284Sdrh ** 1478e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1479e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1480e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1481e78e8284Sdrh ** 1482e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1483e78e8284Sdrh ** individual selects always group from left to right. 148482c3d636Sdrh */ 148584ac9d02Sdanielk1977 static int multiSelect( 1486fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1487fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1488fbc4ee7bSdrh int eDest, /* \___ Store query results as specified */ 1489fbc4ee7bSdrh int iParm, /* / by these two parameters. */ 149084ac9d02Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 149184ac9d02Sdanielk1977 ){ 149284ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 149310e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 149410e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 14958cdbf836Sdrh int nCol; /* Number of columns in the result set */ 14960342b1f5Sdrh ExprList *pOrderBy; /* The ORDER BY clause on p */ 14970342b1f5Sdrh int aSetP2[2]; /* Set P2 value of these op to number of columns */ 14980342b1f5Sdrh int nSetP2 = 0; /* Number of slots in aSetP2[] used */ 149982c3d636Sdrh 15007b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1501fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 150282c3d636Sdrh */ 150384ac9d02Sdanielk1977 if( p==0 || p->pPrior==0 ){ 150484ac9d02Sdanielk1977 rc = 1; 150584ac9d02Sdanielk1977 goto multi_select_end; 150684ac9d02Sdanielk1977 } 1507d8bc7086Sdrh pPrior = p->pPrior; 15080342b1f5Sdrh assert( pPrior->pRightmost!=pPrior ); 15090342b1f5Sdrh assert( pPrior->pRightmost==p->pRightmost ); 1510d8bc7086Sdrh if( pPrior->pOrderBy ){ 15114adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1512da93d238Sdrh selectOpName(p->op)); 151384ac9d02Sdanielk1977 rc = 1; 151484ac9d02Sdanielk1977 goto multi_select_end; 151582c3d636Sdrh } 1516a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 15174adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 15187b58daeaSdrh selectOpName(p->op)); 151984ac9d02Sdanielk1977 rc = 1; 152084ac9d02Sdanielk1977 goto multi_select_end; 15217b58daeaSdrh } 152282c3d636Sdrh 1523d8bc7086Sdrh /* Make sure we have a valid query engine. If not, create a new one. 1524d8bc7086Sdrh */ 15254adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 152684ac9d02Sdanielk1977 if( v==0 ){ 152784ac9d02Sdanielk1977 rc = 1; 152884ac9d02Sdanielk1977 goto multi_select_end; 152984ac9d02Sdanielk1977 } 1530d8bc7086Sdrh 15311cc3d75fSdrh /* Create the destination temporary table if necessary 15321cc3d75fSdrh */ 15339d2985c7Sdrh if( eDest==SRT_VirtualTab ){ 1534b4964b72Sdanielk1977 assert( p->pEList ); 15350342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 15360342b1f5Sdrh aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 0); 15371cc3d75fSdrh eDest = SRT_Table; 15381cc3d75fSdrh } 15391cc3d75fSdrh 1540f46f905aSdrh /* Generate code for the left and right SELECT statements. 1541d8bc7086Sdrh */ 15420342b1f5Sdrh pOrderBy = p->pOrderBy; 154382c3d636Sdrh switch( p->op ){ 1544f46f905aSdrh case TK_ALL: { 15450342b1f5Sdrh if( pOrderBy==0 ){ 1546ec7429aeSdrh int addr = 0; 1547a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 1548a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 1549a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 1550b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff); 155184ac9d02Sdanielk1977 if( rc ){ 155284ac9d02Sdanielk1977 goto multi_select_end; 155384ac9d02Sdanielk1977 } 1554f46f905aSdrh p->pPrior = 0; 15557b58daeaSdrh p->iLimit = pPrior->iLimit; 15567b58daeaSdrh p->iOffset = pPrior->iOffset; 1557a2dc3b1aSdanielk1977 p->pLimit = 0; 1558a2dc3b1aSdanielk1977 p->pOffset = 0; 1559ec7429aeSdrh if( p->iLimit>=0 ){ 1560ec7429aeSdrh addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0); 1561ec7429aeSdrh VdbeComment((v, "# Jump ahead if LIMIT reached")); 1562ec7429aeSdrh } 1563b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff); 1564f46f905aSdrh p->pPrior = pPrior; 156584ac9d02Sdanielk1977 if( rc ){ 156684ac9d02Sdanielk1977 goto multi_select_end; 156784ac9d02Sdanielk1977 } 1568ec7429aeSdrh if( addr ){ 1569ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 1570ec7429aeSdrh } 1571f46f905aSdrh break; 1572f46f905aSdrh } 1573f46f905aSdrh /* For UNION ALL ... ORDER BY fall through to the next case */ 1574f46f905aSdrh } 157582c3d636Sdrh case TK_EXCEPT: 157682c3d636Sdrh case TK_UNION: { 1577d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1578742f947bSdanielk1977 int op = 0; /* One of the SRT_ operations to apply to self */ 1579d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 1580a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 1581dc1bdc4fSdanielk1977 int addr; 158282c3d636Sdrh 1583d8bc7086Sdrh priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 15840342b1f5Sdrh if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ 1585d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1586c926afbcSdrh ** right. 1587d8bc7086Sdrh */ 158882c3d636Sdrh unionTab = iParm; 158982c3d636Sdrh }else{ 1590d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1591d8bc7086Sdrh ** intermediate results. 1592d8bc7086Sdrh */ 159382c3d636Sdrh unionTab = pParse->nTab++; 15940342b1f5Sdrh if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){ 159584ac9d02Sdanielk1977 rc = 1; 159684ac9d02Sdanielk1977 goto multi_select_end; 1597d8bc7086Sdrh } 15989170dd7eSdrh addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, unionTab, 0); 15990342b1f5Sdrh if( priorOp==SRT_Table ){ 16000342b1f5Sdrh assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); 16010342b1f5Sdrh aSetP2[nSetP2++] = addr; 16020342b1f5Sdrh }else{ 16030342b1f5Sdrh assert( p->addrOpenVirt[0] == -1 ); 16040342b1f5Sdrh p->addrOpenVirt[0] = addr; 16050342b1f5Sdrh p->pRightmost->usesVirt = 1; 1606dc1bdc4fSdanielk1977 } 16070342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 160884ac9d02Sdanielk1977 assert( p->pEList ); 1609d8bc7086Sdrh } 1610d8bc7086Sdrh 1611d8bc7086Sdrh /* Code the SELECT statements to our left 1612d8bc7086Sdrh */ 1613b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 1614b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); 161584ac9d02Sdanielk1977 if( rc ){ 161684ac9d02Sdanielk1977 goto multi_select_end; 161784ac9d02Sdanielk1977 } 1618d8bc7086Sdrh 1619d8bc7086Sdrh /* Code the current SELECT statement 1620d8bc7086Sdrh */ 1621d8bc7086Sdrh switch( p->op ){ 1622d8bc7086Sdrh case TK_EXCEPT: op = SRT_Except; break; 1623d8bc7086Sdrh case TK_UNION: op = SRT_Union; break; 1624d8bc7086Sdrh case TK_ALL: op = SRT_Table; break; 1625d8bc7086Sdrh } 162682c3d636Sdrh p->pPrior = 0; 1627c926afbcSdrh p->pOrderBy = 0; 16284b14b4d7Sdrh p->disallowOrderBy = pOrderBy!=0; 1629a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1630a2dc3b1aSdanielk1977 p->pLimit = 0; 1631a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1632a2dc3b1aSdanielk1977 p->pOffset = 0; 1633b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff); 163482c3d636Sdrh p->pPrior = pPrior; 1635c926afbcSdrh p->pOrderBy = pOrderBy; 1636a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 1637a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1638a2dc3b1aSdanielk1977 p->pOffset = pOffset; 1639be5fd490Sdrh p->iLimit = -1; 1640be5fd490Sdrh p->iOffset = -1; 164184ac9d02Sdanielk1977 if( rc ){ 164284ac9d02Sdanielk1977 goto multi_select_end; 164384ac9d02Sdanielk1977 } 164484ac9d02Sdanielk1977 1645d8bc7086Sdrh 1646d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1647d8bc7086Sdrh ** it is that we currently need. 1648d8bc7086Sdrh */ 1649c926afbcSdrh if( eDest!=priorOp || unionTab!=iParm ){ 16506b56344dSdrh int iCont, iBreak, iStart; 165182c3d636Sdrh assert( p->pEList ); 165241202ccaSdrh if( eDest==SRT_Callback ){ 16536a3ea0e6Sdrh generateColumnNames(pParse, 0, p->pEList); 165441202ccaSdrh } 16554adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 16564adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1657ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 16584adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); 16594adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 166038640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 16610342b1f5Sdrh pOrderBy, -1, eDest, iParm, 166284ac9d02Sdanielk1977 iCont, iBreak, 0); 166384ac9d02Sdanielk1977 if( rc ){ 166484ac9d02Sdanielk1977 rc = 1; 166584ac9d02Sdanielk1977 goto multi_select_end; 166684ac9d02Sdanielk1977 } 16674adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 16684adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); 16694adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 16704adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); 167182c3d636Sdrh } 167282c3d636Sdrh break; 167382c3d636Sdrh } 167482c3d636Sdrh case TK_INTERSECT: { 167582c3d636Sdrh int tab1, tab2; 16766b56344dSdrh int iCont, iBreak, iStart; 1677a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 1678dc1bdc4fSdanielk1977 int addr; 167982c3d636Sdrh 1680d8bc7086Sdrh /* INTERSECT is different from the others since it requires 16816206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1682d8bc7086Sdrh ** by allocating the tables we will need. 1683d8bc7086Sdrh */ 168482c3d636Sdrh tab1 = pParse->nTab++; 168582c3d636Sdrh tab2 = pParse->nTab++; 16860342b1f5Sdrh if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){ 168784ac9d02Sdanielk1977 rc = 1; 168884ac9d02Sdanielk1977 goto multi_select_end; 1689d8bc7086Sdrh } 16900342b1f5Sdrh createSortingIndex(pParse, p, pOrderBy); 1691dc1bdc4fSdanielk1977 16929170dd7eSdrh addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab1, 0); 16930342b1f5Sdrh assert( p->addrOpenVirt[0] == -1 ); 16940342b1f5Sdrh p->addrOpenVirt[0] = addr; 16950342b1f5Sdrh p->pRightmost->usesVirt = 1; 169684ac9d02Sdanielk1977 assert( p->pEList ); 1697d8bc7086Sdrh 1698d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1699d8bc7086Sdrh */ 1700b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); 170184ac9d02Sdanielk1977 if( rc ){ 170284ac9d02Sdanielk1977 goto multi_select_end; 170384ac9d02Sdanielk1977 } 1704d8bc7086Sdrh 1705d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1706d8bc7086Sdrh */ 17079170dd7eSdrh addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, tab2, 0); 17080342b1f5Sdrh assert( p->addrOpenVirt[1] == -1 ); 17090342b1f5Sdrh p->addrOpenVirt[1] = addr; 171082c3d636Sdrh p->pPrior = 0; 1711a2dc3b1aSdanielk1977 pLimit = p->pLimit; 1712a2dc3b1aSdanielk1977 p->pLimit = 0; 1713a2dc3b1aSdanielk1977 pOffset = p->pOffset; 1714a2dc3b1aSdanielk1977 p->pOffset = 0; 1715b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); 171682c3d636Sdrh p->pPrior = pPrior; 1717a2dc3b1aSdanielk1977 sqlite3ExprDelete(p->pLimit); 1718a2dc3b1aSdanielk1977 p->pLimit = pLimit; 1719a2dc3b1aSdanielk1977 p->pOffset = pOffset; 172084ac9d02Sdanielk1977 if( rc ){ 172184ac9d02Sdanielk1977 goto multi_select_end; 172284ac9d02Sdanielk1977 } 1723d8bc7086Sdrh 1724d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1725d8bc7086Sdrh ** tables. 1726d8bc7086Sdrh */ 172782c3d636Sdrh assert( p->pEList ); 172841202ccaSdrh if( eDest==SRT_Callback ){ 17296a3ea0e6Sdrh generateColumnNames(pParse, 0, p->pEList); 173041202ccaSdrh } 17314adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 17324adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 1733ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 17344adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak); 17354a9f241cSdrh iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0); 17364adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont); 173738640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 17380342b1f5Sdrh pOrderBy, -1, eDest, iParm, 173984ac9d02Sdanielk1977 iCont, iBreak, 0); 174084ac9d02Sdanielk1977 if( rc ){ 174184ac9d02Sdanielk1977 rc = 1; 174284ac9d02Sdanielk1977 goto multi_select_end; 174384ac9d02Sdanielk1977 } 17444adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 17454adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); 17464adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 17474adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab2, 0); 17484adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab1, 0); 174982c3d636Sdrh break; 175082c3d636Sdrh } 175182c3d636Sdrh } 17528cdbf836Sdrh 17538cdbf836Sdrh /* Make sure all SELECTs in the statement have the same number of elements 17548cdbf836Sdrh ** in their result sets. 17558cdbf836Sdrh */ 175682c3d636Sdrh assert( p->pEList && pPrior->pEList ); 175782c3d636Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 17584adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1759da93d238Sdrh " do not have the same number of result columns", selectOpName(p->op)); 176084ac9d02Sdanielk1977 rc = 1; 176184ac9d02Sdanielk1977 goto multi_select_end; 17622282792aSdrh } 176384ac9d02Sdanielk1977 17648cdbf836Sdrh /* Set the number of columns in temporary tables 17658cdbf836Sdrh */ 17668cdbf836Sdrh nCol = p->pEList->nExpr; 17670342b1f5Sdrh while( nSetP2 ){ 17680342b1f5Sdrh sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol); 17698cdbf836Sdrh } 17708cdbf836Sdrh 1771fbc4ee7bSdrh /* Compute collating sequences used by either the ORDER BY clause or 1772fbc4ee7bSdrh ** by any temporary tables needed to implement the compound select. 1773fbc4ee7bSdrh ** Attach the KeyInfo structure to all temporary tables. Invoke the 1774fbc4ee7bSdrh ** ORDER BY processing if there is an ORDER BY clause. 17758cdbf836Sdrh ** 17768cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 17778cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 17788cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 17798cdbf836Sdrh ** no temp tables are required. 1780fbc4ee7bSdrh */ 17810342b1f5Sdrh if( pOrderBy || p->usesVirt ){ 1782fbc4ee7bSdrh int i; /* Loop counter */ 1783fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 17840342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 17850342b1f5Sdrh CollSeq **apColl; 17860342b1f5Sdrh CollSeq **aCopy; 1787fbc4ee7bSdrh 17880342b1f5Sdrh assert( p->pRightmost==p ); 17894db38a70Sdrh pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*2*sizeof(CollSeq*) + nCol); 1790dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1791dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1792dc1bdc4fSdanielk1977 goto multi_select_end; 1793dc1bdc4fSdanielk1977 } 1794dc1bdc4fSdanielk1977 1795dc1bdc4fSdanielk1977 pKeyInfo->enc = pParse->db->enc; 1796dc1bdc4fSdanielk1977 pKeyInfo->nField = nCol; 1797dc1bdc4fSdanielk1977 17980342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 17990342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 18000342b1f5Sdrh if( 0==*apColl ){ 18010342b1f5Sdrh *apColl = pParse->db->pDfltColl; 1802dc1bdc4fSdanielk1977 } 1803dc1bdc4fSdanielk1977 } 1804dc1bdc4fSdanielk1977 18050342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 18060342b1f5Sdrh for(i=0; i<2; i++){ 18070342b1f5Sdrh int addr = pLoop->addrOpenVirt[i]; 18080342b1f5Sdrh if( addr<0 ){ 18090342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 18100342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 18110342b1f5Sdrh assert( pLoop->addrOpenVirt[1]<0 ); 18120342b1f5Sdrh break; 18130342b1f5Sdrh } 18140342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 18150342b1f5Sdrh sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO); 18160342b1f5Sdrh } 1817dc1bdc4fSdanielk1977 } 1818dc1bdc4fSdanielk1977 18190342b1f5Sdrh if( pOrderBy ){ 18200342b1f5Sdrh struct ExprList_item *pOTerm = pOrderBy->a; 18214efc083fSdrh int nOrderByExpr = pOrderBy->nExpr; 18220342b1f5Sdrh int addr; 18234db38a70Sdrh u8 *pSortOrder; 18240342b1f5Sdrh 18250342b1f5Sdrh aCopy = (CollSeq**)&pKeyInfo[1]; 18264efc083fSdrh pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol]; 18270342b1f5Sdrh memcpy(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*)); 18280342b1f5Sdrh apColl = pKeyInfo->aColl; 18294efc083fSdrh for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){ 18300342b1f5Sdrh Expr *pExpr = pOTerm->pExpr; 18310342b1f5Sdrh char *zName = pOTerm->zName; 1832dc1bdc4fSdanielk1977 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol ); 1833dc1bdc4fSdanielk1977 if( zName ){ 18340342b1f5Sdrh *apColl = sqlite3LocateCollSeq(pParse, zName, -1); 183584ac9d02Sdanielk1977 }else{ 18360342b1f5Sdrh *apColl = aCopy[pExpr->iColumn]; 183784ac9d02Sdanielk1977 } 18384db38a70Sdrh *pSortOrder = pOTerm->sortOrder; 183984ac9d02Sdanielk1977 } 18400342b1f5Sdrh assert( p->pRightmost==p ); 18410342b1f5Sdrh assert( p->addrOpenVirt[2]>=0 ); 18420342b1f5Sdrh addr = p->addrOpenVirt[2]; 18434db38a70Sdrh sqlite3VdbeChangeP2(v, addr, p->pEList->nExpr+2); 18444efc083fSdrh pKeyInfo->nField = nOrderByExpr; 18454db38a70Sdrh sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 18464db38a70Sdrh pKeyInfo = 0; 1847dc1bdc4fSdanielk1977 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm); 1848dc1bdc4fSdanielk1977 } 1849dc1bdc4fSdanielk1977 1850dc1bdc4fSdanielk1977 sqliteFree(pKeyInfo); 1851dc1bdc4fSdanielk1977 } 1852dc1bdc4fSdanielk1977 1853dc1bdc4fSdanielk1977 multi_select_end: 185484ac9d02Sdanielk1977 return rc; 18552282792aSdrh } 1856b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 18572282792aSdrh 1858b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 18592282792aSdrh /* 1860832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 18616a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 186284e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 18636a3ea0e6Sdrh ** unchanged.) 1864832508b7Sdrh ** 1865832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 1866832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 1867832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 1868832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 1869832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 1870832508b7Sdrh ** of the subquery rather the result set of the subquery. 1871832508b7Sdrh */ 18726a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */ 1873b3bce662Sdanielk1977 static void substSelect(Select *, int, ExprList *); /* Forward Decl */ 18746a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){ 1875832508b7Sdrh if( pExpr==0 ) return; 187650350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 187750350a15Sdrh if( pExpr->iColumn<0 ){ 187850350a15Sdrh pExpr->op = TK_NULL; 187950350a15Sdrh }else{ 1880832508b7Sdrh Expr *pNew; 188184e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 1882832508b7Sdrh assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 1883832508b7Sdrh pNew = pEList->a[pExpr->iColumn].pExpr; 1884832508b7Sdrh assert( pNew!=0 ); 1885832508b7Sdrh pExpr->op = pNew->op; 1886d94a6698Sdrh assert( pExpr->pLeft==0 ); 18874adee20fSdanielk1977 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft); 1888d94a6698Sdrh assert( pExpr->pRight==0 ); 18894adee20fSdanielk1977 pExpr->pRight = sqlite3ExprDup(pNew->pRight); 1890d94a6698Sdrh assert( pExpr->pList==0 ); 18914adee20fSdanielk1977 pExpr->pList = sqlite3ExprListDup(pNew->pList); 1892832508b7Sdrh pExpr->iTable = pNew->iTable; 1893832508b7Sdrh pExpr->iColumn = pNew->iColumn; 1894832508b7Sdrh pExpr->iAgg = pNew->iAgg; 18954adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->token, &pNew->token); 18964adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->span, &pNew->span); 1897a1cb183dSdanielk1977 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect); 1898a1cb183dSdanielk1977 pExpr->flags = pNew->flags; 189950350a15Sdrh } 1900832508b7Sdrh }else{ 19016a3ea0e6Sdrh substExpr(pExpr->pLeft, iTable, pEList); 19026a3ea0e6Sdrh substExpr(pExpr->pRight, iTable, pEList); 1903b3bce662Sdanielk1977 substSelect(pExpr->pSelect, iTable, pEList); 19046a3ea0e6Sdrh substExprList(pExpr->pList, iTable, pEList); 1905832508b7Sdrh } 1906832508b7Sdrh } 1907b3bce662Sdanielk1977 static void substExprList(ExprList *pList, int iTable, ExprList *pEList){ 1908832508b7Sdrh int i; 1909832508b7Sdrh if( pList==0 ) return; 1910832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 19116a3ea0e6Sdrh substExpr(pList->a[i].pExpr, iTable, pEList); 1912832508b7Sdrh } 1913832508b7Sdrh } 1914b3bce662Sdanielk1977 static void substSelect(Select *p, int iTable, ExprList *pEList){ 1915b3bce662Sdanielk1977 if( !p ) return; 1916b3bce662Sdanielk1977 substExprList(p->pEList, iTable, pEList); 1917b3bce662Sdanielk1977 substExprList(p->pGroupBy, iTable, pEList); 1918b3bce662Sdanielk1977 substExprList(p->pOrderBy, iTable, pEList); 1919b3bce662Sdanielk1977 substExpr(p->pHaving, iTable, pEList); 1920b3bce662Sdanielk1977 substExpr(p->pWhere, iTable, pEList); 1921b3bce662Sdanielk1977 } 1922b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */ 1923832508b7Sdrh 1924b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 1925832508b7Sdrh /* 19261350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 19271350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 19281350b030Sdrh ** occurs. 19291350b030Sdrh ** 19301350b030Sdrh ** To understand the concept of flattening, consider the following 19311350b030Sdrh ** query: 19321350b030Sdrh ** 19331350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 19341350b030Sdrh ** 19351350b030Sdrh ** The default way of implementing this query is to execute the 19361350b030Sdrh ** subquery first and store the results in a temporary table, then 19371350b030Sdrh ** run the outer query on that temporary table. This requires two 19381350b030Sdrh ** passes over the data. Furthermore, because the temporary table 19391350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 1940832508b7Sdrh ** optimized. 19411350b030Sdrh ** 1942832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 19431350b030Sdrh ** a single flat select, like this: 19441350b030Sdrh ** 19451350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 19461350b030Sdrh ** 19471350b030Sdrh ** The code generated for this simpification gives the same result 1948832508b7Sdrh ** but only has to scan the data once. And because indices might 1949832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 1950832508b7Sdrh ** avoided. 19511350b030Sdrh ** 1952832508b7Sdrh ** Flattening is only attempted if all of the following are true: 19531350b030Sdrh ** 1954832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 19551350b030Sdrh ** 1956832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 1957832508b7Sdrh ** 19588af4d3acSdrh ** (3) The subquery is not the right operand of a left outer join, or 19598af4d3acSdrh ** the subquery is not itself a join. (Ticket #306) 1960832508b7Sdrh ** 1961832508b7Sdrh ** (4) The subquery is not DISTINCT or the outer query is not a join. 1962832508b7Sdrh ** 1963832508b7Sdrh ** (5) The subquery is not DISTINCT or the outer query does not use 1964832508b7Sdrh ** aggregates. 1965832508b7Sdrh ** 1966832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 1967832508b7Sdrh ** DISTINCT. 1968832508b7Sdrh ** 196908192d5fSdrh ** (7) The subquery has a FROM clause. 197008192d5fSdrh ** 1971df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 1972df199a25Sdrh ** 1973df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 1974df199a25Sdrh ** aggregates. 1975df199a25Sdrh ** 1976df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 1977df199a25Sdrh ** use LIMIT. 1978df199a25Sdrh ** 1979174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 1980174b6195Sdrh ** 19813fc673e6Sdrh ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 19823fc673e6Sdrh ** subquery has no WHERE clause. (added by ticket #350) 19833fc673e6Sdrh ** 1984832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 1985832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 1986832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 1987832508b7Sdrh ** 1988665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 1989832508b7Sdrh ** If flattening is attempted this routine returns 1. 1990832508b7Sdrh ** 1991832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 1992832508b7Sdrh ** the subquery before this routine runs. 19931350b030Sdrh */ 19948c74a8caSdrh static int flattenSubquery( 19958c74a8caSdrh Parse *pParse, /* The parsing context */ 19968c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 19978c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 19988c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 19998c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 20008c74a8caSdrh ){ 20010bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 2002ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 2003ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 20040bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 20056a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 200691bb0eedSdrh int i; /* Loop counter */ 200791bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 200891bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 20091350b030Sdrh 2010832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 2011832508b7Sdrh */ 2012832508b7Sdrh if( p==0 ) return 0; 2013832508b7Sdrh pSrc = p->pSrc; 2014ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 201591bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 201691bb0eedSdrh pSub = pSubitem->pSelect; 2017832508b7Sdrh assert( pSub!=0 ); 2018832508b7Sdrh if( isAgg && subqueryIsAgg ) return 0; 2019ad3cab52Sdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; 2020832508b7Sdrh pSubSrc = pSub->pSrc; 2021832508b7Sdrh assert( pSubSrc ); 2022a2dc3b1aSdanielk1977 if( (pSub->pLimit && p->pLimit) || pSub->pOffset || 2023a2dc3b1aSdanielk1977 (pSub->pLimit && isAgg) ) return 0; 2024c31c2eb8Sdrh if( pSubSrc->nSrc==0 ) return 0; 2025a2dc3b1aSdanielk1977 if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){ 2026df199a25Sdrh return 0; 2027df199a25Sdrh } 2028a2dc3b1aSdanielk1977 if( p->isDistinct && subqueryIsAgg ) return 0; 20294b14b4d7Sdrh if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ) return 0; 2030832508b7Sdrh 20318af4d3acSdrh /* Restriction 3: If the subquery is a join, make sure the subquery is 20328af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 20338af4d3acSdrh ** is not allowed: 20348af4d3acSdrh ** 20358af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 20368af4d3acSdrh ** 20378af4d3acSdrh ** If we flatten the above, we would get 20388af4d3acSdrh ** 20398af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 20408af4d3acSdrh ** 20418af4d3acSdrh ** which is not at all the same thing. 20428af4d3acSdrh */ 20438af4d3acSdrh if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){ 20448af4d3acSdrh return 0; 20458af4d3acSdrh } 20468af4d3acSdrh 20473fc673e6Sdrh /* Restriction 12: If the subquery is the right operand of a left outer 20483fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 20493fc673e6Sdrh ** An examples of why this is not allowed: 20503fc673e6Sdrh ** 20513fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 20523fc673e6Sdrh ** 20533fc673e6Sdrh ** If we flatten the above, we would get 20543fc673e6Sdrh ** 20553fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 20563fc673e6Sdrh ** 20573fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 20583fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 20593fc673e6Sdrh */ 20603fc673e6Sdrh if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 20613fc673e6Sdrh && pSub->pWhere!=0 ){ 20623fc673e6Sdrh return 0; 20633fc673e6Sdrh } 20643fc673e6Sdrh 20650bb28106Sdrh /* If we reach this point, it means flattening is permitted for the 206663eb5f29Sdrh ** iFrom-th entry of the FROM clause in the outer query. 2067832508b7Sdrh */ 2068c31c2eb8Sdrh 2069c31c2eb8Sdrh /* Move all of the FROM elements of the subquery into the 2070c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2071c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2072c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2073c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2074c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2075c31c2eb8Sdrh ** elements we are now copying in. 2076c31c2eb8Sdrh */ 207791bb0eedSdrh iParent = pSubitem->iCursor; 2078c31c2eb8Sdrh { 2079c31c2eb8Sdrh int nSubSrc = pSubSrc->nSrc; 208091bb0eedSdrh int jointype = pSubitem->jointype; 2081c31c2eb8Sdrh 208291bb0eedSdrh sqlite3DeleteTable(0, pSubitem->pTab); 208391bb0eedSdrh sqliteFree(pSubitem->zDatabase); 208491bb0eedSdrh sqliteFree(pSubitem->zName); 208591bb0eedSdrh sqliteFree(pSubitem->zAlias); 2086c31c2eb8Sdrh if( nSubSrc>1 ){ 2087c31c2eb8Sdrh int extra = nSubSrc - 1; 2088c31c2eb8Sdrh for(i=1; i<nSubSrc; i++){ 20894adee20fSdanielk1977 pSrc = sqlite3SrcListAppend(pSrc, 0, 0); 2090c31c2eb8Sdrh } 2091c31c2eb8Sdrh p->pSrc = pSrc; 2092c31c2eb8Sdrh for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 2093c31c2eb8Sdrh pSrc->a[i] = pSrc->a[i-extra]; 2094c31c2eb8Sdrh } 2095c31c2eb8Sdrh } 2096c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2097c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2098c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2099c31c2eb8Sdrh } 21008af4d3acSdrh pSrc->a[iFrom+nSubSrc-1].jointype = jointype; 2101c31c2eb8Sdrh } 2102c31c2eb8Sdrh 2103c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2104c31c2eb8Sdrh ** references to the iParent in the outer query. 2105c31c2eb8Sdrh ** 2106c31c2eb8Sdrh ** Example: 2107c31c2eb8Sdrh ** 2108c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2109c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 2110c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 2111c31c2eb8Sdrh ** 2112c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 2113c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2114c31c2eb8Sdrh */ 21156a3ea0e6Sdrh substExprList(p->pEList, iParent, pSub->pEList); 2116832508b7Sdrh pList = p->pEList; 2117832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 21186977fea8Sdrh Expr *pExpr; 21196977fea8Sdrh if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 2120*2646da7eSdrh pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n); 2121832508b7Sdrh } 2122832508b7Sdrh } 21231b2e0329Sdrh if( isAgg ){ 21246a3ea0e6Sdrh substExprList(p->pGroupBy, iParent, pSub->pEList); 21256a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 21261b2e0329Sdrh } 2127174b6195Sdrh if( pSub->pOrderBy ){ 2128174b6195Sdrh assert( p->pOrderBy==0 ); 2129174b6195Sdrh p->pOrderBy = pSub->pOrderBy; 2130174b6195Sdrh pSub->pOrderBy = 0; 2131174b6195Sdrh }else if( p->pOrderBy ){ 21326a3ea0e6Sdrh substExprList(p->pOrderBy, iParent, pSub->pEList); 2133174b6195Sdrh } 2134832508b7Sdrh if( pSub->pWhere ){ 21354adee20fSdanielk1977 pWhere = sqlite3ExprDup(pSub->pWhere); 2136832508b7Sdrh }else{ 2137832508b7Sdrh pWhere = 0; 2138832508b7Sdrh } 2139832508b7Sdrh if( subqueryIsAgg ){ 2140832508b7Sdrh assert( p->pHaving==0 ); 21411b2e0329Sdrh p->pHaving = p->pWhere; 21421b2e0329Sdrh p->pWhere = pWhere; 21436a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 214491bb0eedSdrh p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving)); 21451b2e0329Sdrh assert( p->pGroupBy==0 ); 21464adee20fSdanielk1977 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy); 2147832508b7Sdrh }else{ 21486a3ea0e6Sdrh substExpr(p->pWhere, iParent, pSub->pEList); 214991bb0eedSdrh p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere); 2150832508b7Sdrh } 2151c31c2eb8Sdrh 2152c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 2153c31c2eb8Sdrh ** outer query is distinct. 2154c31c2eb8Sdrh */ 2155832508b7Sdrh p->isDistinct = p->isDistinct || pSub->isDistinct; 21568c74a8caSdrh 2157a58fdfb1Sdanielk1977 /* 2158a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 2159a58fdfb1Sdanielk1977 */ 2160a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 2161a2dc3b1aSdanielk1977 p->pLimit = pSub->pLimit; 2162a2dc3b1aSdanielk1977 pSub->pLimit = 0; 2163df199a25Sdrh } 21648c74a8caSdrh 2165c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 2166c31c2eb8Sdrh ** success. 2167c31c2eb8Sdrh */ 21684adee20fSdanielk1977 sqlite3SelectDelete(pSub); 2169832508b7Sdrh return 1; 21701350b030Sdrh } 2171b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 21721350b030Sdrh 21731350b030Sdrh /* 21749562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it 21759562b551Sdrh ** is a simple min() or max() query. If it is and this query can be 21769562b551Sdrh ** satisfied using a single seek to the beginning or end of an index, 2177e78e8284Sdrh ** then generate the code for this SELECT and return 1. If this is not a 21789562b551Sdrh ** simple min() or max() query, then return 0; 21799562b551Sdrh ** 21809562b551Sdrh ** A simply min() or max() query looks like this: 21819562b551Sdrh ** 21829562b551Sdrh ** SELECT min(a) FROM table; 21839562b551Sdrh ** SELECT max(a) FROM table; 21849562b551Sdrh ** 21859562b551Sdrh ** The query may have only a single table in its FROM argument. There 21869562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses. The result set must 21879562b551Sdrh ** be the min() or max() of a single column of the table. The column 21889562b551Sdrh ** in the min() or max() function must be indexed. 21899562b551Sdrh ** 21904adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select(). 21919562b551Sdrh ** See the header comment on that routine for additional information. 21929562b551Sdrh */ 21939562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ 21949562b551Sdrh Expr *pExpr; 21959562b551Sdrh int iCol; 21969562b551Sdrh Table *pTab; 21979562b551Sdrh Index *pIdx; 21989562b551Sdrh int base; 21999562b551Sdrh Vdbe *v; 22009562b551Sdrh int seekOp; 22016e17529eSdrh ExprList *pEList, *pList, eList; 22029562b551Sdrh struct ExprList_item eListItem; 22036e17529eSdrh SrcList *pSrc; 2204ec7429aeSdrh int brk; 22056e17529eSdrh 22069562b551Sdrh /* Check to see if this query is a simple min() or max() query. Return 22079562b551Sdrh ** zero if it is not. 22089562b551Sdrh */ 22099562b551Sdrh if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; 22106e17529eSdrh pSrc = p->pSrc; 22116e17529eSdrh if( pSrc->nSrc!=1 ) return 0; 22126e17529eSdrh pEList = p->pEList; 22136e17529eSdrh if( pEList->nExpr!=1 ) return 0; 22146e17529eSdrh pExpr = pEList->a[0].pExpr; 22159562b551Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 22166e17529eSdrh pList = pExpr->pList; 22176e17529eSdrh if( pList==0 || pList->nExpr!=1 ) return 0; 22186977fea8Sdrh if( pExpr->token.n!=3 ) return 0; 2219*2646da7eSdrh if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ 22200bce8354Sdrh seekOp = OP_Rewind; 2221*2646da7eSdrh }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ 22220bce8354Sdrh seekOp = OP_Last; 22230bce8354Sdrh }else{ 22240bce8354Sdrh return 0; 22250bce8354Sdrh } 22266e17529eSdrh pExpr = pList->a[0].pExpr; 22279562b551Sdrh if( pExpr->op!=TK_COLUMN ) return 0; 22289562b551Sdrh iCol = pExpr->iColumn; 22296e17529eSdrh pTab = pSrc->a[0].pTab; 22309562b551Sdrh 22319562b551Sdrh /* If we get to here, it means the query is of the correct form. 223217f71934Sdrh ** Check to make sure we have an index and make pIdx point to the 223317f71934Sdrh ** appropriate index. If the min() or max() is on an INTEGER PRIMARY 223417f71934Sdrh ** key column, no index is necessary so set pIdx to NULL. If no 223517f71934Sdrh ** usable index is found, return 0. 22369562b551Sdrh */ 22379562b551Sdrh if( iCol<0 ){ 22389562b551Sdrh pIdx = 0; 22399562b551Sdrh }else{ 2240dc1bdc4fSdanielk1977 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr); 22419562b551Sdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 22429562b551Sdrh assert( pIdx->nColumn>=1 ); 2243dc1bdc4fSdanielk1977 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break; 22449562b551Sdrh } 22459562b551Sdrh if( pIdx==0 ) return 0; 22469562b551Sdrh } 22479562b551Sdrh 2248e5f50722Sdrh /* Identify column types if we will be using the callback. This 22499562b551Sdrh ** step is skipped if the output is going to a table or a memory cell. 2250e5f50722Sdrh ** The column names have already been generated in the calling function. 22519562b551Sdrh */ 22524adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 22539562b551Sdrh if( v==0 ) return 0; 22549562b551Sdrh 22550c37e630Sdrh /* If the output is destined for a temporary table, open that table. 22560c37e630Sdrh */ 22579d2985c7Sdrh if( eDest==SRT_VirtualTab ){ 2258d81bd4e2Sdrh sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, 1); 22590c37e630Sdrh } 22600c37e630Sdrh 226117f71934Sdrh /* Generating code to find the min or the max. Basically all we have 226217f71934Sdrh ** to do is find the first or the last entry in the chosen index. If 226317f71934Sdrh ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first 226417f71934Sdrh ** or last entry in the main table. 22659562b551Sdrh */ 22664adee20fSdanielk1977 sqlite3CodeVerifySchema(pParse, pTab->iDb); 22676e17529eSdrh base = pSrc->a[0].iCursor; 2268ec7429aeSdrh brk = sqlite3VdbeMakeLabel(v); 2269ec7429aeSdrh computeLimitRegisters(pParse, p, brk); 22706e17529eSdrh if( pSrc->a[0].pSelect==0 ){ 2271ad6d9460Sdrh sqlite3OpenTableForReading(v, base, pTab); 22726e17529eSdrh } 22739562b551Sdrh if( pIdx==0 ){ 22744adee20fSdanielk1977 sqlite3VdbeAddOp(v, seekOp, base, 0); 22759562b551Sdrh }else{ 22763719d7f9Sdanielk1977 /* Even though the cursor used to open the index here is closed 22773719d7f9Sdanielk1977 ** as soon as a single value has been read from it, allocate it 22783719d7f9Sdanielk1977 ** using (pParse->nTab++) to prevent the cursor id from being 22793719d7f9Sdanielk1977 ** reused. This is important for statements of the form 22803719d7f9Sdanielk1977 ** "INSERT INTO x SELECT max() FROM x". 22813719d7f9Sdanielk1977 */ 22823719d7f9Sdanielk1977 int iIdx; 22833719d7f9Sdanielk1977 iIdx = pParse->nTab++; 22844adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0); 22853719d7f9Sdanielk1977 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, 2286d3d39e93Sdrh (char*)&pIdx->keyInfo, P3_KEYINFO); 22879eb516c0Sdrh if( seekOp==OP_Rewind ){ 2288f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_Null, 0, 0); 22891af3fdb4Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0); 22901af3fdb4Sdrh seekOp = OP_MoveGt; 22919eb516c0Sdrh } 22923719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, seekOp, iIdx, 0); 2293f0863fe5Sdrh sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0); 22943719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); 22957cf6e4deSdrh sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 22969562b551Sdrh } 22975cf8e8c7Sdrh eList.nExpr = 1; 22985cf8e8c7Sdrh memset(&eListItem, 0, sizeof(eListItem)); 22995cf8e8c7Sdrh eList.a = &eListItem; 23005cf8e8c7Sdrh eList.a[0].pExpr = pExpr; 2301ec7429aeSdrh selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0); 2302ec7429aeSdrh sqlite3VdbeResolveLabel(v, brk); 23034adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, base, 0); 23046e17529eSdrh 23059562b551Sdrh return 1; 23069562b551Sdrh } 23079562b551Sdrh 23089562b551Sdrh /* 2309290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return 2310290c1948Sdrh ** the number of errors seen. 2311290c1948Sdrh ** 2312290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions. If any expression 2313290c1948Sdrh ** is an integer constant, then that expression is replaced by the 2314290c1948Sdrh ** corresponding entry in the result set. 2315290c1948Sdrh */ 2316290c1948Sdrh static int processOrderGroupBy( 2317b3bce662Sdanielk1977 NameContext *pNC, /* Name context of the SELECT statement. */ 2318290c1948Sdrh ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 2319290c1948Sdrh const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 2320290c1948Sdrh ){ 2321290c1948Sdrh int i; 2322b3bce662Sdanielk1977 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */ 2323b3bce662Sdanielk1977 Parse *pParse = pNC->pParse; /* The result set of the SELECT */ 2324b3bce662Sdanielk1977 assert( pEList ); 2325b3bce662Sdanielk1977 2326290c1948Sdrh if( pOrderBy==0 ) return 0; 2327290c1948Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 2328290c1948Sdrh int iCol; 2329290c1948Sdrh Expr *pE = pOrderBy->a[i].pExpr; 2330b3bce662Sdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 2331b3bce662Sdanielk1977 if( iCol>0 && iCol<=pEList->nExpr ){ 2332290c1948Sdrh sqlite3ExprDelete(pE); 2333290c1948Sdrh pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr); 2334b3bce662Sdanielk1977 }else{ 2335290c1948Sdrh sqlite3ErrorMsg(pParse, 2336290c1948Sdrh "%s BY column number %d out of range - should be " 2337290c1948Sdrh "between 1 and %d", zType, iCol, pEList->nExpr); 2338290c1948Sdrh return 1; 2339290c1948Sdrh } 2340290c1948Sdrh } 2341b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(pNC, pE) ){ 2342b3bce662Sdanielk1977 return 1; 2343b3bce662Sdanielk1977 } 2344b3bce662Sdanielk1977 if( sqlite3ExprIsConstant(pE) ){ 2345b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, 2346b3bce662Sdanielk1977 "%s BY terms must not be non-integer constants", zType); 2347b3bce662Sdanielk1977 return 1; 2348b3bce662Sdanielk1977 } 2349290c1948Sdrh } 2350290c1948Sdrh return 0; 2351290c1948Sdrh } 2352290c1948Sdrh 2353290c1948Sdrh /* 2354b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the 2355b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved 2356b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext 2357b3bce662Sdanielk1977 ** of the parent SELECT. 2358b3bce662Sdanielk1977 */ 2359b3bce662Sdanielk1977 int sqlite3SelectResolve( 2360b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 2361b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 2362b3bce662Sdanielk1977 NameContext *pOuterNC /* The outer name context. May be NULL. */ 2363b3bce662Sdanielk1977 ){ 2364b3bce662Sdanielk1977 ExprList *pEList; /* Result set. */ 2365b3bce662Sdanielk1977 int i; /* For-loop variable used in multiple places */ 2366b3bce662Sdanielk1977 NameContext sNC; /* Local name-context */ 236713449892Sdrh ExprList *pGroupBy; /* The group by clause */ 2368b3bce662Sdanielk1977 2369b3bce662Sdanielk1977 /* If this routine has run before, return immediately. */ 2370b3bce662Sdanielk1977 if( p->isResolved ){ 2371b3bce662Sdanielk1977 assert( !pOuterNC ); 2372b3bce662Sdanielk1977 return SQLITE_OK; 2373b3bce662Sdanielk1977 } 2374b3bce662Sdanielk1977 p->isResolved = 1; 2375b3bce662Sdanielk1977 2376b3bce662Sdanielk1977 /* If there have already been errors, do nothing. */ 2377b3bce662Sdanielk1977 if( pParse->nErr>0 ){ 2378b3bce662Sdanielk1977 return SQLITE_ERROR; 2379b3bce662Sdanielk1977 } 2380b3bce662Sdanielk1977 2381b3bce662Sdanielk1977 /* Prepare the select statement. This call will allocate all cursors 2382b3bce662Sdanielk1977 ** required to handle the tables and subqueries in the FROM clause. 2383b3bce662Sdanielk1977 */ 2384b3bce662Sdanielk1977 if( prepSelectStmt(pParse, p) ){ 2385b3bce662Sdanielk1977 return SQLITE_ERROR; 2386b3bce662Sdanielk1977 } 2387b3bce662Sdanielk1977 2388a2dc3b1aSdanielk1977 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 2389a2dc3b1aSdanielk1977 ** are not allowed to refer to any names, so pass an empty NameContext. 2390a2dc3b1aSdanielk1977 */ 2391ffe07b2dSdrh memset(&sNC, 0, sizeof(sNC)); 2392b3bce662Sdanielk1977 sNC.pParse = pParse; 2393a2dc3b1aSdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pLimit) || 2394a2dc3b1aSdanielk1977 sqlite3ExprResolveNames(&sNC, p->pOffset) ){ 2395a2dc3b1aSdanielk1977 return SQLITE_ERROR; 2396a2dc3b1aSdanielk1977 } 2397a2dc3b1aSdanielk1977 2398a2dc3b1aSdanielk1977 /* Set up the local name-context to pass to ExprResolveNames() to 2399a2dc3b1aSdanielk1977 ** resolve the expression-list. 2400a2dc3b1aSdanielk1977 */ 2401a2dc3b1aSdanielk1977 sNC.allowAgg = 1; 2402a2dc3b1aSdanielk1977 sNC.pSrcList = p->pSrc; 2403a2dc3b1aSdanielk1977 sNC.pNext = pOuterNC; 2404b3bce662Sdanielk1977 2405b3bce662Sdanielk1977 /* Resolve names in the result set. */ 2406b3bce662Sdanielk1977 pEList = p->pEList; 2407b3bce662Sdanielk1977 if( !pEList ) return SQLITE_ERROR; 2408b3bce662Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 2409b3bce662Sdanielk1977 Expr *pX = pEList->a[i].pExpr; 2410b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pX) ){ 2411b3bce662Sdanielk1977 return SQLITE_ERROR; 2412b3bce662Sdanielk1977 } 2413b3bce662Sdanielk1977 } 2414b3bce662Sdanielk1977 2415b3bce662Sdanielk1977 /* If there are no aggregate functions in the result-set, and no GROUP BY 2416b3bce662Sdanielk1977 ** expression, do not allow aggregates in any of the other expressions. 2417b3bce662Sdanielk1977 */ 2418b3bce662Sdanielk1977 assert( !p->isAgg ); 241913449892Sdrh pGroupBy = p->pGroupBy; 242013449892Sdrh if( pGroupBy || sNC.hasAgg ){ 2421b3bce662Sdanielk1977 p->isAgg = 1; 2422b3bce662Sdanielk1977 }else{ 2423b3bce662Sdanielk1977 sNC.allowAgg = 0; 2424b3bce662Sdanielk1977 } 2425b3bce662Sdanielk1977 2426b3bce662Sdanielk1977 /* If a HAVING clause is present, then there must be a GROUP BY clause. 2427b3bce662Sdanielk1977 */ 242813449892Sdrh if( p->pHaving && !pGroupBy ){ 2429b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2430b3bce662Sdanielk1977 return SQLITE_ERROR; 2431b3bce662Sdanielk1977 } 2432b3bce662Sdanielk1977 2433b3bce662Sdanielk1977 /* Add the expression list to the name-context before parsing the 2434b3bce662Sdanielk1977 ** other expressions in the SELECT statement. This is so that 2435b3bce662Sdanielk1977 ** expressions in the WHERE clause (etc.) can refer to expressions by 2436b3bce662Sdanielk1977 ** aliases in the result set. 2437b3bce662Sdanielk1977 ** 2438b3bce662Sdanielk1977 ** Minor point: If this is the case, then the expression will be 2439b3bce662Sdanielk1977 ** re-evaluated for each reference to it. 2440b3bce662Sdanielk1977 */ 2441b3bce662Sdanielk1977 sNC.pEList = p->pEList; 2442b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pWhere) || 2443b3bce662Sdanielk1977 sqlite3ExprResolveNames(&sNC, p->pHaving) || 2444b3bce662Sdanielk1977 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") || 244513449892Sdrh processOrderGroupBy(&sNC, pGroupBy, "GROUP") 2446b3bce662Sdanielk1977 ){ 2447b3bce662Sdanielk1977 return SQLITE_ERROR; 2448b3bce662Sdanielk1977 } 2449b3bce662Sdanielk1977 245013449892Sdrh /* Make sure the GROUP BY clause does not contain aggregate functions. 245113449892Sdrh */ 245213449892Sdrh if( pGroupBy ){ 245313449892Sdrh struct ExprList_item *pItem; 245413449892Sdrh 245513449892Sdrh for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 245613449892Sdrh if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 245713449892Sdrh sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 245813449892Sdrh "the GROUP BY clause"); 245913449892Sdrh return SQLITE_ERROR; 246013449892Sdrh } 246113449892Sdrh } 246213449892Sdrh } 246313449892Sdrh 2464b3bce662Sdanielk1977 return SQLITE_OK; 2465b3bce662Sdanielk1977 } 2466b3bce662Sdanielk1977 2467b3bce662Sdanielk1977 /* 246813449892Sdrh ** Reset the aggregate accumulator. 246913449892Sdrh ** 247013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 247113449892Sdrh ** intermediate results while calculating an aggregate. This 247213449892Sdrh ** routine simply stores NULLs in all of those memory cells. 2473b3bce662Sdanielk1977 */ 247413449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 247513449892Sdrh Vdbe *v = pParse->pVdbe; 247613449892Sdrh int i; 2477c99130fdSdrh struct AggInfo_func *pFunc; 247813449892Sdrh if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ 247913449892Sdrh return; 248013449892Sdrh } 248113449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 2482d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0); 248313449892Sdrh } 2484c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 2485d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0); 2486c99130fdSdrh if( pFunc->iDistinct>=0 ){ 2487c99130fdSdrh Expr *pE = pFunc->pExpr; 2488c99130fdSdrh if( pE->pList==0 || pE->pList->nExpr!=1 ){ 2489c99130fdSdrh sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " 2490c99130fdSdrh "by an expression"); 2491c99130fdSdrh pFunc->iDistinct = -1; 2492c99130fdSdrh }else{ 2493c99130fdSdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); 2494c99130fdSdrh sqlite3VdbeOp3(v, OP_OpenVirtual, pFunc->iDistinct, 0, 2495c99130fdSdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 2496c99130fdSdrh } 2497c99130fdSdrh } 249813449892Sdrh } 2499b3bce662Sdanielk1977 } 2500b3bce662Sdanielk1977 2501b3bce662Sdanielk1977 /* 250213449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 250313449892Sdrh ** in the AggInfo structure. 2504b3bce662Sdanielk1977 */ 250513449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 250613449892Sdrh Vdbe *v = pParse->pVdbe; 250713449892Sdrh int i; 250813449892Sdrh struct AggInfo_func *pF; 250913449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 2510a10a34b8Sdrh ExprList *pList = pF->pExpr->pList; 2511a10a34b8Sdrh sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 2512a10a34b8Sdrh (void*)pF->pFunc, P3_FUNCDEF); 2513b3bce662Sdanielk1977 } 251413449892Sdrh } 251513449892Sdrh 251613449892Sdrh /* 251713449892Sdrh ** Update the accumulator memory cells for an aggregate based on 251813449892Sdrh ** the current cursor position. 251913449892Sdrh */ 252013449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 252113449892Sdrh Vdbe *v = pParse->pVdbe; 252213449892Sdrh int i; 252313449892Sdrh struct AggInfo_func *pF; 252413449892Sdrh struct AggInfo_col *pC; 252513449892Sdrh 252613449892Sdrh pAggInfo->directMode = 1; 252713449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 252813449892Sdrh int nArg; 2529c99130fdSdrh int addrNext = 0; 253013449892Sdrh ExprList *pList = pF->pExpr->pList; 253113449892Sdrh if( pList ){ 253213449892Sdrh nArg = pList->nExpr; 253313449892Sdrh sqlite3ExprCodeExprList(pParse, pList); 253413449892Sdrh }else{ 253513449892Sdrh nArg = 0; 253613449892Sdrh } 2537c99130fdSdrh if( pF->iDistinct>=0 ){ 2538c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 2539c99130fdSdrh assert( nArg==1 ); 25409d4673a9Sdrh codeDistinct(v, pF->iDistinct, addrNext, 1, 2); 2541c99130fdSdrh } 254213449892Sdrh if( pF->pFunc->needCollSeq ){ 254313449892Sdrh CollSeq *pColl = 0; 254413449892Sdrh struct ExprList_item *pItem; 254513449892Sdrh int j; 254613449892Sdrh for(j=0, pItem=pList->a; !pColl && j<pList->nExpr; j++, pItem++){ 254713449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 254813449892Sdrh } 254913449892Sdrh if( !pColl ){ 255013449892Sdrh pColl = pParse->db->pDfltColl; 255113449892Sdrh } 255213449892Sdrh sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); 255313449892Sdrh } 255413449892Sdrh sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF); 2555c99130fdSdrh if( addrNext ){ 2556c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 2557c99130fdSdrh } 255813449892Sdrh } 255913449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 25605774b806Sdrh sqlite3ExprCode(pParse, pC->pExpr); 256113449892Sdrh sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1); 256213449892Sdrh } 256313449892Sdrh pAggInfo->directMode = 0; 256413449892Sdrh } 256513449892Sdrh 2566b3bce662Sdanielk1977 2567b3bce662Sdanielk1977 /* 25689bb61fe7Sdrh ** Generate code for the given SELECT statement. 25699bb61fe7Sdrh ** 2570fef5208cSdrh ** The results are distributed in various ways depending on the 2571fef5208cSdrh ** value of eDest and iParm. 2572fef5208cSdrh ** 2573fef5208cSdrh ** eDest Value Result 2574fef5208cSdrh ** ------------ ------------------------------------------- 2575fef5208cSdrh ** SRT_Callback Invoke the callback for each row of the result. 2576fef5208cSdrh ** 2577fef5208cSdrh ** SRT_Mem Store first result in memory cell iParm 2578fef5208cSdrh ** 2579e014a838Sdanielk1977 ** SRT_Set Store results as keys of table iParm. 2580fef5208cSdrh ** 258182c3d636Sdrh ** SRT_Union Store results as a key in a temporary table iParm 258282c3d636Sdrh ** 25834b11c6d3Sjplyon ** SRT_Except Remove results from the temporary table iParm. 2584c4a3c779Sdrh ** 2585c4a3c779Sdrh ** SRT_Table Store results in temporary table iParm 25869bb61fe7Sdrh ** 2587e78e8284Sdrh ** The table above is incomplete. Additional eDist value have be added 2588e78e8284Sdrh ** since this comment was written. See the selectInnerLoop() function for 2589e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings. 2590e78e8284Sdrh ** 25919bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 25929bb61fe7Sdrh ** encountered, then an appropriate error message is left in 25939bb61fe7Sdrh ** pParse->zErrMsg. 25949bb61fe7Sdrh ** 25959bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 25969bb61fe7Sdrh ** calling function needs to do that. 25971b2e0329Sdrh ** 25981b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this 25991b2e0329Sdrh ** SELECT is a subquery. This routine may try to combine this SELECT 26001b2e0329Sdrh ** with its parent to form a single flat query. In so doing, it might 26011b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query. 26021b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it 26031b2e0329Sdrh ** can be changed. 2604e78e8284Sdrh ** 2605e78e8284Sdrh ** Example 1: The meaning of the pParent parameter. 2606e78e8284Sdrh ** 2607e78e8284Sdrh ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2608e78e8284Sdrh ** \ \_______ subquery _______/ / 2609e78e8284Sdrh ** \ / 2610e78e8284Sdrh ** \____________________ outer query ___________________/ 2611e78e8284Sdrh ** 2612e78e8284Sdrh ** This routine is called for the outer query first. For that call, 2613e78e8284Sdrh ** pParent will be NULL. During the processing of the outer query, this 2614e78e8284Sdrh ** routine is called recursively to handle the subquery. For the recursive 2615e78e8284Sdrh ** call, pParent will point to the outer query. Because the subquery is 2616e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will 2617e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.) 26189bb61fe7Sdrh */ 26194adee20fSdanielk1977 int sqlite3Select( 2620cce7d176Sdrh Parse *pParse, /* The parser context */ 26219bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 2622e78e8284Sdrh int eDest, /* How to dispose of the results */ 2623e78e8284Sdrh int iParm, /* A parameter used by the eDest disposal method */ 2624832508b7Sdrh Select *pParent, /* Another SELECT for which this is a sub-query */ 2625832508b7Sdrh int parentTab, /* Index in pParent->pSrc of this query */ 262684ac9d02Sdanielk1977 int *pParentAgg, /* True if pParent uses aggregate functions */ 2627b3bce662Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 2628cce7d176Sdrh ){ 262913449892Sdrh int i, j; /* Loop counters */ 263013449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 263113449892Sdrh Vdbe *v; /* The virtual machine under construction */ 2632b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 2633a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 2634ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 26359bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 26369bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 26372282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 26382282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 263919a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 264019a775c2Sdrh int distinct; /* Table to use for the distinct set */ 26411d83f052Sdrh int rc = 1; /* Value to return from this function */ 26429d2985c7Sdrh int addrSortIndex; /* Address of an OP_OpenVirtual instruction */ 264313449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 2644ec7429aeSdrh int iEnd; /* Address of the end of the query */ 26459bb61fe7Sdrh 2646261919ccSdanielk1977 if( sqlite3Tsd()->mallocFailed || pParse->nErr || p==0 ) return 1; 26474adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 264813449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 2649daffd0e5Sdrh 2650b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 265182c3d636Sdrh /* If there is are a sequence of queries, do the earlier ones first. 265282c3d636Sdrh */ 265382c3d636Sdrh if( p->pPrior ){ 26540342b1f5Sdrh if( p->pRightmost==0 ){ 26550342b1f5Sdrh Select *pLoop; 26560342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 26570342b1f5Sdrh pLoop->pRightmost = p; 26580342b1f5Sdrh } 26590342b1f5Sdrh } 266084ac9d02Sdanielk1977 return multiSelect(pParse, p, eDest, iParm, aff); 266182c3d636Sdrh } 2662b7f9164eSdrh #endif 266382c3d636Sdrh 2664b3bce662Sdanielk1977 pOrderBy = p->pOrderBy; 266513449892Sdrh if( IgnorableOrderby(eDest) ){ 2666b3bce662Sdanielk1977 p->pOrderBy = 0; 2667b3bce662Sdanielk1977 } 2668b3bce662Sdanielk1977 if( sqlite3SelectResolve(pParse, p, 0) ){ 2669b3bce662Sdanielk1977 goto select_end; 2670b3bce662Sdanielk1977 } 2671b3bce662Sdanielk1977 p->pOrderBy = pOrderBy; 2672b3bce662Sdanielk1977 267382c3d636Sdrh /* Make local copies of the parameters for this query. 267482c3d636Sdrh */ 26759bb61fe7Sdrh pTabList = p->pSrc; 26769bb61fe7Sdrh pWhere = p->pWhere; 26772282792aSdrh pGroupBy = p->pGroupBy; 26782282792aSdrh pHaving = p->pHaving; 2679b3bce662Sdanielk1977 isAgg = p->isAgg; 268019a775c2Sdrh isDistinct = p->isDistinct; 2681b3bce662Sdanielk1977 pEList = p->pEList; 2682b3bce662Sdanielk1977 if( pEList==0 ) goto select_end; 26839bb61fe7Sdrh 26849bb61fe7Sdrh /* 26859bb61fe7Sdrh ** Do not even attempt to generate any code if we have already seen 26869bb61fe7Sdrh ** errors before this routine starts. 26879bb61fe7Sdrh */ 26881d83f052Sdrh if( pParse->nErr>0 ) goto select_end; 2689cce7d176Sdrh 26902282792aSdrh /* If writing to memory or generating a set 26912282792aSdrh ** only a single column may be output. 269219a775c2Sdrh */ 269393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 2694fef5208cSdrh if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){ 26954adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "only a single result allowed for " 2696da93d238Sdrh "a SELECT that is part of an expression"); 26971d83f052Sdrh goto select_end; 269819a775c2Sdrh } 269993758c8dSdanielk1977 #endif 270019a775c2Sdrh 2701c926afbcSdrh /* ORDER BY is ignored for some destinations. 27022282792aSdrh */ 270313449892Sdrh if( IgnorableOrderby(eDest) ){ 2704acd4c695Sdrh pOrderBy = 0; 27052282792aSdrh } 27062282792aSdrh 2707d820cb1bSdrh /* Begin generating code. 2708d820cb1bSdrh */ 27094adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2710d820cb1bSdrh if( v==0 ) goto select_end; 2711d820cb1bSdrh 2712e78e8284Sdrh /* Identify column names if we will be using them in a callback. This 2713e78e8284Sdrh ** step is skipped if the output is going to some other destination. 27140bb28106Sdrh */ 27150bb28106Sdrh if( eDest==SRT_Callback ){ 27166a3ea0e6Sdrh generateColumnNames(pParse, pTabList, pEList); 27170bb28106Sdrh } 27180bb28106Sdrh 2719d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 2720d820cb1bSdrh */ 272151522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 2722ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 2723742f947bSdanielk1977 const char *zSavedAuthContext = 0; 2724c31c2eb8Sdrh int needRestoreContext; 272513449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 2726c31c2eb8Sdrh 272713449892Sdrh if( pItem->pSelect==0 ) continue; 272813449892Sdrh if( pItem->zName!=0 ){ 27295cf590c1Sdrh zSavedAuthContext = pParse->zAuthContext; 273013449892Sdrh pParse->zAuthContext = pItem->zName; 2731c31c2eb8Sdrh needRestoreContext = 1; 2732c31c2eb8Sdrh }else{ 2733c31c2eb8Sdrh needRestoreContext = 0; 27345cf590c1Sdrh } 27359d2985c7Sdrh sqlite3Select(pParse, pItem->pSelect, SRT_VirtualTab, 273613449892Sdrh pItem->iCursor, p, i, &isAgg, 0); 2737c31c2eb8Sdrh if( needRestoreContext ){ 27385cf590c1Sdrh pParse->zAuthContext = zSavedAuthContext; 27395cf590c1Sdrh } 2740832508b7Sdrh pTabList = p->pSrc; 2741832508b7Sdrh pWhere = p->pWhere; 274213449892Sdrh if( !IgnorableOrderby(eDest) ){ 2743832508b7Sdrh pOrderBy = p->pOrderBy; 2744acd4c695Sdrh } 2745832508b7Sdrh pGroupBy = p->pGroupBy; 2746832508b7Sdrh pHaving = p->pHaving; 2747832508b7Sdrh isDistinct = p->isDistinct; 27481b2e0329Sdrh } 274951522cd3Sdrh #endif 27501b2e0329Sdrh 27516e17529eSdrh /* Check for the special case of a min() or max() function by itself 27526e17529eSdrh ** in the result set. 27536e17529eSdrh */ 27546e17529eSdrh if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ 27556e17529eSdrh rc = 0; 27566e17529eSdrh goto select_end; 27576e17529eSdrh } 27586e17529eSdrh 27591b2e0329Sdrh /* Check to see if this is a subquery that can be "flattened" into its parent. 27601b2e0329Sdrh ** If flattening is a possiblity, do so and return immediately. 27611b2e0329Sdrh */ 2762b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 27631b2e0329Sdrh if( pParent && pParentAgg && 27648c74a8caSdrh flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){ 27651b2e0329Sdrh if( isAgg ) *pParentAgg = 1; 2766b3bce662Sdanielk1977 goto select_end; 27671b2e0329Sdrh } 2768b7f9164eSdrh #endif 2769832508b7Sdrh 27707cedc8d4Sdanielk1977 /* If there is an ORDER BY clause, resolve any collation sequences 27719d2985c7Sdrh ** names that have been explicitly specified and create a sorting index. 27729d2985c7Sdrh ** 27739d2985c7Sdrh ** This sorting index might end up being unused if the data can be 27749d2985c7Sdrh ** extracted in pre-sorted order. If that is the case, then the 27759d2985c7Sdrh ** OP_OpenVirtual instruction will be changed to an OP_Noop once 27769d2985c7Sdrh ** we figure out that the sorting index is not needed. The addrSortIndex 27779d2985c7Sdrh ** variable is used to facilitate that change. 27787cedc8d4Sdanielk1977 */ 27797cedc8d4Sdanielk1977 if( pOrderBy ){ 27805d9a4af9Sdrh struct ExprList_item *pTerm; 27810342b1f5Sdrh KeyInfo *pKeyInfo; 27825d9a4af9Sdrh for(i=0, pTerm=pOrderBy->a; i<pOrderBy->nExpr; i++, pTerm++){ 27835d9a4af9Sdrh if( pTerm->zName ){ 27845d9a4af9Sdrh pTerm->pExpr->pColl = sqlite3LocateCollSeq(pParse, pTerm->zName, -1); 27857cedc8d4Sdanielk1977 } 27867cedc8d4Sdanielk1977 } 27877cedc8d4Sdanielk1977 if( pParse->nErr ){ 27887cedc8d4Sdanielk1977 goto select_end; 27897cedc8d4Sdanielk1977 } 27900342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); 27919d2985c7Sdrh pOrderBy->iECursor = pParse->nTab++; 27929d2985c7Sdrh p->addrOpenVirt[2] = addrSortIndex = 27939d2985c7Sdrh sqlite3VdbeOp3(v, OP_OpenVirtual, pOrderBy->iECursor, pOrderBy->nExpr+2, 27940342b1f5Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 27959d2985c7Sdrh }else{ 27969d2985c7Sdrh addrSortIndex = -1; 27977cedc8d4Sdanielk1977 } 27987cedc8d4Sdanielk1977 27997b58daeaSdrh /* Set the limiter. 28007b58daeaSdrh */ 2801ec7429aeSdrh iEnd = sqlite3VdbeMakeLabel(v); 2802ec7429aeSdrh computeLimitRegisters(pParse, p, iEnd); 28037b58daeaSdrh 28042d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 28052d0794e3Sdrh */ 28069d2985c7Sdrh if( eDest==SRT_VirtualTab ){ 28070342b1f5Sdrh sqlite3VdbeAddOp(v, OP_OpenVirtual, iParm, pEList->nExpr); 28082d0794e3Sdrh } 28092d0794e3Sdrh 2810dece1a84Sdrh /* Open a virtual index to use for the distinct set. 2811cce7d176Sdrh */ 281219a775c2Sdrh if( isDistinct ){ 28130342b1f5Sdrh KeyInfo *pKeyInfo; 2814832508b7Sdrh distinct = pParse->nTab++; 28150342b1f5Sdrh pKeyInfo = keyInfoFromExprList(pParse, p->pEList); 28160342b1f5Sdrh sqlite3VdbeOp3(v, OP_OpenVirtual, distinct, 0, 28170342b1f5Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 2818832508b7Sdrh }else{ 2819832508b7Sdrh distinct = -1; 2820efb7251dSdrh } 2821832508b7Sdrh 282213449892Sdrh /* Aggregate and non-aggregate queries are handled differently */ 282313449892Sdrh if( !isAgg && pGroupBy==0 ){ 282413449892Sdrh /* This case is for non-aggregate queries 282513449892Sdrh ** Begin the database scan 2826832508b7Sdrh */ 282713449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy); 28281d83f052Sdrh if( pWInfo==0 ) goto select_end; 2829cce7d176Sdrh 28309d2985c7Sdrh /* If sorting index that was created by a prior OP_OpenVirtual 28319d2985c7Sdrh ** instruction ended up not being needed, then change the OP_OpenVirtual 28329d2985c7Sdrh ** into an OP_Noop. 28339d2985c7Sdrh */ 28349d2985c7Sdrh if( addrSortIndex>=0 && pOrderBy==0 ){ 28359d2985c7Sdrh uncreateSortingIndex(pParse, addrSortIndex); 28369d2985c7Sdrh p->addrOpenVirt[2] = -1; 28379d2985c7Sdrh } 28389d2985c7Sdrh 283913449892Sdrh /* Use the standard inner loop 2840cce7d176Sdrh */ 2841df199a25Sdrh if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 284284ac9d02Sdanielk1977 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ 28431d83f052Sdrh goto select_end; 2844cce7d176Sdrh } 28452282792aSdrh 2846cce7d176Sdrh /* End the database scan loop. 2847cce7d176Sdrh */ 28484adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 284913449892Sdrh }else{ 285013449892Sdrh /* This is the processing for aggregate queries */ 285113449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 285213449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 285313449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 285413449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 285513449892Sdrh ** one row of the input to the aggregator has been 285613449892Sdrh ** processed */ 285713449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 285813449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 2859cce7d176Sdrh 286013449892Sdrh 286113449892Sdrh /* The following variables hold addresses or labels for parts of the 286213449892Sdrh ** virtual machine program we are putting together */ 286313449892Sdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 286413449892Sdrh int addrSetAbort; /* Set the abort flag and return */ 286513449892Sdrh int addrInitializeLoop; /* Start of code that initializes the input loop */ 286613449892Sdrh int addrTopOfLoop; /* Top of the input loop */ 286713449892Sdrh int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ 286813449892Sdrh int addrProcessRow; /* Code to process a single input row */ 286913449892Sdrh int addrEnd; /* End of all processing */ 287013449892Sdrh int addrSortingIdx; /* The OP_OpenVirtual for the sorting index */ 2871e313382eSdrh int addrReset; /* Subroutine for resetting the accumulator */ 287213449892Sdrh 287313449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 287413449892Sdrh 287513449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 287613449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 287713449892Sdrh ** SELECT statement. 28782282792aSdrh */ 287913449892Sdrh memset(&sNC, 0, sizeof(sNC)); 288013449892Sdrh sNC.pParse = pParse; 288113449892Sdrh sNC.pSrcList = pTabList; 288213449892Sdrh sNC.pAggInfo = &sAggInfo; 288313449892Sdrh sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; 28849d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 288513449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){ 28861d83f052Sdrh goto select_end; 28872282792aSdrh } 288813449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){ 288913449892Sdrh goto select_end; 28902282792aSdrh } 289113449892Sdrh if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){ 289213449892Sdrh goto select_end; 289313449892Sdrh } 289413449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 289513449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 289613449892Sdrh if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){ 289713449892Sdrh goto select_end; 289813449892Sdrh } 289913449892Sdrh } 2900261919ccSdanielk1977 if( sqlite3Tsd()->mallocFailed ) goto select_end; 290113449892Sdrh 290213449892Sdrh /* Processing for aggregates with GROUP BY is very different and 290313449892Sdrh ** much more complex tha aggregates without a GROUP BY. 290413449892Sdrh */ 290513449892Sdrh if( pGroupBy ){ 290613449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 290713449892Sdrh 290813449892Sdrh /* Create labels that we will be needing 290913449892Sdrh */ 291013449892Sdrh 291113449892Sdrh addrInitializeLoop = sqlite3VdbeMakeLabel(v); 291213449892Sdrh addrGroupByChange = sqlite3VdbeMakeLabel(v); 291313449892Sdrh addrProcessRow = sqlite3VdbeMakeLabel(v); 291413449892Sdrh 291513449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 291613449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 291713449892Sdrh ** that we do not need it after all, the OpenVirtual instruction 291813449892Sdrh ** will be converted into a Noop. 291913449892Sdrh */ 292013449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 292113449892Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); 292213449892Sdrh addrSortingIdx = 292313449892Sdrh sqlite3VdbeOp3(v, OP_OpenVirtual, sAggInfo.sortingIdx, 292413449892Sdrh sAggInfo.nSortingColumn, 292513449892Sdrh (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 292613449892Sdrh 292713449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 292813449892Sdrh */ 292913449892Sdrh iUseFlag = pParse->nMem++; 293013449892Sdrh iAbortFlag = pParse->nMem++; 293113449892Sdrh iAMem = pParse->nMem; 293213449892Sdrh pParse->nMem += pGroupBy->nExpr; 293313449892Sdrh iBMem = pParse->nMem; 293413449892Sdrh pParse->nMem += pGroupBy->nExpr; 2935d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag); 2936de29e3e9Sdrh VdbeComment((v, "# clear abort flag")); 2937d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag); 2938de29e3e9Sdrh VdbeComment((v, "# indicate accumulator empty")); 293913449892Sdrh sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop); 294013449892Sdrh 294113449892Sdrh /* Generate a subroutine that outputs a single row of the result 294213449892Sdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 294313449892Sdrh ** is less than or equal to zero, the subroutine is a no-op. If 294413449892Sdrh ** the processing calls for the query to abort, this subroutine 294513449892Sdrh ** increments the iAbortFlag memory location before returning in 294613449892Sdrh ** order to signal the caller to abort. 294713449892Sdrh */ 294813449892Sdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 2949de29e3e9Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag); 2950de29e3e9Sdrh VdbeComment((v, "# set abort flag")); 295113449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 295213449892Sdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 295313449892Sdrh sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2); 2954de29e3e9Sdrh VdbeComment((v, "# Groupby result generator entry point")); 295513449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 295613449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 295713449892Sdrh if( pHaving ){ 295813449892Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1); 295913449892Sdrh } 296013449892Sdrh rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, 296113449892Sdrh distinct, eDest, iParm, 296213449892Sdrh addrOutputRow+1, addrSetAbort, aff); 296313449892Sdrh if( rc ){ 296413449892Sdrh goto select_end; 296513449892Sdrh } 296613449892Sdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 2967de29e3e9Sdrh VdbeComment((v, "# end groupby result generator")); 296813449892Sdrh 2969e313382eSdrh /* Generate a subroutine that will reset the group-by accumulator 2970e313382eSdrh */ 2971e313382eSdrh addrReset = sqlite3VdbeCurrentAddr(v); 2972e313382eSdrh resetAccumulator(pParse, &sAggInfo); 2973e313382eSdrh sqlite3VdbeAddOp(v, OP_Return, 0, 0); 2974e313382eSdrh 297513449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 297613449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 297713449892Sdrh ** it might be a single loop that uses an index to extract information 297813449892Sdrh ** in the right order to begin with. 297913449892Sdrh */ 298013449892Sdrh sqlite3VdbeResolveLabel(v, addrInitializeLoop); 2981e313382eSdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); 298213449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy); 29835360ad34Sdrh if( pWInfo==0 ) goto select_end; 298413449892Sdrh if( pGroupBy==0 ){ 298513449892Sdrh /* The optimizer is able to deliver rows in group by order so 298613449892Sdrh ** we do not have to sort. The OP_OpenVirtual table will be 298713449892Sdrh ** cancelled later because we still need to use the pKeyInfo 298813449892Sdrh */ 298913449892Sdrh pGroupBy = p->pGroupBy; 299013449892Sdrh groupBySort = 0; 299113449892Sdrh }else{ 299213449892Sdrh /* Rows are coming out in undetermined order. We have to push 299313449892Sdrh ** each row into a sorting index, terminate the first loop, 299413449892Sdrh ** then loop over the sorting index in order to get the output 299513449892Sdrh ** in sorted order 299613449892Sdrh */ 299713449892Sdrh groupBySort = 1; 299813449892Sdrh sqlite3ExprCodeExprList(pParse, pGroupBy); 299913449892Sdrh sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0); 300013449892Sdrh j = pGroupBy->nExpr+1; 300113449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 300213449892Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 300313449892Sdrh if( pCol->iSorterColumn<j ) continue; 300413449892Sdrh if( pCol->iColumn<0 ){ 300513449892Sdrh sqlite3VdbeAddOp(v, OP_Rowid, pCol->iTable, 0); 300613449892Sdrh }else{ 300713449892Sdrh sqlite3VdbeAddOp(v, OP_Column, pCol->iTable, pCol->iColumn); 300813449892Sdrh } 300913449892Sdrh j++; 301013449892Sdrh } 301113449892Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0); 301213449892Sdrh sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0); 301313449892Sdrh sqlite3WhereEnd(pWInfo); 301497571957Sdrh sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); 3015de29e3e9Sdrh VdbeComment((v, "# GROUP BY sort")); 301613449892Sdrh sAggInfo.useSortingIdx = 1; 301713449892Sdrh } 301813449892Sdrh 301913449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 302013449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 302113449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 302213449892Sdrh ** from the previous row currently stored in a0, a1, a2... 302313449892Sdrh */ 302413449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 302513449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 302613449892Sdrh if( groupBySort ){ 302713449892Sdrh sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j); 302813449892Sdrh }else{ 302913449892Sdrh sAggInfo.directMode = 1; 303013449892Sdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr); 303113449892Sdrh } 303213449892Sdrh sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1); 303313449892Sdrh } 303413449892Sdrh for(j=pGroupBy->nExpr-1; j>=0; j--){ 303513449892Sdrh if( j<pGroupBy->nExpr-1 ){ 303613449892Sdrh sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0); 303713449892Sdrh } 303813449892Sdrh sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0); 303913449892Sdrh if( j==0 ){ 3040e313382eSdrh sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow); 304113449892Sdrh }else{ 30424f686238Sdrh sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange); 304313449892Sdrh } 304413449892Sdrh sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ); 304513449892Sdrh } 304613449892Sdrh 304713449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 304813449892Sdrh ** Change in the GROUP BY are detected by the previous code 304913449892Sdrh ** block. If there were no changes, this block is skipped. 305013449892Sdrh ** 305113449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 305213449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 305313449892Sdrh ** and resets the aggregate accumulator registers in preparation 305413449892Sdrh ** for the next GROUP BY batch. 305513449892Sdrh */ 305613449892Sdrh sqlite3VdbeResolveLabel(v, addrGroupByChange); 305713449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 3058d654be80Sdrh sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j); 305913449892Sdrh } 306013449892Sdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); 3061de29e3e9Sdrh VdbeComment((v, "# output one row")); 306213449892Sdrh sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd); 3063de29e3e9Sdrh VdbeComment((v, "# check abort flag")); 3064e313382eSdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); 3065de29e3e9Sdrh VdbeComment((v, "# reset accumulator")); 306613449892Sdrh 306713449892Sdrh /* Update the aggregate accumulators based on the content of 306813449892Sdrh ** the current row 306913449892Sdrh */ 307013449892Sdrh sqlite3VdbeResolveLabel(v, addrProcessRow); 307113449892Sdrh updateAccumulator(pParse, &sAggInfo); 3072de29e3e9Sdrh sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag); 3073de29e3e9Sdrh VdbeComment((v, "# indicate data in accumulator")); 307413449892Sdrh 307513449892Sdrh /* End of the loop 307613449892Sdrh */ 307713449892Sdrh if( groupBySort ){ 307813449892Sdrh sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); 307913449892Sdrh }else{ 308013449892Sdrh sqlite3WhereEnd(pWInfo); 308113449892Sdrh uncreateSortingIndex(pParse, addrSortingIdx); 308213449892Sdrh } 308313449892Sdrh 308413449892Sdrh /* Output the final row of result 308513449892Sdrh */ 308613449892Sdrh sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); 3087de29e3e9Sdrh VdbeComment((v, "# output final row")); 308813449892Sdrh 308913449892Sdrh } /* endif pGroupBy */ 309013449892Sdrh else { 309113449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 309213449892Sdrh ** processing is much simpler since there is only a single row 309313449892Sdrh ** of output. 309413449892Sdrh */ 309513449892Sdrh resetAccumulator(pParse, &sAggInfo); 309613449892Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); 30975360ad34Sdrh if( pWInfo==0 ) goto select_end; 309813449892Sdrh updateAccumulator(pParse, &sAggInfo); 309913449892Sdrh sqlite3WhereEnd(pWInfo); 310013449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 310113449892Sdrh pOrderBy = 0; 31025774b806Sdrh if( pHaving ){ 31035774b806Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1); 31045774b806Sdrh } 310513449892Sdrh selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 310613449892Sdrh eDest, iParm, addrEnd, addrEnd, aff); 310713449892Sdrh } 310813449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 310913449892Sdrh 311013449892Sdrh } /* endif aggregate query */ 31112282792aSdrh 3112cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 3113cce7d176Sdrh ** and send them to the callback one by one. 3114cce7d176Sdrh */ 3115cce7d176Sdrh if( pOrderBy ){ 3116ffbc3088Sdrh generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm); 3117cce7d176Sdrh } 31186a535340Sdrh 311993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 3120f620b4e2Sdrh /* If this was a subquery, we have now converted the subquery into a 3121f620b4e2Sdrh ** temporary table. So delete the subquery structure from the parent 3122f620b4e2Sdrh ** to prevent this subquery from being evaluated again and to force the 3123f620b4e2Sdrh ** the use of the temporary table. 3124f620b4e2Sdrh */ 3125f620b4e2Sdrh if( pParent ){ 3126f620b4e2Sdrh assert( pParent->pSrc->nSrc>parentTab ); 3127f620b4e2Sdrh assert( pParent->pSrc->a[parentTab].pSelect==p ); 31284adee20fSdanielk1977 sqlite3SelectDelete(p); 3129f620b4e2Sdrh pParent->pSrc->a[parentTab].pSelect = 0; 3130f620b4e2Sdrh } 313193758c8dSdanielk1977 #endif 3132f620b4e2Sdrh 3133ec7429aeSdrh /* Jump here to skip this query 3134ec7429aeSdrh */ 3135ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 3136ec7429aeSdrh 31371d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 31381d83f052Sdrh ** to indicate no errors. 31391d83f052Sdrh */ 31401d83f052Sdrh rc = 0; 31411d83f052Sdrh 31421d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 31431d83f052Sdrh ** successful coding of the SELECT. 31441d83f052Sdrh */ 31451d83f052Sdrh select_end: 314613449892Sdrh sqliteFree(sAggInfo.aCol); 314713449892Sdrh sqliteFree(sAggInfo.aFunc); 31481d83f052Sdrh return rc; 3149cce7d176Sdrh } 3150