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