xref: /sqlite-3.40.0/src/resolve.c (revision e099b67c)
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, n, enc, 0);
660       if( pDef==0 ){
661         pDef = sqlite3FindFunction(pParse->db, zId, -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 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
723                 && pParse->explain==0
724 #endif
725       ){
726         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
727         pNC->nErr++;
728       }else if( wrong_num_args ){
729         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
730              nId, zId);
731         pNC->nErr++;
732       }
733       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
734       sqlite3WalkExprList(pWalker, pList);
735       if( is_agg ){
736         NameContext *pNC2 = pNC;
737         pExpr->op = TK_AGG_FUNCTION;
738         pExpr->op2 = 0;
739         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
740           pExpr->op2++;
741           pNC2 = pNC2->pNext;
742         }
743         assert( pDef!=0 );
744         if( pNC2 ){
745           assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
746           testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
747           pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
748 
749         }
750         pNC->ncFlags |= NC_AllowAgg;
751       }
752       /* FIX ME:  Compute pExpr->affinity based on the expected return
753       ** type of the function
754       */
755       return WRC_Prune;
756     }
757 #ifndef SQLITE_OMIT_SUBQUERY
758     case TK_SELECT:
759     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
760 #endif
761     case TK_IN: {
762       testcase( pExpr->op==TK_IN );
763       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
764         int nRef = pNC->nRef;
765         notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
766         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
767         assert( pNC->nRef>=nRef );
768         if( nRef!=pNC->nRef ){
769           ExprSetProperty(pExpr, EP_VarSelect);
770           pNC->ncFlags |= NC_VarSelect;
771         }
772       }
773       break;
774     }
775     case TK_VARIABLE: {
776       notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
777       break;
778     }
779   }
780   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
781 }
782 
783 /*
784 ** pEList is a list of expressions which are really the result set of the
785 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
786 ** This routine checks to see if pE is a simple identifier which corresponds
787 ** to the AS-name of one of the terms of the expression list.  If it is,
788 ** this routine return an integer between 1 and N where N is the number of
789 ** elements in pEList, corresponding to the matching entry.  If there is
790 ** no match, or if pE is not a simple identifier, then this routine
791 ** return 0.
792 **
793 ** pEList has been resolved.  pE has not.
794 */
795 static int resolveAsName(
796   Parse *pParse,     /* Parsing context for error messages */
797   ExprList *pEList,  /* List of expressions to scan */
798   Expr *pE           /* Expression we are trying to match */
799 ){
800   int i;             /* Loop counter */
801 
802   UNUSED_PARAMETER(pParse);
803 
804   if( pE->op==TK_ID ){
805     char *zCol = pE->u.zToken;
806     for(i=0; i<pEList->nExpr; i++){
807       char *zAs = pEList->a[i].zName;
808       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
809         return i+1;
810       }
811     }
812   }
813   return 0;
814 }
815 
816 /*
817 ** pE is a pointer to an expression which is a single term in the
818 ** ORDER BY of a compound SELECT.  The expression has not been
819 ** name resolved.
820 **
821 ** At the point this routine is called, we already know that the
822 ** ORDER BY term is not an integer index into the result set.  That
823 ** case is handled by the calling routine.
824 **
825 ** Attempt to match pE against result set columns in the left-most
826 ** SELECT statement.  Return the index i of the matching column,
827 ** as an indication to the caller that it should sort by the i-th column.
828 ** The left-most column is 1.  In other words, the value returned is the
829 ** same integer value that would be used in the SQL statement to indicate
830 ** the column.
831 **
832 ** If there is no match, return 0.  Return -1 if an error occurs.
833 */
834 static int resolveOrderByTermToExprList(
835   Parse *pParse,     /* Parsing context for error messages */
836   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
837   Expr *pE           /* The specific ORDER BY term */
838 ){
839   int i;             /* Loop counter */
840   ExprList *pEList;  /* The columns of the result set */
841   NameContext nc;    /* Name context for resolving pE */
842   sqlite3 *db;       /* Database connection */
843   int rc;            /* Return code from subprocedures */
844   u8 savedSuppErr;   /* Saved value of db->suppressErr */
845 
846   assert( sqlite3ExprIsInteger(pE, &i)==0 );
847   pEList = pSelect->pEList;
848 
849   /* Resolve all names in the ORDER BY term expression
850   */
851   memset(&nc, 0, sizeof(nc));
852   nc.pParse = pParse;
853   nc.pSrcList = pSelect->pSrc;
854   nc.pEList = pEList;
855   nc.ncFlags = NC_AllowAgg;
856   nc.nErr = 0;
857   db = pParse->db;
858   savedSuppErr = db->suppressErr;
859   db->suppressErr = 1;
860   rc = sqlite3ResolveExprNames(&nc, pE);
861   db->suppressErr = savedSuppErr;
862   if( rc ) return 0;
863 
864   /* Try to match the ORDER BY expression against an expression
865   ** in the result set.  Return an 1-based index of the matching
866   ** result-set entry.
867   */
868   for(i=0; i<pEList->nExpr; i++){
869     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
870       return i+1;
871     }
872   }
873 
874   /* If no match, return 0. */
875   return 0;
876 }
877 
878 /*
879 ** Generate an ORDER BY or GROUP BY term out-of-range error.
880 */
881 static void resolveOutOfRangeError(
882   Parse *pParse,         /* The error context into which to write the error */
883   const char *zType,     /* "ORDER" or "GROUP" */
884   int i,                 /* The index (1-based) of the term out of range */
885   int mx                 /* Largest permissible value of i */
886 ){
887   sqlite3ErrorMsg(pParse,
888     "%r %s BY term out of range - should be "
889     "between 1 and %d", i, zType, mx);
890 }
891 
892 /*
893 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
894 ** each term of the ORDER BY clause is a constant integer between 1
895 ** and N where N is the number of columns in the compound SELECT.
896 **
897 ** ORDER BY terms that are already an integer between 1 and N are
898 ** unmodified.  ORDER BY terms that are integers outside the range of
899 ** 1 through N generate an error.  ORDER BY terms that are expressions
900 ** are matched against result set expressions of compound SELECT
901 ** beginning with the left-most SELECT and working toward the right.
902 ** At the first match, the ORDER BY expression is transformed into
903 ** the integer column number.
904 **
905 ** Return the number of errors seen.
906 */
907 static int resolveCompoundOrderBy(
908   Parse *pParse,        /* Parsing context.  Leave error messages here */
909   Select *pSelect       /* The SELECT statement containing the ORDER BY */
910 ){
911   int i;
912   ExprList *pOrderBy;
913   ExprList *pEList;
914   sqlite3 *db;
915   int moreToDo = 1;
916 
917   pOrderBy = pSelect->pOrderBy;
918   if( pOrderBy==0 ) return 0;
919   db = pParse->db;
920 #if SQLITE_MAX_COLUMN
921   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
922     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
923     return 1;
924   }
925 #endif
926   for(i=0; i<pOrderBy->nExpr; i++){
927     pOrderBy->a[i].done = 0;
928   }
929   pSelect->pNext = 0;
930   while( pSelect->pPrior ){
931     pSelect->pPrior->pNext = pSelect;
932     pSelect = pSelect->pPrior;
933   }
934   while( pSelect && moreToDo ){
935     struct ExprList_item *pItem;
936     moreToDo = 0;
937     pEList = pSelect->pEList;
938     assert( pEList!=0 );
939     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
940       int iCol = -1;
941       Expr *pE, *pDup;
942       if( pItem->done ) continue;
943       pE = sqlite3ExprSkipCollate(pItem->pExpr);
944       if( sqlite3ExprIsInteger(pE, &iCol) ){
945         if( iCol<=0 || iCol>pEList->nExpr ){
946           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
947           return 1;
948         }
949       }else{
950         iCol = resolveAsName(pParse, pEList, pE);
951         if( iCol==0 ){
952           pDup = sqlite3ExprDup(db, pE, 0);
953           if( !db->mallocFailed ){
954             assert(pDup);
955             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
956           }
957           sqlite3ExprDelete(db, pDup);
958         }
959       }
960       if( iCol>0 ){
961         /* Convert the ORDER BY term into an integer column number iCol,
962         ** taking care to preserve the COLLATE clause if it exists */
963         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
964         if( pNew==0 ) return 1;
965         pNew->flags |= EP_IntValue;
966         pNew->u.iValue = iCol;
967         if( pItem->pExpr==pE ){
968           pItem->pExpr = pNew;
969         }else{
970           Expr *pParent = pItem->pExpr;
971           assert( pParent->op==TK_COLLATE );
972           while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
973           assert( pParent->pLeft==pE );
974           pParent->pLeft = pNew;
975         }
976         sqlite3ExprDelete(db, pE);
977         pItem->u.x.iOrderByCol = (u16)iCol;
978         pItem->done = 1;
979       }else{
980         moreToDo = 1;
981       }
982     }
983     pSelect = pSelect->pNext;
984   }
985   for(i=0; i<pOrderBy->nExpr; i++){
986     if( pOrderBy->a[i].done==0 ){
987       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
988             "column in the result set", i+1);
989       return 1;
990     }
991   }
992   return 0;
993 }
994 
995 /*
996 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
997 ** the SELECT statement pSelect.  If any term is reference to a
998 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
999 ** field) then convert that term into a copy of the corresponding result set
1000 ** column.
1001 **
1002 ** If any errors are detected, add an error message to pParse and
1003 ** return non-zero.  Return zero if no errors are seen.
1004 */
1005 int sqlite3ResolveOrderGroupBy(
1006   Parse *pParse,        /* Parsing context.  Leave error messages here */
1007   Select *pSelect,      /* The SELECT statement containing the clause */
1008   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
1009   const char *zType     /* "ORDER" or "GROUP" */
1010 ){
1011   int i;
1012   sqlite3 *db = pParse->db;
1013   ExprList *pEList;
1014   struct ExprList_item *pItem;
1015 
1016   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
1017 #if SQLITE_MAX_COLUMN
1018   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1019     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1020     return 1;
1021   }
1022 #endif
1023   pEList = pSelect->pEList;
1024   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
1025   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1026     if( pItem->u.x.iOrderByCol ){
1027       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
1028         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
1029         return 1;
1030       }
1031       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
1032                    zType,0);
1033     }
1034   }
1035   return 0;
1036 }
1037 
1038 /*
1039 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1040 ** The Name context of the SELECT statement is pNC.  zType is either
1041 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1042 **
1043 ** This routine resolves each term of the clause into an expression.
1044 ** If the order-by term is an integer I between 1 and N (where N is the
1045 ** number of columns in the result set of the SELECT) then the expression
1046 ** in the resolution is a copy of the I-th result-set expression.  If
1047 ** the order-by term is an identifier that corresponds to the AS-name of
1048 ** a result-set expression, then the term resolves to a copy of the
1049 ** result-set expression.  Otherwise, the expression is resolved in
1050 ** the usual way - using sqlite3ResolveExprNames().
1051 **
1052 ** This routine returns the number of errors.  If errors occur, then
1053 ** an appropriate error message might be left in pParse.  (OOM errors
1054 ** excepted.)
1055 */
1056 static int resolveOrderGroupBy(
1057   NameContext *pNC,     /* The name context of the SELECT statement */
1058   Select *pSelect,      /* The SELECT statement holding pOrderBy */
1059   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
1060   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
1061 ){
1062   int i, j;                      /* Loop counters */
1063   int iCol;                      /* Column number */
1064   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
1065   Parse *pParse;                 /* Parsing context */
1066   int nResult;                   /* Number of terms in the result set */
1067 
1068   if( pOrderBy==0 ) return 0;
1069   nResult = pSelect->pEList->nExpr;
1070   pParse = pNC->pParse;
1071   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1072     Expr *pE = pItem->pExpr;
1073     Expr *pE2 = sqlite3ExprSkipCollate(pE);
1074     if( zType[0]!='G' ){
1075       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1076       if( iCol>0 ){
1077         /* If an AS-name match is found, mark this ORDER BY column as being
1078         ** a copy of the iCol-th result-set column.  The subsequent call to
1079         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1080         ** copy of the iCol-th result-set expression. */
1081         pItem->u.x.iOrderByCol = (u16)iCol;
1082         continue;
1083       }
1084     }
1085     if( sqlite3ExprIsInteger(pE2, &iCol) ){
1086       /* The ORDER BY term is an integer constant.  Again, set the column
1087       ** number so that sqlite3ResolveOrderGroupBy() will convert the
1088       ** order-by term to a copy of the result-set expression */
1089       if( iCol<1 || iCol>0xffff ){
1090         resolveOutOfRangeError(pParse, zType, i+1, nResult);
1091         return 1;
1092       }
1093       pItem->u.x.iOrderByCol = (u16)iCol;
1094       continue;
1095     }
1096 
1097     /* Otherwise, treat the ORDER BY term as an ordinary expression */
1098     pItem->u.x.iOrderByCol = 0;
1099     if( sqlite3ResolveExprNames(pNC, pE) ){
1100       return 1;
1101     }
1102     for(j=0; j<pSelect->pEList->nExpr; j++){
1103       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
1104         pItem->u.x.iOrderByCol = j+1;
1105       }
1106     }
1107   }
1108   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1109 }
1110 
1111 /*
1112 ** Resolve names in the SELECT statement p and all of its descendants.
1113 */
1114 static int resolveSelectStep(Walker *pWalker, Select *p){
1115   NameContext *pOuterNC;  /* Context that contains this SELECT */
1116   NameContext sNC;        /* Name context of this SELECT */
1117   int isCompound;         /* True if p is a compound select */
1118   int nCompound;          /* Number of compound terms processed so far */
1119   Parse *pParse;          /* Parsing context */
1120   int i;                  /* Loop counter */
1121   ExprList *pGroupBy;     /* The GROUP BY clause */
1122   Select *pLeftmost;      /* Left-most of SELECT of a compound */
1123   sqlite3 *db;            /* Database connection */
1124 
1125 
1126   assert( p!=0 );
1127   if( p->selFlags & SF_Resolved ){
1128     return WRC_Prune;
1129   }
1130   pOuterNC = pWalker->u.pNC;
1131   pParse = pWalker->pParse;
1132   db = pParse->db;
1133 
1134   /* Normally sqlite3SelectExpand() will be called first and will have
1135   ** already expanded this SELECT.  However, if this is a subquery within
1136   ** an expression, sqlite3ResolveExprNames() will be called without a
1137   ** prior call to sqlite3SelectExpand().  When that happens, let
1138   ** sqlite3SelectPrep() do all of the processing for this SELECT.
1139   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1140   ** this routine in the correct order.
1141   */
1142   if( (p->selFlags & SF_Expanded)==0 ){
1143     sqlite3SelectPrep(pParse, p, pOuterNC);
1144     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1145   }
1146 
1147   isCompound = p->pPrior!=0;
1148   nCompound = 0;
1149   pLeftmost = p;
1150   while( p ){
1151     assert( (p->selFlags & SF_Expanded)!=0 );
1152     assert( (p->selFlags & SF_Resolved)==0 );
1153     p->selFlags |= SF_Resolved;
1154 
1155     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1156     ** are not allowed to refer to any names, so pass an empty NameContext.
1157     */
1158     memset(&sNC, 0, sizeof(sNC));
1159     sNC.pParse = pParse;
1160     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1161         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1162       return WRC_Abort;
1163     }
1164 
1165     /* If the SF_Converted flags is set, then this Select object was
1166     ** was created by the convertCompoundSelectToSubquery() function.
1167     ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1168     ** as if it were part of the sub-query, not the parent. This block
1169     ** moves the pOrderBy down to the sub-query. It will be moved back
1170     ** after the names have been resolved.  */
1171     if( p->selFlags & SF_Converted ){
1172       Select *pSub = p->pSrc->a[0].pSelect;
1173       assert( p->pSrc->nSrc==1 && p->pOrderBy );
1174       assert( pSub->pPrior && pSub->pOrderBy==0 );
1175       pSub->pOrderBy = p->pOrderBy;
1176       p->pOrderBy = 0;
1177     }
1178 
1179     /* Recursively resolve names in all subqueries
1180     */
1181     for(i=0; i<p->pSrc->nSrc; i++){
1182       struct SrcList_item *pItem = &p->pSrc->a[i];
1183       if( pItem->pSelect ){
1184         NameContext *pNC;         /* Used to iterate name contexts */
1185         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
1186         const char *zSavedContext = pParse->zAuthContext;
1187 
1188         /* Count the total number of references to pOuterNC and all of its
1189         ** parent contexts. After resolving references to expressions in
1190         ** pItem->pSelect, check if this value has changed. If so, then
1191         ** SELECT statement pItem->pSelect must be correlated. Set the
1192         ** pItem->fg.isCorrelated flag if this is the case. */
1193         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1194 
1195         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1196         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
1197         pParse->zAuthContext = zSavedContext;
1198         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
1199 
1200         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1201         assert( pItem->fg.isCorrelated==0 && nRef<=0 );
1202         pItem->fg.isCorrelated = (nRef!=0);
1203       }
1204     }
1205 
1206     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1207     ** resolve the result-set expression list.
1208     */
1209     sNC.ncFlags = NC_AllowAgg;
1210     sNC.pSrcList = p->pSrc;
1211     sNC.pNext = pOuterNC;
1212 
1213     /* Resolve names in the result set. */
1214     if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
1215 
1216     /* If there are no aggregate functions in the result-set, and no GROUP BY
1217     ** expression, do not allow aggregates in any of the other expressions.
1218     */
1219     assert( (p->selFlags & SF_Aggregate)==0 );
1220     pGroupBy = p->pGroupBy;
1221     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
1222       assert( NC_MinMaxAgg==SF_MinMaxAgg );
1223       p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
1224     }else{
1225       sNC.ncFlags &= ~NC_AllowAgg;
1226     }
1227 
1228     /* If a HAVING clause is present, then there must be a GROUP BY clause.
1229     */
1230     if( p->pHaving && !pGroupBy ){
1231       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1232       return WRC_Abort;
1233     }
1234 
1235     /* Add the output column list to the name-context before parsing the
1236     ** other expressions in the SELECT statement. This is so that
1237     ** expressions in the WHERE clause (etc.) can refer to expressions by
1238     ** aliases in the result set.
1239     **
1240     ** Minor point: If this is the case, then the expression will be
1241     ** re-evaluated for each reference to it.
1242     */
1243     sNC.pEList = p->pEList;
1244     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1245     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
1246 
1247     /* Resolve names in table-valued-function arguments */
1248     for(i=0; i<p->pSrc->nSrc; i++){
1249       struct SrcList_item *pItem = &p->pSrc->a[i];
1250       if( pItem->fg.isTabFunc
1251        && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
1252       ){
1253         return WRC_Abort;
1254       }
1255     }
1256 
1257     /* The ORDER BY and GROUP BY clauses may not refer to terms in
1258     ** outer queries
1259     */
1260     sNC.pNext = 0;
1261     sNC.ncFlags |= NC_AllowAgg;
1262 
1263     /* If this is a converted compound query, move the ORDER BY clause from
1264     ** the sub-query back to the parent query. At this point each term
1265     ** within the ORDER BY clause has been transformed to an integer value.
1266     ** These integers will be replaced by copies of the corresponding result
1267     ** set expressions by the call to resolveOrderGroupBy() below.  */
1268     if( p->selFlags & SF_Converted ){
1269       Select *pSub = p->pSrc->a[0].pSelect;
1270       p->pOrderBy = pSub->pOrderBy;
1271       pSub->pOrderBy = 0;
1272     }
1273 
1274     /* Process the ORDER BY clause for singleton SELECT statements.
1275     ** The ORDER BY clause for compounds SELECT statements is handled
1276     ** below, after all of the result-sets for all of the elements of
1277     ** the compound have been resolved.
1278     **
1279     ** If there is an ORDER BY clause on a term of a compound-select other
1280     ** than the right-most term, then that is a syntax error.  But the error
1281     ** is not detected until much later, and so we need to go ahead and
1282     ** resolve those symbols on the incorrect ORDER BY for consistency.
1283     */
1284     if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
1285      && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
1286     ){
1287       return WRC_Abort;
1288     }
1289     if( db->mallocFailed ){
1290       return WRC_Abort;
1291     }
1292 
1293     /* Resolve the GROUP BY clause.  At the same time, make sure
1294     ** the GROUP BY clause does not contain aggregate functions.
1295     */
1296     if( pGroupBy ){
1297       struct ExprList_item *pItem;
1298 
1299       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1300         return WRC_Abort;
1301       }
1302       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1303         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1304           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1305               "the GROUP BY clause");
1306           return WRC_Abort;
1307         }
1308       }
1309     }
1310 
1311     /* If this is part of a compound SELECT, check that it has the right
1312     ** number of expressions in the select list. */
1313     if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
1314       sqlite3SelectWrongNumTermsError(pParse, p->pNext);
1315       return WRC_Abort;
1316     }
1317 
1318     /* Advance to the next term of the compound
1319     */
1320     p = p->pPrior;
1321     nCompound++;
1322   }
1323 
1324   /* Resolve the ORDER BY on a compound SELECT after all terms of
1325   ** the compound have been resolved.
1326   */
1327   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1328     return WRC_Abort;
1329   }
1330 
1331   return WRC_Prune;
1332 }
1333 
1334 /*
1335 ** This routine walks an expression tree and resolves references to
1336 ** table columns and result-set columns.  At the same time, do error
1337 ** checking on function usage and set a flag if any aggregate functions
1338 ** are seen.
1339 **
1340 ** To resolve table columns references we look for nodes (or subtrees) of the
1341 ** form X.Y.Z or Y.Z or just Z where
1342 **
1343 **      X:   The name of a database.  Ex:  "main" or "temp" or
1344 **           the symbolic name assigned to an ATTACH-ed database.
1345 **
1346 **      Y:   The name of a table in a FROM clause.  Or in a trigger
1347 **           one of the special names "old" or "new".
1348 **
1349 **      Z:   The name of a column in table Y.
1350 **
1351 ** The node at the root of the subtree is modified as follows:
1352 **
1353 **    Expr.op        Changed to TK_COLUMN
1354 **    Expr.pTab      Points to the Table object for X.Y
1355 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
1356 **    Expr.iTable    The VDBE cursor number for X.Y
1357 **
1358 **
1359 ** To resolve result-set references, look for expression nodes of the
1360 ** form Z (with no X and Y prefix) where the Z matches the right-hand
1361 ** size of an AS clause in the result-set of a SELECT.  The Z expression
1362 ** is replaced by a copy of the left-hand side of the result-set expression.
1363 ** Table-name and function resolution occurs on the substituted expression
1364 ** tree.  For example, in:
1365 **
1366 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1367 **
1368 ** The "x" term of the order by is replaced by "a+b" to render:
1369 **
1370 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1371 **
1372 ** Function calls are checked to make sure that the function is
1373 ** defined and that the correct number of arguments are specified.
1374 ** If the function is an aggregate function, then the NC_HasAgg flag is
1375 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1376 ** If an expression contains aggregate functions then the EP_Agg
1377 ** property on the expression is set.
1378 **
1379 ** An error message is left in pParse if anything is amiss.  The number
1380 ** if errors is returned.
1381 */
1382 int sqlite3ResolveExprNames(
1383   NameContext *pNC,       /* Namespace to resolve expressions in. */
1384   Expr *pExpr             /* The expression to be analyzed. */
1385 ){
1386   u16 savedHasAgg;
1387   Walker w;
1388 
1389   if( pExpr==0 ) return 0;
1390 #if SQLITE_MAX_EXPR_DEPTH>0
1391   {
1392     Parse *pParse = pNC->pParse;
1393     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1394       return 1;
1395     }
1396     pParse->nHeight += pExpr->nHeight;
1397   }
1398 #endif
1399   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
1400   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
1401   w.pParse = pNC->pParse;
1402   w.xExprCallback = resolveExprStep;
1403   w.xSelectCallback = resolveSelectStep;
1404   w.xSelectCallback2 = 0;
1405   w.walkerDepth = 0;
1406   w.eCode = 0;
1407   w.u.pNC = pNC;
1408   sqlite3WalkExpr(&w, pExpr);
1409 #if SQLITE_MAX_EXPR_DEPTH>0
1410   pNC->pParse->nHeight -= pExpr->nHeight;
1411 #endif
1412   if( pNC->nErr>0 || w.pParse->nErr>0 ){
1413     ExprSetProperty(pExpr, EP_Error);
1414   }
1415   if( pNC->ncFlags & NC_HasAgg ){
1416     ExprSetProperty(pExpr, EP_Agg);
1417   }
1418   pNC->ncFlags |= savedHasAgg;
1419   return ExprHasProperty(pExpr, EP_Error);
1420 }
1421 
1422 /*
1423 ** Resolve all names for all expression in an expression list.  This is
1424 ** just like sqlite3ResolveExprNames() except that it works for an expression
1425 ** list rather than a single expression.
1426 */
1427 int sqlite3ResolveExprListNames(
1428   NameContext *pNC,       /* Namespace to resolve expressions in. */
1429   ExprList *pList         /* The expression list to be analyzed. */
1430 ){
1431   int i;
1432   if( pList ){
1433     for(i=0; i<pList->nExpr; i++){
1434       if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
1435     }
1436   }
1437   return WRC_Continue;
1438 }
1439 
1440 /*
1441 ** Resolve all names in all expressions of a SELECT and in all
1442 ** decendents of the SELECT, including compounds off of p->pPrior,
1443 ** subqueries in expressions, and subqueries used as FROM clause
1444 ** terms.
1445 **
1446 ** See sqlite3ResolveExprNames() for a description of the kinds of
1447 ** transformations that occur.
1448 **
1449 ** All SELECT statements should have been expanded using
1450 ** sqlite3SelectExpand() prior to invoking this routine.
1451 */
1452 void sqlite3ResolveSelectNames(
1453   Parse *pParse,         /* The parser context */
1454   Select *p,             /* The SELECT statement being coded. */
1455   NameContext *pOuterNC  /* Name context for parent SELECT statement */
1456 ){
1457   Walker w;
1458 
1459   assert( p!=0 );
1460   memset(&w, 0, sizeof(w));
1461   w.xExprCallback = resolveExprStep;
1462   w.xSelectCallback = resolveSelectStep;
1463   w.pParse = pParse;
1464   w.u.pNC = pOuterNC;
1465   sqlite3WalkSelect(&w, p);
1466 }
1467 
1468 /*
1469 ** Resolve names in expressions that can only reference a single table:
1470 **
1471 **    *   CHECK constraints
1472 **    *   WHERE clauses on partial indices
1473 **
1474 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
1475 ** is set to -1 and the Expr.iColumn value is set to the column number.
1476 **
1477 ** Any errors cause an error message to be set in pParse.
1478 */
1479 void sqlite3ResolveSelfReference(
1480   Parse *pParse,      /* Parsing context */
1481   Table *pTab,        /* The table being referenced */
1482   int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
1483   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
1484   ExprList *pList     /* Expression list to resolve.  May be NUL. */
1485 ){
1486   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
1487   NameContext sNC;                /* Name context for pParse->pNewTable */
1488 
1489   assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
1490   memset(&sNC, 0, sizeof(sNC));
1491   memset(&sSrc, 0, sizeof(sSrc));
1492   sSrc.nSrc = 1;
1493   sSrc.a[0].zName = pTab->zName;
1494   sSrc.a[0].pTab = pTab;
1495   sSrc.a[0].iCursor = -1;
1496   sNC.pParse = pParse;
1497   sNC.pSrcList = &sSrc;
1498   sNC.ncFlags = type;
1499   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
1500   if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
1501 }
1502