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