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