xref: /sqlite-3.40.0/src/resolve.c (revision 5a05be1b)
17d10d5a6Sdrh /*
27d10d5a6Sdrh ** 2008 August 18
37d10d5a6Sdrh **
47d10d5a6Sdrh ** The author disclaims copyright to this source code.  In place of
57d10d5a6Sdrh ** a legal notice, here is a blessing:
67d10d5a6Sdrh **
77d10d5a6Sdrh **    May you do good and not evil.
87d10d5a6Sdrh **    May you find forgiveness for yourself and forgive others.
97d10d5a6Sdrh **    May you share freely, never taking more than you give.
107d10d5a6Sdrh **
117d10d5a6Sdrh *************************************************************************
127d10d5a6Sdrh **
137d10d5a6Sdrh ** This file contains routines used for walking the parser tree and
147d10d5a6Sdrh ** resolve all identifiers by associating them with a particular
157d10d5a6Sdrh ** table and column.
167d10d5a6Sdrh */
177d10d5a6Sdrh #include "sqliteInt.h"
187d10d5a6Sdrh #include <stdlib.h>
197d10d5a6Sdrh #include <string.h>
207d10d5a6Sdrh 
217d10d5a6Sdrh /*
22ed551b95Sdrh ** Walk the expression tree pExpr and increase the aggregate function
23ed551b95Sdrh ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
24ed551b95Sdrh ** This needs to occur when copying a TK_AGG_FUNCTION node from an
25ed551b95Sdrh ** outer query into an inner subquery.
26ed551b95Sdrh **
27ed551b95Sdrh ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
28ed551b95Sdrh ** is a helper function - a callback for the tree walker.
29ed551b95Sdrh */
30ed551b95Sdrh static int incrAggDepth(Walker *pWalker, Expr *pExpr){
31ed551b95Sdrh   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
32ed551b95Sdrh   return WRC_Continue;
33ed551b95Sdrh }
34ed551b95Sdrh static void incrAggFunctionDepth(Expr *pExpr, int N){
35ed551b95Sdrh   if( N>0 ){
36ed551b95Sdrh     Walker w;
37ed551b95Sdrh     memset(&w, 0, sizeof(w));
38ed551b95Sdrh     w.xExprCallback = incrAggDepth;
39ed551b95Sdrh     w.u.i = N;
40ed551b95Sdrh     sqlite3WalkExpr(&w, pExpr);
41ed551b95Sdrh   }
42ed551b95Sdrh }
43ed551b95Sdrh 
44ed551b95Sdrh /*
458b213899Sdrh ** Turn the pExpr expression into an alias for the iCol-th column of the
468b213899Sdrh ** result set in pEList.
478b213899Sdrh **
488b213899Sdrh ** If the result set column is a simple column reference, then this routine
498b213899Sdrh ** makes an exact copy.  But for any other kind of expression, this
508b213899Sdrh ** routine make a copy of the result set column as the argument to the
518b213899Sdrh ** TK_AS operator.  The TK_AS operator causes the expression to be
528b213899Sdrh ** evaluated just once and then reused for each alias.
538b213899Sdrh **
548b213899Sdrh ** The reason for suppressing the TK_AS term when the expression is a simple
558b213899Sdrh ** column reference is so that the column reference will be recognized as
568b213899Sdrh ** usable by indices within the WHERE clause processing logic.
578b213899Sdrh **
588b213899Sdrh ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
598b213899Sdrh ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
608b213899Sdrh **
618b213899Sdrh **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
628b213899Sdrh **
638b213899Sdrh ** Is equivalent to:
648b213899Sdrh **
658b213899Sdrh **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
668b213899Sdrh **
678b213899Sdrh ** The result of random()%5 in the GROUP BY clause is probably different
688b213899Sdrh ** from the result in the result-set.  We might fix this someday.  Or
698b213899Sdrh ** then again, we might not...
70ed551b95Sdrh **
71ed551b95Sdrh ** The nSubquery parameter specifies how many levels of subquery the
72ed551b95Sdrh ** alias is removed from the original expression.  The usually value is
73ed551b95Sdrh ** zero but it might be more if the alias is contained within a subquery
74ed551b95Sdrh ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
75ed551b95Sdrh ** structures must be increased by the nSubquery amount.
768b213899Sdrh */
778b213899Sdrh static void resolveAlias(
788b213899Sdrh   Parse *pParse,         /* Parsing context */
798b213899Sdrh   ExprList *pEList,      /* A result set */
808b213899Sdrh   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
818b213899Sdrh   Expr *pExpr,           /* Transform this into an alias to the result set */
82ed551b95Sdrh   const char *zType,     /* "GROUP" or "ORDER" or "" */
83ed551b95Sdrh   int nSubquery          /* Number of subqueries that the label is moving */
848b213899Sdrh ){
858b213899Sdrh   Expr *pOrig;           /* The iCol-th column of the result set */
868b213899Sdrh   Expr *pDup;            /* Copy of pOrig */
878b213899Sdrh   sqlite3 *db;           /* The database connection */
888b213899Sdrh 
898b213899Sdrh   assert( iCol>=0 && iCol<pEList->nExpr );
908b213899Sdrh   pOrig = pEList->a[iCol].pExpr;
918b213899Sdrh   assert( pOrig!=0 );
928b213899Sdrh   assert( pOrig->flags & EP_Resolved );
938b213899Sdrh   db = pParse->db;
94b7916a78Sdrh   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
956ab3a2ecSdanielk1977     pDup = sqlite3ExprDup(db, pOrig, 0);
96ed551b95Sdrh     incrAggFunctionDepth(pDup, nSubquery);
978b213899Sdrh     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
988b213899Sdrh     if( pDup==0 ) return;
998b213899Sdrh     if( pEList->a[iCol].iAlias==0 ){
100ea678832Sdrh       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
1018b213899Sdrh     }
1028b213899Sdrh     pDup->iTable = pEList->a[iCol].iAlias;
1030b0745aeSdrh   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
1040b0745aeSdrh     pDup = sqlite3ExprDup(db, pOrig, 0);
1052c220455Sdrh     if( pDup==0 ) return;
106b7916a78Sdrh   }else{
10733e619fcSdrh     char *zToken = pOrig->u.zToken;
10873c0fdc7Sdrh     assert( zToken!=0 );
10933e619fcSdrh     pOrig->u.zToken = 0;
110b7916a78Sdrh     pDup = sqlite3ExprDup(db, pOrig, 0);
11133e619fcSdrh     pOrig->u.zToken = zToken;
112b7916a78Sdrh     if( pDup==0 ) return;
113b7916a78Sdrh     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
11433e619fcSdrh     pDup->flags2 |= EP2_MallocedToken;
11533e619fcSdrh     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
116b7916a78Sdrh   }
1178b213899Sdrh   if( pExpr->flags & EP_ExpCollate ){
1188b213899Sdrh     pDup->pColl = pExpr->pColl;
1198b213899Sdrh     pDup->flags |= EP_ExpCollate;
1208b213899Sdrh   }
121f6963f99Sdan 
122f6963f99Sdan   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
123f6963f99Sdan   ** prevents ExprDelete() from deleting the Expr structure itself,
124f6963f99Sdan   ** allowing it to be repopulated by the memcpy() on the following line.
125f6963f99Sdan   */
126f6963f99Sdan   ExprSetProperty(pExpr, EP_Static);
127f6963f99Sdan   sqlite3ExprDelete(db, pExpr);
1288b213899Sdrh   memcpy(pExpr, pDup, sizeof(*pExpr));
1298b213899Sdrh   sqlite3DbFree(db, pDup);
1308b213899Sdrh }
1318b213899Sdrh 
132e802c5daSdrh 
133e802c5daSdrh /*
134e802c5daSdrh ** Return TRUE if the name zCol occurs anywhere in the USING clause.
135e802c5daSdrh **
136e802c5daSdrh ** Return FALSE if the USING clause is NULL or if it does not contain
137e802c5daSdrh ** zCol.
138e802c5daSdrh */
139e802c5daSdrh static int nameInUsingClause(IdList *pUsing, const char *zCol){
140e802c5daSdrh   if( pUsing ){
141e802c5daSdrh     int k;
142e802c5daSdrh     for(k=0; k<pUsing->nId; k++){
143e802c5daSdrh       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
144e802c5daSdrh     }
145e802c5daSdrh   }
146e802c5daSdrh   return 0;
147e802c5daSdrh }
148e802c5daSdrh 
149e802c5daSdrh 
1508b213899Sdrh /*
1517d10d5a6Sdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
1527d10d5a6Sdrh ** that name in the set of source tables in pSrcList and make the pExpr
1537d10d5a6Sdrh ** expression node refer back to that source column.  The following changes
1547d10d5a6Sdrh ** are made to pExpr:
1557d10d5a6Sdrh **
1567d10d5a6Sdrh **    pExpr->iDb           Set the index in db->aDb[] of the database X
1577d10d5a6Sdrh **                         (even if X is implied).
1587d10d5a6Sdrh **    pExpr->iTable        Set to the cursor number for the table obtained
1597d10d5a6Sdrh **                         from pSrcList.
1607d10d5a6Sdrh **    pExpr->pTab          Points to the Table structure of X.Y (even if
1617d10d5a6Sdrh **                         X and/or Y are implied.)
1627d10d5a6Sdrh **    pExpr->iColumn       Set to the column number within the table.
1637d10d5a6Sdrh **    pExpr->op            Set to TK_COLUMN.
1647d10d5a6Sdrh **    pExpr->pLeft         Any expression this points to is deleted
1657d10d5a6Sdrh **    pExpr->pRight        Any expression this points to is deleted.
1667d10d5a6Sdrh **
167b7916a78Sdrh ** The zDb variable is the name of the database (the "X").  This value may be
1687d10d5a6Sdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
169b7916a78Sdrh ** can be used.  The zTable variable is the name of the table (the "Y").  This
170b7916a78Sdrh ** value can be NULL if zDb is also NULL.  If zTable is NULL it
1717d10d5a6Sdrh ** means that the form of the name is Z and that columns from any table
1727d10d5a6Sdrh ** can be used.
1737d10d5a6Sdrh **
1747d10d5a6Sdrh ** If the name cannot be resolved unambiguously, leave an error message
175f7828b5cSdrh ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
1767d10d5a6Sdrh */
1777d10d5a6Sdrh static int lookupName(
1787d10d5a6Sdrh   Parse *pParse,       /* The parsing context */
179b7916a78Sdrh   const char *zDb,     /* Name of the database containing table, or NULL */
180b7916a78Sdrh   const char *zTab,    /* Name of table containing column, or NULL */
181b7916a78Sdrh   const char *zCol,    /* Name of the column. */
1827d10d5a6Sdrh   NameContext *pNC,    /* The name context used to resolve the name */
1837d10d5a6Sdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
1847d10d5a6Sdrh ){
1857d10d5a6Sdrh   int i, j;                         /* Loop counters */
1867d10d5a6Sdrh   int cnt = 0;                      /* Number of matching column names */
1877d10d5a6Sdrh   int cntTab = 0;                   /* Number of matching table names */
188ed551b95Sdrh   int nSubquery = 0;                /* How many levels of subquery */
1897d10d5a6Sdrh   sqlite3 *db = pParse->db;         /* The database connection */
1907d10d5a6Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
1917d10d5a6Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
1927d10d5a6Sdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
1937d10d5a6Sdrh   Schema *pSchema = 0;              /* Schema of the expression */
1942bd93516Sdan   int isTrigger = 0;
1957d10d5a6Sdrh 
196e34c647eSshane   assert( pNC );     /* the name context cannot be NULL. */
197b7916a78Sdrh   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
198*5a05be1bSdrh   assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
1997d10d5a6Sdrh 
2007d10d5a6Sdrh   /* Initialize the node to no-match */
2017d10d5a6Sdrh   pExpr->iTable = -1;
2027d10d5a6Sdrh   pExpr->pTab = 0;
20333e619fcSdrh   ExprSetIrreducible(pExpr);
2047d10d5a6Sdrh 
2057d10d5a6Sdrh   /* Start at the inner-most context and move outward until a match is found */
2067d10d5a6Sdrh   while( pNC && cnt==0 ){
2077d10d5a6Sdrh     ExprList *pEList;
2087d10d5a6Sdrh     SrcList *pSrcList = pNC->pSrcList;
2097d10d5a6Sdrh 
2107d10d5a6Sdrh     if( pSrcList ){
2117d10d5a6Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
2127d10d5a6Sdrh         Table *pTab;
2137d10d5a6Sdrh         int iDb;
2147d10d5a6Sdrh         Column *pCol;
2157d10d5a6Sdrh 
2167d10d5a6Sdrh         pTab = pItem->pTab;
217f436620eSdrh         assert( pTab!=0 && pTab->zName!=0 );
2187d10d5a6Sdrh         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2197d10d5a6Sdrh         assert( pTab->nCol>0 );
2207d10d5a6Sdrh         if( zTab ){
2217d10d5a6Sdrh           if( pItem->zAlias ){
2227d10d5a6Sdrh             char *zTabName = pItem->zAlias;
2237d10d5a6Sdrh             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
2247d10d5a6Sdrh           }else{
2257d10d5a6Sdrh             char *zTabName = pTab->zName;
22673c0fdc7Sdrh             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
22773c0fdc7Sdrh               continue;
22873c0fdc7Sdrh             }
2297d10d5a6Sdrh             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
2307d10d5a6Sdrh               continue;
2317d10d5a6Sdrh             }
2327d10d5a6Sdrh           }
2337d10d5a6Sdrh         }
2347d10d5a6Sdrh         if( 0==(cntTab++) ){
2357d10d5a6Sdrh           pExpr->iTable = pItem->iCursor;
2367d10d5a6Sdrh           pExpr->pTab = pTab;
2377d10d5a6Sdrh           pSchema = pTab->pSchema;
2387d10d5a6Sdrh           pMatch = pItem;
2397d10d5a6Sdrh         }
2407d10d5a6Sdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
2417d10d5a6Sdrh           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
242e802c5daSdrh             /* If there has been exactly one prior match and this match
243e802c5daSdrh             ** is for the right-hand table of a NATURAL JOIN or is in a
244e802c5daSdrh             ** USING clause, then skip this match.
245e802c5daSdrh             */
246e802c5daSdrh             if( cnt==1 ){
247e802c5daSdrh               if( pItem->jointype & JT_NATURAL ) continue;
248e802c5daSdrh               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
249e802c5daSdrh             }
2507d10d5a6Sdrh             cnt++;
2517d10d5a6Sdrh             pExpr->iTable = pItem->iCursor;
2527d10d5a6Sdrh             pExpr->pTab = pTab;
2537d10d5a6Sdrh             pMatch = pItem;
2547d10d5a6Sdrh             pSchema = pTab->pSchema;
2557d10d5a6Sdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
256cf697396Sshane             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
2577d10d5a6Sdrh             break;
2587d10d5a6Sdrh           }
2597d10d5a6Sdrh         }
2607d10d5a6Sdrh       }
2617d10d5a6Sdrh     }
2627d10d5a6Sdrh 
2637d10d5a6Sdrh #ifndef SQLITE_OMIT_TRIGGER
2647d10d5a6Sdrh     /* If we have not already resolved the name, then maybe
2657d10d5a6Sdrh     ** it is a new.* or old.* trigger argument reference
2667d10d5a6Sdrh     */
267165921a7Sdan     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
26865a7cd16Sdan       int op = pParse->eTriggerOp;
2697d10d5a6Sdrh       Table *pTab = 0;
27065a7cd16Sdan       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
27165a7cd16Sdan       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
272165921a7Sdan         pExpr->iTable = 1;
273165921a7Sdan         pTab = pParse->pTriggerTab;
27465a7cd16Sdan       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
275165921a7Sdan         pExpr->iTable = 0;
276165921a7Sdan         pTab = pParse->pTriggerTab;
2777d10d5a6Sdrh       }
2787d10d5a6Sdrh 
2797d10d5a6Sdrh       if( pTab ){
2807d10d5a6Sdrh         int iCol;
2817d10d5a6Sdrh         pSchema = pTab->pSchema;
2827d10d5a6Sdrh         cntTab++;
283165921a7Sdan         for(iCol=0; iCol<pTab->nCol; iCol++){
284165921a7Sdan           Column *pCol = &pTab->aCol[iCol];
2857d10d5a6Sdrh           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
2862bd93516Sdan             if( iCol==pTab->iPKey ){
2872bd93516Sdan               iCol = -1;
2882bd93516Sdan             }
2897d10d5a6Sdrh             break;
2907d10d5a6Sdrh           }
2917d10d5a6Sdrh         }
29225e978dfSdrh         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
293c79c761fSdrh           iCol = -1;        /* IMP: R-44911-55124 */
2947d10d5a6Sdrh         }
2952bd93516Sdan         if( iCol<pTab->nCol ){
2962bd93516Sdan           cnt++;
2972bd93516Sdan           if( iCol<0 ){
2982bd93516Sdan             pExpr->affinity = SQLITE_AFF_INTEGER;
2992832ad42Sdan           }else if( pExpr->iTable==0 ){
3002832ad42Sdan             testcase( iCol==31 );
3012832ad42Sdan             testcase( iCol==32 );
3022832ad42Sdan             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
303bb5f168fSdan           }else{
304bb5f168fSdan             testcase( iCol==31 );
305bb5f168fSdan             testcase( iCol==32 );
306bb5f168fSdan             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
3072bd93516Sdan           }
308cea72b2dSshane           pExpr->iColumn = (i16)iCol;
3092bd93516Sdan           pExpr->pTab = pTab;
3102bd93516Sdan           isTrigger = 1;
3112bd93516Sdan         }
3122bd93516Sdan       }
3137d10d5a6Sdrh     }
3147d10d5a6Sdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
3157d10d5a6Sdrh 
3167d10d5a6Sdrh     /*
3177d10d5a6Sdrh     ** Perhaps the name is a reference to the ROWID
3187d10d5a6Sdrh     */
3197d10d5a6Sdrh     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
3207d10d5a6Sdrh       cnt = 1;
321c79c761fSdrh       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
3227d10d5a6Sdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
3237d10d5a6Sdrh     }
3247d10d5a6Sdrh 
3257d10d5a6Sdrh     /*
3267d10d5a6Sdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
3277d10d5a6Sdrh     ** might refer to an result-set alias.  This happens, for example, when
3287d10d5a6Sdrh     ** we are resolving names in the WHERE clause of the following command:
3297d10d5a6Sdrh     **
3307d10d5a6Sdrh     **     SELECT a+b AS x FROM table WHERE x<10;
3317d10d5a6Sdrh     **
3327d10d5a6Sdrh     ** In cases like this, replace pExpr with a copy of the expression that
3337d10d5a6Sdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
3347d10d5a6Sdrh     ** Note that the expression in the result set should have already been
3357d10d5a6Sdrh     ** resolved by the time the WHERE clause is resolved.
3367d10d5a6Sdrh     */
3377d10d5a6Sdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
3387d10d5a6Sdrh       for(j=0; j<pEList->nExpr; j++){
3397d10d5a6Sdrh         char *zAs = pEList->a[j].zName;
3407d10d5a6Sdrh         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
3418b213899Sdrh           Expr *pOrig;
3427d10d5a6Sdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
3436ab3a2ecSdanielk1977           assert( pExpr->x.pList==0 );
3446ab3a2ecSdanielk1977           assert( pExpr->x.pSelect==0 );
3457d10d5a6Sdrh           pOrig = pEList->a[j].pExpr;
346a51009b2Sdrh           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
3477d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
348f7828b5cSdrh             return WRC_Abort;
3497d10d5a6Sdrh           }
350ed551b95Sdrh           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
3517d10d5a6Sdrh           cnt = 1;
3527d10d5a6Sdrh           pMatch = 0;
3537d10d5a6Sdrh           assert( zTab==0 && zDb==0 );
354b7916a78Sdrh           goto lookupname_end;
3557d10d5a6Sdrh         }
3567d10d5a6Sdrh       }
3577d10d5a6Sdrh     }
3587d10d5a6Sdrh 
3597d10d5a6Sdrh     /* Advance to the next name context.  The loop will exit when either
3607d10d5a6Sdrh     ** we have a match (cnt>0) or when we run out of name contexts.
3617d10d5a6Sdrh     */
3627d10d5a6Sdrh     if( cnt==0 ){
3637d10d5a6Sdrh       pNC = pNC->pNext;
364ed551b95Sdrh       nSubquery++;
3657d10d5a6Sdrh     }
3667d10d5a6Sdrh   }
3677d10d5a6Sdrh 
3687d10d5a6Sdrh   /*
3697d10d5a6Sdrh   ** If X and Y are NULL (in other words if only the column name Z is
3707d10d5a6Sdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
3717d10d5a6Sdrh   ** Z is a string literal if it doesn't match any column names.  In that
3727d10d5a6Sdrh   ** case, we need to return right away and not make any changes to
3737d10d5a6Sdrh   ** pExpr.
3747d10d5a6Sdrh   **
3757d10d5a6Sdrh   ** Because no reference was made to outer contexts, the pNC->nRef
3767d10d5a6Sdrh   ** fields are not changed in any context.
3777d10d5a6Sdrh   */
37824fb627aSdrh   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
3797d10d5a6Sdrh     pExpr->op = TK_STRING;
3801885d1c2Sdrh     pExpr->pTab = 0;
381f7828b5cSdrh     return WRC_Prune;
3827d10d5a6Sdrh   }
3837d10d5a6Sdrh 
3847d10d5a6Sdrh   /*
3857d10d5a6Sdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
3867d10d5a6Sdrh   ** more matches.  Either way, we have an error.
3877d10d5a6Sdrh   */
3887d10d5a6Sdrh   if( cnt!=1 ){
3897d10d5a6Sdrh     const char *zErr;
3907d10d5a6Sdrh     zErr = cnt==0 ? "no such column" : "ambiguous column name";
3917d10d5a6Sdrh     if( zDb ){
3927d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
3937d10d5a6Sdrh     }else if( zTab ){
3947d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
3957d10d5a6Sdrh     }else{
3967d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
3977d10d5a6Sdrh     }
3981db95106Sdan     pParse->checkSchema = 1;
3997d10d5a6Sdrh     pTopNC->nErr++;
4007d10d5a6Sdrh   }
4017d10d5a6Sdrh 
4027d10d5a6Sdrh   /* If a column from a table in pSrcList is referenced, then record
4037d10d5a6Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
4047d10d5a6Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
4057d10d5a6Sdrh   ** column number is greater than the number of bits in the bitmask
4067d10d5a6Sdrh   ** then set the high-order bit of the bitmask.
4077d10d5a6Sdrh   */
4082d2e7bd3Sdanielk1977   if( pExpr->iColumn>=0 && pMatch!=0 ){
4097d10d5a6Sdrh     int n = pExpr->iColumn;
41000e13613Sdanielk1977     testcase( n==BMS-1 );
41100e13613Sdanielk1977     if( n>=BMS ){
41200e13613Sdanielk1977       n = BMS-1;
4137d10d5a6Sdrh     }
4147d10d5a6Sdrh     assert( pMatch->iCursor==pExpr->iTable );
4157d10d5a6Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
4167d10d5a6Sdrh   }
4177d10d5a6Sdrh 
4187d10d5a6Sdrh   /* Clean up and return
4197d10d5a6Sdrh   */
4207d10d5a6Sdrh   sqlite3ExprDelete(db, pExpr->pLeft);
4217d10d5a6Sdrh   pExpr->pLeft = 0;
4227d10d5a6Sdrh   sqlite3ExprDelete(db, pExpr->pRight);
4237d10d5a6Sdrh   pExpr->pRight = 0;
4242bd93516Sdan   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
425b7916a78Sdrh lookupname_end:
4267d10d5a6Sdrh   if( cnt==1 ){
4277d10d5a6Sdrh     assert( pNC!=0 );
4287d10d5a6Sdrh     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
4297d10d5a6Sdrh     /* Increment the nRef value on all name contexts from TopNC up to
4307d10d5a6Sdrh     ** the point where the name matched. */
4317d10d5a6Sdrh     for(;;){
4327d10d5a6Sdrh       assert( pTopNC!=0 );
4337d10d5a6Sdrh       pTopNC->nRef++;
4347d10d5a6Sdrh       if( pTopNC==pNC ) break;
4357d10d5a6Sdrh       pTopNC = pTopNC->pNext;
4367d10d5a6Sdrh     }
437f7828b5cSdrh     return WRC_Prune;
4387d10d5a6Sdrh   } else {
439f7828b5cSdrh     return WRC_Abort;
4407d10d5a6Sdrh   }
4417d10d5a6Sdrh }
4427d10d5a6Sdrh 
4437d10d5a6Sdrh /*
444f7b0b0adSdan ** Allocate and return a pointer to an expression to load the column iCol
4459e48165bSdrh ** from datasource iSrc in SrcList pSrc.
446f7b0b0adSdan */
447f7b0b0adSdan Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
448f7b0b0adSdan   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
449f7b0b0adSdan   if( p ){
450f7b0b0adSdan     struct SrcList_item *pItem = &pSrc->a[iSrc];
451f7b0b0adSdan     p->pTab = pItem->pTab;
452f7b0b0adSdan     p->iTable = pItem->iCursor;
453f7b0b0adSdan     if( p->pTab->iPKey==iCol ){
454f7b0b0adSdan       p->iColumn = -1;
455f7b0b0adSdan     }else{
4568677d308Sdrh       p->iColumn = (ynVar)iCol;
4577caba669Sdrh       testcase( iCol==BMS );
4587caba669Sdrh       testcase( iCol==BMS-1 );
459f7b0b0adSdan       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
460f7b0b0adSdan     }
461f7b0b0adSdan     ExprSetProperty(p, EP_Resolved);
462f7b0b0adSdan   }
463f7b0b0adSdan   return p;
464f7b0b0adSdan }
465f7b0b0adSdan 
466f7b0b0adSdan /*
4677d10d5a6Sdrh ** This routine is callback for sqlite3WalkExpr().
4687d10d5a6Sdrh **
4697d10d5a6Sdrh ** Resolve symbolic names into TK_COLUMN operators for the current
4707d10d5a6Sdrh ** node in the expression tree.  Return 0 to continue the search down
4717d10d5a6Sdrh ** the tree or 2 to abort the tree walk.
4727d10d5a6Sdrh **
4737d10d5a6Sdrh ** This routine also does error checking and name resolution for
4747d10d5a6Sdrh ** function names.  The operator for aggregate functions is changed
4757d10d5a6Sdrh ** to TK_AGG_FUNCTION.
4767d10d5a6Sdrh */
4777d10d5a6Sdrh static int resolveExprStep(Walker *pWalker, Expr *pExpr){
4787d10d5a6Sdrh   NameContext *pNC;
4797d10d5a6Sdrh   Parse *pParse;
4807d10d5a6Sdrh 
4817d10d5a6Sdrh   pNC = pWalker->u.pNC;
4827d10d5a6Sdrh   assert( pNC!=0 );
4837d10d5a6Sdrh   pParse = pNC->pParse;
4847d10d5a6Sdrh   assert( pParse==pWalker->pParse );
4857d10d5a6Sdrh 
4867d10d5a6Sdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
4877d10d5a6Sdrh   ExprSetProperty(pExpr, EP_Resolved);
4887d10d5a6Sdrh #ifndef NDEBUG
4897d10d5a6Sdrh   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
4907d10d5a6Sdrh     SrcList *pSrcList = pNC->pSrcList;
4917d10d5a6Sdrh     int i;
4927d10d5a6Sdrh     for(i=0; i<pNC->pSrcList->nSrc; i++){
4937d10d5a6Sdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
4947d10d5a6Sdrh     }
4957d10d5a6Sdrh   }
4967d10d5a6Sdrh #endif
4977d10d5a6Sdrh   switch( pExpr->op ){
49841204f1fSdrh 
499273f619bSshane #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
50041204f1fSdrh     /* The special operator TK_ROW means use the rowid for the first
50141204f1fSdrh     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
50241204f1fSdrh     ** clause processing on UPDATE and DELETE statements.
50341204f1fSdrh     */
50441204f1fSdrh     case TK_ROW: {
50541204f1fSdrh       SrcList *pSrcList = pNC->pSrcList;
50641204f1fSdrh       struct SrcList_item *pItem;
50741204f1fSdrh       assert( pSrcList && pSrcList->nSrc==1 );
50841204f1fSdrh       pItem = pSrcList->a;
50941204f1fSdrh       pExpr->op = TK_COLUMN;
51041204f1fSdrh       pExpr->pTab = pItem->pTab;
51141204f1fSdrh       pExpr->iTable = pItem->iCursor;
51241204f1fSdrh       pExpr->iColumn = -1;
51341204f1fSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
51441204f1fSdrh       break;
51541204f1fSdrh     }
516273f619bSshane #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
51741204f1fSdrh 
5187d10d5a6Sdrh     /* A lone identifier is the name of a column.
5197d10d5a6Sdrh     */
5207d10d5a6Sdrh     case TK_ID: {
521f7828b5cSdrh       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
5227d10d5a6Sdrh     }
5237d10d5a6Sdrh 
5247d10d5a6Sdrh     /* A table name and column name:     ID.ID
5257d10d5a6Sdrh     ** Or a database, table and column:  ID.ID.ID
5267d10d5a6Sdrh     */
5277d10d5a6Sdrh     case TK_DOT: {
528b7916a78Sdrh       const char *zColumn;
529b7916a78Sdrh       const char *zTable;
530b7916a78Sdrh       const char *zDb;
5317d10d5a6Sdrh       Expr *pRight;
5327d10d5a6Sdrh 
5337d10d5a6Sdrh       /* if( pSrcList==0 ) break; */
5347d10d5a6Sdrh       pRight = pExpr->pRight;
5357d10d5a6Sdrh       if( pRight->op==TK_ID ){
536b7916a78Sdrh         zDb = 0;
53733e619fcSdrh         zTable = pExpr->pLeft->u.zToken;
53833e619fcSdrh         zColumn = pRight->u.zToken;
5397d10d5a6Sdrh       }else{
5407d10d5a6Sdrh         assert( pRight->op==TK_DOT );
54133e619fcSdrh         zDb = pExpr->pLeft->u.zToken;
54233e619fcSdrh         zTable = pRight->pLeft->u.zToken;
54333e619fcSdrh         zColumn = pRight->pRight->u.zToken;
5447d10d5a6Sdrh       }
545f7828b5cSdrh       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
5467d10d5a6Sdrh     }
5477d10d5a6Sdrh 
5487d10d5a6Sdrh     /* Resolve function names
5497d10d5a6Sdrh     */
5507d10d5a6Sdrh     case TK_CONST_FUNC:
5517d10d5a6Sdrh     case TK_FUNCTION: {
5526ab3a2ecSdanielk1977       ExprList *pList = pExpr->x.pList;    /* The argument list */
5537d10d5a6Sdrh       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
5547d10d5a6Sdrh       int no_such_func = 0;       /* True if no such function exists */
5557d10d5a6Sdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
5567d10d5a6Sdrh       int is_agg = 0;             /* True if is an aggregate function */
5577d10d5a6Sdrh       int auth;                   /* Authorization to use the function */
5587d10d5a6Sdrh       int nId;                    /* Number of characters in function name */
5597d10d5a6Sdrh       const char *zId;            /* The function name. */
5607d10d5a6Sdrh       FuncDef *pDef;              /* Information about the function */
561ea678832Sdrh       u8 enc = ENC(pParse->db);   /* The database encoding */
5627d10d5a6Sdrh 
56373c0fdc7Sdrh       testcase( pExpr->op==TK_CONST_FUNC );
5646ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
56533e619fcSdrh       zId = pExpr->u.zToken;
566b7916a78Sdrh       nId = sqlite3Strlen30(zId);
5677d10d5a6Sdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
5687d10d5a6Sdrh       if( pDef==0 ){
56989d5d6a2Sdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
5707d10d5a6Sdrh         if( pDef==0 ){
5717d10d5a6Sdrh           no_such_func = 1;
5727d10d5a6Sdrh         }else{
5737d10d5a6Sdrh           wrong_num_args = 1;
5747d10d5a6Sdrh         }
5757d10d5a6Sdrh       }else{
5767d10d5a6Sdrh         is_agg = pDef->xFunc==0;
5777d10d5a6Sdrh       }
5787d10d5a6Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION
5797d10d5a6Sdrh       if( pDef ){
5807d10d5a6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
5817d10d5a6Sdrh         if( auth!=SQLITE_OK ){
5827d10d5a6Sdrh           if( auth==SQLITE_DENY ){
5837d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
5847d10d5a6Sdrh                                     pDef->zName);
5857d10d5a6Sdrh             pNC->nErr++;
5867d10d5a6Sdrh           }
5877d10d5a6Sdrh           pExpr->op = TK_NULL;
5887d10d5a6Sdrh           return WRC_Prune;
5897d10d5a6Sdrh         }
5907d10d5a6Sdrh       }
5917d10d5a6Sdrh #endif
592a51009b2Sdrh       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
5937d10d5a6Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
5947d10d5a6Sdrh         pNC->nErr++;
5957d10d5a6Sdrh         is_agg = 0;
5967d10d5a6Sdrh       }else if( no_such_func ){
5977d10d5a6Sdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
5987d10d5a6Sdrh         pNC->nErr++;
5997d10d5a6Sdrh       }else if( wrong_num_args ){
6007d10d5a6Sdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
6017d10d5a6Sdrh              nId, zId);
6027d10d5a6Sdrh         pNC->nErr++;
6037d10d5a6Sdrh       }
604a51009b2Sdrh       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
6057d10d5a6Sdrh       sqlite3WalkExprList(pWalker, pList);
606030796dfSdrh       if( is_agg ){
607030796dfSdrh         NameContext *pNC2 = pNC;
608030796dfSdrh         pExpr->op = TK_AGG_FUNCTION;
609030796dfSdrh         pExpr->op2 = 0;
610030796dfSdrh         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
611030796dfSdrh           pExpr->op2++;
612030796dfSdrh           pNC2 = pNC2->pNext;
613030796dfSdrh         }
614030796dfSdrh         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
615030796dfSdrh         pNC->ncFlags |= NC_AllowAgg;
616030796dfSdrh       }
6177d10d5a6Sdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
6187d10d5a6Sdrh       ** type of the function
6197d10d5a6Sdrh       */
6207d10d5a6Sdrh       return WRC_Prune;
6217d10d5a6Sdrh     }
6227d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
6237d10d5a6Sdrh     case TK_SELECT:
62473c0fdc7Sdrh     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
6257d10d5a6Sdrh #endif
6267d10d5a6Sdrh     case TK_IN: {
62773c0fdc7Sdrh       testcase( pExpr->op==TK_IN );
6286ab3a2ecSdanielk1977       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
6297d10d5a6Sdrh         int nRef = pNC->nRef;
6307d10d5a6Sdrh #ifndef SQLITE_OMIT_CHECK
631a51009b2Sdrh         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
6327d10d5a6Sdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
6337d10d5a6Sdrh         }
6347d10d5a6Sdrh #endif
6356ab3a2ecSdanielk1977         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
6367d10d5a6Sdrh         assert( pNC->nRef>=nRef );
6377d10d5a6Sdrh         if( nRef!=pNC->nRef ){
6387d10d5a6Sdrh           ExprSetProperty(pExpr, EP_VarSelect);
6397d10d5a6Sdrh         }
6407d10d5a6Sdrh       }
6417d10d5a6Sdrh       break;
6427d10d5a6Sdrh     }
6437d10d5a6Sdrh #ifndef SQLITE_OMIT_CHECK
6447d10d5a6Sdrh     case TK_VARIABLE: {
645a51009b2Sdrh       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
6467d10d5a6Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
6477d10d5a6Sdrh       }
6487d10d5a6Sdrh       break;
6497d10d5a6Sdrh     }
6507d10d5a6Sdrh #endif
6517d10d5a6Sdrh   }
6527d10d5a6Sdrh   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
6537d10d5a6Sdrh }
6547d10d5a6Sdrh 
6557d10d5a6Sdrh /*
6567d10d5a6Sdrh ** pEList is a list of expressions which are really the result set of the
6577d10d5a6Sdrh ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
6587d10d5a6Sdrh ** This routine checks to see if pE is a simple identifier which corresponds
6597d10d5a6Sdrh ** to the AS-name of one of the terms of the expression list.  If it is,
6607d10d5a6Sdrh ** this routine return an integer between 1 and N where N is the number of
6617d10d5a6Sdrh ** elements in pEList, corresponding to the matching entry.  If there is
6627d10d5a6Sdrh ** no match, or if pE is not a simple identifier, then this routine
6637d10d5a6Sdrh ** return 0.
6647d10d5a6Sdrh **
6657d10d5a6Sdrh ** pEList has been resolved.  pE has not.
6667d10d5a6Sdrh */
6677d10d5a6Sdrh static int resolveAsName(
6687d10d5a6Sdrh   Parse *pParse,     /* Parsing context for error messages */
6697d10d5a6Sdrh   ExprList *pEList,  /* List of expressions to scan */
6707d10d5a6Sdrh   Expr *pE           /* Expression we are trying to match */
6717d10d5a6Sdrh ){
6727d10d5a6Sdrh   int i;             /* Loop counter */
6737d10d5a6Sdrh 
674cf697396Sshane   UNUSED_PARAMETER(pParse);
675cf697396Sshane 
67673c0fdc7Sdrh   if( pE->op==TK_ID ){
67733e619fcSdrh     char *zCol = pE->u.zToken;
6787d10d5a6Sdrh     for(i=0; i<pEList->nExpr; i++){
6797d10d5a6Sdrh       char *zAs = pEList->a[i].zName;
6807d10d5a6Sdrh       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
6817d10d5a6Sdrh         return i+1;
6827d10d5a6Sdrh       }
6837d10d5a6Sdrh     }
6847d10d5a6Sdrh   }
6857d10d5a6Sdrh   return 0;
6867d10d5a6Sdrh }
6877d10d5a6Sdrh 
6887d10d5a6Sdrh /*
6897d10d5a6Sdrh ** pE is a pointer to an expression which is a single term in the
6907d10d5a6Sdrh ** ORDER BY of a compound SELECT.  The expression has not been
6917d10d5a6Sdrh ** name resolved.
6927d10d5a6Sdrh **
6937d10d5a6Sdrh ** At the point this routine is called, we already know that the
6947d10d5a6Sdrh ** ORDER BY term is not an integer index into the result set.  That
6957d10d5a6Sdrh ** case is handled by the calling routine.
6967d10d5a6Sdrh **
6977d10d5a6Sdrh ** Attempt to match pE against result set columns in the left-most
6987d10d5a6Sdrh ** SELECT statement.  Return the index i of the matching column,
6997d10d5a6Sdrh ** as an indication to the caller that it should sort by the i-th column.
7007d10d5a6Sdrh ** The left-most column is 1.  In other words, the value returned is the
7017d10d5a6Sdrh ** same integer value that would be used in the SQL statement to indicate
7027d10d5a6Sdrh ** the column.
7037d10d5a6Sdrh **
7047d10d5a6Sdrh ** If there is no match, return 0.  Return -1 if an error occurs.
7057d10d5a6Sdrh */
7067d10d5a6Sdrh static int resolveOrderByTermToExprList(
7077d10d5a6Sdrh   Parse *pParse,     /* Parsing context for error messages */
7087d10d5a6Sdrh   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
7097d10d5a6Sdrh   Expr *pE           /* The specific ORDER BY term */
7107d10d5a6Sdrh ){
7117d10d5a6Sdrh   int i;             /* Loop counter */
7127d10d5a6Sdrh   ExprList *pEList;  /* The columns of the result set */
7137d10d5a6Sdrh   NameContext nc;    /* Name context for resolving pE */
714a7564663Sdrh   sqlite3 *db;       /* Database connection */
715a7564663Sdrh   int rc;            /* Return code from subprocedures */
716a7564663Sdrh   u8 savedSuppErr;   /* Saved value of db->suppressErr */
7177d10d5a6Sdrh 
7187d10d5a6Sdrh   assert( sqlite3ExprIsInteger(pE, &i)==0 );
7197d10d5a6Sdrh   pEList = pSelect->pEList;
7207d10d5a6Sdrh 
7217d10d5a6Sdrh   /* Resolve all names in the ORDER BY term expression
7227d10d5a6Sdrh   */
7237d10d5a6Sdrh   memset(&nc, 0, sizeof(nc));
7247d10d5a6Sdrh   nc.pParse = pParse;
7257d10d5a6Sdrh   nc.pSrcList = pSelect->pSrc;
7267d10d5a6Sdrh   nc.pEList = pEList;
727a51009b2Sdrh   nc.ncFlags = NC_AllowAgg;
7287d10d5a6Sdrh   nc.nErr = 0;
729a7564663Sdrh   db = pParse->db;
730a7564663Sdrh   savedSuppErr = db->suppressErr;
731a7564663Sdrh   db->suppressErr = 1;
732a7564663Sdrh   rc = sqlite3ResolveExprNames(&nc, pE);
733a7564663Sdrh   db->suppressErr = savedSuppErr;
734a7564663Sdrh   if( rc ) return 0;
7357d10d5a6Sdrh 
7367d10d5a6Sdrh   /* Try to match the ORDER BY expression against an expression
7377d10d5a6Sdrh   ** in the result set.  Return an 1-based index of the matching
7387d10d5a6Sdrh   ** result-set entry.
7397d10d5a6Sdrh   */
7407d10d5a6Sdrh   for(i=0; i<pEList->nExpr; i++){
7411d9da70aSdrh     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
7427d10d5a6Sdrh       return i+1;
7437d10d5a6Sdrh     }
7447d10d5a6Sdrh   }
7457d10d5a6Sdrh 
7467d10d5a6Sdrh   /* If no match, return 0. */
7477d10d5a6Sdrh   return 0;
7487d10d5a6Sdrh }
7497d10d5a6Sdrh 
7507d10d5a6Sdrh /*
7517d10d5a6Sdrh ** Generate an ORDER BY or GROUP BY term out-of-range error.
7527d10d5a6Sdrh */
7537d10d5a6Sdrh static void resolveOutOfRangeError(
7547d10d5a6Sdrh   Parse *pParse,         /* The error context into which to write the error */
7557d10d5a6Sdrh   const char *zType,     /* "ORDER" or "GROUP" */
7567d10d5a6Sdrh   int i,                 /* The index (1-based) of the term out of range */
7577d10d5a6Sdrh   int mx                 /* Largest permissible value of i */
7587d10d5a6Sdrh ){
7597d10d5a6Sdrh   sqlite3ErrorMsg(pParse,
7607d10d5a6Sdrh     "%r %s BY term out of range - should be "
7617d10d5a6Sdrh     "between 1 and %d", i, zType, mx);
7627d10d5a6Sdrh }
7637d10d5a6Sdrh 
7647d10d5a6Sdrh /*
7657d10d5a6Sdrh ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
7667d10d5a6Sdrh ** each term of the ORDER BY clause is a constant integer between 1
7677d10d5a6Sdrh ** and N where N is the number of columns in the compound SELECT.
7687d10d5a6Sdrh **
7697d10d5a6Sdrh ** ORDER BY terms that are already an integer between 1 and N are
7707d10d5a6Sdrh ** unmodified.  ORDER BY terms that are integers outside the range of
7717d10d5a6Sdrh ** 1 through N generate an error.  ORDER BY terms that are expressions
7727d10d5a6Sdrh ** are matched against result set expressions of compound SELECT
7737d10d5a6Sdrh ** beginning with the left-most SELECT and working toward the right.
7747d10d5a6Sdrh ** At the first match, the ORDER BY expression is transformed into
7757d10d5a6Sdrh ** the integer column number.
7767d10d5a6Sdrh **
7777d10d5a6Sdrh ** Return the number of errors seen.
7787d10d5a6Sdrh */
7797d10d5a6Sdrh static int resolveCompoundOrderBy(
7807d10d5a6Sdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
7817d10d5a6Sdrh   Select *pSelect       /* The SELECT statement containing the ORDER BY */
7827d10d5a6Sdrh ){
7837d10d5a6Sdrh   int i;
7847d10d5a6Sdrh   ExprList *pOrderBy;
7857d10d5a6Sdrh   ExprList *pEList;
7867d10d5a6Sdrh   sqlite3 *db;
7877d10d5a6Sdrh   int moreToDo = 1;
7887d10d5a6Sdrh 
7897d10d5a6Sdrh   pOrderBy = pSelect->pOrderBy;
7907d10d5a6Sdrh   if( pOrderBy==0 ) return 0;
7917d10d5a6Sdrh   db = pParse->db;
7927d10d5a6Sdrh #if SQLITE_MAX_COLUMN
7937d10d5a6Sdrh   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
7947d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
7957d10d5a6Sdrh     return 1;
7967d10d5a6Sdrh   }
7977d10d5a6Sdrh #endif
7987d10d5a6Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
7997d10d5a6Sdrh     pOrderBy->a[i].done = 0;
8007d10d5a6Sdrh   }
8017d10d5a6Sdrh   pSelect->pNext = 0;
8027d10d5a6Sdrh   while( pSelect->pPrior ){
8037d10d5a6Sdrh     pSelect->pPrior->pNext = pSelect;
8047d10d5a6Sdrh     pSelect = pSelect->pPrior;
8057d10d5a6Sdrh   }
8067d10d5a6Sdrh   while( pSelect && moreToDo ){
8077d10d5a6Sdrh     struct ExprList_item *pItem;
8087d10d5a6Sdrh     moreToDo = 0;
8097d10d5a6Sdrh     pEList = pSelect->pEList;
8100a846f96Sdrh     assert( pEList!=0 );
8117d10d5a6Sdrh     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
8127d10d5a6Sdrh       int iCol = -1;
8137d10d5a6Sdrh       Expr *pE, *pDup;
8147d10d5a6Sdrh       if( pItem->done ) continue;
8157d10d5a6Sdrh       pE = pItem->pExpr;
8167d10d5a6Sdrh       if( sqlite3ExprIsInteger(pE, &iCol) ){
81773c0fdc7Sdrh         if( iCol<=0 || iCol>pEList->nExpr ){
8187d10d5a6Sdrh           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
8197d10d5a6Sdrh           return 1;
8207d10d5a6Sdrh         }
8217d10d5a6Sdrh       }else{
8227d10d5a6Sdrh         iCol = resolveAsName(pParse, pEList, pE);
8237d10d5a6Sdrh         if( iCol==0 ){
8246ab3a2ecSdanielk1977           pDup = sqlite3ExprDup(db, pE, 0);
8257d10d5a6Sdrh           if( !db->mallocFailed ){
8267d10d5a6Sdrh             assert(pDup);
8277d10d5a6Sdrh             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
8287d10d5a6Sdrh           }
8297d10d5a6Sdrh           sqlite3ExprDelete(db, pDup);
8307d10d5a6Sdrh         }
8317d10d5a6Sdrh       }
8327d10d5a6Sdrh       if( iCol>0 ){
8337d10d5a6Sdrh         CollSeq *pColl = pE->pColl;
8347d10d5a6Sdrh         int flags = pE->flags & EP_ExpCollate;
8357d10d5a6Sdrh         sqlite3ExprDelete(db, pE);
836b7916a78Sdrh         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
8377d10d5a6Sdrh         if( pE==0 ) return 1;
8387d10d5a6Sdrh         pE->pColl = pColl;
8397d10d5a6Sdrh         pE->flags |= EP_IntValue | flags;
84033e619fcSdrh         pE->u.iValue = iCol;
8414b3ac73cSdrh         pItem->iOrderByCol = (u16)iCol;
8427d10d5a6Sdrh         pItem->done = 1;
8437d10d5a6Sdrh       }else{
8447d10d5a6Sdrh         moreToDo = 1;
8457d10d5a6Sdrh       }
8467d10d5a6Sdrh     }
8477d10d5a6Sdrh     pSelect = pSelect->pNext;
8487d10d5a6Sdrh   }
8497d10d5a6Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
8507d10d5a6Sdrh     if( pOrderBy->a[i].done==0 ){
8517d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
8527d10d5a6Sdrh             "column in the result set", i+1);
8537d10d5a6Sdrh       return 1;
8547d10d5a6Sdrh     }
8557d10d5a6Sdrh   }
8567d10d5a6Sdrh   return 0;
8577d10d5a6Sdrh }
8587d10d5a6Sdrh 
8597d10d5a6Sdrh /*
8607d10d5a6Sdrh ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
8617d10d5a6Sdrh ** the SELECT statement pSelect.  If any term is reference to a
8627d10d5a6Sdrh ** result set expression (as determined by the ExprList.a.iCol field)
8637d10d5a6Sdrh ** then convert that term into a copy of the corresponding result set
8647d10d5a6Sdrh ** column.
8657d10d5a6Sdrh **
8667d10d5a6Sdrh ** If any errors are detected, add an error message to pParse and
8677d10d5a6Sdrh ** return non-zero.  Return zero if no errors are seen.
8687d10d5a6Sdrh */
8697d10d5a6Sdrh int sqlite3ResolveOrderGroupBy(
8707d10d5a6Sdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
8717d10d5a6Sdrh   Select *pSelect,      /* The SELECT statement containing the clause */
8727d10d5a6Sdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
8737d10d5a6Sdrh   const char *zType     /* "ORDER" or "GROUP" */
8747d10d5a6Sdrh ){
8757d10d5a6Sdrh   int i;
8767d10d5a6Sdrh   sqlite3 *db = pParse->db;
8777d10d5a6Sdrh   ExprList *pEList;
8787d10d5a6Sdrh   struct ExprList_item *pItem;
8797d10d5a6Sdrh 
8807d10d5a6Sdrh   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
8817d10d5a6Sdrh #if SQLITE_MAX_COLUMN
8827d10d5a6Sdrh   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
8837d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
8847d10d5a6Sdrh     return 1;
8857d10d5a6Sdrh   }
8867d10d5a6Sdrh #endif
8877d10d5a6Sdrh   pEList = pSelect->pEList;
8880a846f96Sdrh   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
8897d10d5a6Sdrh   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
8904b3ac73cSdrh     if( pItem->iOrderByCol ){
8914b3ac73cSdrh       if( pItem->iOrderByCol>pEList->nExpr ){
8927d10d5a6Sdrh         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
8937d10d5a6Sdrh         return 1;
8947d10d5a6Sdrh       }
895ed551b95Sdrh       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
8967d10d5a6Sdrh     }
8977d10d5a6Sdrh   }
8987d10d5a6Sdrh   return 0;
8997d10d5a6Sdrh }
9007d10d5a6Sdrh 
9017d10d5a6Sdrh /*
9027d10d5a6Sdrh ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
9037d10d5a6Sdrh ** The Name context of the SELECT statement is pNC.  zType is either
9047d10d5a6Sdrh ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
9057d10d5a6Sdrh **
9067d10d5a6Sdrh ** This routine resolves each term of the clause into an expression.
9077d10d5a6Sdrh ** If the order-by term is an integer I between 1 and N (where N is the
9087d10d5a6Sdrh ** number of columns in the result set of the SELECT) then the expression
9097d10d5a6Sdrh ** in the resolution is a copy of the I-th result-set expression.  If
9107d10d5a6Sdrh ** the order-by term is an identify that corresponds to the AS-name of
9117d10d5a6Sdrh ** a result-set expression, then the term resolves to a copy of the
9127d10d5a6Sdrh ** result-set expression.  Otherwise, the expression is resolved in
9137d10d5a6Sdrh ** the usual way - using sqlite3ResolveExprNames().
9147d10d5a6Sdrh **
9157d10d5a6Sdrh ** This routine returns the number of errors.  If errors occur, then
9167d10d5a6Sdrh ** an appropriate error message might be left in pParse.  (OOM errors
9177d10d5a6Sdrh ** excepted.)
9187d10d5a6Sdrh */
9197d10d5a6Sdrh static int resolveOrderGroupBy(
9207d10d5a6Sdrh   NameContext *pNC,     /* The name context of the SELECT statement */
9217d10d5a6Sdrh   Select *pSelect,      /* The SELECT statement holding pOrderBy */
9227d10d5a6Sdrh   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
9237d10d5a6Sdrh   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
9247d10d5a6Sdrh ){
92570331cd7Sdrh   int i, j;                      /* Loop counters */
9267d10d5a6Sdrh   int iCol;                      /* Column number */
9277d10d5a6Sdrh   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
9287d10d5a6Sdrh   Parse *pParse;                 /* Parsing context */
9297d10d5a6Sdrh   int nResult;                   /* Number of terms in the result set */
9307d10d5a6Sdrh 
9317d10d5a6Sdrh   if( pOrderBy==0 ) return 0;
9327d10d5a6Sdrh   nResult = pSelect->pEList->nExpr;
9337d10d5a6Sdrh   pParse = pNC->pParse;
9347d10d5a6Sdrh   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
9357d10d5a6Sdrh     Expr *pE = pItem->pExpr;
9367d10d5a6Sdrh     iCol = resolveAsName(pParse, pSelect->pEList, pE);
9377d10d5a6Sdrh     if( iCol>0 ){
9387d10d5a6Sdrh       /* If an AS-name match is found, mark this ORDER BY column as being
9397d10d5a6Sdrh       ** a copy of the iCol-th result-set column.  The subsequent call to
9407d10d5a6Sdrh       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
9417d10d5a6Sdrh       ** copy of the iCol-th result-set expression. */
9424b3ac73cSdrh       pItem->iOrderByCol = (u16)iCol;
9437d10d5a6Sdrh       continue;
9447d10d5a6Sdrh     }
9457d10d5a6Sdrh     if( sqlite3ExprIsInteger(pE, &iCol) ){
9467d10d5a6Sdrh       /* The ORDER BY term is an integer constant.  Again, set the column
9477d10d5a6Sdrh       ** number so that sqlite3ResolveOrderGroupBy() will convert the
9487d10d5a6Sdrh       ** order-by term to a copy of the result-set expression */
9490a846f96Sdrh       if( iCol<1 ){
9507d10d5a6Sdrh         resolveOutOfRangeError(pParse, zType, i+1, nResult);
9517d10d5a6Sdrh         return 1;
9527d10d5a6Sdrh       }
9534b3ac73cSdrh       pItem->iOrderByCol = (u16)iCol;
9547d10d5a6Sdrh       continue;
9557d10d5a6Sdrh     }
9567d10d5a6Sdrh 
9577d10d5a6Sdrh     /* Otherwise, treat the ORDER BY term as an ordinary expression */
9584b3ac73cSdrh     pItem->iOrderByCol = 0;
9597d10d5a6Sdrh     if( sqlite3ResolveExprNames(pNC, pE) ){
9607d10d5a6Sdrh       return 1;
9617d10d5a6Sdrh     }
96270331cd7Sdrh     for(j=0; j<pSelect->pEList->nExpr; j++){
96370331cd7Sdrh       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
96470331cd7Sdrh         pItem->iOrderByCol = j+1;
96570331cd7Sdrh       }
96670331cd7Sdrh     }
9677d10d5a6Sdrh   }
9687d10d5a6Sdrh   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
9697d10d5a6Sdrh }
9707d10d5a6Sdrh 
9717d10d5a6Sdrh /*
9727d10d5a6Sdrh ** Resolve names in the SELECT statement p and all of its descendents.
9737d10d5a6Sdrh */
9747d10d5a6Sdrh static int resolveSelectStep(Walker *pWalker, Select *p){
9757d10d5a6Sdrh   NameContext *pOuterNC;  /* Context that contains this SELECT */
9767d10d5a6Sdrh   NameContext sNC;        /* Name context of this SELECT */
9777d10d5a6Sdrh   int isCompound;         /* True if p is a compound select */
9787d10d5a6Sdrh   int nCompound;          /* Number of compound terms processed so far */
9797d10d5a6Sdrh   Parse *pParse;          /* Parsing context */
9807d10d5a6Sdrh   ExprList *pEList;       /* Result set expression list */
9817d10d5a6Sdrh   int i;                  /* Loop counter */
9827d10d5a6Sdrh   ExprList *pGroupBy;     /* The GROUP BY clause */
9837d10d5a6Sdrh   Select *pLeftmost;      /* Left-most of SELECT of a compound */
9847d10d5a6Sdrh   sqlite3 *db;            /* Database connection */
9857d10d5a6Sdrh 
9867d10d5a6Sdrh 
9870a846f96Sdrh   assert( p!=0 );
9887d10d5a6Sdrh   if( p->selFlags & SF_Resolved ){
9897d10d5a6Sdrh     return WRC_Prune;
9907d10d5a6Sdrh   }
9917d10d5a6Sdrh   pOuterNC = pWalker->u.pNC;
9927d10d5a6Sdrh   pParse = pWalker->pParse;
9937d10d5a6Sdrh   db = pParse->db;
9947d10d5a6Sdrh 
9957d10d5a6Sdrh   /* Normally sqlite3SelectExpand() will be called first and will have
9967d10d5a6Sdrh   ** already expanded this SELECT.  However, if this is a subquery within
9977d10d5a6Sdrh   ** an expression, sqlite3ResolveExprNames() will be called without a
9987d10d5a6Sdrh   ** prior call to sqlite3SelectExpand().  When that happens, let
9997d10d5a6Sdrh   ** sqlite3SelectPrep() do all of the processing for this SELECT.
10007d10d5a6Sdrh   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
10017d10d5a6Sdrh   ** this routine in the correct order.
10027d10d5a6Sdrh   */
10037d10d5a6Sdrh   if( (p->selFlags & SF_Expanded)==0 ){
10047d10d5a6Sdrh     sqlite3SelectPrep(pParse, p, pOuterNC);
10057d10d5a6Sdrh     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
10067d10d5a6Sdrh   }
10077d10d5a6Sdrh 
10087d10d5a6Sdrh   isCompound = p->pPrior!=0;
10097d10d5a6Sdrh   nCompound = 0;
10107d10d5a6Sdrh   pLeftmost = p;
10117d10d5a6Sdrh   while( p ){
10127d10d5a6Sdrh     assert( (p->selFlags & SF_Expanded)!=0 );
10137d10d5a6Sdrh     assert( (p->selFlags & SF_Resolved)==0 );
10147d10d5a6Sdrh     p->selFlags |= SF_Resolved;
10157d10d5a6Sdrh 
10167d10d5a6Sdrh     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
10177d10d5a6Sdrh     ** are not allowed to refer to any names, so pass an empty NameContext.
10187d10d5a6Sdrh     */
10197d10d5a6Sdrh     memset(&sNC, 0, sizeof(sNC));
10207d10d5a6Sdrh     sNC.pParse = pParse;
10217d10d5a6Sdrh     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
10227d10d5a6Sdrh         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
10237d10d5a6Sdrh       return WRC_Abort;
10247d10d5a6Sdrh     }
10257d10d5a6Sdrh 
10267d10d5a6Sdrh     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
10277d10d5a6Sdrh     ** resolve the result-set expression list.
10287d10d5a6Sdrh     */
1029a51009b2Sdrh     sNC.ncFlags = NC_AllowAgg;
10307d10d5a6Sdrh     sNC.pSrcList = p->pSrc;
10317d10d5a6Sdrh     sNC.pNext = pOuterNC;
10327d10d5a6Sdrh 
10337d10d5a6Sdrh     /* Resolve names in the result set. */
10347d10d5a6Sdrh     pEList = p->pEList;
10350a846f96Sdrh     assert( pEList!=0 );
10367d10d5a6Sdrh     for(i=0; i<pEList->nExpr; i++){
10377d10d5a6Sdrh       Expr *pX = pEList->a[i].pExpr;
10387d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pX) ){
10397d10d5a6Sdrh         return WRC_Abort;
10407d10d5a6Sdrh       }
10417d10d5a6Sdrh     }
10427d10d5a6Sdrh 
10437d10d5a6Sdrh     /* Recursively resolve names in all subqueries
10447d10d5a6Sdrh     */
10457d10d5a6Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
10467d10d5a6Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
10477d10d5a6Sdrh       if( pItem->pSelect ){
1048da79cf0cSdan         NameContext *pNC;         /* Used to iterate name contexts */
1049da79cf0cSdan         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
10507d10d5a6Sdrh         const char *zSavedContext = pParse->zAuthContext;
1051da79cf0cSdan 
1052da79cf0cSdan         /* Count the total number of references to pOuterNC and all of its
1053da79cf0cSdan         ** parent contexts. After resolving references to expressions in
1054da79cf0cSdan         ** pItem->pSelect, check if this value has changed. If so, then
1055da79cf0cSdan         ** SELECT statement pItem->pSelect must be correlated. Set the
1056da79cf0cSdan         ** pItem->isCorrelated flag if this is the case. */
1057da79cf0cSdan         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1058da79cf0cSdan 
10597d10d5a6Sdrh         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1060cd2b5613Sdrh         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
10617d10d5a6Sdrh         pParse->zAuthContext = zSavedContext;
10627d10d5a6Sdrh         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
1063da79cf0cSdan 
1064da79cf0cSdan         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1065da79cf0cSdan         assert( pItem->isCorrelated==0 && nRef<=0 );
1066da79cf0cSdan         pItem->isCorrelated = (nRef!=0);
10677d10d5a6Sdrh       }
10687d10d5a6Sdrh     }
10697d10d5a6Sdrh 
10707d10d5a6Sdrh     /* If there are no aggregate functions in the result-set, and no GROUP BY
10717d10d5a6Sdrh     ** expression, do not allow aggregates in any of the other expressions.
10727d10d5a6Sdrh     */
10737d10d5a6Sdrh     assert( (p->selFlags & SF_Aggregate)==0 );
10747d10d5a6Sdrh     pGroupBy = p->pGroupBy;
1075a51009b2Sdrh     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
10767d10d5a6Sdrh       p->selFlags |= SF_Aggregate;
10777d10d5a6Sdrh     }else{
1078a51009b2Sdrh       sNC.ncFlags &= ~NC_AllowAgg;
10797d10d5a6Sdrh     }
10807d10d5a6Sdrh 
10817d10d5a6Sdrh     /* If a HAVING clause is present, then there must be a GROUP BY clause.
10827d10d5a6Sdrh     */
10837d10d5a6Sdrh     if( p->pHaving && !pGroupBy ){
10847d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
10857d10d5a6Sdrh       return WRC_Abort;
10867d10d5a6Sdrh     }
10877d10d5a6Sdrh 
10887d10d5a6Sdrh     /* Add the expression list to the name-context before parsing the
10897d10d5a6Sdrh     ** other expressions in the SELECT statement. This is so that
10907d10d5a6Sdrh     ** expressions in the WHERE clause (etc.) can refer to expressions by
10917d10d5a6Sdrh     ** aliases in the result set.
10927d10d5a6Sdrh     **
10937d10d5a6Sdrh     ** Minor point: If this is the case, then the expression will be
10947d10d5a6Sdrh     ** re-evaluated for each reference to it.
10957d10d5a6Sdrh     */
10967d10d5a6Sdrh     sNC.pEList = p->pEList;
10977d10d5a6Sdrh     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
10987d10d5a6Sdrh        sqlite3ResolveExprNames(&sNC, p->pHaving)
10997d10d5a6Sdrh     ){
11007d10d5a6Sdrh       return WRC_Abort;
11017d10d5a6Sdrh     }
11027d10d5a6Sdrh 
11037d10d5a6Sdrh     /* The ORDER BY and GROUP BY clauses may not refer to terms in
11047d10d5a6Sdrh     ** outer queries
11057d10d5a6Sdrh     */
11067d10d5a6Sdrh     sNC.pNext = 0;
1107a51009b2Sdrh     sNC.ncFlags |= NC_AllowAgg;
11087d10d5a6Sdrh 
11097d10d5a6Sdrh     /* Process the ORDER BY clause for singleton SELECT statements.
11107d10d5a6Sdrh     ** The ORDER BY clause for compounds SELECT statements is handled
11117d10d5a6Sdrh     ** below, after all of the result-sets for all of the elements of
11127d10d5a6Sdrh     ** the compound have been resolved.
11137d10d5a6Sdrh     */
11147d10d5a6Sdrh     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
11157d10d5a6Sdrh       return WRC_Abort;
11167d10d5a6Sdrh     }
11177d10d5a6Sdrh     if( db->mallocFailed ){
11187d10d5a6Sdrh       return WRC_Abort;
11197d10d5a6Sdrh     }
11207d10d5a6Sdrh 
11217d10d5a6Sdrh     /* Resolve the GROUP BY clause.  At the same time, make sure
11227d10d5a6Sdrh     ** the GROUP BY clause does not contain aggregate functions.
11237d10d5a6Sdrh     */
11247d10d5a6Sdrh     if( pGroupBy ){
11257d10d5a6Sdrh       struct ExprList_item *pItem;
11267d10d5a6Sdrh 
11277d10d5a6Sdrh       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
11287d10d5a6Sdrh         return WRC_Abort;
11297d10d5a6Sdrh       }
11307d10d5a6Sdrh       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
11317d10d5a6Sdrh         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
11327d10d5a6Sdrh           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
11337d10d5a6Sdrh               "the GROUP BY clause");
11347d10d5a6Sdrh           return WRC_Abort;
11357d10d5a6Sdrh         }
11367d10d5a6Sdrh       }
11377d10d5a6Sdrh     }
11387d10d5a6Sdrh 
11397d10d5a6Sdrh     /* Advance to the next term of the compound
11407d10d5a6Sdrh     */
11417d10d5a6Sdrh     p = p->pPrior;
11427d10d5a6Sdrh     nCompound++;
11437d10d5a6Sdrh   }
11447d10d5a6Sdrh 
11457d10d5a6Sdrh   /* Resolve the ORDER BY on a compound SELECT after all terms of
11467d10d5a6Sdrh   ** the compound have been resolved.
11477d10d5a6Sdrh   */
11487d10d5a6Sdrh   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
11497d10d5a6Sdrh     return WRC_Abort;
11507d10d5a6Sdrh   }
11517d10d5a6Sdrh 
11527d10d5a6Sdrh   return WRC_Prune;
11537d10d5a6Sdrh }
11547d10d5a6Sdrh 
11557d10d5a6Sdrh /*
11567d10d5a6Sdrh ** This routine walks an expression tree and resolves references to
11577d10d5a6Sdrh ** table columns and result-set columns.  At the same time, do error
11587d10d5a6Sdrh ** checking on function usage and set a flag if any aggregate functions
11597d10d5a6Sdrh ** are seen.
11607d10d5a6Sdrh **
11617d10d5a6Sdrh ** To resolve table columns references we look for nodes (or subtrees) of the
11627d10d5a6Sdrh ** form X.Y.Z or Y.Z or just Z where
11637d10d5a6Sdrh **
11647d10d5a6Sdrh **      X:   The name of a database.  Ex:  "main" or "temp" or
11657d10d5a6Sdrh **           the symbolic name assigned to an ATTACH-ed database.
11667d10d5a6Sdrh **
11677d10d5a6Sdrh **      Y:   The name of a table in a FROM clause.  Or in a trigger
11687d10d5a6Sdrh **           one of the special names "old" or "new".
11697d10d5a6Sdrh **
11707d10d5a6Sdrh **      Z:   The name of a column in table Y.
11717d10d5a6Sdrh **
11727d10d5a6Sdrh ** The node at the root of the subtree is modified as follows:
11737d10d5a6Sdrh **
11747d10d5a6Sdrh **    Expr.op        Changed to TK_COLUMN
11757d10d5a6Sdrh **    Expr.pTab      Points to the Table object for X.Y
11767d10d5a6Sdrh **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
11777d10d5a6Sdrh **    Expr.iTable    The VDBE cursor number for X.Y
11787d10d5a6Sdrh **
11797d10d5a6Sdrh **
11807d10d5a6Sdrh ** To resolve result-set references, look for expression nodes of the
11817d10d5a6Sdrh ** form Z (with no X and Y prefix) where the Z matches the right-hand
11827d10d5a6Sdrh ** size of an AS clause in the result-set of a SELECT.  The Z expression
11837d10d5a6Sdrh ** is replaced by a copy of the left-hand side of the result-set expression.
11847d10d5a6Sdrh ** Table-name and function resolution occurs on the substituted expression
11857d10d5a6Sdrh ** tree.  For example, in:
11867d10d5a6Sdrh **
11877d10d5a6Sdrh **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
11887d10d5a6Sdrh **
11897d10d5a6Sdrh ** The "x" term of the order by is replaced by "a+b" to render:
11907d10d5a6Sdrh **
11917d10d5a6Sdrh **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
11927d10d5a6Sdrh **
11937d10d5a6Sdrh ** Function calls are checked to make sure that the function is
11947d10d5a6Sdrh ** defined and that the correct number of arguments are specified.
1195a51009b2Sdrh ** If the function is an aggregate function, then the NC_HasAgg flag is
11967d10d5a6Sdrh ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
11977d10d5a6Sdrh ** If an expression contains aggregate functions then the EP_Agg
11987d10d5a6Sdrh ** property on the expression is set.
11997d10d5a6Sdrh **
12007d10d5a6Sdrh ** An error message is left in pParse if anything is amiss.  The number
12017d10d5a6Sdrh ** if errors is returned.
12027d10d5a6Sdrh */
12037d10d5a6Sdrh int sqlite3ResolveExprNames(
12047d10d5a6Sdrh   NameContext *pNC,       /* Namespace to resolve expressions in. */
12057d10d5a6Sdrh   Expr *pExpr             /* The expression to be analyzed. */
12067d10d5a6Sdrh ){
1207a51009b2Sdrh   u8 savedHasAgg;
12087d10d5a6Sdrh   Walker w;
12097d10d5a6Sdrh 
12107d10d5a6Sdrh   if( pExpr==0 ) return 0;
12117d10d5a6Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
12127d10d5a6Sdrh   {
12137d10d5a6Sdrh     Parse *pParse = pNC->pParse;
12147d10d5a6Sdrh     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
12157d10d5a6Sdrh       return 1;
12167d10d5a6Sdrh     }
12177d10d5a6Sdrh     pParse->nHeight += pExpr->nHeight;
12187d10d5a6Sdrh   }
12197d10d5a6Sdrh #endif
1220a51009b2Sdrh   savedHasAgg = pNC->ncFlags & NC_HasAgg;
1221a51009b2Sdrh   pNC->ncFlags &= ~NC_HasAgg;
12227d10d5a6Sdrh   w.xExprCallback = resolveExprStep;
12237d10d5a6Sdrh   w.xSelectCallback = resolveSelectStep;
12247d10d5a6Sdrh   w.pParse = pNC->pParse;
12257d10d5a6Sdrh   w.u.pNC = pNC;
12267d10d5a6Sdrh   sqlite3WalkExpr(&w, pExpr);
12277d10d5a6Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
12287d10d5a6Sdrh   pNC->pParse->nHeight -= pExpr->nHeight;
12297d10d5a6Sdrh #endif
1230fd773cf9Sdrh   if( pNC->nErr>0 || w.pParse->nErr>0 ){
12317d10d5a6Sdrh     ExprSetProperty(pExpr, EP_Error);
12327d10d5a6Sdrh   }
1233a51009b2Sdrh   if( pNC->ncFlags & NC_HasAgg ){
12347d10d5a6Sdrh     ExprSetProperty(pExpr, EP_Agg);
12357d10d5a6Sdrh   }else if( savedHasAgg ){
1236a51009b2Sdrh     pNC->ncFlags |= NC_HasAgg;
12377d10d5a6Sdrh   }
12387d10d5a6Sdrh   return ExprHasProperty(pExpr, EP_Error);
12397d10d5a6Sdrh }
12407d10d5a6Sdrh 
12417d10d5a6Sdrh 
12427d10d5a6Sdrh /*
12437d10d5a6Sdrh ** Resolve all names in all expressions of a SELECT and in all
12447d10d5a6Sdrh ** decendents of the SELECT, including compounds off of p->pPrior,
12457d10d5a6Sdrh ** subqueries in expressions, and subqueries used as FROM clause
12467d10d5a6Sdrh ** terms.
12477d10d5a6Sdrh **
12487d10d5a6Sdrh ** See sqlite3ResolveExprNames() for a description of the kinds of
12497d10d5a6Sdrh ** transformations that occur.
12507d10d5a6Sdrh **
12517d10d5a6Sdrh ** All SELECT statements should have been expanded using
12527d10d5a6Sdrh ** sqlite3SelectExpand() prior to invoking this routine.
12537d10d5a6Sdrh */
12547d10d5a6Sdrh void sqlite3ResolveSelectNames(
12557d10d5a6Sdrh   Parse *pParse,         /* The parser context */
12567d10d5a6Sdrh   Select *p,             /* The SELECT statement being coded. */
12577d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for parent SELECT statement */
12587d10d5a6Sdrh ){
12597d10d5a6Sdrh   Walker w;
12607d10d5a6Sdrh 
12610a846f96Sdrh   assert( p!=0 );
12627d10d5a6Sdrh   w.xExprCallback = resolveExprStep;
12637d10d5a6Sdrh   w.xSelectCallback = resolveSelectStep;
12647d10d5a6Sdrh   w.pParse = pParse;
12657d10d5a6Sdrh   w.u.pNC = pOuterNC;
12667d10d5a6Sdrh   sqlite3WalkSelect(&w, p);
12677d10d5a6Sdrh }
1268