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