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