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