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