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