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