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