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