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