xref: /sqlite-3.40.0/src/resolve.c (revision fd779e2f)
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         sqlite3ResolveNotValid(pParse, pNC, "subqueries",
1123                  NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
1124         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
1125         assert( pNC->nRef>=nRef );
1126         if( nRef!=pNC->nRef ){
1127           ExprSetProperty(pExpr, EP_VarSelect);
1128           pNC->ncFlags |= NC_VarSelect;
1129         }
1130       }
1131       break;
1132     }
1133     case TK_VARIABLE: {
1134       testcase( pNC->ncFlags & NC_IsCheck );
1135       testcase( pNC->ncFlags & NC_PartIdx );
1136       testcase( pNC->ncFlags & NC_IdxExpr );
1137       testcase( pNC->ncFlags & NC_GenCol );
1138       sqlite3ResolveNotValid(pParse, pNC, "parameters",
1139                NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
1140       break;
1141     }
1142     case TK_IS:
1143     case TK_ISNOT: {
1144       Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
1145       assert( !ExprHasProperty(pExpr, EP_Reduced) );
1146       /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1147       ** and "x IS NOT FALSE". */
1148       if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
1149         int rc = resolveExprStep(pWalker, pRight);
1150         if( rc==WRC_Abort ) return WRC_Abort;
1151         if( pRight->op==TK_TRUEFALSE ){
1152           pExpr->op2 = pExpr->op;
1153           pExpr->op = TK_TRUTH;
1154           return WRC_Continue;
1155         }
1156       }
1157       /* no break */ deliberate_fall_through
1158     }
1159     case TK_BETWEEN:
1160     case TK_EQ:
1161     case TK_NE:
1162     case TK_LT:
1163     case TK_LE:
1164     case TK_GT:
1165     case TK_GE: {
1166       int nLeft, nRight;
1167       if( pParse->db->mallocFailed ) break;
1168       assert( pExpr->pLeft!=0 );
1169       nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
1170       if( pExpr->op==TK_BETWEEN ){
1171         nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
1172         if( nRight==nLeft ){
1173           nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
1174         }
1175       }else{
1176         assert( pExpr->pRight!=0 );
1177         nRight = sqlite3ExprVectorSize(pExpr->pRight);
1178       }
1179       if( nLeft!=nRight ){
1180         testcase( pExpr->op==TK_EQ );
1181         testcase( pExpr->op==TK_NE );
1182         testcase( pExpr->op==TK_LT );
1183         testcase( pExpr->op==TK_LE );
1184         testcase( pExpr->op==TK_GT );
1185         testcase( pExpr->op==TK_GE );
1186         testcase( pExpr->op==TK_IS );
1187         testcase( pExpr->op==TK_ISNOT );
1188         testcase( pExpr->op==TK_BETWEEN );
1189         sqlite3ErrorMsg(pParse, "row value misused");
1190       }
1191       break;
1192     }
1193   }
1194   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
1195 }
1196 
1197 /*
1198 ** pEList is a list of expressions which are really the result set of the
1199 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
1200 ** This routine checks to see if pE is a simple identifier which corresponds
1201 ** to the AS-name of one of the terms of the expression list.  If it is,
1202 ** this routine return an integer between 1 and N where N is the number of
1203 ** elements in pEList, corresponding to the matching entry.  If there is
1204 ** no match, or if pE is not a simple identifier, then this routine
1205 ** return 0.
1206 **
1207 ** pEList has been resolved.  pE has not.
1208 */
1209 static int resolveAsName(
1210   Parse *pParse,     /* Parsing context for error messages */
1211   ExprList *pEList,  /* List of expressions to scan */
1212   Expr *pE           /* Expression we are trying to match */
1213 ){
1214   int i;             /* Loop counter */
1215 
1216   UNUSED_PARAMETER(pParse);
1217 
1218   if( pE->op==TK_ID ){
1219     char *zCol = pE->u.zToken;
1220     for(i=0; i<pEList->nExpr; i++){
1221       if( pEList->a[i].eEName==ENAME_NAME
1222        && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
1223       ){
1224         return i+1;
1225       }
1226     }
1227   }
1228   return 0;
1229 }
1230 
1231 /*
1232 ** pE is a pointer to an expression which is a single term in the
1233 ** ORDER BY of a compound SELECT.  The expression has not been
1234 ** name resolved.
1235 **
1236 ** At the point this routine is called, we already know that the
1237 ** ORDER BY term is not an integer index into the result set.  That
1238 ** case is handled by the calling routine.
1239 **
1240 ** Attempt to match pE against result set columns in the left-most
1241 ** SELECT statement.  Return the index i of the matching column,
1242 ** as an indication to the caller that it should sort by the i-th column.
1243 ** The left-most column is 1.  In other words, the value returned is the
1244 ** same integer value that would be used in the SQL statement to indicate
1245 ** the column.
1246 **
1247 ** If there is no match, return 0.  Return -1 if an error occurs.
1248 */
1249 static int resolveOrderByTermToExprList(
1250   Parse *pParse,     /* Parsing context for error messages */
1251   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
1252   Expr *pE           /* The specific ORDER BY term */
1253 ){
1254   int i;             /* Loop counter */
1255   ExprList *pEList;  /* The columns of the result set */
1256   NameContext nc;    /* Name context for resolving pE */
1257   sqlite3 *db;       /* Database connection */
1258   int rc;            /* Return code from subprocedures */
1259   u8 savedSuppErr;   /* Saved value of db->suppressErr */
1260 
1261   assert( sqlite3ExprIsInteger(pE, &i)==0 );
1262   pEList = pSelect->pEList;
1263 
1264   /* Resolve all names in the ORDER BY term expression
1265   */
1266   memset(&nc, 0, sizeof(nc));
1267   nc.pParse = pParse;
1268   nc.pSrcList = pSelect->pSrc;
1269   nc.uNC.pEList = pEList;
1270   nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
1271   nc.nNcErr = 0;
1272   db = pParse->db;
1273   savedSuppErr = db->suppressErr;
1274   db->suppressErr = 1;
1275   rc = sqlite3ResolveExprNames(&nc, pE);
1276   db->suppressErr = savedSuppErr;
1277   if( rc ) return 0;
1278 
1279   /* Try to match the ORDER BY expression against an expression
1280   ** in the result set.  Return an 1-based index of the matching
1281   ** result-set entry.
1282   */
1283   for(i=0; i<pEList->nExpr; i++){
1284     if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
1285       return i+1;
1286     }
1287   }
1288 
1289   /* If no match, return 0. */
1290   return 0;
1291 }
1292 
1293 /*
1294 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1295 */
1296 static void resolveOutOfRangeError(
1297   Parse *pParse,         /* The error context into which to write the error */
1298   const char *zType,     /* "ORDER" or "GROUP" */
1299   int i,                 /* The index (1-based) of the term out of range */
1300   int mx                 /* Largest permissible value of i */
1301 ){
1302   sqlite3ErrorMsg(pParse,
1303     "%r %s BY term out of range - should be "
1304     "between 1 and %d", i, zType, mx);
1305 }
1306 
1307 /*
1308 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
1309 ** each term of the ORDER BY clause is a constant integer between 1
1310 ** and N where N is the number of columns in the compound SELECT.
1311 **
1312 ** ORDER BY terms that are already an integer between 1 and N are
1313 ** unmodified.  ORDER BY terms that are integers outside the range of
1314 ** 1 through N generate an error.  ORDER BY terms that are expressions
1315 ** are matched against result set expressions of compound SELECT
1316 ** beginning with the left-most SELECT and working toward the right.
1317 ** At the first match, the ORDER BY expression is transformed into
1318 ** the integer column number.
1319 **
1320 ** Return the number of errors seen.
1321 */
1322 static int resolveCompoundOrderBy(
1323   Parse *pParse,        /* Parsing context.  Leave error messages here */
1324   Select *pSelect       /* The SELECT statement containing the ORDER BY */
1325 ){
1326   int i;
1327   ExprList *pOrderBy;
1328   ExprList *pEList;
1329   sqlite3 *db;
1330   int moreToDo = 1;
1331 
1332   pOrderBy = pSelect->pOrderBy;
1333   if( pOrderBy==0 ) return 0;
1334   db = pParse->db;
1335   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1336     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
1337     return 1;
1338   }
1339   for(i=0; i<pOrderBy->nExpr; i++){
1340     pOrderBy->a[i].done = 0;
1341   }
1342   pSelect->pNext = 0;
1343   while( pSelect->pPrior ){
1344     pSelect->pPrior->pNext = pSelect;
1345     pSelect = pSelect->pPrior;
1346   }
1347   while( pSelect && moreToDo ){
1348     struct ExprList_item *pItem;
1349     moreToDo = 0;
1350     pEList = pSelect->pEList;
1351     assert( pEList!=0 );
1352     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1353       int iCol = -1;
1354       Expr *pE, *pDup;
1355       if( pItem->done ) continue;
1356       pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
1357       if( NEVER(pE==0) ) continue;
1358       if( sqlite3ExprIsInteger(pE, &iCol) ){
1359         if( iCol<=0 || iCol>pEList->nExpr ){
1360           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
1361           return 1;
1362         }
1363       }else{
1364         iCol = resolveAsName(pParse, pEList, pE);
1365         if( iCol==0 ){
1366           /* Now test if expression pE matches one of the values returned
1367           ** by pSelect. In the usual case this is done by duplicating the
1368           ** expression, resolving any symbols in it, and then comparing
1369           ** it against each expression returned by the SELECT statement.
1370           ** Once the comparisons are finished, the duplicate expression
1371           ** is deleted.
1372           **
1373           ** If this is running as part of an ALTER TABLE operation and
1374           ** the symbols resolve successfully, also resolve the symbols in the
1375           ** actual expression. This allows the code in alter.c to modify
1376           ** column references within the ORDER BY expression as required.  */
1377           pDup = sqlite3ExprDup(db, pE, 0);
1378           if( !db->mallocFailed ){
1379             assert(pDup);
1380             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
1381             if( IN_RENAME_OBJECT && iCol>0 ){
1382               resolveOrderByTermToExprList(pParse, pSelect, pE);
1383             }
1384           }
1385           sqlite3ExprDelete(db, pDup);
1386         }
1387       }
1388       if( iCol>0 ){
1389         /* Convert the ORDER BY term into an integer column number iCol,
1390         ** taking care to preserve the COLLATE clause if it exists. */
1391         if( !IN_RENAME_OBJECT ){
1392           Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
1393           if( pNew==0 ) return 1;
1394           pNew->flags |= EP_IntValue;
1395           pNew->u.iValue = iCol;
1396           if( pItem->pExpr==pE ){
1397             pItem->pExpr = pNew;
1398           }else{
1399             Expr *pParent = pItem->pExpr;
1400             assert( pParent->op==TK_COLLATE );
1401             while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
1402             assert( pParent->pLeft==pE );
1403             pParent->pLeft = pNew;
1404           }
1405           sqlite3ExprDelete(db, pE);
1406           pItem->u.x.iOrderByCol = (u16)iCol;
1407         }
1408         pItem->done = 1;
1409       }else{
1410         moreToDo = 1;
1411       }
1412     }
1413     pSelect = pSelect->pNext;
1414   }
1415   for(i=0; i<pOrderBy->nExpr; i++){
1416     if( pOrderBy->a[i].done==0 ){
1417       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
1418             "column in the result set", i+1);
1419       return 1;
1420     }
1421   }
1422   return 0;
1423 }
1424 
1425 /*
1426 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1427 ** the SELECT statement pSelect.  If any term is reference to a
1428 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1429 ** field) then convert that term into a copy of the corresponding result set
1430 ** column.
1431 **
1432 ** If any errors are detected, add an error message to pParse and
1433 ** return non-zero.  Return zero if no errors are seen.
1434 */
1435 int sqlite3ResolveOrderGroupBy(
1436   Parse *pParse,        /* Parsing context.  Leave error messages here */
1437   Select *pSelect,      /* The SELECT statement containing the clause */
1438   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
1439   const char *zType     /* "ORDER" or "GROUP" */
1440 ){
1441   int i;
1442   sqlite3 *db = pParse->db;
1443   ExprList *pEList;
1444   struct ExprList_item *pItem;
1445 
1446   if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
1447   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1448     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1449     return 1;
1450   }
1451   pEList = pSelect->pEList;
1452   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
1453   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1454     if( pItem->u.x.iOrderByCol ){
1455       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
1456         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
1457         return 1;
1458       }
1459       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
1460     }
1461   }
1462   return 0;
1463 }
1464 
1465 #ifndef SQLITE_OMIT_WINDOWFUNC
1466 /*
1467 ** Walker callback for windowRemoveExprFromSelect().
1468 */
1469 static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
1470   UNUSED_PARAMETER(pWalker);
1471   if( ExprHasProperty(pExpr, EP_WinFunc) ){
1472     Window *pWin = pExpr->y.pWin;
1473     sqlite3WindowUnlinkFromSelect(pWin);
1474   }
1475   return WRC_Continue;
1476 }
1477 
1478 /*
1479 ** Remove any Window objects owned by the expression pExpr from the
1480 ** Select.pWin list of Select object pSelect.
1481 */
1482 static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
1483   if( pSelect->pWin ){
1484     Walker sWalker;
1485     memset(&sWalker, 0, sizeof(Walker));
1486     sWalker.xExprCallback = resolveRemoveWindowsCb;
1487     sWalker.u.pSelect = pSelect;
1488     sqlite3WalkExpr(&sWalker, pExpr);
1489   }
1490 }
1491 #else
1492 # define windowRemoveExprFromSelect(a, b)
1493 #endif /* SQLITE_OMIT_WINDOWFUNC */
1494 
1495 /*
1496 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1497 ** The Name context of the SELECT statement is pNC.  zType is either
1498 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1499 **
1500 ** This routine resolves each term of the clause into an expression.
1501 ** If the order-by term is an integer I between 1 and N (where N is the
1502 ** number of columns in the result set of the SELECT) then the expression
1503 ** in the resolution is a copy of the I-th result-set expression.  If
1504 ** the order-by term is an identifier that corresponds to the AS-name of
1505 ** a result-set expression, then the term resolves to a copy of the
1506 ** result-set expression.  Otherwise, the expression is resolved in
1507 ** the usual way - using sqlite3ResolveExprNames().
1508 **
1509 ** This routine returns the number of errors.  If errors occur, then
1510 ** an appropriate error message might be left in pParse.  (OOM errors
1511 ** excepted.)
1512 */
1513 static int resolveOrderGroupBy(
1514   NameContext *pNC,     /* The name context of the SELECT statement */
1515   Select *pSelect,      /* The SELECT statement holding pOrderBy */
1516   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
1517   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
1518 ){
1519   int i, j;                      /* Loop counters */
1520   int iCol;                      /* Column number */
1521   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
1522   Parse *pParse;                 /* Parsing context */
1523   int nResult;                   /* Number of terms in the result set */
1524 
1525   assert( pOrderBy!=0 );
1526   nResult = pSelect->pEList->nExpr;
1527   pParse = pNC->pParse;
1528   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1529     Expr *pE = pItem->pExpr;
1530     Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
1531     if( NEVER(pE2==0) ) continue;
1532     if( zType[0]!='G' ){
1533       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1534       if( iCol>0 ){
1535         /* If an AS-name match is found, mark this ORDER BY column as being
1536         ** a copy of the iCol-th result-set column.  The subsequent call to
1537         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1538         ** copy of the iCol-th result-set expression. */
1539         pItem->u.x.iOrderByCol = (u16)iCol;
1540         continue;
1541       }
1542     }
1543     if( sqlite3ExprIsInteger(pE2, &iCol) ){
1544       /* The ORDER BY term is an integer constant.  Again, set the column
1545       ** number so that sqlite3ResolveOrderGroupBy() will convert the
1546       ** order-by term to a copy of the result-set expression */
1547       if( iCol<1 || iCol>0xffff ){
1548         resolveOutOfRangeError(pParse, zType, i+1, nResult);
1549         return 1;
1550       }
1551       pItem->u.x.iOrderByCol = (u16)iCol;
1552       continue;
1553     }
1554 
1555     /* Otherwise, treat the ORDER BY term as an ordinary expression */
1556     pItem->u.x.iOrderByCol = 0;
1557     if( sqlite3ResolveExprNames(pNC, pE) ){
1558       return 1;
1559     }
1560     for(j=0; j<pSelect->pEList->nExpr; j++){
1561       if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
1562         /* Since this expresion is being changed into a reference
1563         ** to an identical expression in the result set, remove all Window
1564         ** objects belonging to the expression from the Select.pWin list. */
1565         windowRemoveExprFromSelect(pSelect, pE);
1566         pItem->u.x.iOrderByCol = j+1;
1567       }
1568     }
1569   }
1570   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1571 }
1572 
1573 /*
1574 ** Resolve names in the SELECT statement p and all of its descendants.
1575 */
1576 static int resolveSelectStep(Walker *pWalker, Select *p){
1577   NameContext *pOuterNC;  /* Context that contains this SELECT */
1578   NameContext sNC;        /* Name context of this SELECT */
1579   int isCompound;         /* True if p is a compound select */
1580   int nCompound;          /* Number of compound terms processed so far */
1581   Parse *pParse;          /* Parsing context */
1582   int i;                  /* Loop counter */
1583   ExprList *pGroupBy;     /* The GROUP BY clause */
1584   Select *pLeftmost;      /* Left-most of SELECT of a compound */
1585   sqlite3 *db;            /* Database connection */
1586 
1587 
1588   assert( p!=0 );
1589   if( p->selFlags & SF_Resolved ){
1590     return WRC_Prune;
1591   }
1592   pOuterNC = pWalker->u.pNC;
1593   pParse = pWalker->pParse;
1594   db = pParse->db;
1595 
1596   /* Normally sqlite3SelectExpand() will be called first and will have
1597   ** already expanded this SELECT.  However, if this is a subquery within
1598   ** an expression, sqlite3ResolveExprNames() will be called without a
1599   ** prior call to sqlite3SelectExpand().  When that happens, let
1600   ** sqlite3SelectPrep() do all of the processing for this SELECT.
1601   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1602   ** this routine in the correct order.
1603   */
1604   if( (p->selFlags & SF_Expanded)==0 ){
1605     sqlite3SelectPrep(pParse, p, pOuterNC);
1606     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1607   }
1608 
1609   isCompound = p->pPrior!=0;
1610   nCompound = 0;
1611   pLeftmost = p;
1612   while( p ){
1613     assert( (p->selFlags & SF_Expanded)!=0 );
1614     assert( (p->selFlags & SF_Resolved)==0 );
1615     assert( db->suppressErr==0 ); /* SF_Resolved not set if errors suppressed */
1616     p->selFlags |= SF_Resolved;
1617 
1618 
1619     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1620     ** are not allowed to refer to any names, so pass an empty NameContext.
1621     */
1622     memset(&sNC, 0, sizeof(sNC));
1623     sNC.pParse = pParse;
1624     sNC.pWinSelect = p;
1625     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
1626       return WRC_Abort;
1627     }
1628 
1629     /* If the SF_Converted flags is set, then this Select object was
1630     ** was created by the convertCompoundSelectToSubquery() function.
1631     ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1632     ** as if it were part of the sub-query, not the parent. This block
1633     ** moves the pOrderBy down to the sub-query. It will be moved back
1634     ** after the names have been resolved.  */
1635     if( p->selFlags & SF_Converted ){
1636       Select *pSub = p->pSrc->a[0].pSelect;
1637       assert( p->pSrc->nSrc==1 && p->pOrderBy );
1638       assert( pSub->pPrior && pSub->pOrderBy==0 );
1639       pSub->pOrderBy = p->pOrderBy;
1640       p->pOrderBy = 0;
1641     }
1642 
1643     /* Recursively resolve names in all subqueries in the FROM clause
1644     */
1645     for(i=0; i<p->pSrc->nSrc; i++){
1646       SrcItem *pItem = &p->pSrc->a[i];
1647       if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
1648         int nRef = pOuterNC ? pOuterNC->nRef : 0;
1649         const char *zSavedContext = pParse->zAuthContext;
1650 
1651         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1652         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
1653         pParse->zAuthContext = zSavedContext;
1654         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
1655 
1656         /* If the number of references to the outer context changed when
1657         ** expressions in the sub-select were resolved, the sub-select
1658         ** is correlated. It is not required to check the refcount on any
1659         ** but the innermost outer context object, as lookupName() increments
1660         ** the refcount on all contexts between the current one and the
1661         ** context containing the column when it resolves a name. */
1662         if( pOuterNC ){
1663           assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
1664           pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
1665         }
1666       }
1667     }
1668 
1669     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1670     ** resolve the result-set expression list.
1671     */
1672     sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
1673     sNC.pSrcList = p->pSrc;
1674     sNC.pNext = pOuterNC;
1675 
1676     /* Resolve names in the result set. */
1677     if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
1678     sNC.ncFlags &= ~NC_AllowWin;
1679 
1680     /* If there are no aggregate functions in the result-set, and no GROUP BY
1681     ** expression, do not allow aggregates in any of the other expressions.
1682     */
1683     assert( (p->selFlags & SF_Aggregate)==0 );
1684     pGroupBy = p->pGroupBy;
1685     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
1686       assert( NC_MinMaxAgg==SF_MinMaxAgg );
1687       assert( NC_OrderAgg==SF_OrderByReqd );
1688       p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
1689     }else{
1690       sNC.ncFlags &= ~NC_AllowAgg;
1691     }
1692 
1693     /* Add the output column list to the name-context before parsing the
1694     ** other expressions in the SELECT statement. This is so that
1695     ** expressions in the WHERE clause (etc.) can refer to expressions by
1696     ** aliases in the result set.
1697     **
1698     ** Minor point: If this is the case, then the expression will be
1699     ** re-evaluated for each reference to it.
1700     */
1701     assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
1702     sNC.uNC.pEList = p->pEList;
1703     sNC.ncFlags |= NC_UEList;
1704     if( p->pHaving ){
1705       if( !pGroupBy ){
1706         sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1707         return WRC_Abort;
1708       }
1709       if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1710     }
1711     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
1712 
1713     /* Resolve names in table-valued-function arguments */
1714     for(i=0; i<p->pSrc->nSrc; i++){
1715       SrcItem *pItem = &p->pSrc->a[i];
1716       if( pItem->fg.isTabFunc
1717        && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
1718       ){
1719         return WRC_Abort;
1720       }
1721     }
1722 
1723 #ifndef SQLITE_OMIT_WINDOWFUNC
1724     if( IN_RENAME_OBJECT ){
1725       Window *pWin;
1726       for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
1727         if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
1728          || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
1729         ){
1730           return WRC_Abort;
1731         }
1732       }
1733     }
1734 #endif
1735 
1736     /* The ORDER BY and GROUP BY clauses may not refer to terms in
1737     ** outer queries
1738     */
1739     sNC.pNext = 0;
1740     sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
1741 
1742     /* If this is a converted compound query, move the ORDER BY clause from
1743     ** the sub-query back to the parent query. At this point each term
1744     ** within the ORDER BY clause has been transformed to an integer value.
1745     ** These integers will be replaced by copies of the corresponding result
1746     ** set expressions by the call to resolveOrderGroupBy() below.  */
1747     if( p->selFlags & SF_Converted ){
1748       Select *pSub = p->pSrc->a[0].pSelect;
1749       p->pOrderBy = pSub->pOrderBy;
1750       pSub->pOrderBy = 0;
1751     }
1752 
1753     /* Process the ORDER BY clause for singleton SELECT statements.
1754     ** The ORDER BY clause for compounds SELECT statements is handled
1755     ** below, after all of the result-sets for all of the elements of
1756     ** the compound have been resolved.
1757     **
1758     ** If there is an ORDER BY clause on a term of a compound-select other
1759     ** than the right-most term, then that is a syntax error.  But the error
1760     ** is not detected until much later, and so we need to go ahead and
1761     ** resolve those symbols on the incorrect ORDER BY for consistency.
1762     */
1763     if( p->pOrderBy!=0
1764      && isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
1765      && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
1766     ){
1767       return WRC_Abort;
1768     }
1769     if( db->mallocFailed ){
1770       return WRC_Abort;
1771     }
1772     sNC.ncFlags &= ~NC_AllowWin;
1773 
1774     /* Resolve the GROUP BY clause.  At the same time, make sure
1775     ** the GROUP BY clause does not contain aggregate functions.
1776     */
1777     if( pGroupBy ){
1778       struct ExprList_item *pItem;
1779 
1780       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1781         return WRC_Abort;
1782       }
1783       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1784         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1785           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1786               "the GROUP BY clause");
1787           return WRC_Abort;
1788         }
1789       }
1790     }
1791 
1792     /* If this is part of a compound SELECT, check that it has the right
1793     ** number of expressions in the select list. */
1794     if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
1795       sqlite3SelectWrongNumTermsError(pParse, p->pNext);
1796       return WRC_Abort;
1797     }
1798 
1799     /* Advance to the next term of the compound
1800     */
1801     p = p->pPrior;
1802     nCompound++;
1803   }
1804 
1805   /* Resolve the ORDER BY on a compound SELECT after all terms of
1806   ** the compound have been resolved.
1807   */
1808   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1809     return WRC_Abort;
1810   }
1811 
1812   return WRC_Prune;
1813 }
1814 
1815 /*
1816 ** This routine walks an expression tree and resolves references to
1817 ** table columns and result-set columns.  At the same time, do error
1818 ** checking on function usage and set a flag if any aggregate functions
1819 ** are seen.
1820 **
1821 ** To resolve table columns references we look for nodes (or subtrees) of the
1822 ** form X.Y.Z or Y.Z or just Z where
1823 **
1824 **      X:   The name of a database.  Ex:  "main" or "temp" or
1825 **           the symbolic name assigned to an ATTACH-ed database.
1826 **
1827 **      Y:   The name of a table in a FROM clause.  Or in a trigger
1828 **           one of the special names "old" or "new".
1829 **
1830 **      Z:   The name of a column in table Y.
1831 **
1832 ** The node at the root of the subtree is modified as follows:
1833 **
1834 **    Expr.op        Changed to TK_COLUMN
1835 **    Expr.pTab      Points to the Table object for X.Y
1836 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
1837 **    Expr.iTable    The VDBE cursor number for X.Y
1838 **
1839 **
1840 ** To resolve result-set references, look for expression nodes of the
1841 ** form Z (with no X and Y prefix) where the Z matches the right-hand
1842 ** size of an AS clause in the result-set of a SELECT.  The Z expression
1843 ** is replaced by a copy of the left-hand side of the result-set expression.
1844 ** Table-name and function resolution occurs on the substituted expression
1845 ** tree.  For example, in:
1846 **
1847 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1848 **
1849 ** The "x" term of the order by is replaced by "a+b" to render:
1850 **
1851 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1852 **
1853 ** Function calls are checked to make sure that the function is
1854 ** defined and that the correct number of arguments are specified.
1855 ** If the function is an aggregate function, then the NC_HasAgg flag is
1856 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1857 ** If an expression contains aggregate functions then the EP_Agg
1858 ** property on the expression is set.
1859 **
1860 ** An error message is left in pParse if anything is amiss.  The number
1861 ** if errors is returned.
1862 */
1863 int sqlite3ResolveExprNames(
1864   NameContext *pNC,       /* Namespace to resolve expressions in. */
1865   Expr *pExpr             /* The expression to be analyzed. */
1866 ){
1867   int savedHasAgg;
1868   Walker w;
1869 
1870   if( pExpr==0 ) return SQLITE_OK;
1871   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1872   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1873   w.pParse = pNC->pParse;
1874   w.xExprCallback = resolveExprStep;
1875   w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
1876   w.xSelectCallback2 = 0;
1877   w.u.pNC = pNC;
1878 #if SQLITE_MAX_EXPR_DEPTH>0
1879   w.pParse->nHeight += pExpr->nHeight;
1880   if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
1881     return SQLITE_ERROR;
1882   }
1883 #endif
1884   sqlite3WalkExpr(&w, pExpr);
1885 #if SQLITE_MAX_EXPR_DEPTH>0
1886   w.pParse->nHeight -= pExpr->nHeight;
1887 #endif
1888   assert( EP_Agg==NC_HasAgg );
1889   assert( EP_Win==NC_HasWin );
1890   testcase( pNC->ncFlags & NC_HasAgg );
1891   testcase( pNC->ncFlags & NC_HasWin );
1892   ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
1893   pNC->ncFlags |= savedHasAgg;
1894   return pNC->nNcErr>0 || w.pParse->nErr>0;
1895 }
1896 
1897 /*
1898 ** Resolve all names for all expression in an expression list.  This is
1899 ** just like sqlite3ResolveExprNames() except that it works for an expression
1900 ** list rather than a single expression.
1901 */
1902 int sqlite3ResolveExprListNames(
1903   NameContext *pNC,       /* Namespace to resolve expressions in. */
1904   ExprList *pList         /* The expression list to be analyzed. */
1905 ){
1906   int i;
1907   int savedHasAgg = 0;
1908   Walker w;
1909   if( pList==0 ) return WRC_Continue;
1910   w.pParse = pNC->pParse;
1911   w.xExprCallback = resolveExprStep;
1912   w.xSelectCallback = resolveSelectStep;
1913   w.xSelectCallback2 = 0;
1914   w.u.pNC = pNC;
1915   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1916   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1917   for(i=0; i<pList->nExpr; i++){
1918     Expr *pExpr = pList->a[i].pExpr;
1919     if( pExpr==0 ) continue;
1920 #if SQLITE_MAX_EXPR_DEPTH>0
1921     w.pParse->nHeight += pExpr->nHeight;
1922     if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
1923       return WRC_Abort;
1924     }
1925 #endif
1926     sqlite3WalkExpr(&w, pExpr);
1927 #if SQLITE_MAX_EXPR_DEPTH>0
1928     w.pParse->nHeight -= pExpr->nHeight;
1929 #endif
1930     assert( EP_Agg==NC_HasAgg );
1931     assert( EP_Win==NC_HasWin );
1932     testcase( pNC->ncFlags & NC_HasAgg );
1933     testcase( pNC->ncFlags & NC_HasWin );
1934     if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
1935       ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
1936       savedHasAgg |= pNC->ncFlags &
1937                           (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1938       pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1939     }
1940     if( w.pParse->nErr>0 ) return WRC_Abort;
1941   }
1942   pNC->ncFlags |= savedHasAgg;
1943   return WRC_Continue;
1944 }
1945 
1946 /*
1947 ** Resolve all names in all expressions of a SELECT and in all
1948 ** decendents of the SELECT, including compounds off of p->pPrior,
1949 ** subqueries in expressions, and subqueries used as FROM clause
1950 ** terms.
1951 **
1952 ** See sqlite3ResolveExprNames() for a description of the kinds of
1953 ** transformations that occur.
1954 **
1955 ** All SELECT statements should have been expanded using
1956 ** sqlite3SelectExpand() prior to invoking this routine.
1957 */
1958 void sqlite3ResolveSelectNames(
1959   Parse *pParse,         /* The parser context */
1960   Select *p,             /* The SELECT statement being coded. */
1961   NameContext *pOuterNC  /* Name context for parent SELECT statement */
1962 ){
1963   Walker w;
1964 
1965   assert( p!=0 );
1966   w.xExprCallback = resolveExprStep;
1967   w.xSelectCallback = resolveSelectStep;
1968   w.xSelectCallback2 = 0;
1969   w.pParse = pParse;
1970   w.u.pNC = pOuterNC;
1971   sqlite3WalkSelect(&w, p);
1972 }
1973 
1974 /*
1975 ** Resolve names in expressions that can only reference a single table
1976 ** or which cannot reference any tables at all.  Examples:
1977 **
1978 **                                                    "type" flag
1979 **                                                    ------------
1980 **    (1)   CHECK constraints                         NC_IsCheck
1981 **    (2)   WHERE clauses on partial indices          NC_PartIdx
1982 **    (3)   Expressions in indexes on expressions     NC_IdxExpr
1983 **    (4)   Expression arguments to VACUUM INTO.      0
1984 **    (5)   GENERATED ALWAYS as expressions           NC_GenCol
1985 **
1986 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
1987 ** nodes of the expression is set to -1 and the Expr.iColumn value is
1988 ** set to the column number.  In case (4), TK_COLUMN nodes cause an error.
1989 **
1990 ** Any errors cause an error message to be set in pParse.
1991 */
1992 int sqlite3ResolveSelfReference(
1993   Parse *pParse,   /* Parsing context */
1994   Table *pTab,     /* The table being referenced, or NULL */
1995   int type,        /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
1996   Expr *pExpr,     /* Expression to resolve.  May be NULL. */
1997   ExprList *pList  /* Expression list to resolve.  May be NULL. */
1998 ){
1999   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
2000   NameContext sNC;                /* Name context for pParse->pNewTable */
2001   int rc;
2002 
2003   assert( type==0 || pTab!=0 );
2004   assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
2005           || type==NC_GenCol || pTab==0 );
2006   memset(&sNC, 0, sizeof(sNC));
2007   memset(&sSrc, 0, sizeof(sSrc));
2008   if( pTab ){
2009     sSrc.nSrc = 1;
2010     sSrc.a[0].zName = pTab->zName;
2011     sSrc.a[0].pTab = pTab;
2012     sSrc.a[0].iCursor = -1;
2013     if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
2014       /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2015       ** schema elements */
2016       type |= NC_FromDDL;
2017     }
2018   }
2019   sNC.pParse = pParse;
2020   sNC.pSrcList = &sSrc;
2021   sNC.ncFlags = type | NC_IsDDL;
2022   if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
2023   if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
2024   return rc;
2025 }
2026