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