xref: /sqlite-3.40.0/src/resolve.c (revision 48864df9)
1 /*
2 ** 2008 August 18
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 **
13 ** This file contains routines used for walking the parser tree and
14 ** resolve all identifiers by associating them with a particular
15 ** table and column.
16 */
17 #include "sqliteInt.h"
18 #include <stdlib.h>
19 #include <string.h>
20 
21 /*
22 ** Walk the expression tree pExpr and increase the aggregate function
23 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
24 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
25 ** outer query into an inner subquery.
26 **
27 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
28 ** is a helper function - a callback for the tree walker.
29 */
30 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
31   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
32   return WRC_Continue;
33 }
34 static void incrAggFunctionDepth(Expr *pExpr, int N){
35   if( N>0 ){
36     Walker w;
37     memset(&w, 0, sizeof(w));
38     w.xExprCallback = incrAggDepth;
39     w.u.i = N;
40     sqlite3WalkExpr(&w, pExpr);
41   }
42 }
43 
44 /*
45 ** Turn the pExpr expression into an alias for the iCol-th column of the
46 ** result set in pEList.
47 **
48 ** If the result set column is a simple column reference, then this routine
49 ** makes an exact copy.  But for any other kind of expression, this
50 ** routine make a copy of the result set column as the argument to the
51 ** TK_AS operator.  The TK_AS operator causes the expression to be
52 ** evaluated just once and then reused for each alias.
53 **
54 ** The reason for suppressing the TK_AS term when the expression is a simple
55 ** column reference is so that the column reference will be recognized as
56 ** usable by indices within the WHERE clause processing logic.
57 **
58 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
59 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
60 **
61 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
62 **
63 ** Is equivalent to:
64 **
65 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
66 **
67 ** The result of random()%5 in the GROUP BY clause is probably different
68 ** from the result in the result-set.  We might fix this someday.  Or
69 ** then again, we might not...
70 **
71 ** If the reference is followed by a COLLATE operator, then make sure
72 ** the COLLATE operator is preserved.  For example:
73 **
74 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
75 **
76 ** Should be transformed into:
77 **
78 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
79 **
80 ** The nSubquery parameter specifies how many levels of subquery the
81 ** alias is removed from the original expression.  The usually value is
82 ** zero but it might be more if the alias is contained within a subquery
83 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
84 ** structures must be increased by the nSubquery amount.
85 */
86 static void resolveAlias(
87   Parse *pParse,         /* Parsing context */
88   ExprList *pEList,      /* A result set */
89   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
90   Expr *pExpr,           /* Transform this into an alias to the result set */
91   const char *zType,     /* "GROUP" or "ORDER" or "" */
92   int nSubquery          /* Number of subqueries that the label is moving */
93 ){
94   Expr *pOrig;           /* The iCol-th column of the result set */
95   Expr *pDup;            /* Copy of pOrig */
96   sqlite3 *db;           /* The database connection */
97 
98   assert( iCol>=0 && iCol<pEList->nExpr );
99   pOrig = pEList->a[iCol].pExpr;
100   assert( pOrig!=0 );
101   assert( pOrig->flags & EP_Resolved );
102   db = pParse->db;
103   pDup = sqlite3ExprDup(db, pOrig, 0);
104   if( pDup==0 ) return;
105   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
106     incrAggFunctionDepth(pDup, nSubquery);
107     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
108     if( pDup==0 ) return;
109     if( pEList->a[iCol].iAlias==0 ){
110       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
111     }
112     pDup->iTable = pEList->a[iCol].iAlias;
113   }
114   if( pExpr->op==TK_COLLATE ){
115     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
116   }
117 
118   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
119   ** prevents ExprDelete() from deleting the Expr structure itself,
120   ** allowing it to be repopulated by the memcpy() on the following line.
121   ** The pExpr->u.zToken might point into memory that will be freed by the
122   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
123   ** make a copy of the token before doing the sqlite3DbFree().
124   */
125   ExprSetProperty(pExpr, EP_Static);
126   sqlite3ExprDelete(db, pExpr);
127   memcpy(pExpr, pDup, sizeof(*pExpr));
128   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
129     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
130     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
131     pExpr->flags2 |= EP2_MallocedToken;
132   }
133   sqlite3DbFree(db, pDup);
134 }
135 
136 
137 /*
138 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
139 **
140 ** Return FALSE if the USING clause is NULL or if it does not contain
141 ** zCol.
142 */
143 static int nameInUsingClause(IdList *pUsing, const char *zCol){
144   if( pUsing ){
145     int k;
146     for(k=0; k<pUsing->nId; k++){
147       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
148     }
149   }
150   return 0;
151 }
152 
153 /*
154 ** Subqueries stores the original database, table and column names for their
155 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
156 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
157 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
158 ** match anything.
159 */
160 int sqlite3MatchSpanName(
161   const char *zSpan,
162   const char *zCol,
163   const char *zTab,
164   const char *zDb
165 ){
166   int n;
167   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
168   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
169     return 0;
170   }
171   zSpan += n+1;
172   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
173   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
174     return 0;
175   }
176   zSpan += n+1;
177   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
178     return 0;
179   }
180   return 1;
181 }
182 
183 /*
184 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
185 ** that name in the set of source tables in pSrcList and make the pExpr
186 ** expression node refer back to that source column.  The following changes
187 ** are made to pExpr:
188 **
189 **    pExpr->iDb           Set the index in db->aDb[] of the database X
190 **                         (even if X is implied).
191 **    pExpr->iTable        Set to the cursor number for the table obtained
192 **                         from pSrcList.
193 **    pExpr->pTab          Points to the Table structure of X.Y (even if
194 **                         X and/or Y are implied.)
195 **    pExpr->iColumn       Set to the column number within the table.
196 **    pExpr->op            Set to TK_COLUMN.
197 **    pExpr->pLeft         Any expression this points to is deleted
198 **    pExpr->pRight        Any expression this points to is deleted.
199 **
200 ** The zDb variable is the name of the database (the "X").  This value may be
201 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
202 ** can be used.  The zTable variable is the name of the table (the "Y").  This
203 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
204 ** means that the form of the name is Z and that columns from any table
205 ** can be used.
206 **
207 ** If the name cannot be resolved unambiguously, leave an error message
208 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
209 */
210 static int lookupName(
211   Parse *pParse,       /* The parsing context */
212   const char *zDb,     /* Name of the database containing table, or NULL */
213   const char *zTab,    /* Name of table containing column, or NULL */
214   const char *zCol,    /* Name of the column. */
215   NameContext *pNC,    /* The name context used to resolve the name */
216   Expr *pExpr          /* Make this EXPR node point to the selected column */
217 ){
218   int i, j;                         /* Loop counters */
219   int cnt = 0;                      /* Number of matching column names */
220   int cntTab = 0;                   /* Number of matching table names */
221   int nSubquery = 0;                /* How many levels of subquery */
222   sqlite3 *db = pParse->db;         /* The database connection */
223   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
224   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
225   NameContext *pTopNC = pNC;        /* First namecontext in the list */
226   Schema *pSchema = 0;              /* Schema of the expression */
227   int isTrigger = 0;
228 
229   assert( pNC );     /* the name context cannot be NULL. */
230   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
231   assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
232 
233   /* Initialize the node to no-match */
234   pExpr->iTable = -1;
235   pExpr->pTab = 0;
236   ExprSetIrreducible(pExpr);
237 
238   /* Translate the schema name in zDb into a pointer to the corresponding
239   ** schema.  If not found, pSchema will remain NULL and nothing will match
240   ** resulting in an appropriate error message toward the end of this routine
241   */
242   if( zDb ){
243     for(i=0; i<db->nDb; i++){
244       assert( db->aDb[i].zName );
245       if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
246         pSchema = db->aDb[i].pSchema;
247         break;
248       }
249     }
250   }
251 
252   /* Start at the inner-most context and move outward until a match is found */
253   while( pNC && cnt==0 ){
254     ExprList *pEList;
255     SrcList *pSrcList = pNC->pSrcList;
256 
257     if( pSrcList ){
258       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
259         Table *pTab;
260         Column *pCol;
261 
262         pTab = pItem->pTab;
263         assert( pTab!=0 && pTab->zName!=0 );
264         assert( pTab->nCol>0 );
265         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
266           int hit = 0;
267           pEList = pItem->pSelect->pEList;
268           for(j=0; j<pEList->nExpr; j++){
269             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
270               cnt++;
271               cntTab = 2;
272               pMatch = pItem;
273               pExpr->iColumn = j;
274               hit = 1;
275             }
276           }
277           if( hit || zTab==0 ) continue;
278         }
279         if( zDb && pTab->pSchema!=pSchema ){
280           continue;
281         }
282         if( zTab ){
283           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
284           assert( zTabName!=0 );
285           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
286             continue;
287           }
288         }
289         if( 0==(cntTab++) ){
290           pMatch = pItem;
291         }
292         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
293           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
294             /* If there has been exactly one prior match and this match
295             ** is for the right-hand table of a NATURAL JOIN or is in a
296             ** USING clause, then skip this match.
297             */
298             if( cnt==1 ){
299               if( pItem->jointype & JT_NATURAL ) continue;
300               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
301             }
302             cnt++;
303             pMatch = pItem;
304             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
305             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
306             break;
307           }
308         }
309       }
310       if( pMatch ){
311         pExpr->iTable = pMatch->iCursor;
312         pExpr->pTab = pMatch->pTab;
313         pSchema = pExpr->pTab->pSchema;
314       }
315     } /* if( pSrcList ) */
316 
317 #ifndef SQLITE_OMIT_TRIGGER
318     /* If we have not already resolved the name, then maybe
319     ** it is a new.* or old.* trigger argument reference
320     */
321     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
322       int op = pParse->eTriggerOp;
323       Table *pTab = 0;
324       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
325       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
326         pExpr->iTable = 1;
327         pTab = pParse->pTriggerTab;
328       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
329         pExpr->iTable = 0;
330         pTab = pParse->pTriggerTab;
331       }
332 
333       if( pTab ){
334         int iCol;
335         pSchema = pTab->pSchema;
336         cntTab++;
337         for(iCol=0; iCol<pTab->nCol; iCol++){
338           Column *pCol = &pTab->aCol[iCol];
339           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
340             if( iCol==pTab->iPKey ){
341               iCol = -1;
342             }
343             break;
344           }
345         }
346         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
347           iCol = -1;        /* IMP: R-44911-55124 */
348         }
349         if( iCol<pTab->nCol ){
350           cnt++;
351           if( iCol<0 ){
352             pExpr->affinity = SQLITE_AFF_INTEGER;
353           }else if( pExpr->iTable==0 ){
354             testcase( iCol==31 );
355             testcase( iCol==32 );
356             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
357           }else{
358             testcase( iCol==31 );
359             testcase( iCol==32 );
360             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
361           }
362           pExpr->iColumn = (i16)iCol;
363           pExpr->pTab = pTab;
364           isTrigger = 1;
365         }
366       }
367     }
368 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
369 
370     /*
371     ** Perhaps the name is a reference to the ROWID
372     */
373     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
374       cnt = 1;
375       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
376       pExpr->affinity = SQLITE_AFF_INTEGER;
377     }
378 
379     /*
380     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
381     ** might refer to an result-set alias.  This happens, for example, when
382     ** we are resolving names in the WHERE clause of the following command:
383     **
384     **     SELECT a+b AS x FROM table WHERE x<10;
385     **
386     ** In cases like this, replace pExpr with a copy of the expression that
387     ** forms the result set entry ("a+b" in the example) and return immediately.
388     ** Note that the expression in the result set should have already been
389     ** resolved by the time the WHERE clause is resolved.
390     */
391     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
392       for(j=0; j<pEList->nExpr; j++){
393         char *zAs = pEList->a[j].zName;
394         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
395           Expr *pOrig;
396           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
397           assert( pExpr->x.pList==0 );
398           assert( pExpr->x.pSelect==0 );
399           pOrig = pEList->a[j].pExpr;
400           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
401             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
402             return WRC_Abort;
403           }
404           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
405           cnt = 1;
406           pMatch = 0;
407           assert( zTab==0 && zDb==0 );
408           goto lookupname_end;
409         }
410       }
411     }
412 
413     /* Advance to the next name context.  The loop will exit when either
414     ** we have a match (cnt>0) or when we run out of name contexts.
415     */
416     if( cnt==0 ){
417       pNC = pNC->pNext;
418       nSubquery++;
419     }
420   }
421 
422   /*
423   ** If X and Y are NULL (in other words if only the column name Z is
424   ** supplied) and the value of Z is enclosed in double-quotes, then
425   ** Z is a string literal if it doesn't match any column names.  In that
426   ** case, we need to return right away and not make any changes to
427   ** pExpr.
428   **
429   ** Because no reference was made to outer contexts, the pNC->nRef
430   ** fields are not changed in any context.
431   */
432   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
433     pExpr->op = TK_STRING;
434     pExpr->pTab = 0;
435     return WRC_Prune;
436   }
437 
438   /*
439   ** cnt==0 means there was not match.  cnt>1 means there were two or
440   ** more matches.  Either way, we have an error.
441   */
442   if( cnt!=1 ){
443     const char *zErr;
444     zErr = cnt==0 ? "no such column" : "ambiguous column name";
445     if( zDb ){
446       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
447     }else if( zTab ){
448       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
449     }else{
450       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
451     }
452     pParse->checkSchema = 1;
453     pTopNC->nErr++;
454   }
455 
456   /* If a column from a table in pSrcList is referenced, then record
457   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
458   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
459   ** column number is greater than the number of bits in the bitmask
460   ** then set the high-order bit of the bitmask.
461   */
462   if( pExpr->iColumn>=0 && pMatch!=0 ){
463     int n = pExpr->iColumn;
464     testcase( n==BMS-1 );
465     if( n>=BMS ){
466       n = BMS-1;
467     }
468     assert( pMatch->iCursor==pExpr->iTable );
469     pMatch->colUsed |= ((Bitmask)1)<<n;
470   }
471 
472   /* Clean up and return
473   */
474   sqlite3ExprDelete(db, pExpr->pLeft);
475   pExpr->pLeft = 0;
476   sqlite3ExprDelete(db, pExpr->pRight);
477   pExpr->pRight = 0;
478   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
479 lookupname_end:
480   if( cnt==1 ){
481     assert( pNC!=0 );
482     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
483     /* Increment the nRef value on all name contexts from TopNC up to
484     ** the point where the name matched. */
485     for(;;){
486       assert( pTopNC!=0 );
487       pTopNC->nRef++;
488       if( pTopNC==pNC ) break;
489       pTopNC = pTopNC->pNext;
490     }
491     return WRC_Prune;
492   } else {
493     return WRC_Abort;
494   }
495 }
496 
497 /*
498 ** Allocate and return a pointer to an expression to load the column iCol
499 ** from datasource iSrc in SrcList pSrc.
500 */
501 Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
502   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
503   if( p ){
504     struct SrcList_item *pItem = &pSrc->a[iSrc];
505     p->pTab = pItem->pTab;
506     p->iTable = pItem->iCursor;
507     if( p->pTab->iPKey==iCol ){
508       p->iColumn = -1;
509     }else{
510       p->iColumn = (ynVar)iCol;
511       testcase( iCol==BMS );
512       testcase( iCol==BMS-1 );
513       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
514     }
515     ExprSetProperty(p, EP_Resolved);
516   }
517   return p;
518 }
519 
520 /*
521 ** This routine is callback for sqlite3WalkExpr().
522 **
523 ** Resolve symbolic names into TK_COLUMN operators for the current
524 ** node in the expression tree.  Return 0 to continue the search down
525 ** the tree or 2 to abort the tree walk.
526 **
527 ** This routine also does error checking and name resolution for
528 ** function names.  The operator for aggregate functions is changed
529 ** to TK_AGG_FUNCTION.
530 */
531 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
532   NameContext *pNC;
533   Parse *pParse;
534 
535   pNC = pWalker->u.pNC;
536   assert( pNC!=0 );
537   pParse = pNC->pParse;
538   assert( pParse==pWalker->pParse );
539 
540   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
541   ExprSetProperty(pExpr, EP_Resolved);
542 #ifndef NDEBUG
543   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
544     SrcList *pSrcList = pNC->pSrcList;
545     int i;
546     for(i=0; i<pNC->pSrcList->nSrc; i++){
547       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
548     }
549   }
550 #endif
551   switch( pExpr->op ){
552 
553 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
554     /* The special operator TK_ROW means use the rowid for the first
555     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
556     ** clause processing on UPDATE and DELETE statements.
557     */
558     case TK_ROW: {
559       SrcList *pSrcList = pNC->pSrcList;
560       struct SrcList_item *pItem;
561       assert( pSrcList && pSrcList->nSrc==1 );
562       pItem = pSrcList->a;
563       pExpr->op = TK_COLUMN;
564       pExpr->pTab = pItem->pTab;
565       pExpr->iTable = pItem->iCursor;
566       pExpr->iColumn = -1;
567       pExpr->affinity = SQLITE_AFF_INTEGER;
568       break;
569     }
570 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
571 
572     /* A lone identifier is the name of a column.
573     */
574     case TK_ID: {
575       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
576     }
577 
578     /* A table name and column name:     ID.ID
579     ** Or a database, table and column:  ID.ID.ID
580     */
581     case TK_DOT: {
582       const char *zColumn;
583       const char *zTable;
584       const char *zDb;
585       Expr *pRight;
586 
587       /* if( pSrcList==0 ) break; */
588       pRight = pExpr->pRight;
589       if( pRight->op==TK_ID ){
590         zDb = 0;
591         zTable = pExpr->pLeft->u.zToken;
592         zColumn = pRight->u.zToken;
593       }else{
594         assert( pRight->op==TK_DOT );
595         zDb = pExpr->pLeft->u.zToken;
596         zTable = pRight->pLeft->u.zToken;
597         zColumn = pRight->pRight->u.zToken;
598       }
599       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
600     }
601 
602     /* Resolve function names
603     */
604     case TK_CONST_FUNC:
605     case TK_FUNCTION: {
606       ExprList *pList = pExpr->x.pList;    /* The argument list */
607       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
608       int no_such_func = 0;       /* True if no such function exists */
609       int wrong_num_args = 0;     /* True if wrong number of arguments */
610       int is_agg = 0;             /* True if is an aggregate function */
611       int auth;                   /* Authorization to use the function */
612       int nId;                    /* Number of characters in function name */
613       const char *zId;            /* The function name. */
614       FuncDef *pDef;              /* Information about the function */
615       u8 enc = ENC(pParse->db);   /* The database encoding */
616 
617       testcase( pExpr->op==TK_CONST_FUNC );
618       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
619       zId = pExpr->u.zToken;
620       nId = sqlite3Strlen30(zId);
621       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
622       if( pDef==0 ){
623         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
624         if( pDef==0 ){
625           no_such_func = 1;
626         }else{
627           wrong_num_args = 1;
628         }
629       }else{
630         is_agg = pDef->xFunc==0;
631       }
632 #ifndef SQLITE_OMIT_AUTHORIZATION
633       if( pDef ){
634         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
635         if( auth!=SQLITE_OK ){
636           if( auth==SQLITE_DENY ){
637             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
638                                     pDef->zName);
639             pNC->nErr++;
640           }
641           pExpr->op = TK_NULL;
642           return WRC_Prune;
643         }
644       }
645 #endif
646       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
647         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
648         pNC->nErr++;
649         is_agg = 0;
650       }else if( no_such_func && pParse->db->init.busy==0 ){
651         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
652         pNC->nErr++;
653       }else if( wrong_num_args ){
654         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
655              nId, zId);
656         pNC->nErr++;
657       }
658       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
659       sqlite3WalkExprList(pWalker, pList);
660       if( is_agg ){
661         NameContext *pNC2 = pNC;
662         pExpr->op = TK_AGG_FUNCTION;
663         pExpr->op2 = 0;
664         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
665           pExpr->op2++;
666           pNC2 = pNC2->pNext;
667         }
668         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
669         pNC->ncFlags |= NC_AllowAgg;
670       }
671       /* FIX ME:  Compute pExpr->affinity based on the expected return
672       ** type of the function
673       */
674       return WRC_Prune;
675     }
676 #ifndef SQLITE_OMIT_SUBQUERY
677     case TK_SELECT:
678     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
679 #endif
680     case TK_IN: {
681       testcase( pExpr->op==TK_IN );
682       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
683         int nRef = pNC->nRef;
684 #ifndef SQLITE_OMIT_CHECK
685         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
686           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
687         }
688 #endif
689         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
690         assert( pNC->nRef>=nRef );
691         if( nRef!=pNC->nRef ){
692           ExprSetProperty(pExpr, EP_VarSelect);
693         }
694       }
695       break;
696     }
697 #ifndef SQLITE_OMIT_CHECK
698     case TK_VARIABLE: {
699       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
700         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
701       }
702       break;
703     }
704 #endif
705   }
706   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
707 }
708 
709 /*
710 ** pEList is a list of expressions which are really the result set of the
711 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
712 ** This routine checks to see if pE is a simple identifier which corresponds
713 ** to the AS-name of one of the terms of the expression list.  If it is,
714 ** this routine return an integer between 1 and N where N is the number of
715 ** elements in pEList, corresponding to the matching entry.  If there is
716 ** no match, or if pE is not a simple identifier, then this routine
717 ** return 0.
718 **
719 ** pEList has been resolved.  pE has not.
720 */
721 static int resolveAsName(
722   Parse *pParse,     /* Parsing context for error messages */
723   ExprList *pEList,  /* List of expressions to scan */
724   Expr *pE           /* Expression we are trying to match */
725 ){
726   int i;             /* Loop counter */
727 
728   UNUSED_PARAMETER(pParse);
729 
730   if( pE->op==TK_ID ){
731     char *zCol = pE->u.zToken;
732     for(i=0; i<pEList->nExpr; i++){
733       char *zAs = pEList->a[i].zName;
734       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
735         return i+1;
736       }
737     }
738   }
739   return 0;
740 }
741 
742 /*
743 ** pE is a pointer to an expression which is a single term in the
744 ** ORDER BY of a compound SELECT.  The expression has not been
745 ** name resolved.
746 **
747 ** At the point this routine is called, we already know that the
748 ** ORDER BY term is not an integer index into the result set.  That
749 ** case is handled by the calling routine.
750 **
751 ** Attempt to match pE against result set columns in the left-most
752 ** SELECT statement.  Return the index i of the matching column,
753 ** as an indication to the caller that it should sort by the i-th column.
754 ** The left-most column is 1.  In other words, the value returned is the
755 ** same integer value that would be used in the SQL statement to indicate
756 ** the column.
757 **
758 ** If there is no match, return 0.  Return -1 if an error occurs.
759 */
760 static int resolveOrderByTermToExprList(
761   Parse *pParse,     /* Parsing context for error messages */
762   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
763   Expr *pE           /* The specific ORDER BY term */
764 ){
765   int i;             /* Loop counter */
766   ExprList *pEList;  /* The columns of the result set */
767   NameContext nc;    /* Name context for resolving pE */
768   sqlite3 *db;       /* Database connection */
769   int rc;            /* Return code from subprocedures */
770   u8 savedSuppErr;   /* Saved value of db->suppressErr */
771 
772   assert( sqlite3ExprIsInteger(pE, &i)==0 );
773   pEList = pSelect->pEList;
774 
775   /* Resolve all names in the ORDER BY term expression
776   */
777   memset(&nc, 0, sizeof(nc));
778   nc.pParse = pParse;
779   nc.pSrcList = pSelect->pSrc;
780   nc.pEList = pEList;
781   nc.ncFlags = NC_AllowAgg;
782   nc.nErr = 0;
783   db = pParse->db;
784   savedSuppErr = db->suppressErr;
785   db->suppressErr = 1;
786   rc = sqlite3ResolveExprNames(&nc, pE);
787   db->suppressErr = savedSuppErr;
788   if( rc ) return 0;
789 
790   /* Try to match the ORDER BY expression against an expression
791   ** in the result set.  Return an 1-based index of the matching
792   ** result-set entry.
793   */
794   for(i=0; i<pEList->nExpr; i++){
795     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
796       return i+1;
797     }
798   }
799 
800   /* If no match, return 0. */
801   return 0;
802 }
803 
804 /*
805 ** Generate an ORDER BY or GROUP BY term out-of-range error.
806 */
807 static void resolveOutOfRangeError(
808   Parse *pParse,         /* The error context into which to write the error */
809   const char *zType,     /* "ORDER" or "GROUP" */
810   int i,                 /* The index (1-based) of the term out of range */
811   int mx                 /* Largest permissible value of i */
812 ){
813   sqlite3ErrorMsg(pParse,
814     "%r %s BY term out of range - should be "
815     "between 1 and %d", i, zType, mx);
816 }
817 
818 /*
819 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
820 ** each term of the ORDER BY clause is a constant integer between 1
821 ** and N where N is the number of columns in the compound SELECT.
822 **
823 ** ORDER BY terms that are already an integer between 1 and N are
824 ** unmodified.  ORDER BY terms that are integers outside the range of
825 ** 1 through N generate an error.  ORDER BY terms that are expressions
826 ** are matched against result set expressions of compound SELECT
827 ** beginning with the left-most SELECT and working toward the right.
828 ** At the first match, the ORDER BY expression is transformed into
829 ** the integer column number.
830 **
831 ** Return the number of errors seen.
832 */
833 static int resolveCompoundOrderBy(
834   Parse *pParse,        /* Parsing context.  Leave error messages here */
835   Select *pSelect       /* The SELECT statement containing the ORDER BY */
836 ){
837   int i;
838   ExprList *pOrderBy;
839   ExprList *pEList;
840   sqlite3 *db;
841   int moreToDo = 1;
842 
843   pOrderBy = pSelect->pOrderBy;
844   if( pOrderBy==0 ) return 0;
845   db = pParse->db;
846 #if SQLITE_MAX_COLUMN
847   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
848     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
849     return 1;
850   }
851 #endif
852   for(i=0; i<pOrderBy->nExpr; i++){
853     pOrderBy->a[i].done = 0;
854   }
855   pSelect->pNext = 0;
856   while( pSelect->pPrior ){
857     pSelect->pPrior->pNext = pSelect;
858     pSelect = pSelect->pPrior;
859   }
860   while( pSelect && moreToDo ){
861     struct ExprList_item *pItem;
862     moreToDo = 0;
863     pEList = pSelect->pEList;
864     assert( pEList!=0 );
865     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
866       int iCol = -1;
867       Expr *pE, *pDup;
868       if( pItem->done ) continue;
869       pE = sqlite3ExprSkipCollate(pItem->pExpr);
870       if( sqlite3ExprIsInteger(pE, &iCol) ){
871         if( iCol<=0 || iCol>pEList->nExpr ){
872           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
873           return 1;
874         }
875       }else{
876         iCol = resolveAsName(pParse, pEList, pE);
877         if( iCol==0 ){
878           pDup = sqlite3ExprDup(db, pE, 0);
879           if( !db->mallocFailed ){
880             assert(pDup);
881             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
882           }
883           sqlite3ExprDelete(db, pDup);
884         }
885       }
886       if( iCol>0 ){
887         /* Convert the ORDER BY term into an integer column number iCol,
888         ** taking care to preserve the COLLATE clause if it exists */
889         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
890         if( pNew==0 ) return 1;
891         pNew->flags |= EP_IntValue;
892         pNew->u.iValue = iCol;
893         if( pItem->pExpr==pE ){
894           pItem->pExpr = pNew;
895         }else{
896           assert( pItem->pExpr->op==TK_COLLATE );
897           assert( pItem->pExpr->pLeft==pE );
898           pItem->pExpr->pLeft = pNew;
899         }
900         sqlite3ExprDelete(db, pE);
901         pItem->iOrderByCol = (u16)iCol;
902         pItem->done = 1;
903       }else{
904         moreToDo = 1;
905       }
906     }
907     pSelect = pSelect->pNext;
908   }
909   for(i=0; i<pOrderBy->nExpr; i++){
910     if( pOrderBy->a[i].done==0 ){
911       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
912             "column in the result set", i+1);
913       return 1;
914     }
915   }
916   return 0;
917 }
918 
919 /*
920 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
921 ** the SELECT statement pSelect.  If any term is reference to a
922 ** result set expression (as determined by the ExprList.a.iCol field)
923 ** then convert that term into a copy of the corresponding result set
924 ** column.
925 **
926 ** If any errors are detected, add an error message to pParse and
927 ** return non-zero.  Return zero if no errors are seen.
928 */
929 int sqlite3ResolveOrderGroupBy(
930   Parse *pParse,        /* Parsing context.  Leave error messages here */
931   Select *pSelect,      /* The SELECT statement containing the clause */
932   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
933   const char *zType     /* "ORDER" or "GROUP" */
934 ){
935   int i;
936   sqlite3 *db = pParse->db;
937   ExprList *pEList;
938   struct ExprList_item *pItem;
939 
940   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
941 #if SQLITE_MAX_COLUMN
942   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
943     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
944     return 1;
945   }
946 #endif
947   pEList = pSelect->pEList;
948   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
949   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
950     if( pItem->iOrderByCol ){
951       if( pItem->iOrderByCol>pEList->nExpr ){
952         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
953         return 1;
954       }
955       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
956     }
957   }
958   return 0;
959 }
960 
961 /*
962 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
963 ** The Name context of the SELECT statement is pNC.  zType is either
964 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
965 **
966 ** This routine resolves each term of the clause into an expression.
967 ** If the order-by term is an integer I between 1 and N (where N is the
968 ** number of columns in the result set of the SELECT) then the expression
969 ** in the resolution is a copy of the I-th result-set expression.  If
970 ** the order-by term is an identify that corresponds to the AS-name of
971 ** a result-set expression, then the term resolves to a copy of the
972 ** result-set expression.  Otherwise, the expression is resolved in
973 ** the usual way - using sqlite3ResolveExprNames().
974 **
975 ** This routine returns the number of errors.  If errors occur, then
976 ** an appropriate error message might be left in pParse.  (OOM errors
977 ** excepted.)
978 */
979 static int resolveOrderGroupBy(
980   NameContext *pNC,     /* The name context of the SELECT statement */
981   Select *pSelect,      /* The SELECT statement holding pOrderBy */
982   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
983   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
984 ){
985   int i, j;                      /* Loop counters */
986   int iCol;                      /* Column number */
987   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
988   Parse *pParse;                 /* Parsing context */
989   int nResult;                   /* Number of terms in the result set */
990 
991   if( pOrderBy==0 ) return 0;
992   nResult = pSelect->pEList->nExpr;
993   pParse = pNC->pParse;
994   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
995     Expr *pE = pItem->pExpr;
996     iCol = resolveAsName(pParse, pSelect->pEList, pE);
997     if( iCol>0 ){
998       /* If an AS-name match is found, mark this ORDER BY column as being
999       ** a copy of the iCol-th result-set column.  The subsequent call to
1000       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1001       ** copy of the iCol-th result-set expression. */
1002       pItem->iOrderByCol = (u16)iCol;
1003       continue;
1004     }
1005     if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
1006       /* The ORDER BY term is an integer constant.  Again, set the column
1007       ** number so that sqlite3ResolveOrderGroupBy() will convert the
1008       ** order-by term to a copy of the result-set expression */
1009       if( iCol<1 || iCol>0xffff ){
1010         resolveOutOfRangeError(pParse, zType, i+1, nResult);
1011         return 1;
1012       }
1013       pItem->iOrderByCol = (u16)iCol;
1014       continue;
1015     }
1016 
1017     /* Otherwise, treat the ORDER BY term as an ordinary expression */
1018     pItem->iOrderByCol = 0;
1019     if( sqlite3ResolveExprNames(pNC, pE) ){
1020       return 1;
1021     }
1022     for(j=0; j<pSelect->pEList->nExpr; j++){
1023       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
1024         pItem->iOrderByCol = j+1;
1025       }
1026     }
1027   }
1028   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1029 }
1030 
1031 /*
1032 ** Resolve names in the SELECT statement p and all of its descendents.
1033 */
1034 static int resolveSelectStep(Walker *pWalker, Select *p){
1035   NameContext *pOuterNC;  /* Context that contains this SELECT */
1036   NameContext sNC;        /* Name context of this SELECT */
1037   int isCompound;         /* True if p is a compound select */
1038   int nCompound;          /* Number of compound terms processed so far */
1039   Parse *pParse;          /* Parsing context */
1040   ExprList *pEList;       /* Result set expression list */
1041   int i;                  /* Loop counter */
1042   ExprList *pGroupBy;     /* The GROUP BY clause */
1043   Select *pLeftmost;      /* Left-most of SELECT of a compound */
1044   sqlite3 *db;            /* Database connection */
1045 
1046 
1047   assert( p!=0 );
1048   if( p->selFlags & SF_Resolved ){
1049     return WRC_Prune;
1050   }
1051   pOuterNC = pWalker->u.pNC;
1052   pParse = pWalker->pParse;
1053   db = pParse->db;
1054 
1055   /* Normally sqlite3SelectExpand() will be called first and will have
1056   ** already expanded this SELECT.  However, if this is a subquery within
1057   ** an expression, sqlite3ResolveExprNames() will be called without a
1058   ** prior call to sqlite3SelectExpand().  When that happens, let
1059   ** sqlite3SelectPrep() do all of the processing for this SELECT.
1060   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1061   ** this routine in the correct order.
1062   */
1063   if( (p->selFlags & SF_Expanded)==0 ){
1064     sqlite3SelectPrep(pParse, p, pOuterNC);
1065     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1066   }
1067 
1068   isCompound = p->pPrior!=0;
1069   nCompound = 0;
1070   pLeftmost = p;
1071   while( p ){
1072     assert( (p->selFlags & SF_Expanded)!=0 );
1073     assert( (p->selFlags & SF_Resolved)==0 );
1074     p->selFlags |= SF_Resolved;
1075 
1076     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1077     ** are not allowed to refer to any names, so pass an empty NameContext.
1078     */
1079     memset(&sNC, 0, sizeof(sNC));
1080     sNC.pParse = pParse;
1081     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1082         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1083       return WRC_Abort;
1084     }
1085 
1086     /* Recursively resolve names in all subqueries
1087     */
1088     for(i=0; i<p->pSrc->nSrc; i++){
1089       struct SrcList_item *pItem = &p->pSrc->a[i];
1090       if( pItem->pSelect ){
1091         NameContext *pNC;         /* Used to iterate name contexts */
1092         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
1093         const char *zSavedContext = pParse->zAuthContext;
1094 
1095         /* Count the total number of references to pOuterNC and all of its
1096         ** parent contexts. After resolving references to expressions in
1097         ** pItem->pSelect, check if this value has changed. If so, then
1098         ** SELECT statement pItem->pSelect must be correlated. Set the
1099         ** pItem->isCorrelated flag if this is the case. */
1100         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1101 
1102         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1103         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
1104         pParse->zAuthContext = zSavedContext;
1105         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
1106 
1107         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1108         assert( pItem->isCorrelated==0 && nRef<=0 );
1109         pItem->isCorrelated = (nRef!=0);
1110       }
1111     }
1112 
1113     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1114     ** resolve the result-set expression list.
1115     */
1116     sNC.ncFlags = NC_AllowAgg;
1117     sNC.pSrcList = p->pSrc;
1118     sNC.pNext = pOuterNC;
1119 
1120     /* Resolve names in the result set. */
1121     pEList = p->pEList;
1122     assert( pEList!=0 );
1123     for(i=0; i<pEList->nExpr; i++){
1124       Expr *pX = pEList->a[i].pExpr;
1125       if( sqlite3ResolveExprNames(&sNC, pX) ){
1126         return WRC_Abort;
1127       }
1128     }
1129 
1130     /* If there are no aggregate functions in the result-set, and no GROUP BY
1131     ** expression, do not allow aggregates in any of the other expressions.
1132     */
1133     assert( (p->selFlags & SF_Aggregate)==0 );
1134     pGroupBy = p->pGroupBy;
1135     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
1136       p->selFlags |= SF_Aggregate;
1137     }else{
1138       sNC.ncFlags &= ~NC_AllowAgg;
1139     }
1140 
1141     /* If a HAVING clause is present, then there must be a GROUP BY clause.
1142     */
1143     if( p->pHaving && !pGroupBy ){
1144       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1145       return WRC_Abort;
1146     }
1147 
1148     /* Add the expression list to the name-context before parsing the
1149     ** other expressions in the SELECT statement. This is so that
1150     ** expressions in the WHERE clause (etc.) can refer to expressions by
1151     ** aliases in the result set.
1152     **
1153     ** Minor point: If this is the case, then the expression will be
1154     ** re-evaluated for each reference to it.
1155     */
1156     sNC.pEList = p->pEList;
1157     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1158        sqlite3ResolveExprNames(&sNC, p->pHaving)
1159     ){
1160       return WRC_Abort;
1161     }
1162 
1163     /* The ORDER BY and GROUP BY clauses may not refer to terms in
1164     ** outer queries
1165     */
1166     sNC.pNext = 0;
1167     sNC.ncFlags |= NC_AllowAgg;
1168 
1169     /* Process the ORDER BY clause for singleton SELECT statements.
1170     ** The ORDER BY clause for compounds SELECT statements is handled
1171     ** below, after all of the result-sets for all of the elements of
1172     ** the compound have been resolved.
1173     */
1174     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1175       return WRC_Abort;
1176     }
1177     if( db->mallocFailed ){
1178       return WRC_Abort;
1179     }
1180 
1181     /* Resolve the GROUP BY clause.  At the same time, make sure
1182     ** the GROUP BY clause does not contain aggregate functions.
1183     */
1184     if( pGroupBy ){
1185       struct ExprList_item *pItem;
1186 
1187       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1188         return WRC_Abort;
1189       }
1190       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1191         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1192           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1193               "the GROUP BY clause");
1194           return WRC_Abort;
1195         }
1196       }
1197     }
1198 
1199     /* Advance to the next term of the compound
1200     */
1201     p = p->pPrior;
1202     nCompound++;
1203   }
1204 
1205   /* Resolve the ORDER BY on a compound SELECT after all terms of
1206   ** the compound have been resolved.
1207   */
1208   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1209     return WRC_Abort;
1210   }
1211 
1212   return WRC_Prune;
1213 }
1214 
1215 /*
1216 ** This routine walks an expression tree and resolves references to
1217 ** table columns and result-set columns.  At the same time, do error
1218 ** checking on function usage and set a flag if any aggregate functions
1219 ** are seen.
1220 **
1221 ** To resolve table columns references we look for nodes (or subtrees) of the
1222 ** form X.Y.Z or Y.Z or just Z where
1223 **
1224 **      X:   The name of a database.  Ex:  "main" or "temp" or
1225 **           the symbolic name assigned to an ATTACH-ed database.
1226 **
1227 **      Y:   The name of a table in a FROM clause.  Or in a trigger
1228 **           one of the special names "old" or "new".
1229 **
1230 **      Z:   The name of a column in table Y.
1231 **
1232 ** The node at the root of the subtree is modified as follows:
1233 **
1234 **    Expr.op        Changed to TK_COLUMN
1235 **    Expr.pTab      Points to the Table object for X.Y
1236 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
1237 **    Expr.iTable    The VDBE cursor number for X.Y
1238 **
1239 **
1240 ** To resolve result-set references, look for expression nodes of the
1241 ** form Z (with no X and Y prefix) where the Z matches the right-hand
1242 ** size of an AS clause in the result-set of a SELECT.  The Z expression
1243 ** is replaced by a copy of the left-hand side of the result-set expression.
1244 ** Table-name and function resolution occurs on the substituted expression
1245 ** tree.  For example, in:
1246 **
1247 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1248 **
1249 ** The "x" term of the order by is replaced by "a+b" to render:
1250 **
1251 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1252 **
1253 ** Function calls are checked to make sure that the function is
1254 ** defined and that the correct number of arguments are specified.
1255 ** If the function is an aggregate function, then the NC_HasAgg flag is
1256 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1257 ** If an expression contains aggregate functions then the EP_Agg
1258 ** property on the expression is set.
1259 **
1260 ** An error message is left in pParse if anything is amiss.  The number
1261 ** if errors is returned.
1262 */
1263 int sqlite3ResolveExprNames(
1264   NameContext *pNC,       /* Namespace to resolve expressions in. */
1265   Expr *pExpr             /* The expression to be analyzed. */
1266 ){
1267   u8 savedHasAgg;
1268   Walker w;
1269 
1270   if( pExpr==0 ) return 0;
1271 #if SQLITE_MAX_EXPR_DEPTH>0
1272   {
1273     Parse *pParse = pNC->pParse;
1274     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1275       return 1;
1276     }
1277     pParse->nHeight += pExpr->nHeight;
1278   }
1279 #endif
1280   savedHasAgg = pNC->ncFlags & NC_HasAgg;
1281   pNC->ncFlags &= ~NC_HasAgg;
1282   w.xExprCallback = resolveExprStep;
1283   w.xSelectCallback = resolveSelectStep;
1284   w.pParse = pNC->pParse;
1285   w.u.pNC = pNC;
1286   sqlite3WalkExpr(&w, pExpr);
1287 #if SQLITE_MAX_EXPR_DEPTH>0
1288   pNC->pParse->nHeight -= pExpr->nHeight;
1289 #endif
1290   if( pNC->nErr>0 || w.pParse->nErr>0 ){
1291     ExprSetProperty(pExpr, EP_Error);
1292   }
1293   if( pNC->ncFlags & NC_HasAgg ){
1294     ExprSetProperty(pExpr, EP_Agg);
1295   }else if( savedHasAgg ){
1296     pNC->ncFlags |= NC_HasAgg;
1297   }
1298   return ExprHasProperty(pExpr, EP_Error);
1299 }
1300 
1301 
1302 /*
1303 ** Resolve all names in all expressions of a SELECT and in all
1304 ** decendents of the SELECT, including compounds off of p->pPrior,
1305 ** subqueries in expressions, and subqueries used as FROM clause
1306 ** terms.
1307 **
1308 ** See sqlite3ResolveExprNames() for a description of the kinds of
1309 ** transformations that occur.
1310 **
1311 ** All SELECT statements should have been expanded using
1312 ** sqlite3SelectExpand() prior to invoking this routine.
1313 */
1314 void sqlite3ResolveSelectNames(
1315   Parse *pParse,         /* The parser context */
1316   Select *p,             /* The SELECT statement being coded. */
1317   NameContext *pOuterNC  /* Name context for parent SELECT statement */
1318 ){
1319   Walker w;
1320 
1321   assert( p!=0 );
1322   w.xExprCallback = resolveExprStep;
1323   w.xSelectCallback = resolveSelectStep;
1324   w.pParse = pParse;
1325   w.u.pNC = pOuterNC;
1326   sqlite3WalkSelect(&w, p);
1327 }
1328