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