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