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