xref: /sqlite-3.40.0/src/resolve.c (revision 2627cbd4)
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 ** Magic table number to mean the EXCLUDED table in an UPSERT statement.
21 */
22 #define EXCLUDED_TABLE_NUMBER  2
23 
24 /*
25 ** Walk the expression tree pExpr and increase the aggregate function
26 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
27 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
28 ** outer query into an inner subquery.
29 **
30 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
31 ** is a helper function - a callback for the tree walker.
32 **
33 ** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
34 */
35 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
36   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
37   return WRC_Continue;
38 }
39 static void incrAggFunctionDepth(Expr *pExpr, int N){
40   if( N>0 ){
41     Walker w;
42     memset(&w, 0, sizeof(w));
43     w.xExprCallback = incrAggDepth;
44     w.u.n = N;
45     sqlite3WalkExpr(&w, pExpr);
46   }
47 }
48 
49 /*
50 ** Turn the pExpr expression into an alias for the iCol-th column of the
51 ** result set in pEList.
52 **
53 ** If the reference is followed by a COLLATE operator, then make sure
54 ** the COLLATE operator is preserved.  For example:
55 **
56 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
57 **
58 ** Should be transformed into:
59 **
60 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
61 **
62 ** The nSubquery parameter specifies how many levels of subquery the
63 ** alias is removed from the original expression.  The usual value is
64 ** zero but it might be more if the alias is contained within a subquery
65 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
66 ** structures must be increased by the nSubquery amount.
67 */
68 static void resolveAlias(
69   Parse *pParse,         /* Parsing context */
70   ExprList *pEList,      /* A result set */
71   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
72   Expr *pExpr,           /* Transform this into an alias to the result set */
73   int nSubquery          /* Number of subqueries that the label is moving */
74 ){
75   Expr *pOrig;           /* The iCol-th column of the result set */
76   Expr *pDup;            /* Copy of pOrig */
77   sqlite3 *db;           /* The database connection */
78 
79   assert( iCol>=0 && iCol<pEList->nExpr );
80   pOrig = pEList->a[iCol].pExpr;
81   assert( pOrig!=0 );
82   db = pParse->db;
83   pDup = sqlite3ExprDup(db, pOrig, 0);
84   if( db->mallocFailed ){
85     sqlite3ExprDelete(db, pDup);
86     pDup = 0;
87   }else{
88     incrAggFunctionDepth(pDup, nSubquery);
89     if( pExpr->op==TK_COLLATE ){
90       assert( !ExprHasProperty(pExpr, EP_IntValue) );
91       pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
92     }
93 
94     /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
95     ** prevents ExprDelete() from deleting the Expr structure itself,
96     ** allowing it to be repopulated by the memcpy() on the following line.
97     ** The pExpr->u.zToken might point into memory that will be freed by the
98     ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
99     ** make a copy of the token before doing the sqlite3DbFree().
100     */
101     ExprSetProperty(pExpr, EP_Static);
102     sqlite3ExprDelete(db, pExpr);
103     memcpy(pExpr, pDup, sizeof(*pExpr));
104     if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
105       assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
106       pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
107       pExpr->flags |= EP_MemToken;
108     }
109     if( ExprHasProperty(pExpr, EP_WinFunc) ){
110       if( ALWAYS(pExpr->y.pWin!=0) ){
111         pExpr->y.pWin->pOwner = pExpr;
112       }
113     }
114     sqlite3DbFree(db, pDup);
115   }
116 }
117 
118 /*
119 ** Subqueries stores the original database, table and column names for their
120 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
121 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
122 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
123 ** match anything.
124 */
125 int sqlite3MatchEName(
126   const struct ExprList_item *pItem,
127   const char *zCol,
128   const char *zTab,
129   const char *zDb
130 ){
131   int n;
132   const char *zSpan;
133   if( pItem->eEName!=ENAME_TAB ) return 0;
134   zSpan = pItem->zEName;
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 ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
170 ** return the appropriate colUsed mask.
171 */
172 Bitmask sqlite3ExprColUsed(Expr *pExpr){
173   int n;
174   Table *pExTab;
175 
176   n = pExpr->iColumn;
177   assert( ExprUseYTab(pExpr) );
178   pExTab = pExpr->y.pTab;
179   assert( pExTab!=0 );
180   if( (pExTab->tabFlags & TF_HasGenerated)!=0
181    && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
182   ){
183     testcase( pExTab->nCol==BMS-1 );
184     testcase( pExTab->nCol==BMS );
185     return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
186   }else{
187     testcase( n==BMS-1 );
188     testcase( n==BMS );
189     if( n>=BMS ) n = BMS-1;
190     return ((Bitmask)1)<<n;
191   }
192 }
193 
194 /*
195 ** Create a new expression term for the column specified by pMatch and
196 ** iColumn.  Append this new expression term to the FULL JOIN Match set
197 ** in *ppList.  Create a new *ppList if this is the first term in the
198 ** set.
199 */
200 static void extendFJMatch(
201   Parse *pParse,          /* Parsing context */
202   ExprList **ppList,      /* ExprList to extend */
203   SrcItem *pMatch,        /* Source table containing the column */
204   i16 iColumn             /* The column number */
205 ){
206   Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
207   if( pNew ){
208     pNew->iTable = pMatch->iCursor;
209     pNew->iColumn = iColumn;
210     pNew->y.pTab = pMatch->pTab;
211     assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
212     ExprSetProperty(pNew, EP_CanBeNull);
213     *ppList = sqlite3ExprListAppend(pParse, *ppList, pNew);
214   }
215 }
216 
217 /*
218 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
219 ** that name in the set of source tables in pSrcList and make the pExpr
220 ** expression node refer back to that source column.  The following changes
221 ** are made to pExpr:
222 **
223 **    pExpr->iDb           Set the index in db->aDb[] of the database X
224 **                         (even if X is implied).
225 **    pExpr->iTable        Set to the cursor number for the table obtained
226 **                         from pSrcList.
227 **    pExpr->y.pTab        Points to the Table structure of X.Y (even if
228 **                         X and/or Y are implied.)
229 **    pExpr->iColumn       Set to the column number within the table.
230 **    pExpr->op            Set to TK_COLUMN.
231 **    pExpr->pLeft         Any expression this points to is deleted
232 **    pExpr->pRight        Any expression this points to is deleted.
233 **
234 ** The zDb variable is the name of the database (the "X").  This value may be
235 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
236 ** can be used.  The zTable variable is the name of the table (the "Y").  This
237 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
238 ** means that the form of the name is Z and that columns from any table
239 ** can be used.
240 **
241 ** If the name cannot be resolved unambiguously, leave an error message
242 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
243 */
244 static int lookupName(
245   Parse *pParse,       /* The parsing context */
246   const char *zDb,     /* Name of the database containing table, or NULL */
247   const char *zTab,    /* Name of table containing column, or NULL */
248   const char *zCol,    /* Name of the column. */
249   NameContext *pNC,    /* The name context used to resolve the name */
250   Expr *pExpr          /* Make this EXPR node point to the selected column */
251 ){
252   int i, j;                         /* Loop counters */
253   int cnt = 0;                      /* Number of matching column names */
254   int cntTab = 0;                   /* Number of matching table names */
255   int nSubquery = 0;                /* How many levels of subquery */
256   sqlite3 *db = pParse->db;         /* The database connection */
257   SrcItem *pItem;                   /* Use for looping over pSrcList items */
258   SrcItem *pMatch = 0;              /* The matching pSrcList item */
259   NameContext *pTopNC = pNC;        /* First namecontext in the list */
260   Schema *pSchema = 0;              /* Schema of the expression */
261   int eNewExprOp = TK_COLUMN;       /* New value for pExpr->op on success */
262   Table *pTab = 0;                  /* Table holding the row */
263   Column *pCol;                     /* A column of pTab */
264   ExprList *pFJMatch = 0;           /* Matches for FULL JOIN .. USING */
265 
266   assert( pNC );     /* the name context cannot be NULL. */
267   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
268   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
269 
270   /* Initialize the node to no-match */
271   pExpr->iTable = -1;
272   ExprSetVVAProperty(pExpr, EP_NoReduce);
273 
274   /* Translate the schema name in zDb into a pointer to the corresponding
275   ** schema.  If not found, pSchema will remain NULL and nothing will match
276   ** resulting in an appropriate error message toward the end of this routine
277   */
278   if( zDb ){
279     testcase( pNC->ncFlags & NC_PartIdx );
280     testcase( pNC->ncFlags & NC_IsCheck );
281     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
282       /* Silently ignore database qualifiers inside CHECK constraints and
283       ** partial indices.  Do not raise errors because that might break
284       ** legacy and because it does not hurt anything to just ignore the
285       ** database name. */
286       zDb = 0;
287     }else{
288       for(i=0; i<db->nDb; i++){
289         assert( db->aDb[i].zDbSName );
290         if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
291           pSchema = db->aDb[i].pSchema;
292           break;
293         }
294       }
295       if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
296         /* This branch is taken when the main database has been renamed
297         ** using SQLITE_DBCONFIG_MAINDBNAME. */
298         pSchema = db->aDb[0].pSchema;
299         zDb = db->aDb[0].zDbSName;
300       }
301     }
302   }
303 
304   /* Start at the inner-most context and move outward until a match is found */
305   assert( pNC && cnt==0 );
306   do{
307     ExprList *pEList;
308     SrcList *pSrcList = pNC->pSrcList;
309 
310     if( pSrcList ){
311       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
312         u8 hCol;
313         pTab = pItem->pTab;
314         assert( pTab!=0 && pTab->zName!=0 );
315         assert( pTab->nCol>0 || pParse->nErr );
316         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
317           /* In this case, pItem is a subquery that has been formed from a
318           ** parenthesized subset of the FROM clause terms.  Example:
319           **   .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
320           **                          \_________________________/
321           **             This pItem -------------^
322           */
323           int hit = 0;
324           pEList = pItem->pSelect->pEList;
325           for(j=0; j<pEList->nExpr; j++){
326             if( sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){
327               if( cnt>0 ){
328                 if( pItem->fg.isUsing==0
329                  || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
330                 ){
331                   /* Two or more tables have the same column name which is
332                   ** not joined by USING.  This is an error.  Signal as much
333                   ** by clearing pFJMatch and letting cnt go above 1. */
334                   sqlite3ExprListDelete(db, pFJMatch);
335                   pFJMatch = 0;
336                 }else
337                 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
338                   /* An INNER or LEFT JOIN.  Use the left-most table */
339                   continue;
340                 }else
341                 if( (pItem->fg.jointype & JT_LEFT)==0 ){
342                   /* A RIGHT JOIN.  Use the right-most table */
343                   cnt = 0;
344                   sqlite3ExprListDelete(db, pFJMatch);
345                   pFJMatch = 0;
346                 }else{
347                   /* For a FULL JOIN, we must construct a coalesce() func */
348                   extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
349                 }
350               }
351               cnt++;
352               cntTab = 2;
353               pMatch = pItem;
354               pExpr->iColumn = j;
355               hit = 1;
356             }
357           }
358           if( hit || zTab==0 ) continue;
359         }
360         if( zDb ){
361           if( pTab->pSchema!=pSchema ) continue;
362           if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue;
363         }
364         if( zTab ){
365           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
366           assert( zTabName!=0 );
367           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
368             continue;
369           }
370           assert( ExprUseYTab(pExpr) );
371           if( IN_RENAME_OBJECT && pItem->zAlias ){
372             sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
373           }
374         }
375         hCol = sqlite3StrIHash(zCol);
376         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
377           if( pCol->hName==hCol
378            && sqlite3StrICmp(pCol->zCnName, zCol)==0
379           ){
380             if( cnt>0 ){
381               if( pItem->fg.isUsing==0
382                || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
383               ){
384                 /* Two or more tables have the same column name which is
385                 ** not joined by USING.  This is an error.  Signal as much
386                 ** by clearing pFJMatch and letting cnt go above 1. */
387                 sqlite3ExprListDelete(db, pFJMatch);
388                 pFJMatch = 0;
389               }else
390               if( (pItem->fg.jointype & JT_RIGHT)==0 ){
391                 /* An INNER or LEFT JOIN.  Use the left-most table */
392                 continue;
393               }else
394               if( (pItem->fg.jointype & JT_LEFT)==0 ){
395                 /* A RIGHT JOIN.  Use the right-most table */
396                 cnt = 0;
397                 sqlite3ExprListDelete(db, pFJMatch);
398                 pFJMatch = 0;
399               }else{
400                 /* For a FULL JOIN, we must construct a coalesce() func */
401                 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
402               }
403             }
404             cnt++;
405             pMatch = pItem;
406             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
407             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
408             break;
409           }
410         }
411         if( 0==cnt && VisibleRowid(pTab) ){
412           cntTab++;
413           pMatch = pItem;
414         }
415       }
416       if( pMatch ){
417         pExpr->iTable = pMatch->iCursor;
418         assert( ExprUseYTab(pExpr) );
419         pExpr->y.pTab = pMatch->pTab;
420         if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
421           ExprSetProperty(pExpr, EP_CanBeNull);
422         }
423         pSchema = pExpr->y.pTab->pSchema;
424       }
425     } /* if( pSrcList ) */
426 
427 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
428     /* If we have not already resolved the name, then maybe
429     ** it is a new.* or old.* trigger argument reference.  Or
430     ** maybe it is an excluded.* from an upsert.  Or maybe it is
431     ** a reference in the RETURNING clause to a table being modified.
432     */
433     if( cnt==0 && zDb==0 ){
434       pTab = 0;
435 #ifndef SQLITE_OMIT_TRIGGER
436       if( pParse->pTriggerTab!=0 ){
437         int op = pParse->eTriggerOp;
438         assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
439         if( pParse->bReturning ){
440           if( (pNC->ncFlags & NC_UBaseReg)!=0
441            && (zTab==0 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0)
442           ){
443             pExpr->iTable = op!=TK_DELETE;
444             pTab = pParse->pTriggerTab;
445           }
446         }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
447           pExpr->iTable = 1;
448           pTab = pParse->pTriggerTab;
449         }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){
450           pExpr->iTable = 0;
451           pTab = pParse->pTriggerTab;
452         }
453       }
454 #endif /* SQLITE_OMIT_TRIGGER */
455 #ifndef SQLITE_OMIT_UPSERT
456       if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
457         Upsert *pUpsert = pNC->uNC.pUpsert;
458         if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
459           pTab = pUpsert->pUpsertSrc->a[0].pTab;
460           pExpr->iTable = EXCLUDED_TABLE_NUMBER;
461         }
462       }
463 #endif /* SQLITE_OMIT_UPSERT */
464 
465       if( pTab ){
466         int iCol;
467         u8 hCol = sqlite3StrIHash(zCol);
468         pSchema = pTab->pSchema;
469         cntTab++;
470         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
471           if( pCol->hName==hCol
472            && sqlite3StrICmp(pCol->zCnName, zCol)==0
473           ){
474             if( iCol==pTab->iPKey ){
475               iCol = -1;
476             }
477             break;
478           }
479         }
480         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
481           /* IMP: R-51414-32910 */
482           iCol = -1;
483         }
484         if( iCol<pTab->nCol ){
485           cnt++;
486           pMatch = 0;
487 #ifndef SQLITE_OMIT_UPSERT
488           if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
489             testcase( iCol==(-1) );
490             assert( ExprUseYTab(pExpr) );
491             if( IN_RENAME_OBJECT ){
492               pExpr->iColumn = iCol;
493               pExpr->y.pTab = pTab;
494               eNewExprOp = TK_COLUMN;
495             }else{
496               pExpr->iTable = pNC->uNC.pUpsert->regData +
497                  sqlite3TableColumnToStorage(pTab, iCol);
498               eNewExprOp = TK_REGISTER;
499             }
500           }else
501 #endif /* SQLITE_OMIT_UPSERT */
502           {
503             assert( ExprUseYTab(pExpr) );
504             pExpr->y.pTab = pTab;
505             if( pParse->bReturning ){
506               eNewExprOp = TK_REGISTER;
507               pExpr->op2 = TK_COLUMN;
508               pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
509                  sqlite3TableColumnToStorage(pTab, iCol) + 1;
510             }else{
511               pExpr->iColumn = (i16)iCol;
512               eNewExprOp = TK_TRIGGER;
513 #ifndef SQLITE_OMIT_TRIGGER
514               if( iCol<0 ){
515                 pExpr->affExpr = SQLITE_AFF_INTEGER;
516               }else if( pExpr->iTable==0 ){
517                 testcase( iCol==31 );
518                 testcase( iCol==32 );
519                 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
520               }else{
521                 testcase( iCol==31 );
522                 testcase( iCol==32 );
523                 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
524               }
525 #endif /* SQLITE_OMIT_TRIGGER */
526             }
527           }
528         }
529       }
530     }
531 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
532 
533     /*
534     ** Perhaps the name is a reference to the ROWID
535     */
536     if( cnt==0
537      && cntTab==1
538      && pMatch
539      && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
540      && sqlite3IsRowid(zCol)
541      && ALWAYS(VisibleRowid(pMatch->pTab))
542     ){
543       cnt = 1;
544       pExpr->iColumn = -1;
545       pExpr->affExpr = SQLITE_AFF_INTEGER;
546     }
547 
548     /*
549     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
550     ** might refer to an result-set alias.  This happens, for example, when
551     ** we are resolving names in the WHERE clause of the following command:
552     **
553     **     SELECT a+b AS x FROM table WHERE x<10;
554     **
555     ** In cases like this, replace pExpr with a copy of the expression that
556     ** forms the result set entry ("a+b" in the example) and return immediately.
557     ** Note that the expression in the result set should have already been
558     ** resolved by the time the WHERE clause is resolved.
559     **
560     ** The ability to use an output result-set column in the WHERE, GROUP BY,
561     ** or HAVING clauses, or as part of a larger expression in the ORDER BY
562     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
563     ** is supported for backwards compatibility only. Hence, we issue a warning
564     ** on sqlite3_log() whenever the capability is used.
565     */
566     if( cnt==0
567      && (pNC->ncFlags & NC_UEList)!=0
568      && zTab==0
569     ){
570       pEList = pNC->uNC.pEList;
571       assert( pEList!=0 );
572       for(j=0; j<pEList->nExpr; j++){
573         char *zAs = pEList->a[j].zEName;
574         if( pEList->a[j].eEName==ENAME_NAME
575          && sqlite3_stricmp(zAs, zCol)==0
576         ){
577           Expr *pOrig;
578           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
579           assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
580           assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
581           pOrig = pEList->a[j].pExpr;
582           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
583             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
584             return WRC_Abort;
585           }
586           if( ExprHasProperty(pOrig, EP_Win)
587            && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
588           ){
589             sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
590             return WRC_Abort;
591           }
592           if( sqlite3ExprVectorSize(pOrig)!=1 ){
593             sqlite3ErrorMsg(pParse, "row value misused");
594             return WRC_Abort;
595           }
596           resolveAlias(pParse, pEList, j, pExpr, nSubquery);
597           cnt = 1;
598           pMatch = 0;
599           assert( zTab==0 && zDb==0 );
600           if( IN_RENAME_OBJECT ){
601             sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
602           }
603           goto lookupname_end;
604         }
605       }
606     }
607 
608     /* Advance to the next name context.  The loop will exit when either
609     ** we have a match (cnt>0) or when we run out of name contexts.
610     */
611     if( cnt ) break;
612     pNC = pNC->pNext;
613     nSubquery++;
614   }while( pNC );
615 
616 
617   /*
618   ** If X and Y are NULL (in other words if only the column name Z is
619   ** supplied) and the value of Z is enclosed in double-quotes, then
620   ** Z is a string literal if it doesn't match any column names.  In that
621   ** case, we need to return right away and not make any changes to
622   ** pExpr.
623   **
624   ** Because no reference was made to outer contexts, the pNC->nRef
625   ** fields are not changed in any context.
626   */
627   if( cnt==0 && zTab==0 ){
628     assert( pExpr->op==TK_ID );
629     if( ExprHasProperty(pExpr,EP_DblQuoted)
630      && areDoubleQuotedStringsEnabled(db, pTopNC)
631     ){
632       /* If a double-quoted identifier does not match any known column name,
633       ** then treat it as a string.
634       **
635       ** This hack was added in the early days of SQLite in a misguided attempt
636       ** to be compatible with MySQL 3.x, which used double-quotes for strings.
637       ** I now sorely regret putting in this hack. The effect of this hack is
638       ** that misspelled identifier names are silently converted into strings
639       ** rather than causing an error, to the frustration of countless
640       ** programmers. To all those frustrated programmers, my apologies.
641       **
642       ** Someday, I hope to get rid of this hack. Unfortunately there is
643       ** a huge amount of legacy SQL that uses it. So for now, we just
644       ** issue a warning.
645       */
646       sqlite3_log(SQLITE_WARNING,
647         "double-quoted string literal: \"%w\"", zCol);
648 #ifdef SQLITE_ENABLE_NORMALIZE
649       sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
650 #endif
651       pExpr->op = TK_STRING;
652       memset(&pExpr->y, 0, sizeof(pExpr->y));
653       return WRC_Prune;
654     }
655     if( sqlite3ExprIdToTrueFalse(pExpr) ){
656       return WRC_Prune;
657     }
658   }
659 
660   /*
661   ** cnt==0 means there was not match.
662   ** cnt>1 means there were two or more matches.
663   **
664   ** cnt==0 is always an error.  cnt>1 is often an error, but might
665   ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
666   */
667   assert( pFJMatch==0 || cnt>0 );
668   assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
669   if( cnt!=1 ){
670     const char *zErr;
671     if( pFJMatch ){
672       if( pFJMatch->nExpr==cnt-1 ){
673         if( ExprHasProperty(pExpr,EP_Leaf) ){
674           ExprClearProperty(pExpr,EP_Leaf);
675         }else{
676           sqlite3ExprDelete(db, pExpr->pLeft);
677           pExpr->pLeft = 0;
678           sqlite3ExprDelete(db, pExpr->pRight);
679           pExpr->pRight = 0;
680         }
681         extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
682         pExpr->op = TK_FUNCTION;
683         pExpr->u.zToken = "coalesce";
684         pExpr->x.pList = pFJMatch;
685         cnt = 1;
686         goto lookupname_end;
687       }else{
688         sqlite3ExprListDelete(db, pFJMatch);
689         pFJMatch = 0;
690       }
691     }
692     zErr = cnt==0 ? "no such column" : "ambiguous column name";
693     if( zDb ){
694       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
695     }else if( zTab ){
696       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
697     }else{
698       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
699     }
700     sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
701     pParse->checkSchema = 1;
702     pTopNC->nNcErr++;
703   }
704   assert( pFJMatch==0 );
705 
706   /* Remove all substructure from pExpr */
707   if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
708     sqlite3ExprDelete(db, pExpr->pLeft);
709     pExpr->pLeft = 0;
710     sqlite3ExprDelete(db, pExpr->pRight);
711     pExpr->pRight = 0;
712     ExprSetProperty(pExpr, EP_Leaf);
713   }
714 
715   /* If a column from a table in pSrcList is referenced, then record
716   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
717   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  Bit 63 is
718   ** set if the 63rd or any subsequent column is used.
719   **
720   ** The colUsed mask is an optimization used to help determine if an
721   ** index is a covering index.  The correct answer is still obtained
722   ** if the mask contains extra set bits.  However, it is important to
723   ** avoid setting bits beyond the maximum column number of the table.
724   ** (See ticket [b92e5e8ec2cdbaa1]).
725   **
726   ** If a generated column is referenced, set bits for every column
727   ** of the table.
728   */
729   if( pExpr->iColumn>=0 && pMatch!=0 ){
730     pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
731   }
732 
733   pExpr->op = eNewExprOp;
734 lookupname_end:
735   if( cnt==1 ){
736     assert( pNC!=0 );
737 #ifndef SQLITE_OMIT_AUTHORIZATION
738     if( pParse->db->xAuth
739      && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
740     ){
741       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
742     }
743 #endif
744     /* Increment the nRef value on all name contexts from TopNC up to
745     ** the point where the name matched. */
746     for(;;){
747       assert( pTopNC!=0 );
748       pTopNC->nRef++;
749       if( pTopNC==pNC ) break;
750       pTopNC = pTopNC->pNext;
751     }
752     return WRC_Prune;
753   } else {
754     return WRC_Abort;
755   }
756 }
757 
758 /*
759 ** Allocate and return a pointer to an expression to load the column iCol
760 ** from datasource iSrc in SrcList pSrc.
761 */
762 Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
763   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
764   if( p ){
765     SrcItem *pItem = &pSrc->a[iSrc];
766     Table *pTab;
767     assert( ExprUseYTab(p) );
768     pTab = p->y.pTab = pItem->pTab;
769     p->iTable = pItem->iCursor;
770     if( p->y.pTab->iPKey==iCol ){
771       p->iColumn = -1;
772     }else{
773       p->iColumn = (ynVar)iCol;
774       if( (pTab->tabFlags & TF_HasGenerated)!=0
775        && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
776       ){
777         testcase( pTab->nCol==63 );
778         testcase( pTab->nCol==64 );
779         pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
780       }else{
781         testcase( iCol==BMS );
782         testcase( iCol==BMS-1 );
783         pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
784       }
785     }
786   }
787   return p;
788 }
789 
790 /*
791 ** Report an error that an expression is not valid for some set of
792 ** pNC->ncFlags values determined by validMask.
793 **
794 ** static void notValid(
795 **   Parse *pParse,       // Leave error message here
796 **   NameContext *pNC,    // The name context
797 **   const char *zMsg,    // Type of error
798 **   int validMask,       // Set of contexts for which prohibited
799 **   Expr *pExpr          // Invalidate this expression on error
800 ** ){...}
801 **
802 ** As an optimization, since the conditional is almost always false
803 ** (because errors are rare), the conditional is moved outside of the
804 ** function call using a macro.
805 */
806 static void notValidImpl(
807    Parse *pParse,       /* Leave error message here */
808    NameContext *pNC,    /* The name context */
809    const char *zMsg,    /* Type of error */
810    Expr *pExpr,         /* Invalidate this expression on error */
811    Expr *pError         /* Associate error with this expression */
812 ){
813   const char *zIn = "partial index WHERE clauses";
814   if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
815 #ifndef SQLITE_OMIT_CHECK
816   else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
817 #endif
818 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
819   else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
820 #endif
821   sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
822   if( pExpr ) pExpr->op = TK_NULL;
823   sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
824 }
825 #define sqlite3ResolveNotValid(P,N,M,X,E,R) \
826   assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
827   if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
828 
829 /*
830 ** Expression p should encode a floating point value between 1.0 and 0.0.
831 ** Return 1024 times this value.  Or return -1 if p is not a floating point
832 ** value between 1.0 and 0.0.
833 */
834 static int exprProbability(Expr *p){
835   double r = -1.0;
836   if( p->op!=TK_FLOAT ) return -1;
837   assert( !ExprHasProperty(p, EP_IntValue) );
838   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
839   assert( r>=0.0 );
840   if( r>1.0 ) return -1;
841   return (int)(r*134217728.0);
842 }
843 
844 /*
845 ** This routine is callback for sqlite3WalkExpr().
846 **
847 ** Resolve symbolic names into TK_COLUMN operators for the current
848 ** node in the expression tree.  Return 0 to continue the search down
849 ** the tree or 2 to abort the tree walk.
850 **
851 ** This routine also does error checking and name resolution for
852 ** function names.  The operator for aggregate functions is changed
853 ** to TK_AGG_FUNCTION.
854 */
855 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
856   NameContext *pNC;
857   Parse *pParse;
858 
859   pNC = pWalker->u.pNC;
860   assert( pNC!=0 );
861   pParse = pNC->pParse;
862   assert( pParse==pWalker->pParse );
863 
864 #ifndef NDEBUG
865   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
866     SrcList *pSrcList = pNC->pSrcList;
867     int i;
868     for(i=0; i<pNC->pSrcList->nSrc; i++){
869       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
870     }
871   }
872 #endif
873   switch( pExpr->op ){
874 
875     /* The special operator TK_ROW means use the rowid for the first
876     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
877     ** clause processing on UPDATE and DELETE statements, and by
878     ** UPDATE ... FROM statement processing.
879     */
880     case TK_ROW: {
881       SrcList *pSrcList = pNC->pSrcList;
882       SrcItem *pItem;
883       assert( pSrcList && pSrcList->nSrc>=1 );
884       pItem = pSrcList->a;
885       pExpr->op = TK_COLUMN;
886       assert( ExprUseYTab(pExpr) );
887       pExpr->y.pTab = pItem->pTab;
888       pExpr->iTable = pItem->iCursor;
889       pExpr->iColumn--;
890       pExpr->affExpr = SQLITE_AFF_INTEGER;
891       break;
892     }
893 
894     /* An optimization:  Attempt to convert
895     **
896     **      "expr IS NOT NULL"  -->  "TRUE"
897     **      "expr IS NULL"      -->  "FALSE"
898     **
899     ** if we can prove that "expr" is never NULL.  Call this the
900     ** "NOT NULL strength reduction optimization".
901     **
902     ** If this optimization occurs, also restore the NameContext ref-counts
903     ** to the state they where in before the "column" LHS expression was
904     ** resolved.  This prevents "column" from being counted as having been
905     ** referenced, which might prevent a SELECT from being erroneously
906     ** marked as correlated.
907     */
908     case TK_NOTNULL:
909     case TK_ISNULL: {
910       int anRef[8];
911       NameContext *p;
912       int i;
913       for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
914         anRef[i] = p->nRef;
915       }
916       sqlite3WalkExpr(pWalker, pExpr->pLeft);
917       if( 0==sqlite3ExprCanBeNull(pExpr->pLeft) && !IN_RENAME_OBJECT ){
918         testcase( ExprHasProperty(pExpr, EP_FromJoin) );
919         assert( !ExprHasProperty(pExpr, EP_IntValue) );
920         if( pExpr->op==TK_NOTNULL ){
921           pExpr->u.zToken = "true";
922           ExprSetProperty(pExpr, EP_IsTrue);
923         }else{
924           pExpr->u.zToken = "false";
925           ExprSetProperty(pExpr, EP_IsFalse);
926         }
927         pExpr->op = TK_TRUEFALSE;
928         for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
929           p->nRef = anRef[i];
930         }
931         sqlite3ExprDelete(pParse->db, pExpr->pLeft);
932         pExpr->pLeft = 0;
933       }
934       return WRC_Prune;
935     }
936 
937     /* A column name:                    ID
938     ** Or table name and column name:    ID.ID
939     ** Or a database, table and column:  ID.ID.ID
940     **
941     ** The TK_ID and TK_OUT cases are combined so that there will only
942     ** be one call to lookupName().  Then the compiler will in-line
943     ** lookupName() for a size reduction and performance increase.
944     */
945     case TK_ID:
946     case TK_DOT: {
947       const char *zColumn;
948       const char *zTable;
949       const char *zDb;
950       Expr *pRight;
951 
952       if( pExpr->op==TK_ID ){
953         zDb = 0;
954         zTable = 0;
955         assert( !ExprHasProperty(pExpr, EP_IntValue) );
956         zColumn = pExpr->u.zToken;
957       }else{
958         Expr *pLeft = pExpr->pLeft;
959         testcase( pNC->ncFlags & NC_IdxExpr );
960         testcase( pNC->ncFlags & NC_GenCol );
961         sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
962                                NC_IdxExpr|NC_GenCol, 0, pExpr);
963         pRight = pExpr->pRight;
964         if( pRight->op==TK_ID ){
965           zDb = 0;
966         }else{
967           assert( pRight->op==TK_DOT );
968           assert( !ExprHasProperty(pRight, EP_IntValue) );
969           zDb = pLeft->u.zToken;
970           pLeft = pRight->pLeft;
971           pRight = pRight->pRight;
972         }
973         assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
974         zTable = pLeft->u.zToken;
975         zColumn = pRight->u.zToken;
976         assert( ExprUseYTab(pExpr) );
977         if( IN_RENAME_OBJECT ){
978           sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
979           sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
980         }
981       }
982       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
983     }
984 
985     /* Resolve function names
986     */
987     case TK_FUNCTION: {
988       ExprList *pList = pExpr->x.pList;    /* The argument list */
989       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
990       int no_such_func = 0;       /* True if no such function exists */
991       int wrong_num_args = 0;     /* True if wrong number of arguments */
992       int is_agg = 0;             /* True if is an aggregate function */
993       const char *zId;            /* The function name. */
994       FuncDef *pDef;              /* Information about the function */
995       u8 enc = ENC(pParse->db);   /* The database encoding */
996       int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
997 #ifndef SQLITE_OMIT_WINDOWFUNC
998       Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
999 #endif
1000       assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
1001       zId = pExpr->u.zToken;
1002       pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
1003       if( pDef==0 ){
1004         pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
1005         if( pDef==0 ){
1006           no_such_func = 1;
1007         }else{
1008           wrong_num_args = 1;
1009         }
1010       }else{
1011         is_agg = pDef->xFinalize!=0;
1012         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
1013           ExprSetProperty(pExpr, EP_Unlikely);
1014           if( n==2 ){
1015             pExpr->iTable = exprProbability(pList->a[1].pExpr);
1016             if( pExpr->iTable<0 ){
1017               sqlite3ErrorMsg(pParse,
1018                 "second argument to %#T() must be a "
1019                 "constant between 0.0 and 1.0", pExpr);
1020               pNC->nNcErr++;
1021             }
1022           }else{
1023             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1024             ** equivalent to likelihood(X, 0.0625).
1025             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1026             ** short-hand for likelihood(X,0.0625).
1027             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1028             ** for likelihood(X,0.9375).
1029             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1030             ** to likelihood(X,0.9375). */
1031             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
1032             pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
1033           }
1034         }
1035 #ifndef SQLITE_OMIT_AUTHORIZATION
1036         {
1037           int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
1038           if( auth!=SQLITE_OK ){
1039             if( auth==SQLITE_DENY ){
1040               sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
1041                                       pExpr);
1042               pNC->nNcErr++;
1043             }
1044             pExpr->op = TK_NULL;
1045             return WRC_Prune;
1046           }
1047         }
1048 #endif
1049         if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
1050           /* For the purposes of the EP_ConstFunc flag, date and time
1051           ** functions and other functions that change slowly are considered
1052           ** constant because they are constant for the duration of one query.
1053           ** This allows them to be factored out of inner loops. */
1054           ExprSetProperty(pExpr,EP_ConstFunc);
1055         }
1056         if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
1057           /* Clearly non-deterministic functions like random(), but also
1058           ** date/time functions that use 'now', and other functions like
1059           ** sqlite_version() that might change over time cannot be used
1060           ** in an index or generated column.  Curiously, they can be used
1061           ** in a CHECK constraint.  SQLServer, MySQL, and PostgreSQL all
1062           ** all this. */
1063           sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
1064                                  NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
1065         }else{
1066           assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
1067           pExpr->op2 = pNC->ncFlags & NC_SelfRef;
1068           if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
1069         }
1070         if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
1071          && pParse->nested==0
1072          && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
1073         ){
1074           /* Internal-use-only functions are disallowed unless the
1075           ** SQL is being compiled using sqlite3NestedParse() or
1076           ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1077           ** used to activate internal functions for testing purposes */
1078           no_such_func = 1;
1079           pDef = 0;
1080         }else
1081         if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
1082          && !IN_RENAME_OBJECT
1083         ){
1084           sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
1085         }
1086       }
1087 
1088       if( 0==IN_RENAME_OBJECT ){
1089 #ifndef SQLITE_OMIT_WINDOWFUNC
1090         assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
1091           || (pDef->xValue==0 && pDef->xInverse==0)
1092           || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
1093         );
1094         if( pDef && pDef->xValue==0 && pWin ){
1095           sqlite3ErrorMsg(pParse,
1096               "%#T() may not be used as a window function", pExpr
1097           );
1098           pNC->nNcErr++;
1099         }else if(
1100               (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
1101            || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
1102            || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
1103         ){
1104           const char *zType;
1105           if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
1106             zType = "window";
1107           }else{
1108             zType = "aggregate";
1109           }
1110           sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
1111           pNC->nNcErr++;
1112           is_agg = 0;
1113         }
1114 #else
1115         if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
1116           sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
1117           pNC->nNcErr++;
1118           is_agg = 0;
1119         }
1120 #endif
1121         else if( no_such_func && pParse->db->init.busy==0
1122 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1123                   && pParse->explain==0
1124 #endif
1125         ){
1126           sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
1127           pNC->nNcErr++;
1128         }else if( wrong_num_args ){
1129           sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
1130                pExpr);
1131           pNC->nNcErr++;
1132         }
1133 #ifndef SQLITE_OMIT_WINDOWFUNC
1134         else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
1135           sqlite3ErrorMsg(pParse,
1136               "FILTER may not be used with non-aggregate %#T()",
1137               pExpr
1138           );
1139           pNC->nNcErr++;
1140         }
1141 #endif
1142         if( is_agg ){
1143           /* Window functions may not be arguments of aggregate functions.
1144           ** Or arguments of other window functions. But aggregate functions
1145           ** may be arguments for window functions.  */
1146 #ifndef SQLITE_OMIT_WINDOWFUNC
1147           pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
1148 #else
1149           pNC->ncFlags &= ~NC_AllowAgg;
1150 #endif
1151         }
1152       }
1153 #ifndef SQLITE_OMIT_WINDOWFUNC
1154       else if( ExprHasProperty(pExpr, EP_WinFunc) ){
1155         is_agg = 1;
1156       }
1157 #endif
1158       sqlite3WalkExprList(pWalker, pList);
1159       if( is_agg ){
1160 #ifndef SQLITE_OMIT_WINDOWFUNC
1161         if( pWin ){
1162           Select *pSel = pNC->pWinSelect;
1163           assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) );
1164           if( IN_RENAME_OBJECT==0 ){
1165             sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
1166             if( pParse->db->mallocFailed ) break;
1167           }
1168           sqlite3WalkExprList(pWalker, pWin->pPartition);
1169           sqlite3WalkExprList(pWalker, pWin->pOrderBy);
1170           sqlite3WalkExpr(pWalker, pWin->pFilter);
1171           sqlite3WindowLink(pSel, pWin);
1172           pNC->ncFlags |= NC_HasWin;
1173         }else
1174 #endif /* SQLITE_OMIT_WINDOWFUNC */
1175         {
1176           NameContext *pNC2;          /* For looping up thru outer contexts */
1177           pExpr->op = TK_AGG_FUNCTION;
1178           pExpr->op2 = 0;
1179 #ifndef SQLITE_OMIT_WINDOWFUNC
1180           if( ExprHasProperty(pExpr, EP_WinFunc) ){
1181             sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
1182           }
1183 #endif
1184           pNC2 = pNC;
1185           while( pNC2
1186               && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
1187           ){
1188             pExpr->op2++;
1189             pNC2 = pNC2->pNext;
1190           }
1191           assert( pDef!=0 || IN_RENAME_OBJECT );
1192           if( pNC2 && pDef ){
1193             assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
1194             assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
1195             testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
1196             testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
1197             pNC2->ncFlags |= NC_HasAgg
1198               | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
1199                   & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
1200           }
1201         }
1202         pNC->ncFlags |= savedAllowFlags;
1203       }
1204       /* FIX ME:  Compute pExpr->affinity based on the expected return
1205       ** type of the function
1206       */
1207       return WRC_Prune;
1208     }
1209 #ifndef SQLITE_OMIT_SUBQUERY
1210     case TK_SELECT:
1211     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
1212 #endif
1213     case TK_IN: {
1214       testcase( pExpr->op==TK_IN );
1215       if( ExprUseXSelect(pExpr) ){
1216         int nRef = pNC->nRef;
1217         testcase( pNC->ncFlags & NC_IsCheck );
1218         testcase( pNC->ncFlags & NC_PartIdx );
1219         testcase( pNC->ncFlags & NC_IdxExpr );
1220         testcase( pNC->ncFlags & NC_GenCol );
1221         if( pNC->ncFlags & NC_SelfRef ){
1222           notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
1223         }else{
1224           sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
1225         }
1226         assert( pNC->nRef>=nRef );
1227         if( nRef!=pNC->nRef ){
1228           ExprSetProperty(pExpr, EP_VarSelect);
1229           pNC->ncFlags |= NC_VarSelect;
1230         }
1231       }
1232       break;
1233     }
1234     case TK_VARIABLE: {
1235       testcase( pNC->ncFlags & NC_IsCheck );
1236       testcase( pNC->ncFlags & NC_PartIdx );
1237       testcase( pNC->ncFlags & NC_IdxExpr );
1238       testcase( pNC->ncFlags & NC_GenCol );
1239       sqlite3ResolveNotValid(pParse, pNC, "parameters",
1240                NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
1241       break;
1242     }
1243     case TK_IS:
1244     case TK_ISNOT: {
1245       Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
1246       assert( !ExprHasProperty(pExpr, EP_Reduced) );
1247       /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1248       ** and "x IS NOT FALSE". */
1249       if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
1250         int rc = resolveExprStep(pWalker, pRight);
1251         if( rc==WRC_Abort ) return WRC_Abort;
1252         if( pRight->op==TK_TRUEFALSE ){
1253           pExpr->op2 = pExpr->op;
1254           pExpr->op = TK_TRUTH;
1255           return WRC_Continue;
1256         }
1257       }
1258       /* no break */ deliberate_fall_through
1259     }
1260     case TK_BETWEEN:
1261     case TK_EQ:
1262     case TK_NE:
1263     case TK_LT:
1264     case TK_LE:
1265     case TK_GT:
1266     case TK_GE: {
1267       int nLeft, nRight;
1268       if( pParse->db->mallocFailed ) break;
1269       assert( pExpr->pLeft!=0 );
1270       nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
1271       if( pExpr->op==TK_BETWEEN ){
1272         assert( ExprUseXList(pExpr) );
1273         nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
1274         if( nRight==nLeft ){
1275           nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
1276         }
1277       }else{
1278         assert( pExpr->pRight!=0 );
1279         nRight = sqlite3ExprVectorSize(pExpr->pRight);
1280       }
1281       if( nLeft!=nRight ){
1282         testcase( pExpr->op==TK_EQ );
1283         testcase( pExpr->op==TK_NE );
1284         testcase( pExpr->op==TK_LT );
1285         testcase( pExpr->op==TK_LE );
1286         testcase( pExpr->op==TK_GT );
1287         testcase( pExpr->op==TK_GE );
1288         testcase( pExpr->op==TK_IS );
1289         testcase( pExpr->op==TK_ISNOT );
1290         testcase( pExpr->op==TK_BETWEEN );
1291         sqlite3ErrorMsg(pParse, "row value misused");
1292         sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1293       }
1294       break;
1295     }
1296   }
1297   assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
1298   return pParse->nErr ? WRC_Abort : WRC_Continue;
1299 }
1300 
1301 /*
1302 ** pEList is a list of expressions which are really the result set of the
1303 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
1304 ** This routine checks to see if pE is a simple identifier which corresponds
1305 ** to the AS-name of one of the terms of the expression list.  If it is,
1306 ** this routine return an integer between 1 and N where N is the number of
1307 ** elements in pEList, corresponding to the matching entry.  If there is
1308 ** no match, or if pE is not a simple identifier, then this routine
1309 ** return 0.
1310 **
1311 ** pEList has been resolved.  pE has not.
1312 */
1313 static int resolveAsName(
1314   Parse *pParse,     /* Parsing context for error messages */
1315   ExprList *pEList,  /* List of expressions to scan */
1316   Expr *pE           /* Expression we are trying to match */
1317 ){
1318   int i;             /* Loop counter */
1319 
1320   UNUSED_PARAMETER(pParse);
1321 
1322   if( pE->op==TK_ID ){
1323     const char *zCol;
1324     assert( !ExprHasProperty(pE, EP_IntValue) );
1325     zCol = pE->u.zToken;
1326     for(i=0; i<pEList->nExpr; i++){
1327       if( pEList->a[i].eEName==ENAME_NAME
1328        && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
1329       ){
1330         return i+1;
1331       }
1332     }
1333   }
1334   return 0;
1335 }
1336 
1337 /*
1338 ** pE is a pointer to an expression which is a single term in the
1339 ** ORDER BY of a compound SELECT.  The expression has not been
1340 ** name resolved.
1341 **
1342 ** At the point this routine is called, we already know that the
1343 ** ORDER BY term is not an integer index into the result set.  That
1344 ** case is handled by the calling routine.
1345 **
1346 ** Attempt to match pE against result set columns in the left-most
1347 ** SELECT statement.  Return the index i of the matching column,
1348 ** as an indication to the caller that it should sort by the i-th column.
1349 ** The left-most column is 1.  In other words, the value returned is the
1350 ** same integer value that would be used in the SQL statement to indicate
1351 ** the column.
1352 **
1353 ** If there is no match, return 0.  Return -1 if an error occurs.
1354 */
1355 static int resolveOrderByTermToExprList(
1356   Parse *pParse,     /* Parsing context for error messages */
1357   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
1358   Expr *pE           /* The specific ORDER BY term */
1359 ){
1360   int i;             /* Loop counter */
1361   ExprList *pEList;  /* The columns of the result set */
1362   NameContext nc;    /* Name context for resolving pE */
1363   sqlite3 *db;       /* Database connection */
1364   int rc;            /* Return code from subprocedures */
1365   u8 savedSuppErr;   /* Saved value of db->suppressErr */
1366 
1367   assert( sqlite3ExprIsInteger(pE, &i)==0 );
1368   pEList = pSelect->pEList;
1369 
1370   /* Resolve all names in the ORDER BY term expression
1371   */
1372   memset(&nc, 0, sizeof(nc));
1373   nc.pParse = pParse;
1374   nc.pSrcList = pSelect->pSrc;
1375   nc.uNC.pEList = pEList;
1376   nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
1377   nc.nNcErr = 0;
1378   db = pParse->db;
1379   savedSuppErr = db->suppressErr;
1380   db->suppressErr = 1;
1381   rc = sqlite3ResolveExprNames(&nc, pE);
1382   db->suppressErr = savedSuppErr;
1383   if( rc ) return 0;
1384 
1385   /* Try to match the ORDER BY expression against an expression
1386   ** in the result set.  Return an 1-based index of the matching
1387   ** result-set entry.
1388   */
1389   for(i=0; i<pEList->nExpr; i++){
1390     if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
1391       return i+1;
1392     }
1393   }
1394 
1395   /* If no match, return 0. */
1396   return 0;
1397 }
1398 
1399 /*
1400 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1401 */
1402 static void resolveOutOfRangeError(
1403   Parse *pParse,         /* The error context into which to write the error */
1404   const char *zType,     /* "ORDER" or "GROUP" */
1405   int i,                 /* The index (1-based) of the term out of range */
1406   int mx,                /* Largest permissible value of i */
1407   Expr *pError           /* Associate the error with the expression */
1408 ){
1409   sqlite3ErrorMsg(pParse,
1410     "%r %s BY term out of range - should be "
1411     "between 1 and %d", i, zType, mx);
1412   sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
1413 }
1414 
1415 /*
1416 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
1417 ** each term of the ORDER BY clause is a constant integer between 1
1418 ** and N where N is the number of columns in the compound SELECT.
1419 **
1420 ** ORDER BY terms that are already an integer between 1 and N are
1421 ** unmodified.  ORDER BY terms that are integers outside the range of
1422 ** 1 through N generate an error.  ORDER BY terms that are expressions
1423 ** are matched against result set expressions of compound SELECT
1424 ** beginning with the left-most SELECT and working toward the right.
1425 ** At the first match, the ORDER BY expression is transformed into
1426 ** the integer column number.
1427 **
1428 ** Return the number of errors seen.
1429 */
1430 static int resolveCompoundOrderBy(
1431   Parse *pParse,        /* Parsing context.  Leave error messages here */
1432   Select *pSelect       /* The SELECT statement containing the ORDER BY */
1433 ){
1434   int i;
1435   ExprList *pOrderBy;
1436   ExprList *pEList;
1437   sqlite3 *db;
1438   int moreToDo = 1;
1439 
1440   pOrderBy = pSelect->pOrderBy;
1441   if( pOrderBy==0 ) return 0;
1442   db = pParse->db;
1443   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1444     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
1445     return 1;
1446   }
1447   for(i=0; i<pOrderBy->nExpr; i++){
1448     pOrderBy->a[i].done = 0;
1449   }
1450   pSelect->pNext = 0;
1451   while( pSelect->pPrior ){
1452     pSelect->pPrior->pNext = pSelect;
1453     pSelect = pSelect->pPrior;
1454   }
1455   while( pSelect && moreToDo ){
1456     struct ExprList_item *pItem;
1457     moreToDo = 0;
1458     pEList = pSelect->pEList;
1459     assert( pEList!=0 );
1460     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1461       int iCol = -1;
1462       Expr *pE, *pDup;
1463       if( pItem->done ) continue;
1464       pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
1465       if( NEVER(pE==0) ) continue;
1466       if( sqlite3ExprIsInteger(pE, &iCol) ){
1467         if( iCol<=0 || iCol>pEList->nExpr ){
1468           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
1469           return 1;
1470         }
1471       }else{
1472         iCol = resolveAsName(pParse, pEList, pE);
1473         if( iCol==0 ){
1474           /* Now test if expression pE matches one of the values returned
1475           ** by pSelect. In the usual case this is done by duplicating the
1476           ** expression, resolving any symbols in it, and then comparing
1477           ** it against each expression returned by the SELECT statement.
1478           ** Once the comparisons are finished, the duplicate expression
1479           ** is deleted.
1480           **
1481           ** If this is running as part of an ALTER TABLE operation and
1482           ** the symbols resolve successfully, also resolve the symbols in the
1483           ** actual expression. This allows the code in alter.c to modify
1484           ** column references within the ORDER BY expression as required.  */
1485           pDup = sqlite3ExprDup(db, pE, 0);
1486           if( !db->mallocFailed ){
1487             assert(pDup);
1488             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
1489             if( IN_RENAME_OBJECT && iCol>0 ){
1490               resolveOrderByTermToExprList(pParse, pSelect, pE);
1491             }
1492           }
1493           sqlite3ExprDelete(db, pDup);
1494         }
1495       }
1496       if( iCol>0 ){
1497         /* Convert the ORDER BY term into an integer column number iCol,
1498         ** taking care to preserve the COLLATE clause if it exists. */
1499         if( !IN_RENAME_OBJECT ){
1500           Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
1501           if( pNew==0 ) return 1;
1502           pNew->flags |= EP_IntValue;
1503           pNew->u.iValue = iCol;
1504           if( pItem->pExpr==pE ){
1505             pItem->pExpr = pNew;
1506           }else{
1507             Expr *pParent = pItem->pExpr;
1508             assert( pParent->op==TK_COLLATE );
1509             while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
1510             assert( pParent->pLeft==pE );
1511             pParent->pLeft = pNew;
1512           }
1513           sqlite3ExprDelete(db, pE);
1514           pItem->u.x.iOrderByCol = (u16)iCol;
1515         }
1516         pItem->done = 1;
1517       }else{
1518         moreToDo = 1;
1519       }
1520     }
1521     pSelect = pSelect->pNext;
1522   }
1523   for(i=0; i<pOrderBy->nExpr; i++){
1524     if( pOrderBy->a[i].done==0 ){
1525       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
1526             "column in the result set", i+1);
1527       return 1;
1528     }
1529   }
1530   return 0;
1531 }
1532 
1533 /*
1534 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1535 ** the SELECT statement pSelect.  If any term is reference to a
1536 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1537 ** field) then convert that term into a copy of the corresponding result set
1538 ** column.
1539 **
1540 ** If any errors are detected, add an error message to pParse and
1541 ** return non-zero.  Return zero if no errors are seen.
1542 */
1543 int sqlite3ResolveOrderGroupBy(
1544   Parse *pParse,        /* Parsing context.  Leave error messages here */
1545   Select *pSelect,      /* The SELECT statement containing the clause */
1546   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
1547   const char *zType     /* "ORDER" or "GROUP" */
1548 ){
1549   int i;
1550   sqlite3 *db = pParse->db;
1551   ExprList *pEList;
1552   struct ExprList_item *pItem;
1553 
1554   if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
1555   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1556     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1557     return 1;
1558   }
1559   pEList = pSelect->pEList;
1560   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
1561   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1562     if( pItem->u.x.iOrderByCol ){
1563       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
1564         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
1565         return 1;
1566       }
1567       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
1568     }
1569   }
1570   return 0;
1571 }
1572 
1573 #ifndef SQLITE_OMIT_WINDOWFUNC
1574 /*
1575 ** Walker callback for windowRemoveExprFromSelect().
1576 */
1577 static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
1578   UNUSED_PARAMETER(pWalker);
1579   if( ExprHasProperty(pExpr, EP_WinFunc) ){
1580     Window *pWin = pExpr->y.pWin;
1581     sqlite3WindowUnlinkFromSelect(pWin);
1582   }
1583   return WRC_Continue;
1584 }
1585 
1586 /*
1587 ** Remove any Window objects owned by the expression pExpr from the
1588 ** Select.pWin list of Select object pSelect.
1589 */
1590 static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
1591   if( pSelect->pWin ){
1592     Walker sWalker;
1593     memset(&sWalker, 0, sizeof(Walker));
1594     sWalker.xExprCallback = resolveRemoveWindowsCb;
1595     sWalker.u.pSelect = pSelect;
1596     sqlite3WalkExpr(&sWalker, pExpr);
1597   }
1598 }
1599 #else
1600 # define windowRemoveExprFromSelect(a, b)
1601 #endif /* SQLITE_OMIT_WINDOWFUNC */
1602 
1603 /*
1604 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1605 ** The Name context of the SELECT statement is pNC.  zType is either
1606 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1607 **
1608 ** This routine resolves each term of the clause into an expression.
1609 ** If the order-by term is an integer I between 1 and N (where N is the
1610 ** number of columns in the result set of the SELECT) then the expression
1611 ** in the resolution is a copy of the I-th result-set expression.  If
1612 ** the order-by term is an identifier that corresponds to the AS-name of
1613 ** a result-set expression, then the term resolves to a copy of the
1614 ** result-set expression.  Otherwise, the expression is resolved in
1615 ** the usual way - using sqlite3ResolveExprNames().
1616 **
1617 ** This routine returns the number of errors.  If errors occur, then
1618 ** an appropriate error message might be left in pParse.  (OOM errors
1619 ** excepted.)
1620 */
1621 static int resolveOrderGroupBy(
1622   NameContext *pNC,     /* The name context of the SELECT statement */
1623   Select *pSelect,      /* The SELECT statement holding pOrderBy */
1624   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
1625   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
1626 ){
1627   int i, j;                      /* Loop counters */
1628   int iCol;                      /* Column number */
1629   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
1630   Parse *pParse;                 /* Parsing context */
1631   int nResult;                   /* Number of terms in the result set */
1632 
1633   assert( pOrderBy!=0 );
1634   nResult = pSelect->pEList->nExpr;
1635   pParse = pNC->pParse;
1636   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1637     Expr *pE = pItem->pExpr;
1638     Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
1639     if( NEVER(pE2==0) ) continue;
1640     if( zType[0]!='G' ){
1641       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1642       if( iCol>0 ){
1643         /* If an AS-name match is found, mark this ORDER BY column as being
1644         ** a copy of the iCol-th result-set column.  The subsequent call to
1645         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1646         ** copy of the iCol-th result-set expression. */
1647         pItem->u.x.iOrderByCol = (u16)iCol;
1648         continue;
1649       }
1650     }
1651     if( sqlite3ExprIsInteger(pE2, &iCol) ){
1652       /* The ORDER BY term is an integer constant.  Again, set the column
1653       ** number so that sqlite3ResolveOrderGroupBy() will convert the
1654       ** order-by term to a copy of the result-set expression */
1655       if( iCol<1 || iCol>0xffff ){
1656         resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
1657         return 1;
1658       }
1659       pItem->u.x.iOrderByCol = (u16)iCol;
1660       continue;
1661     }
1662 
1663     /* Otherwise, treat the ORDER BY term as an ordinary expression */
1664     pItem->u.x.iOrderByCol = 0;
1665     if( sqlite3ResolveExprNames(pNC, pE) ){
1666       return 1;
1667     }
1668     for(j=0; j<pSelect->pEList->nExpr; j++){
1669       if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
1670         /* Since this expresion is being changed into a reference
1671         ** to an identical expression in the result set, remove all Window
1672         ** objects belonging to the expression from the Select.pWin list. */
1673         windowRemoveExprFromSelect(pSelect, pE);
1674         pItem->u.x.iOrderByCol = j+1;
1675       }
1676     }
1677   }
1678   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1679 }
1680 
1681 /*
1682 ** Resolve names in the SELECT statement p and all of its descendants.
1683 */
1684 static int resolveSelectStep(Walker *pWalker, Select *p){
1685   NameContext *pOuterNC;  /* Context that contains this SELECT */
1686   NameContext sNC;        /* Name context of this SELECT */
1687   int isCompound;         /* True if p is a compound select */
1688   int nCompound;          /* Number of compound terms processed so far */
1689   Parse *pParse;          /* Parsing context */
1690   int i;                  /* Loop counter */
1691   ExprList *pGroupBy;     /* The GROUP BY clause */
1692   Select *pLeftmost;      /* Left-most of SELECT of a compound */
1693   sqlite3 *db;            /* Database connection */
1694 
1695 
1696   assert( p!=0 );
1697   if( p->selFlags & SF_Resolved ){
1698     return WRC_Prune;
1699   }
1700   pOuterNC = pWalker->u.pNC;
1701   pParse = pWalker->pParse;
1702   db = pParse->db;
1703 
1704   /* Normally sqlite3SelectExpand() will be called first and will have
1705   ** already expanded this SELECT.  However, if this is a subquery within
1706   ** an expression, sqlite3ResolveExprNames() will be called without a
1707   ** prior call to sqlite3SelectExpand().  When that happens, let
1708   ** sqlite3SelectPrep() do all of the processing for this SELECT.
1709   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1710   ** this routine in the correct order.
1711   */
1712   if( (p->selFlags & SF_Expanded)==0 ){
1713     sqlite3SelectPrep(pParse, p, pOuterNC);
1714     return pParse->nErr ? WRC_Abort : WRC_Prune;
1715   }
1716 
1717   isCompound = p->pPrior!=0;
1718   nCompound = 0;
1719   pLeftmost = p;
1720   while( p ){
1721     assert( (p->selFlags & SF_Expanded)!=0 );
1722     assert( (p->selFlags & SF_Resolved)==0 );
1723     assert( db->suppressErr==0 ); /* SF_Resolved not set if errors suppressed */
1724     p->selFlags |= SF_Resolved;
1725 
1726 
1727     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1728     ** are not allowed to refer to any names, so pass an empty NameContext.
1729     */
1730     memset(&sNC, 0, sizeof(sNC));
1731     sNC.pParse = pParse;
1732     sNC.pWinSelect = p;
1733     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
1734       return WRC_Abort;
1735     }
1736 
1737     /* If the SF_Converted flags is set, then this Select object was
1738     ** was created by the convertCompoundSelectToSubquery() function.
1739     ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1740     ** as if it were part of the sub-query, not the parent. This block
1741     ** moves the pOrderBy down to the sub-query. It will be moved back
1742     ** after the names have been resolved.  */
1743     if( p->selFlags & SF_Converted ){
1744       Select *pSub = p->pSrc->a[0].pSelect;
1745       assert( p->pSrc->nSrc==1 && p->pOrderBy );
1746       assert( pSub->pPrior && pSub->pOrderBy==0 );
1747       pSub->pOrderBy = p->pOrderBy;
1748       p->pOrderBy = 0;
1749     }
1750 
1751     /* Recursively resolve names in all subqueries in the FROM clause
1752     */
1753     for(i=0; i<p->pSrc->nSrc; i++){
1754       SrcItem *pItem = &p->pSrc->a[i];
1755       if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
1756         int nRef = pOuterNC ? pOuterNC->nRef : 0;
1757         const char *zSavedContext = pParse->zAuthContext;
1758 
1759         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1760         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
1761         pParse->zAuthContext = zSavedContext;
1762         if( pParse->nErr ) return WRC_Abort;
1763         assert( db->mallocFailed==0 );
1764 
1765         /* If the number of references to the outer context changed when
1766         ** expressions in the sub-select were resolved, the sub-select
1767         ** is correlated. It is not required to check the refcount on any
1768         ** but the innermost outer context object, as lookupName() increments
1769         ** the refcount on all contexts between the current one and the
1770         ** context containing the column when it resolves a name. */
1771         if( pOuterNC ){
1772           assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
1773           pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
1774         }
1775       }
1776     }
1777 
1778     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1779     ** resolve the result-set expression list.
1780     */
1781     sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
1782     sNC.pSrcList = p->pSrc;
1783     sNC.pNext = pOuterNC;
1784 
1785     /* Resolve names in the result set. */
1786     if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
1787     sNC.ncFlags &= ~NC_AllowWin;
1788 
1789     /* If there are no aggregate functions in the result-set, and no GROUP BY
1790     ** expression, do not allow aggregates in any of the other expressions.
1791     */
1792     assert( (p->selFlags & SF_Aggregate)==0 );
1793     pGroupBy = p->pGroupBy;
1794     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
1795       assert( NC_MinMaxAgg==SF_MinMaxAgg );
1796       assert( NC_OrderAgg==SF_OrderByReqd );
1797       p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
1798     }else{
1799       sNC.ncFlags &= ~NC_AllowAgg;
1800     }
1801 
1802     /* Add the output column list to the name-context before parsing the
1803     ** other expressions in the SELECT statement. This is so that
1804     ** expressions in the WHERE clause (etc.) can refer to expressions by
1805     ** aliases in the result set.
1806     **
1807     ** Minor point: If this is the case, then the expression will be
1808     ** re-evaluated for each reference to it.
1809     */
1810     assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
1811     sNC.uNC.pEList = p->pEList;
1812     sNC.ncFlags |= NC_UEList;
1813     if( p->pHaving ){
1814       if( !pGroupBy ){
1815         sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1816         return WRC_Abort;
1817       }
1818       if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1819     }
1820     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
1821 
1822     /* Resolve names in table-valued-function arguments */
1823     for(i=0; i<p->pSrc->nSrc; i++){
1824       SrcItem *pItem = &p->pSrc->a[i];
1825       if( pItem->fg.isTabFunc
1826        && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
1827       ){
1828         return WRC_Abort;
1829       }
1830     }
1831 
1832 #ifndef SQLITE_OMIT_WINDOWFUNC
1833     if( IN_RENAME_OBJECT ){
1834       Window *pWin;
1835       for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
1836         if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
1837          || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
1838         ){
1839           return WRC_Abort;
1840         }
1841       }
1842     }
1843 #endif
1844 
1845     /* The ORDER BY and GROUP BY clauses may not refer to terms in
1846     ** outer queries
1847     */
1848     sNC.pNext = 0;
1849     sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
1850 
1851     /* If this is a converted compound query, move the ORDER BY clause from
1852     ** the sub-query back to the parent query. At this point each term
1853     ** within the ORDER BY clause has been transformed to an integer value.
1854     ** These integers will be replaced by copies of the corresponding result
1855     ** set expressions by the call to resolveOrderGroupBy() below.  */
1856     if( p->selFlags & SF_Converted ){
1857       Select *pSub = p->pSrc->a[0].pSelect;
1858       p->pOrderBy = pSub->pOrderBy;
1859       pSub->pOrderBy = 0;
1860     }
1861 
1862     /* Process the ORDER BY clause for singleton SELECT statements.
1863     ** The ORDER BY clause for compounds SELECT statements is handled
1864     ** below, after all of the result-sets for all of the elements of
1865     ** the compound have been resolved.
1866     **
1867     ** If there is an ORDER BY clause on a term of a compound-select other
1868     ** than the right-most term, then that is a syntax error.  But the error
1869     ** is not detected until much later, and so we need to go ahead and
1870     ** resolve those symbols on the incorrect ORDER BY for consistency.
1871     */
1872     if( p->pOrderBy!=0
1873      && isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
1874      && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
1875     ){
1876       return WRC_Abort;
1877     }
1878     if( db->mallocFailed ){
1879       return WRC_Abort;
1880     }
1881     sNC.ncFlags &= ~NC_AllowWin;
1882 
1883     /* Resolve the GROUP BY clause.  At the same time, make sure
1884     ** the GROUP BY clause does not contain aggregate functions.
1885     */
1886     if( pGroupBy ){
1887       struct ExprList_item *pItem;
1888 
1889       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1890         return WRC_Abort;
1891       }
1892       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1893         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1894           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1895               "the GROUP BY clause");
1896           return WRC_Abort;
1897         }
1898       }
1899     }
1900 
1901     /* If this is part of a compound SELECT, check that it has the right
1902     ** number of expressions in the select list. */
1903     if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
1904       sqlite3SelectWrongNumTermsError(pParse, p->pNext);
1905       return WRC_Abort;
1906     }
1907 
1908     /* Advance to the next term of the compound
1909     */
1910     p = p->pPrior;
1911     nCompound++;
1912   }
1913 
1914   /* Resolve the ORDER BY on a compound SELECT after all terms of
1915   ** the compound have been resolved.
1916   */
1917   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1918     return WRC_Abort;
1919   }
1920 
1921   return WRC_Prune;
1922 }
1923 
1924 /*
1925 ** This routine walks an expression tree and resolves references to
1926 ** table columns and result-set columns.  At the same time, do error
1927 ** checking on function usage and set a flag if any aggregate functions
1928 ** are seen.
1929 **
1930 ** To resolve table columns references we look for nodes (or subtrees) of the
1931 ** form X.Y.Z or Y.Z or just Z where
1932 **
1933 **      X:   The name of a database.  Ex:  "main" or "temp" or
1934 **           the symbolic name assigned to an ATTACH-ed database.
1935 **
1936 **      Y:   The name of a table in a FROM clause.  Or in a trigger
1937 **           one of the special names "old" or "new".
1938 **
1939 **      Z:   The name of a column in table Y.
1940 **
1941 ** The node at the root of the subtree is modified as follows:
1942 **
1943 **    Expr.op        Changed to TK_COLUMN
1944 **    Expr.pTab      Points to the Table object for X.Y
1945 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
1946 **    Expr.iTable    The VDBE cursor number for X.Y
1947 **
1948 **
1949 ** To resolve result-set references, look for expression nodes of the
1950 ** form Z (with no X and Y prefix) where the Z matches the right-hand
1951 ** size of an AS clause in the result-set of a SELECT.  The Z expression
1952 ** is replaced by a copy of the left-hand side of the result-set expression.
1953 ** Table-name and function resolution occurs on the substituted expression
1954 ** tree.  For example, in:
1955 **
1956 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1957 **
1958 ** The "x" term of the order by is replaced by "a+b" to render:
1959 **
1960 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1961 **
1962 ** Function calls are checked to make sure that the function is
1963 ** defined and that the correct number of arguments are specified.
1964 ** If the function is an aggregate function, then the NC_HasAgg flag is
1965 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1966 ** If an expression contains aggregate functions then the EP_Agg
1967 ** property on the expression is set.
1968 **
1969 ** An error message is left in pParse if anything is amiss.  The number
1970 ** if errors is returned.
1971 */
1972 int sqlite3ResolveExprNames(
1973   NameContext *pNC,       /* Namespace to resolve expressions in. */
1974   Expr *pExpr             /* The expression to be analyzed. */
1975 ){
1976   int savedHasAgg;
1977   Walker w;
1978 
1979   if( pExpr==0 ) return SQLITE_OK;
1980   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1981   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1982   w.pParse = pNC->pParse;
1983   w.xExprCallback = resolveExprStep;
1984   w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
1985   w.xSelectCallback2 = 0;
1986   w.u.pNC = pNC;
1987 #if SQLITE_MAX_EXPR_DEPTH>0
1988   w.pParse->nHeight += pExpr->nHeight;
1989   if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
1990     return SQLITE_ERROR;
1991   }
1992 #endif
1993   sqlite3WalkExpr(&w, pExpr);
1994 #if SQLITE_MAX_EXPR_DEPTH>0
1995   w.pParse->nHeight -= pExpr->nHeight;
1996 #endif
1997   assert( EP_Agg==NC_HasAgg );
1998   assert( EP_Win==NC_HasWin );
1999   testcase( pNC->ncFlags & NC_HasAgg );
2000   testcase( pNC->ncFlags & NC_HasWin );
2001   ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2002   pNC->ncFlags |= savedHasAgg;
2003   return pNC->nNcErr>0 || w.pParse->nErr>0;
2004 }
2005 
2006 /*
2007 ** Resolve all names for all expression in an expression list.  This is
2008 ** just like sqlite3ResolveExprNames() except that it works for an expression
2009 ** list rather than a single expression.
2010 */
2011 int sqlite3ResolveExprListNames(
2012   NameContext *pNC,       /* Namespace to resolve expressions in. */
2013   ExprList *pList         /* The expression list to be analyzed. */
2014 ){
2015   int i;
2016   int savedHasAgg = 0;
2017   Walker w;
2018   if( pList==0 ) return WRC_Continue;
2019   w.pParse = pNC->pParse;
2020   w.xExprCallback = resolveExprStep;
2021   w.xSelectCallback = resolveSelectStep;
2022   w.xSelectCallback2 = 0;
2023   w.u.pNC = pNC;
2024   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2025   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2026   for(i=0; i<pList->nExpr; i++){
2027     Expr *pExpr = pList->a[i].pExpr;
2028     if( pExpr==0 ) continue;
2029 #if SQLITE_MAX_EXPR_DEPTH>0
2030     w.pParse->nHeight += pExpr->nHeight;
2031     if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2032       return WRC_Abort;
2033     }
2034 #endif
2035     sqlite3WalkExpr(&w, pExpr);
2036 #if SQLITE_MAX_EXPR_DEPTH>0
2037     w.pParse->nHeight -= pExpr->nHeight;
2038 #endif
2039     assert( EP_Agg==NC_HasAgg );
2040     assert( EP_Win==NC_HasWin );
2041     testcase( pNC->ncFlags & NC_HasAgg );
2042     testcase( pNC->ncFlags & NC_HasWin );
2043     if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
2044       ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2045       savedHasAgg |= pNC->ncFlags &
2046                           (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2047       pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2048     }
2049     if( w.pParse->nErr>0 ) return WRC_Abort;
2050   }
2051   pNC->ncFlags |= savedHasAgg;
2052   return WRC_Continue;
2053 }
2054 
2055 /*
2056 ** Resolve all names in all expressions of a SELECT and in all
2057 ** decendents of the SELECT, including compounds off of p->pPrior,
2058 ** subqueries in expressions, and subqueries used as FROM clause
2059 ** terms.
2060 **
2061 ** See sqlite3ResolveExprNames() for a description of the kinds of
2062 ** transformations that occur.
2063 **
2064 ** All SELECT statements should have been expanded using
2065 ** sqlite3SelectExpand() prior to invoking this routine.
2066 */
2067 void sqlite3ResolveSelectNames(
2068   Parse *pParse,         /* The parser context */
2069   Select *p,             /* The SELECT statement being coded. */
2070   NameContext *pOuterNC  /* Name context for parent SELECT statement */
2071 ){
2072   Walker w;
2073 
2074   assert( p!=0 );
2075   w.xExprCallback = resolveExprStep;
2076   w.xSelectCallback = resolveSelectStep;
2077   w.xSelectCallback2 = 0;
2078   w.pParse = pParse;
2079   w.u.pNC = pOuterNC;
2080   sqlite3WalkSelect(&w, p);
2081 }
2082 
2083 /*
2084 ** Resolve names in expressions that can only reference a single table
2085 ** or which cannot reference any tables at all.  Examples:
2086 **
2087 **                                                    "type" flag
2088 **                                                    ------------
2089 **    (1)   CHECK constraints                         NC_IsCheck
2090 **    (2)   WHERE clauses on partial indices          NC_PartIdx
2091 **    (3)   Expressions in indexes on expressions     NC_IdxExpr
2092 **    (4)   Expression arguments to VACUUM INTO.      0
2093 **    (5)   GENERATED ALWAYS as expressions           NC_GenCol
2094 **
2095 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2096 ** nodes of the expression is set to -1 and the Expr.iColumn value is
2097 ** set to the column number.  In case (4), TK_COLUMN nodes cause an error.
2098 **
2099 ** Any errors cause an error message to be set in pParse.
2100 */
2101 int sqlite3ResolveSelfReference(
2102   Parse *pParse,   /* Parsing context */
2103   Table *pTab,     /* The table being referenced, or NULL */
2104   int type,        /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2105   Expr *pExpr,     /* Expression to resolve.  May be NULL. */
2106   ExprList *pList  /* Expression list to resolve.  May be NULL. */
2107 ){
2108   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
2109   NameContext sNC;                /* Name context for pParse->pNewTable */
2110   int rc;
2111 
2112   assert( type==0 || pTab!=0 );
2113   assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
2114           || type==NC_GenCol || pTab==0 );
2115   memset(&sNC, 0, sizeof(sNC));
2116   memset(&sSrc, 0, sizeof(sSrc));
2117   if( pTab ){
2118     sSrc.nSrc = 1;
2119     sSrc.a[0].zName = pTab->zName;
2120     sSrc.a[0].pTab = pTab;
2121     sSrc.a[0].iCursor = -1;
2122     if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
2123       /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2124       ** schema elements */
2125       type |= NC_FromDDL;
2126     }
2127   }
2128   sNC.pParse = pParse;
2129   sNC.pSrcList = &sSrc;
2130   sNC.ncFlags = type | NC_IsDDL;
2131   if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
2132   if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
2133   return rc;
2134 }
2135