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