xref: /sqlite-3.40.0/src/select.c (revision 345fda3e)
1cce7d176Sdrh /*
2cce7d176Sdrh ** Copyright (c) 1999, 2000 D. Richard Hipp
3cce7d176Sdrh **
4cce7d176Sdrh ** This program is free software; you can redistribute it and/or
5cce7d176Sdrh ** modify it under the terms of the GNU General Public
6cce7d176Sdrh ** License as published by the Free Software Foundation; either
7cce7d176Sdrh ** version 2 of the License, or (at your option) any later version.
8cce7d176Sdrh **
9cce7d176Sdrh ** This program is distributed in the hope that it will be useful,
10cce7d176Sdrh ** but WITHOUT ANY WARRANTY; without even the implied warranty of
11cce7d176Sdrh ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12cce7d176Sdrh ** General Public License for more details.
13cce7d176Sdrh **
14cce7d176Sdrh ** You should have received a copy of the GNU General Public
15cce7d176Sdrh ** License along with this library; if not, write to the
16cce7d176Sdrh ** Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17cce7d176Sdrh ** Boston, MA  02111-1307, USA.
18cce7d176Sdrh **
19cce7d176Sdrh ** Author contact information:
20cce7d176Sdrh **   [email protected]
21cce7d176Sdrh **   http://www.hwaci.com/drh/
22cce7d176Sdrh **
23cce7d176Sdrh *************************************************************************
24cce7d176Sdrh ** This file contains C code routines that are called by the parser
25cce7d176Sdrh ** to handle SELECT statements.
26cce7d176Sdrh **
27*345fda3eSdrh ** $Id: select.c,v 1.28 2001/01/15 22:51:11 drh Exp $
28cce7d176Sdrh */
29cce7d176Sdrh #include "sqliteInt.h"
30cce7d176Sdrh 
31cce7d176Sdrh /*
329bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
339bb61fe7Sdrh ** structure.
34cce7d176Sdrh */
359bb61fe7Sdrh Select *sqliteSelectNew(
369bb61fe7Sdrh   ExprList *pEList,
379bb61fe7Sdrh   IdList *pSrc,
389bb61fe7Sdrh   Expr *pWhere,
399bb61fe7Sdrh   ExprList *pGroupBy,
409bb61fe7Sdrh   Expr *pHaving,
419bb61fe7Sdrh   ExprList *pOrderBy,
429bb61fe7Sdrh   int isDistinct
439bb61fe7Sdrh ){
449bb61fe7Sdrh   Select *pNew;
459bb61fe7Sdrh   pNew = sqliteMalloc( sizeof(*pNew) );
469bb61fe7Sdrh   if( pNew==0 ) return 0;
479bb61fe7Sdrh   pNew->pEList = pEList;
489bb61fe7Sdrh   pNew->pSrc = pSrc;
499bb61fe7Sdrh   pNew->pWhere = pWhere;
509bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
519bb61fe7Sdrh   pNew->pHaving = pHaving;
529bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
539bb61fe7Sdrh   pNew->isDistinct = isDistinct;
5482c3d636Sdrh   pNew->op = TK_SELECT;
559bb61fe7Sdrh   return pNew;
569bb61fe7Sdrh }
579bb61fe7Sdrh 
589bb61fe7Sdrh /*
599bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
609bb61fe7Sdrh */
619bb61fe7Sdrh void sqliteSelectDelete(Select *p){
6282c3d636Sdrh   if( p==0 ) return;
639bb61fe7Sdrh   sqliteExprListDelete(p->pEList);
649bb61fe7Sdrh   sqliteIdListDelete(p->pSrc);
659bb61fe7Sdrh   sqliteExprDelete(p->pWhere);
669bb61fe7Sdrh   sqliteExprListDelete(p->pGroupBy);
679bb61fe7Sdrh   sqliteExprDelete(p->pHaving);
689bb61fe7Sdrh   sqliteExprListDelete(p->pOrderBy);
6982c3d636Sdrh   sqliteSelectDelete(p->pPrior);
709bb61fe7Sdrh   sqliteFree(p);
719bb61fe7Sdrh }
729bb61fe7Sdrh 
739bb61fe7Sdrh /*
742282792aSdrh ** Delete the aggregate information from the parse structure.
752282792aSdrh */
762282792aSdrh void sqliteParseInfoReset(Parse *pParse){
772282792aSdrh   sqliteFree(pParse->aAgg);
782282792aSdrh   pParse->aAgg = 0;
792282792aSdrh   pParse->nAgg = 0;
802282792aSdrh   pParse->iAggCount = -1;
812282792aSdrh   pParse->useAgg = 0;
822282792aSdrh }
832282792aSdrh 
842282792aSdrh /*
852282792aSdrh ** This routine generates the code for the inside of the inner loop
862282792aSdrh ** of a SELECT.
8782c3d636Sdrh **
8882c3d636Sdrh ** The pEList is used to determine the values for each column in the
89967e8b73Sdrh ** result row.  Except  if pEList==NULL, then we just read nColumn
9082c3d636Sdrh ** elements from the srcTab table.
912282792aSdrh */
922282792aSdrh static int selectInnerLoop(
932282792aSdrh   Parse *pParse,          /* The parser context */
942282792aSdrh   ExprList *pEList,       /* List of values being extracted */
9582c3d636Sdrh   int srcTab,             /* Pull data from this table */
96967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
972282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
982282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
992282792aSdrh   int eDest,              /* How to dispose of the results */
1002282792aSdrh   int iParm,              /* An argument to the disposal method */
1012282792aSdrh   int iContinue,          /* Jump here to continue with next row */
1022282792aSdrh   int iBreak              /* Jump here to break out of the inner loop */
1032282792aSdrh ){
1042282792aSdrh   Vdbe *v = pParse->pVdbe;
1052282792aSdrh   int i;
1062282792aSdrh 
107967e8b73Sdrh   /* Pull the requested columns.
1082282792aSdrh   */
10982c3d636Sdrh   if( pEList ){
1102282792aSdrh     for(i=0; i<pEList->nExpr; i++){
1112282792aSdrh       sqliteExprCode(pParse, pEList->a[i].pExpr);
1122282792aSdrh     }
113967e8b73Sdrh     nColumn = pEList->nExpr;
11482c3d636Sdrh   }else{
115967e8b73Sdrh     for(i=0; i<nColumn; i++){
11682c3d636Sdrh       sqliteVdbeAddOp(v, OP_Field, srcTab, i, 0, 0);
11782c3d636Sdrh     }
11882c3d636Sdrh   }
1192282792aSdrh 
1202282792aSdrh   /* If the current result is not distinct, skip the rest
1212282792aSdrh   ** of the processing for the current row.
1222282792aSdrh   */
1232282792aSdrh   if( distinct>=0 ){
1242282792aSdrh     int lbl = sqliteVdbeMakeLabel(v);
1252282792aSdrh     sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1, 0, 0);
1262282792aSdrh     sqliteVdbeAddOp(v, OP_Distinct, distinct, lbl, 0, 0);
1272282792aSdrh     sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0, 0, 0);
1282282792aSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iContinue, 0, 0);
1292282792aSdrh     sqliteVdbeAddOp(v, OP_String, 0, 0, "", lbl);
1302282792aSdrh     sqliteVdbeAddOp(v, OP_Put, distinct, 0, 0, 0);
1312282792aSdrh   }
13282c3d636Sdrh 
1332282792aSdrh   /* If there is an ORDER BY clause, then store the results
1342282792aSdrh   ** in a sorter.
1352282792aSdrh   */
1362282792aSdrh   if( pOrderBy ){
1372282792aSdrh     char *zSortOrder;
138967e8b73Sdrh     sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0, 0, 0);
1392282792aSdrh     zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
1402282792aSdrh     if( zSortOrder==0 ) return 1;
1412282792aSdrh     for(i=0; i<pOrderBy->nExpr; i++){
142d8bc7086Sdrh       zSortOrder[i] = pOrderBy->a[i].sortOrder ? '-' : '+';
1432282792aSdrh       sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
1442282792aSdrh     }
1452282792aSdrh     zSortOrder[pOrderBy->nExpr] = 0;
1462282792aSdrh     sqliteVdbeAddOp(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, 0);
1476e142f54Sdrh     sqliteFree(zSortOrder);
1482282792aSdrh     sqliteVdbeAddOp(v, OP_SortPut, 0, 0, 0, 0);
1492282792aSdrh   }else
1502282792aSdrh 
15182c3d636Sdrh   /* In this mode, write each query result to the key of the temporary
15282c3d636Sdrh   ** table iParm.
1532282792aSdrh   */
15482c3d636Sdrh   if( eDest==SRT_Union ){
155967e8b73Sdrh     sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0, 0, 0);
15682c3d636Sdrh     sqliteVdbeAddOp(v, OP_String, iParm, 0, "", 0);
15782c3d636Sdrh     sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0);
15882c3d636Sdrh   }else
15982c3d636Sdrh 
1605974a30fSdrh   /* Store the result as data using a unique key.
1615974a30fSdrh   */
1625974a30fSdrh   if( eDest==SRT_Table ){
163967e8b73Sdrh     sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0, 0, 0);
1645974a30fSdrh     sqliteVdbeAddOp(v, OP_New, iParm, 0, 0, 0);
1655974a30fSdrh     sqliteVdbeAddOp(v, OP_Pull, 1, 0, 0, 0);
1665974a30fSdrh     sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0);
1675974a30fSdrh   }else
1685974a30fSdrh 
16982c3d636Sdrh   /* Construct a record from the query result, but instead of
17082c3d636Sdrh   ** saving that record, use it as a key to delete elements from
17182c3d636Sdrh   ** the temporary table iParm.
17282c3d636Sdrh   */
17382c3d636Sdrh   if( eDest==SRT_Except ){
174967e8b73Sdrh     sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0, 0, 0);
1751ecec3c0Sdrh     sqliteVdbeAddOp(v, OP_Delete, iParm, 0, 0, 0);
1762282792aSdrh   }else
1772282792aSdrh 
1782282792aSdrh   /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1792282792aSdrh   ** then there should be a single item on the stack.  Write this
1802282792aSdrh   ** item into the set table with bogus data.
1812282792aSdrh   */
1822282792aSdrh   if( eDest==SRT_Set ){
183967e8b73Sdrh     assert( nColumn==1 );
1842282792aSdrh     sqliteVdbeAddOp(v, OP_String, 0, 0, "", 0);
1852282792aSdrh     sqliteVdbeAddOp(v, OP_Put, iParm, 0, 0, 0);
1862282792aSdrh   }else
1872282792aSdrh 
18882c3d636Sdrh 
1892282792aSdrh   /* If this is a scalar select that is part of an expression, then
1902282792aSdrh   ** store the results in the appropriate memory cell and break out
1912282792aSdrh   ** of the scan loop.
1922282792aSdrh   */
1932282792aSdrh   if( eDest==SRT_Mem ){
194967e8b73Sdrh     assert( nColumn==1 );
1952282792aSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 0, 0, 0);
1962282792aSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, iBreak, 0, 0);
1972282792aSdrh   }else
1982282792aSdrh 
1992282792aSdrh   /* If none of the above, send the data to the callback function.
2002282792aSdrh   */
2012282792aSdrh   {
202967e8b73Sdrh     sqliteVdbeAddOp(v, OP_Callback, nColumn, 0, 0, 0);
20382c3d636Sdrh   }
20482c3d636Sdrh   return 0;
20582c3d636Sdrh }
20682c3d636Sdrh 
20782c3d636Sdrh /*
208d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
209d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
210d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
211d8bc7086Sdrh ** routine generates the code needed to do that.
212d8bc7086Sdrh */
213967e8b73Sdrh static void generateSortTail(Vdbe *v, int nColumn){
214d8bc7086Sdrh   int end = sqliteVdbeMakeLabel(v);
215d8bc7086Sdrh   int addr;
216d8bc7086Sdrh   sqliteVdbeAddOp(v, OP_Sort, 0, 0, 0, 0);
217d8bc7086Sdrh   addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end, 0, 0);
218967e8b73Sdrh   sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0, 0, 0);
219d8bc7086Sdrh   sqliteVdbeAddOp(v, OP_Goto, 0, addr, 0, 0);
220d8bc7086Sdrh   sqliteVdbeAddOp(v, OP_SortClose, 0, 0, 0, end);
221d8bc7086Sdrh }
222d8bc7086Sdrh 
223d8bc7086Sdrh /*
22482c3d636Sdrh ** Generate code that will tell the VDBE how many columns there
22582c3d636Sdrh ** are in the result and the name for each column.  This information
22682c3d636Sdrh ** is used to provide "argc" and "azCol[]" values in the callback.
22782c3d636Sdrh */
228d8bc7086Sdrh static
229d8bc7086Sdrh void generateColumnNames(Parse *pParse, IdList *pTabList, ExprList *pEList){
230d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
23182c3d636Sdrh   int i;
232d8bc7086Sdrh   if( pParse->colNamesSet ) return;
233d8bc7086Sdrh   pParse->colNamesSet = 1;
23482c3d636Sdrh   sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0, 0, 0);
23582c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
23682c3d636Sdrh     Expr *p;
237e1b6a5b8Sdrh     int addr;
23882c3d636Sdrh     if( pEList->a[i].zName ){
23982c3d636Sdrh       char *zName = pEList->a[i].zName;
240d8bc7086Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
24182c3d636Sdrh       continue;
24282c3d636Sdrh     }
24382c3d636Sdrh     p = pEList->a[i].pExpr;
244e1b6a5b8Sdrh     if( p->span.z && p->span.z[0] ){
245e1b6a5b8Sdrh       addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0, 0, 0);
246e1b6a5b8Sdrh       sqliteVdbeChangeP3(v, addr, p->span.z, p->span.n);
247e1b6a5b8Sdrh       sqliteVdbeCompressSpace(v, addr);
248e1b6a5b8Sdrh     }else if( p->op!=TK_COLUMN || pTabList==0 ){
24982c3d636Sdrh       char zName[30];
2505974a30fSdrh       sprintf(zName, "column%d", i+1);
25182c3d636Sdrh       sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
25282c3d636Sdrh     }else{
25382c3d636Sdrh       if( pTabList->nId>1 ){
25482c3d636Sdrh         char *zName = 0;
25582c3d636Sdrh         Table *pTab = pTabList->a[p->iTable].pTab;
25682c3d636Sdrh         char *zTab;
25782c3d636Sdrh 
25882c3d636Sdrh         zTab = pTabList->a[p->iTable].zAlias;
25982c3d636Sdrh         if( zTab==0 ) zTab = pTab->zName;
260967e8b73Sdrh         sqliteSetString(&zName, zTab, ".", pTab->aCol[p->iColumn].zName, 0);
26182c3d636Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
26282c3d636Sdrh         sqliteFree(zName);
26382c3d636Sdrh       }else{
26482c3d636Sdrh         Table *pTab = pTabList->a[0].pTab;
265967e8b73Sdrh         char *zName = pTab->aCol[p->iColumn].zName;
26682c3d636Sdrh         sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
26782c3d636Sdrh       }
26882c3d636Sdrh     }
26982c3d636Sdrh   }
27082c3d636Sdrh }
27182c3d636Sdrh 
27282c3d636Sdrh /*
273d8bc7086Sdrh ** Name of the connection operator, used for error messages.
274d8bc7086Sdrh */
275d8bc7086Sdrh static const char *selectOpName(int id){
276d8bc7086Sdrh   char *z;
277d8bc7086Sdrh   switch( id ){
278d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
279d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
280d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
281d8bc7086Sdrh     default:           z = "UNION";       break;
282d8bc7086Sdrh   }
283d8bc7086Sdrh   return z;
284d8bc7086Sdrh }
285d8bc7086Sdrh 
286d8bc7086Sdrh /*
287d8bc7086Sdrh ** For the given SELECT statement, do two things.
288d8bc7086Sdrh **
289967e8b73Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the IdList that
290967e8b73Sdrh **         defines the set of tables that should be scanned.
291d8bc7086Sdrh **
292d8bc7086Sdrh **    (2)  If the columns to be extracted variable (pEList) is NULL
293d8bc7086Sdrh **         (meaning that a "*" was used in the SQL statement) then
294d8bc7086Sdrh **         create a fake pEList containing the names of all columns
295d8bc7086Sdrh **         of all tables.
296d8bc7086Sdrh **
297d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
298d8bc7086Sdrh ** in pParse and return non-zero.
299d8bc7086Sdrh */
300d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
301d8bc7086Sdrh   int i, j;
302d8bc7086Sdrh   IdList *pTabList = p->pSrc;
303d8bc7086Sdrh   ExprList *pEList = p->pEList;
304d8bc7086Sdrh 
305d8bc7086Sdrh   /* Look up every table in the table list.
306d8bc7086Sdrh   */
307d8bc7086Sdrh   for(i=0; i<pTabList->nId; i++){
308d8bc7086Sdrh     if( pTabList->a[i].pTab ){
309d8bc7086Sdrh       /* This routine has run before!  No need to continue */
310d8bc7086Sdrh       return 0;
311d8bc7086Sdrh     }
312d8bc7086Sdrh     pTabList->a[i].pTab = sqliteFindTable(pParse->db, pTabList->a[i].zName);
313d8bc7086Sdrh     if( pTabList->a[i].pTab==0 ){
314d8bc7086Sdrh       sqliteSetString(&pParse->zErrMsg, "no such table: ",
315d8bc7086Sdrh          pTabList->a[i].zName, 0);
316d8bc7086Sdrh       pParse->nErr++;
317d8bc7086Sdrh       return 1;
318d8bc7086Sdrh     }
319d8bc7086Sdrh   }
320d8bc7086Sdrh 
321d8bc7086Sdrh   /* If the list of columns to retrieve is "*" then replace it with
322d8bc7086Sdrh   ** a list of all columns from all tables.
323d8bc7086Sdrh   */
324d8bc7086Sdrh   if( pEList==0 ){
325d8bc7086Sdrh     for(i=0; i<pTabList->nId; i++){
326d8bc7086Sdrh       Table *pTab = pTabList->a[i].pTab;
327d8bc7086Sdrh       for(j=0; j<pTab->nCol; j++){
328d8bc7086Sdrh         Expr *pExpr = sqliteExpr(TK_DOT, 0, 0, 0);
329d8bc7086Sdrh         pExpr->pLeft = sqliteExpr(TK_ID, 0, 0, 0);
330d8bc7086Sdrh         pExpr->pLeft->token.z = pTab->zName;
331d8bc7086Sdrh         pExpr->pLeft->token.n = strlen(pTab->zName);
332d8bc7086Sdrh         pExpr->pRight = sqliteExpr(TK_ID, 0, 0, 0);
333d8bc7086Sdrh         pExpr->pRight->token.z = pTab->aCol[j].zName;
334d8bc7086Sdrh         pExpr->pRight->token.n = strlen(pTab->aCol[j].zName);
335e1b6a5b8Sdrh         pExpr->span.z = "";
336e1b6a5b8Sdrh         pExpr->span.n = 0;
337d8bc7086Sdrh         pEList = sqliteExprListAppend(pEList, pExpr, 0);
338d8bc7086Sdrh       }
339d8bc7086Sdrh     }
340d8bc7086Sdrh     p->pEList = pEList;
341d8bc7086Sdrh   }
342d8bc7086Sdrh   return 0;
343d8bc7086Sdrh }
344d8bc7086Sdrh 
345d8bc7086Sdrh /*
346d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
347d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
348967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
349d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
350d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
351d8bc7086Sdrh **
352d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
353d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
354d8bc7086Sdrh **
355d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
356d8bc7086Sdrh ** of errors is returned.
357d8bc7086Sdrh */
358d8bc7086Sdrh static int matchOrderbyToColumn(
359d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
360d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
361d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
362d8bc7086Sdrh   int iTable,             /* Insert this this value in iTable */
363d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
364d8bc7086Sdrh ){
365d8bc7086Sdrh   int nErr = 0;
366d8bc7086Sdrh   int i, j;
367d8bc7086Sdrh   ExprList *pEList;
368d8bc7086Sdrh 
369d8bc7086Sdrh   assert( pSelect && pOrderBy );
370d8bc7086Sdrh   if( mustComplete ){
371d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
372d8bc7086Sdrh   }
373d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
374d8bc7086Sdrh     return 1;
375d8bc7086Sdrh   }
376d8bc7086Sdrh   if( pSelect->pPrior ){
37792cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
37892cd52f5Sdrh       return 1;
37992cd52f5Sdrh     }
380d8bc7086Sdrh   }
381d8bc7086Sdrh   pEList = pSelect->pEList;
382d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
383d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
38492cd52f5Sdrh     int match = 0;
385d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
386d8bc7086Sdrh     for(j=0; j<pEList->nExpr; j++){
3874cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
3884cfa7934Sdrh         char *zName = pEList->a[j].zName;
3896e142f54Sdrh         char *zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
390d8bc7086Sdrh         sqliteDequote(zLabel);
391d8bc7086Sdrh         if( sqliteStrICmp(zName, zLabel)==0 ){
392d8bc7086Sdrh           match = 1;
393d8bc7086Sdrh         }
3946e142f54Sdrh         sqliteFree(zLabel);
395d8bc7086Sdrh       }
3964cfa7934Sdrh       if( match==0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
397d8bc7086Sdrh         match = 1;
398d8bc7086Sdrh       }
399d8bc7086Sdrh       if( match ){
400967e8b73Sdrh         pE->op = TK_COLUMN;
401967e8b73Sdrh         pE->iColumn = j;
402d8bc7086Sdrh         pE->iTable = iTable;
403d8bc7086Sdrh         pOrderBy->a[i].done = 1;
404d8bc7086Sdrh         break;
405d8bc7086Sdrh       }
406d8bc7086Sdrh     }
40792cd52f5Sdrh     if( !match && mustComplete ){
408d8bc7086Sdrh       char zBuf[30];
409d8bc7086Sdrh       sprintf(zBuf,"%d",i+1);
410d8bc7086Sdrh       sqliteSetString(&pParse->zErrMsg, "ORDER BY term number ", zBuf,
411d8bc7086Sdrh         " does not match any result column", 0);
412d8bc7086Sdrh       pParse->nErr++;
413d8bc7086Sdrh       nErr++;
414d8bc7086Sdrh       break;
415d8bc7086Sdrh     }
416d8bc7086Sdrh   }
417d8bc7086Sdrh   return nErr;
418d8bc7086Sdrh }
419d8bc7086Sdrh 
420d8bc7086Sdrh /*
421d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
422d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
423d8bc7086Sdrh */
424d8bc7086Sdrh Vdbe *sqliteGetVdbe(Parse *pParse){
425d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
426d8bc7086Sdrh   if( v==0 ){
4274c504391Sdrh     v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
428d8bc7086Sdrh   }
429d8bc7086Sdrh   if( v==0 ){
430d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
431d8bc7086Sdrh     pParse->nErr++;
432d8bc7086Sdrh   }
433d8bc7086Sdrh   return v;
434d8bc7086Sdrh }
435d8bc7086Sdrh 
436d8bc7086Sdrh 
437d8bc7086Sdrh /*
43882c3d636Sdrh ** This routine is called to process a query that is really the union
43982c3d636Sdrh ** or intersection of two or more separate queries.
44082c3d636Sdrh */
44182c3d636Sdrh static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
44210e5e3cfSdrh   int rc;             /* Success code from a subroutine */
44310e5e3cfSdrh   Select *pPrior;     /* Another SELECT immediately to our left */
44410e5e3cfSdrh   Vdbe *v;            /* Generate code to this VDBE */
44510e5e3cfSdrh   int base;           /* Baseline value for pParse->nTab */
44682c3d636Sdrh 
447d8bc7086Sdrh   /* Make sure there is no ORDER BY clause on prior SELECTs.  Only the
448d8bc7086Sdrh   ** last SELECT in the series may have an ORDER BY.
44982c3d636Sdrh   */
450d8bc7086Sdrh   assert( p->pPrior!=0 );
451d8bc7086Sdrh   pPrior = p->pPrior;
452d8bc7086Sdrh   if( pPrior->pOrderBy ){
453d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
454d8bc7086Sdrh       selectOpName(p->op), " not before", 0);
45582c3d636Sdrh     pParse->nErr++;
45682c3d636Sdrh     return 1;
45782c3d636Sdrh   }
45882c3d636Sdrh 
459d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
460d8bc7086Sdrh   */
461d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
462d8bc7086Sdrh   if( v==0 ) return 1;
463d8bc7086Sdrh 
464d8bc7086Sdrh   /* Process the UNION or INTERSECTION
465d8bc7086Sdrh   */
46610e5e3cfSdrh   base = pParse->nTab;
46782c3d636Sdrh   switch( p->op ){
468d8bc7086Sdrh     case TK_ALL:
46982c3d636Sdrh     case TK_EXCEPT:
47082c3d636Sdrh     case TK_UNION: {
471d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
472d8bc7086Sdrh       int op;          /* One of the SRT_ operations to apply to self */
473d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
47482c3d636Sdrh 
475d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
476d8bc7086Sdrh       if( eDest==priorOp ){
477d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
478d8bc7086Sdrh         ** right.  This also means we are not the right-most select and so
479d8bc7086Sdrh         ** we cannot have an ORDER BY clause
480d8bc7086Sdrh         */
48182c3d636Sdrh         unionTab = iParm;
482d8bc7086Sdrh         assert( p->pOrderBy==0 );
48382c3d636Sdrh       }else{
484d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
485d8bc7086Sdrh         ** intermediate results.
486d8bc7086Sdrh         */
48782c3d636Sdrh         unionTab = pParse->nTab++;
488d8bc7086Sdrh         if( p->pOrderBy
489d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
490d8bc7086Sdrh           return 1;
491d8bc7086Sdrh         }
492d8bc7086Sdrh         if( p->op!=TK_ALL ){
493*345fda3eSdrh           sqliteVdbeAddOp(v, OP_OpenIdx, unionTab, 1, 0, 0);
49482c3d636Sdrh           sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1, 0, 0);
495*345fda3eSdrh         }else{
496*345fda3eSdrh           sqliteVdbeAddOp(v, OP_OpenTbl, unionTab, 1, 0, 0);
49782c3d636Sdrh         }
498d8bc7086Sdrh       }
499d8bc7086Sdrh 
500d8bc7086Sdrh       /* Code the SELECT statements to our left
501d8bc7086Sdrh       */
502d8bc7086Sdrh       rc = sqliteSelect(pParse, pPrior, priorOp, unionTab);
50382c3d636Sdrh       if( rc ) return rc;
504d8bc7086Sdrh 
505d8bc7086Sdrh       /* Code the current SELECT statement
506d8bc7086Sdrh       */
507d8bc7086Sdrh       switch( p->op ){
508d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
509d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
510d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
511d8bc7086Sdrh       }
51282c3d636Sdrh       p->pPrior = 0;
51382c3d636Sdrh       rc = sqliteSelect(pParse, p, op, unionTab);
51482c3d636Sdrh       p->pPrior = pPrior;
51582c3d636Sdrh       if( rc ) return rc;
516d8bc7086Sdrh 
517d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
518d8bc7086Sdrh       ** it is that we currently need.
519d8bc7086Sdrh       */
520d8bc7086Sdrh       if( eDest!=priorOp ){
52182c3d636Sdrh         int iCont, iBreak;
52282c3d636Sdrh         assert( p->pEList );
523d8bc7086Sdrh         generateColumnNames(pParse, 0, p->pEList);
52492dba24bSdrh         if( p->pOrderBy ){
52592dba24bSdrh           sqliteVdbeAddOp(v, OP_SortOpen, 0, 0, 0, 0);
52692dba24bSdrh         }
52782c3d636Sdrh         iBreak = sqliteVdbeMakeLabel(v);
52882c3d636Sdrh         iCont = sqliteVdbeAddOp(v, OP_Next, unionTab, iBreak, 0, 0);
52982c3d636Sdrh         rc = selectInnerLoop(pParse, 0, unionTab, p->pEList->nExpr,
530d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
53182c3d636Sdrh                              iCont, iBreak);
53282c3d636Sdrh         if( rc ) return 1;
53382c3d636Sdrh         sqliteVdbeAddOp(v, OP_Goto, 0, iCont, 0, 0);
53482c3d636Sdrh         sqliteVdbeAddOp(v, OP_Close, unionTab, 0, 0, iBreak);
535d8bc7086Sdrh         if( p->pOrderBy ){
536d8bc7086Sdrh           generateSortTail(v, p->pEList->nExpr);
537d8bc7086Sdrh         }
53882c3d636Sdrh       }
53982c3d636Sdrh       break;
54082c3d636Sdrh     }
54182c3d636Sdrh     case TK_INTERSECT: {
54282c3d636Sdrh       int tab1, tab2;
54382c3d636Sdrh       int iCont, iBreak;
54482c3d636Sdrh 
545d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
5466206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
547d8bc7086Sdrh       ** by allocating the tables we will need.
548d8bc7086Sdrh       */
54982c3d636Sdrh       tab1 = pParse->nTab++;
55082c3d636Sdrh       tab2 = pParse->nTab++;
551d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
552d8bc7086Sdrh         return 1;
553d8bc7086Sdrh       }
554*345fda3eSdrh       sqliteVdbeAddOp(v, OP_OpenIdx, tab1, 1, 0, 0);
55582c3d636Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1, 0, 0);
556d8bc7086Sdrh 
557d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
558d8bc7086Sdrh       */
55982c3d636Sdrh       rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1);
56082c3d636Sdrh       if( rc ) return rc;
561d8bc7086Sdrh 
562d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
563d8bc7086Sdrh       */
564*345fda3eSdrh       sqliteVdbeAddOp(v, OP_OpenIdx, tab2, 1, 0, 0);
56582c3d636Sdrh       sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1, 0, 0);
56682c3d636Sdrh       p->pPrior = 0;
56782c3d636Sdrh       rc = sqliteSelect(pParse, p, SRT_Union, tab2);
56882c3d636Sdrh       p->pPrior = pPrior;
56982c3d636Sdrh       if( rc ) return rc;
570d8bc7086Sdrh 
571d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
572d8bc7086Sdrh       ** tables.
573d8bc7086Sdrh       */
57482c3d636Sdrh       assert( p->pEList );
575d8bc7086Sdrh       generateColumnNames(pParse, 0, p->pEList);
57692dba24bSdrh       if( p->pOrderBy ){
57792dba24bSdrh         sqliteVdbeAddOp(v, OP_SortOpen, 0, 0, 0, 0);
57892dba24bSdrh       }
57982c3d636Sdrh       iBreak = sqliteVdbeMakeLabel(v);
58082c3d636Sdrh       iCont = sqliteVdbeAddOp(v, OP_Next, tab1, iBreak, 0, 0);
58182c3d636Sdrh       sqliteVdbeAddOp(v, OP_Key, tab1, 0, 0, 0);
58282c3d636Sdrh       sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont, 0, 0);
58382c3d636Sdrh       rc = selectInnerLoop(pParse, 0, tab1, p->pEList->nExpr,
584d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
58582c3d636Sdrh                              iCont, iBreak);
58682c3d636Sdrh       if( rc ) return 1;
58782c3d636Sdrh       sqliteVdbeAddOp(v, OP_Goto, 0, iCont, 0, 0);
58882c3d636Sdrh       sqliteVdbeAddOp(v, OP_Close, tab2, 0, 0, iBreak);
58982c3d636Sdrh       sqliteVdbeAddOp(v, OP_Close, tab1, 0, 0, 0);
590d8bc7086Sdrh       if( p->pOrderBy ){
591d8bc7086Sdrh         generateSortTail(v, p->pEList->nExpr);
592d8bc7086Sdrh       }
59382c3d636Sdrh       break;
59482c3d636Sdrh     }
59582c3d636Sdrh   }
59682c3d636Sdrh   assert( p->pEList && pPrior->pEList );
59782c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
598d8bc7086Sdrh     sqliteSetString(&pParse->zErrMsg, "SELECTs to the left and right of ",
599d8bc7086Sdrh       selectOpName(p->op), " do not have the same number of result columns", 0);
60082c3d636Sdrh     pParse->nErr++;
60182c3d636Sdrh     return 1;
6022282792aSdrh   }
60310e5e3cfSdrh   pParse->nTab = base;
6042282792aSdrh   return 0;
6052282792aSdrh }
6062282792aSdrh 
6072282792aSdrh /*
6089bb61fe7Sdrh ** Generate code for the given SELECT statement.
6099bb61fe7Sdrh **
610fef5208cSdrh ** The results are distributed in various ways depending on the
611fef5208cSdrh ** value of eDest and iParm.
612fef5208cSdrh **
613fef5208cSdrh **     eDest Value       Result
614fef5208cSdrh **     ------------    -------------------------------------------
615fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
616fef5208cSdrh **
617fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
618fef5208cSdrh **
619fef5208cSdrh **     SRT_Set         Store results as keys of a table with cursor iParm
620fef5208cSdrh **
62182c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
62282c3d636Sdrh **
62382c3d636Sdrh **     SRT_Except      Remove results form the temporary talbe iParm.
6249bb61fe7Sdrh **
6259bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
6269bb61fe7Sdrh ** encountered, then an appropriate error message is left in
6279bb61fe7Sdrh ** pParse->zErrMsg.
6289bb61fe7Sdrh **
6299bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
6309bb61fe7Sdrh ** calling function needs to do that.
6319bb61fe7Sdrh */
6329bb61fe7Sdrh int sqliteSelect(
633cce7d176Sdrh   Parse *pParse,         /* The parser context */
6349bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
63582c3d636Sdrh   int eDest,             /* One of: SRT_Callback Mem Set Union Except */
636fef5208cSdrh   int iParm              /* Save result in this memory location, if >=0 */
637cce7d176Sdrh ){
638d8bc7086Sdrh   int i;
639cce7d176Sdrh   WhereInfo *pWInfo;
640cce7d176Sdrh   Vdbe *v;
641cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
642967e8b73Sdrh   ExprList *pEList;      /* List of columns to extract.  NULL means "*" */
6439bb61fe7Sdrh   IdList *pTabList;      /* List of tables to select from */
6449bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
6459bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
6462282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
6472282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
64819a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
64919a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
65010e5e3cfSdrh   int base;              /* First cursor available for use */
6519bb61fe7Sdrh 
65282c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
65382c3d636Sdrh   */
65482c3d636Sdrh   if( p->pPrior ){
65582c3d636Sdrh     return multiSelect(pParse, p, eDest, iParm);
65682c3d636Sdrh   }
65782c3d636Sdrh 
65882c3d636Sdrh   /* Make local copies of the parameters for this query.
65982c3d636Sdrh   */
6609bb61fe7Sdrh   pTabList = p->pSrc;
6619bb61fe7Sdrh   pWhere = p->pWhere;
6629bb61fe7Sdrh   pOrderBy = p->pOrderBy;
6632282792aSdrh   pGroupBy = p->pGroupBy;
6642282792aSdrh   pHaving = p->pHaving;
66519a775c2Sdrh   isDistinct = p->isDistinct;
6669bb61fe7Sdrh 
66710e5e3cfSdrh   /* Save the current value of pParse->nTab.  Restore this value before
66810e5e3cfSdrh   ** we exit.
66910e5e3cfSdrh   */
67010e5e3cfSdrh   base = pParse->nTab;
67110e5e3cfSdrh 
6729bb61fe7Sdrh   /*
6739bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
6749bb61fe7Sdrh   ** errors before this routine starts.
6759bb61fe7Sdrh   */
67610e5e3cfSdrh   if( pParse->nErr>0 ) return 1;
6772282792aSdrh   sqliteParseInfoReset(pParse);
678cce7d176Sdrh 
679d8bc7086Sdrh   /* Look up every table in the table list and create an appropriate
680d8bc7086Sdrh   ** columnlist in pEList if there isn't one already.  (The parser leaves
681967e8b73Sdrh   ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
682cce7d176Sdrh   */
683d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
6849bb61fe7Sdrh     return 1;
685cce7d176Sdrh   }
686d8bc7086Sdrh   pEList = p->pEList;
687cce7d176Sdrh 
68819a775c2Sdrh   /* Allocate a temporary table to use for the DISTINCT set, if
6892282792aSdrh   ** necessary.  This must be done early to allocate the cursor before
6902282792aSdrh   ** any calls to sqliteExprResolveIds().
69119a775c2Sdrh   */
69219a775c2Sdrh   if( isDistinct ){
69319a775c2Sdrh     distinct = pParse->nTab++;
6942282792aSdrh   }else{
6952282792aSdrh     distinct = -1;
69619a775c2Sdrh   }
69719a775c2Sdrh 
6982282792aSdrh   /* If writing to memory or generating a set
6992282792aSdrh   ** only a single column may be output.
70019a775c2Sdrh   */
701fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
70219a775c2Sdrh     sqliteSetString(&pParse->zErrMsg, "only a single result allowed for "
70319a775c2Sdrh        "a SELECT that is part of an expression", 0);
70419a775c2Sdrh     pParse->nErr++;
70519a775c2Sdrh     return 1;
70619a775c2Sdrh   }
70719a775c2Sdrh 
7082282792aSdrh   /* ORDER BY is ignored if we are not sending the result to a callback.
7092282792aSdrh   */
7102282792aSdrh   if( eDest!=SRT_Callback ){
7112282792aSdrh     pOrderBy = 0;
7122282792aSdrh   }
7132282792aSdrh 
7142282792aSdrh   /* Allocate cursors for "expr IN (SELECT ...)" constructs.
715cce7d176Sdrh   */
716cce7d176Sdrh   for(i=0; i<pEList->nExpr; i++){
7174794b980Sdrh     sqliteExprResolveInSelect(pParse, pEList->a[i].pExpr);
7184794b980Sdrh   }
7194794b980Sdrh   if( pWhere ) sqliteExprResolveInSelect(pParse, pWhere);
7204794b980Sdrh   if( pOrderBy ){
7214794b980Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
7224794b980Sdrh       sqliteExprResolveInSelect(pParse, pOrderBy->a[i].pExpr);
7234794b980Sdrh     }
7244794b980Sdrh   }
7252282792aSdrh   if( pGroupBy ){
7262282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
7272282792aSdrh       sqliteExprResolveInSelect(pParse, pGroupBy->a[i].pExpr);
7282282792aSdrh     }
7292282792aSdrh   }
7302282792aSdrh   if( pHaving ) sqliteExprResolveInSelect(pParse, pHaving);
7312282792aSdrh 
73210e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
73310e5e3cfSdrh   ** need to handle subquerys and temporary tables.  From here on we
73410e5e3cfSdrh   ** are committed to keeping the same value for pParse->nTab.
73510e5e3cfSdrh   **
736967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
7372282792aSdrh   */
7384794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
739cce7d176Sdrh     if( sqliteExprResolveIds(pParse, pTabList, pEList->a[i].pExpr) ){
7409bb61fe7Sdrh       return 1;
741cce7d176Sdrh     }
7422282792aSdrh     if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
7439bb61fe7Sdrh       return 1;
744cce7d176Sdrh     }
745cce7d176Sdrh   }
746cce7d176Sdrh   if( pWhere ){
747cce7d176Sdrh     if( sqliteExprResolveIds(pParse, pTabList, pWhere) ){
7489bb61fe7Sdrh       return 1;
749cce7d176Sdrh     }
750cce7d176Sdrh     if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
7519bb61fe7Sdrh       return 1;
752cce7d176Sdrh     }
753cce7d176Sdrh   }
754cce7d176Sdrh   if( pOrderBy ){
755cce7d176Sdrh     for(i=0; i<pOrderBy->nExpr; i++){
7562282792aSdrh       Expr *pE = pOrderBy->a[i].pExpr;
7572282792aSdrh       if( sqliteExprResolveIds(pParse, pTabList, pE) ){
7589bb61fe7Sdrh         return 1;
759cce7d176Sdrh       }
7602282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
7619bb61fe7Sdrh         return 1;
762cce7d176Sdrh       }
763cce7d176Sdrh     }
764cce7d176Sdrh   }
7652282792aSdrh   if( pGroupBy ){
7662282792aSdrh     for(i=0; i<pGroupBy->nExpr; i++){
7672282792aSdrh       Expr *pE = pGroupBy->a[i].pExpr;
7682282792aSdrh       if( sqliteExprResolveIds(pParse, pTabList, pE) ){
7692282792aSdrh         return 1;
7702282792aSdrh       }
7712282792aSdrh       if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
7722282792aSdrh         return 1;
7732282792aSdrh       }
7742282792aSdrh     }
7752282792aSdrh   }
7762282792aSdrh   if( pHaving ){
7772282792aSdrh     if( pGroupBy==0 ){
778da93281eSdrh       sqliteSetString(&pParse->zErrMsg, "a GROUP BY clause is required "
779da93281eSdrh          "before HAVING", 0);
7802282792aSdrh       pParse->nErr++;
7812282792aSdrh       return 1;
7822282792aSdrh     }
7832282792aSdrh     if( sqliteExprResolveIds(pParse, pTabList, pHaving) ){
7842282792aSdrh       return 1;
7852282792aSdrh     }
786da93281eSdrh     if( sqliteExprCheck(pParse, pHaving, isAgg, 0) ){
7872282792aSdrh       return 1;
7882282792aSdrh     }
789cce7d176Sdrh   }
790cce7d176Sdrh 
7912282792aSdrh   /* Do an analysis of aggregate expressions.
792efb7251dSdrh   */
7932282792aSdrh   if( isAgg ){
794aaf88729Sdrh     assert( pParse->nAgg==0 && pParse->iAggCount<0 );
7952282792aSdrh     for(i=0; i<pEList->nExpr; i++){
7962282792aSdrh       if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
7972282792aSdrh         return 1;
7982282792aSdrh       }
7992282792aSdrh     }
8002282792aSdrh     if( pGroupBy ){
8012282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
8022282792aSdrh         if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
8032282792aSdrh           return 1;
8042282792aSdrh         }
8052282792aSdrh       }
8062282792aSdrh     }
8072282792aSdrh     if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
8082282792aSdrh       return 1;
8092282792aSdrh     }
810191b690eSdrh     if( pOrderBy ){
811191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
812191b690eSdrh         if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
813191b690eSdrh           return 1;
814191b690eSdrh         }
815191b690eSdrh       }
816191b690eSdrh     }
817efb7251dSdrh   }
818efb7251dSdrh 
819cce7d176Sdrh   /* Begin generating code.
820cce7d176Sdrh   */
821cce7d176Sdrh   v = pParse->pVdbe;
822cce7d176Sdrh   if( v==0 ){
8234c504391Sdrh     v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
824cce7d176Sdrh   }
8259bb61fe7Sdrh   if( v==0 ){
8269bb61fe7Sdrh     sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
8279bb61fe7Sdrh     pParse->nErr++;
8289bb61fe7Sdrh     return 1;
8299bb61fe7Sdrh   }
830cce7d176Sdrh   if( pOrderBy ){
831cce7d176Sdrh     sqliteVdbeAddOp(v, OP_SortOpen, 0, 0, 0, 0);
832cce7d176Sdrh   }
833cce7d176Sdrh 
8342282792aSdrh   /* Identify column names if we will be using in the callback.  This
83519a775c2Sdrh   ** step is skipped if the output is going to a table or a memory cell.
836cce7d176Sdrh   */
837fef5208cSdrh   if( eDest==SRT_Callback ){
838d8bc7086Sdrh     generateColumnNames(pParse, pTabList, pEList);
839cce7d176Sdrh   }
840cce7d176Sdrh 
8412282792aSdrh   /* Reset the aggregator
842cce7d176Sdrh   */
843cce7d176Sdrh   if( isAgg ){
8442282792aSdrh     sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg, 0, 0);
845cce7d176Sdrh   }
846cce7d176Sdrh 
84719a775c2Sdrh   /* Initialize the memory cell to NULL
84819a775c2Sdrh   */
849fef5208cSdrh   if( eDest==SRT_Mem ){
85019a775c2Sdrh     sqliteVdbeAddOp(v, OP_Null, 0, 0, 0, 0);
851fef5208cSdrh     sqliteVdbeAddOp(v, OP_MemStore, iParm, 0, 0, 0);
85219a775c2Sdrh   }
85319a775c2Sdrh 
854cce7d176Sdrh   /* Begin the database scan
855cce7d176Sdrh   */
85619a775c2Sdrh   if( isDistinct ){
857*345fda3eSdrh     sqliteVdbeAddOp(v, OP_OpenIdx, distinct, 1, 0, 0);
858efb7251dSdrh   }
859cce7d176Sdrh   pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0);
8609bb61fe7Sdrh   if( pWInfo==0 ) return 1;
861cce7d176Sdrh 
8622282792aSdrh   /* Use the standard inner loop if we are not dealing with
8632282792aSdrh   ** aggregates
864cce7d176Sdrh   */
865da9d6c45Sdrh   if( !isAgg ){
86682c3d636Sdrh     if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
8672282792aSdrh                     pWInfo->iContinue, pWInfo->iBreak) ){
8682282792aSdrh        return 1;
869cce7d176Sdrh     }
870da9d6c45Sdrh   }
871cce7d176Sdrh 
8722282792aSdrh   /* If we are dealing with aggregates, then to the special aggregate
8732282792aSdrh   ** processing.
874efb7251dSdrh   */
8752282792aSdrh   else{
8762282792aSdrh     int doFocus;
8772282792aSdrh     if( pGroupBy ){
8782282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
8792282792aSdrh         sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
880efb7251dSdrh       }
8812282792aSdrh       sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0, 0, 0);
8822282792aSdrh       doFocus = 1;
883cce7d176Sdrh     }else{
8842282792aSdrh       doFocus = 0;
8852282792aSdrh       for(i=0; i<pParse->nAgg; i++){
8862282792aSdrh         if( !pParse->aAgg[i].isAgg ){
8872282792aSdrh           doFocus = 1;
8882282792aSdrh           break;
889cce7d176Sdrh         }
8902282792aSdrh       }
8912282792aSdrh       if( doFocus ){
8922282792aSdrh         sqliteVdbeAddOp(v, OP_String, 0, 0, "", 0);
8932282792aSdrh       }
8942282792aSdrh     }
8952282792aSdrh     if( doFocus ){
8962282792aSdrh       int lbl1 = sqliteVdbeMakeLabel(v);
8972282792aSdrh       sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1, 0, 0);
8982282792aSdrh       for(i=0; i<pParse->nAgg; i++){
8992282792aSdrh         if( pParse->aAgg[i].isAgg ) continue;
9002282792aSdrh         sqliteExprCode(pParse, pParse->aAgg[i].pExpr);
9012282792aSdrh         sqliteVdbeAddOp(v, OP_AggSet, 0, i, 0, 0);
9022282792aSdrh       }
9032282792aSdrh       sqliteVdbeResolveLabel(v, lbl1);
9042282792aSdrh     }
9052282792aSdrh     for(i=0; i<pParse->nAgg; i++){
9062282792aSdrh       Expr *pE;
9072282792aSdrh       int op;
9082282792aSdrh       if( !pParse->aAgg[i].isAgg ) continue;
9092282792aSdrh       pE = pParse->aAgg[i].pExpr;
9102282792aSdrh       if( pE==0 ){
9112282792aSdrh         sqliteVdbeAddOp(v, OP_AggIncr, 1, i, 0, 0);
9122282792aSdrh         continue;
9132282792aSdrh       }
9142282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
9152282792aSdrh       assert( pE->pList!=0 && pE->pList->nExpr==1 );
9162282792aSdrh       sqliteExprCode(pParse, pE->pList->a[0].pExpr);
9172282792aSdrh       sqliteVdbeAddOp(v, OP_AggGet, 0, i, 0, 0);
918967e8b73Sdrh       switch( pE->iColumn ){
9192282792aSdrh         case FN_Min:  op = OP_Min;   break;
9202282792aSdrh         case FN_Max:  op = OP_Max;   break;
9212282792aSdrh         case FN_Avg:  op = OP_Add;   break;
9222282792aSdrh         case FN_Sum:  op = OP_Add;   break;
9232282792aSdrh       }
9242282792aSdrh       sqliteVdbeAddOp(v, op, 0, 0, 0, 0);
9252282792aSdrh       sqliteVdbeAddOp(v, OP_AggSet, 0, i, 0, 0);
9262282792aSdrh     }
9272282792aSdrh   }
9282282792aSdrh 
929cce7d176Sdrh 
930cce7d176Sdrh   /* End the database scan loop.
931cce7d176Sdrh   */
932cce7d176Sdrh   sqliteWhereEnd(pWInfo);
933cce7d176Sdrh 
9342282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
9352282792aSdrh   ** over all of the aggregate values and process them.
9362282792aSdrh   */
9372282792aSdrh   if( isAgg ){
9382282792aSdrh     int endagg = sqliteVdbeMakeLabel(v);
9392282792aSdrh     int startagg;
9402282792aSdrh     startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg, 0, 0);
9412282792aSdrh     pParse->useAgg = 1;
9422282792aSdrh     if( pHaving ){
9432282792aSdrh       sqliteExprIfFalse(pParse, pHaving, startagg);
9442282792aSdrh     }
94582c3d636Sdrh     if( selectInnerLoop(pParse, pEList, 0, 0, pOrderBy, distinct, eDest, iParm,
9462282792aSdrh                     startagg, endagg) ){
9472282792aSdrh       return 1;
9482282792aSdrh     }
9492282792aSdrh     sqliteVdbeAddOp(v, OP_Goto, 0, startagg, 0, 0);
9502282792aSdrh     sqliteVdbeAddOp(v, OP_Noop, 0, 0, 0, endagg);
9512282792aSdrh     pParse->useAgg = 0;
9522282792aSdrh   }
9532282792aSdrh 
954cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
955cce7d176Sdrh   ** and send them to the callback one by one.
956cce7d176Sdrh   */
957cce7d176Sdrh   if( pOrderBy ){
958d8bc7086Sdrh     generateSortTail(v, pEList->nExpr);
959cce7d176Sdrh   }
96010e5e3cfSdrh   pParse->nTab = base;
9619bb61fe7Sdrh   return 0;
962cce7d176Sdrh }
963