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