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