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