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