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