xref: /sqlite-3.40.0/src/resolve.c (revision a514b8eb)
17d10d5a6Sdrh /*
27d10d5a6Sdrh ** 2008 August 18
37d10d5a6Sdrh **
47d10d5a6Sdrh ** The author disclaims copyright to this source code.  In place of
57d10d5a6Sdrh ** a legal notice, here is a blessing:
67d10d5a6Sdrh **
77d10d5a6Sdrh **    May you do good and not evil.
87d10d5a6Sdrh **    May you find forgiveness for yourself and forgive others.
97d10d5a6Sdrh **    May you share freely, never taking more than you give.
107d10d5a6Sdrh **
117d10d5a6Sdrh *************************************************************************
127d10d5a6Sdrh **
137d10d5a6Sdrh ** This file contains routines used for walking the parser tree and
147d10d5a6Sdrh ** resolve all identifiers by associating them with a particular
157d10d5a6Sdrh ** table and column.
167d10d5a6Sdrh */
177d10d5a6Sdrh #include "sqliteInt.h"
187d10d5a6Sdrh #include <stdlib.h>
197d10d5a6Sdrh #include <string.h>
207d10d5a6Sdrh 
217d10d5a6Sdrh /*
22ed551b95Sdrh ** Walk the expression tree pExpr and increase the aggregate function
23ed551b95Sdrh ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
24ed551b95Sdrh ** This needs to occur when copying a TK_AGG_FUNCTION node from an
25ed551b95Sdrh ** outer query into an inner subquery.
26ed551b95Sdrh **
27ed551b95Sdrh ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
28ed551b95Sdrh ** is a helper function - a callback for the tree walker.
29ed551b95Sdrh */
30ed551b95Sdrh static int incrAggDepth(Walker *pWalker, Expr *pExpr){
31059b2d50Sdrh   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
32ed551b95Sdrh   return WRC_Continue;
33ed551b95Sdrh }
34ed551b95Sdrh static void incrAggFunctionDepth(Expr *pExpr, int N){
35ed551b95Sdrh   if( N>0 ){
36ed551b95Sdrh     Walker w;
37ed551b95Sdrh     memset(&w, 0, sizeof(w));
38ed551b95Sdrh     w.xExprCallback = incrAggDepth;
39059b2d50Sdrh     w.u.n = N;
40ed551b95Sdrh     sqlite3WalkExpr(&w, pExpr);
41ed551b95Sdrh   }
42ed551b95Sdrh }
43ed551b95Sdrh 
44ed551b95Sdrh /*
458b213899Sdrh ** Turn the pExpr expression into an alias for the iCol-th column of the
468b213899Sdrh ** result set in pEList.
478b213899Sdrh **
488b213899Sdrh ** If the result set column is a simple column reference, then this routine
498b213899Sdrh ** makes an exact copy.  But for any other kind of expression, this
508b213899Sdrh ** routine make a copy of the result set column as the argument to the
518b213899Sdrh ** TK_AS operator.  The TK_AS operator causes the expression to be
528b213899Sdrh ** evaluated just once and then reused for each alias.
538b213899Sdrh **
548b213899Sdrh ** The reason for suppressing the TK_AS term when the expression is a simple
558b213899Sdrh ** column reference is so that the column reference will be recognized as
568b213899Sdrh ** usable by indices within the WHERE clause processing logic.
578b213899Sdrh **
58e35463b3Sdrh ** The TK_AS operator is inhibited if zType[0]=='G'.  This means
598b213899Sdrh ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
608b213899Sdrh **
618b213899Sdrh **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
628b213899Sdrh **
638b213899Sdrh ** Is equivalent to:
648b213899Sdrh **
658b213899Sdrh **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
668b213899Sdrh **
678b213899Sdrh ** The result of random()%5 in the GROUP BY clause is probably different
68e35463b3Sdrh ** from the result in the result-set.  On the other hand Standard SQL does
69e35463b3Sdrh ** not allow the GROUP BY clause to contain references to result-set columns.
70e35463b3Sdrh ** So this should never come up in well-formed queries.
71ed551b95Sdrh **
720a8a406eSdrh ** If the reference is followed by a COLLATE operator, then make sure
730a8a406eSdrh ** the COLLATE operator is preserved.  For example:
740a8a406eSdrh **
750a8a406eSdrh **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
760a8a406eSdrh **
770a8a406eSdrh ** Should be transformed into:
780a8a406eSdrh **
790a8a406eSdrh **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
800a8a406eSdrh **
81ed551b95Sdrh ** The nSubquery parameter specifies how many levels of subquery the
8241148f83Sdrh ** alias is removed from the original expression.  The usual value is
83ed551b95Sdrh ** zero but it might be more if the alias is contained within a subquery
84ed551b95Sdrh ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
85ed551b95Sdrh ** structures must be increased by the nSubquery amount.
868b213899Sdrh */
878b213899Sdrh static void resolveAlias(
888b213899Sdrh   Parse *pParse,         /* Parsing context */
898b213899Sdrh   ExprList *pEList,      /* A result set */
908b213899Sdrh   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
918b213899Sdrh   Expr *pExpr,           /* Transform this into an alias to the result set */
92ed551b95Sdrh   const char *zType,     /* "GROUP" or "ORDER" or "" */
93ed551b95Sdrh   int nSubquery          /* Number of subqueries that the label is moving */
948b213899Sdrh ){
958b213899Sdrh   Expr *pOrig;           /* The iCol-th column of the result set */
968b213899Sdrh   Expr *pDup;            /* Copy of pOrig */
978b213899Sdrh   sqlite3 *db;           /* The database connection */
988b213899Sdrh 
998b213899Sdrh   assert( iCol>=0 && iCol<pEList->nExpr );
1008b213899Sdrh   pOrig = pEList->a[iCol].pExpr;
1018b213899Sdrh   assert( pOrig!=0 );
1028b213899Sdrh   db = pParse->db;
1036ab3a2ecSdanielk1977   pDup = sqlite3ExprDup(db, pOrig, 0);
1040a8a406eSdrh   if( pDup==0 ) return;
1050a8a406eSdrh   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
106ed551b95Sdrh     incrAggFunctionDepth(pDup, nSubquery);
1078b213899Sdrh     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
1088b213899Sdrh     if( pDup==0 ) return;
109a4c3c87eSdrh     ExprSetProperty(pDup, EP_Skip);
110c2acc4e4Sdrh     if( pEList->a[iCol].u.x.iAlias==0 ){
111c2acc4e4Sdrh       pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
1128b213899Sdrh     }
113c2acc4e4Sdrh     pDup->iTable = pEList->a[iCol].u.x.iAlias;
114b7916a78Sdrh   }
1150a8a406eSdrh   if( pExpr->op==TK_COLLATE ){
1160a8a406eSdrh     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
1170a8a406eSdrh   }
118f6963f99Sdan 
119f6963f99Sdan   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
120f6963f99Sdan   ** prevents ExprDelete() from deleting the Expr structure itself,
121f6963f99Sdan   ** allowing it to be repopulated by the memcpy() on the following line.
122bd13d34bSdrh   ** The pExpr->u.zToken might point into memory that will be freed by the
123bd13d34bSdrh   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
124bd13d34bSdrh   ** make a copy of the token before doing the sqlite3DbFree().
125f6963f99Sdan   */
126f6963f99Sdan   ExprSetProperty(pExpr, EP_Static);
127f6963f99Sdan   sqlite3ExprDelete(db, pExpr);
1288b213899Sdrh   memcpy(pExpr, pDup, sizeof(*pExpr));
1290a8a406eSdrh   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
1300a8a406eSdrh     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
1310a8a406eSdrh     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
132c5cd1249Sdrh     pExpr->flags |= EP_MemToken;
1330a8a406eSdrh   }
1348b213899Sdrh   sqlite3DbFree(db, pDup);
1358b213899Sdrh }
1368b213899Sdrh 
137e802c5daSdrh 
138e802c5daSdrh /*
139e802c5daSdrh ** Return TRUE if the name zCol occurs anywhere in the USING clause.
140e802c5daSdrh **
141e802c5daSdrh ** Return FALSE if the USING clause is NULL or if it does not contain
142e802c5daSdrh ** zCol.
143e802c5daSdrh */
144e802c5daSdrh static int nameInUsingClause(IdList *pUsing, const char *zCol){
145e802c5daSdrh   if( pUsing ){
146e802c5daSdrh     int k;
147e802c5daSdrh     for(k=0; k<pUsing->nId; k++){
148e802c5daSdrh       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
149e802c5daSdrh     }
150e802c5daSdrh   }
151e802c5daSdrh   return 0;
152e802c5daSdrh }
153e802c5daSdrh 
1543e3f1a5bSdrh /*
1553e3f1a5bSdrh ** Subqueries stores the original database, table and column names for their
1563e3f1a5bSdrh ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
1573e3f1a5bSdrh ** Check to see if the zSpan given to this routine matches the zDb, zTab,
1583e3f1a5bSdrh ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
1593e3f1a5bSdrh ** match anything.
1603e3f1a5bSdrh */
1613e3f1a5bSdrh int sqlite3MatchSpanName(
1623e3f1a5bSdrh   const char *zSpan,
1633e3f1a5bSdrh   const char *zCol,
1643e3f1a5bSdrh   const char *zTab,
1653e3f1a5bSdrh   const char *zDb
1663e3f1a5bSdrh ){
1673e3f1a5bSdrh   int n;
1683e3f1a5bSdrh   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
169dd1dd489Sdrh   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
1703e3f1a5bSdrh     return 0;
1713e3f1a5bSdrh   }
1723e3f1a5bSdrh   zSpan += n+1;
1733e3f1a5bSdrh   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
174dd1dd489Sdrh   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
1753e3f1a5bSdrh     return 0;
1763e3f1a5bSdrh   }
1773e3f1a5bSdrh   zSpan += n+1;
1783e3f1a5bSdrh   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
1793e3f1a5bSdrh     return 0;
1803e3f1a5bSdrh   }
1813e3f1a5bSdrh   return 1;
1823e3f1a5bSdrh }
183e802c5daSdrh 
1848b213899Sdrh /*
1857d10d5a6Sdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
1867d10d5a6Sdrh ** that name in the set of source tables in pSrcList and make the pExpr
1877d10d5a6Sdrh ** expression node refer back to that source column.  The following changes
1887d10d5a6Sdrh ** are made to pExpr:
1897d10d5a6Sdrh **
1907d10d5a6Sdrh **    pExpr->iDb           Set the index in db->aDb[] of the database X
1917d10d5a6Sdrh **                         (even if X is implied).
1927d10d5a6Sdrh **    pExpr->iTable        Set to the cursor number for the table obtained
1937d10d5a6Sdrh **                         from pSrcList.
1947d10d5a6Sdrh **    pExpr->pTab          Points to the Table structure of X.Y (even if
1957d10d5a6Sdrh **                         X and/or Y are implied.)
1967d10d5a6Sdrh **    pExpr->iColumn       Set to the column number within the table.
1977d10d5a6Sdrh **    pExpr->op            Set to TK_COLUMN.
1987d10d5a6Sdrh **    pExpr->pLeft         Any expression this points to is deleted
1997d10d5a6Sdrh **    pExpr->pRight        Any expression this points to is deleted.
2007d10d5a6Sdrh **
201b7916a78Sdrh ** The zDb variable is the name of the database (the "X").  This value may be
2027d10d5a6Sdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
203b7916a78Sdrh ** can be used.  The zTable variable is the name of the table (the "Y").  This
204b7916a78Sdrh ** value can be NULL if zDb is also NULL.  If zTable is NULL it
2057d10d5a6Sdrh ** means that the form of the name is Z and that columns from any table
2067d10d5a6Sdrh ** can be used.
2077d10d5a6Sdrh **
2087d10d5a6Sdrh ** If the name cannot be resolved unambiguously, leave an error message
209f7828b5cSdrh ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
2107d10d5a6Sdrh */
2117d10d5a6Sdrh static int lookupName(
2127d10d5a6Sdrh   Parse *pParse,       /* The parsing context */
213b7916a78Sdrh   const char *zDb,     /* Name of the database containing table, or NULL */
214b7916a78Sdrh   const char *zTab,    /* Name of table containing column, or NULL */
215b7916a78Sdrh   const char *zCol,    /* Name of the column. */
2167d10d5a6Sdrh   NameContext *pNC,    /* The name context used to resolve the name */
2177d10d5a6Sdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
2187d10d5a6Sdrh ){
2197d10d5a6Sdrh   int i, j;                         /* Loop counters */
2207d10d5a6Sdrh   int cnt = 0;                      /* Number of matching column names */
2217d10d5a6Sdrh   int cntTab = 0;                   /* Number of matching table names */
222ed551b95Sdrh   int nSubquery = 0;                /* How many levels of subquery */
2237d10d5a6Sdrh   sqlite3 *db = pParse->db;         /* The database connection */
2247d10d5a6Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
2257d10d5a6Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
2267d10d5a6Sdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
2277d10d5a6Sdrh   Schema *pSchema = 0;              /* Schema of the expression */
22811f9b033Sdrh   int isTrigger = 0;                /* True if resolved to a trigger column */
22911f9b033Sdrh   Table *pTab = 0;                  /* Table hold the row */
23011f9b033Sdrh   Column *pCol;                     /* A column of pTab */
2317d10d5a6Sdrh 
232e34c647eSshane   assert( pNC );     /* the name context cannot be NULL. */
233b7916a78Sdrh   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
234c5cd1249Sdrh   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
2357d10d5a6Sdrh 
2367d10d5a6Sdrh   /* Initialize the node to no-match */
2377d10d5a6Sdrh   pExpr->iTable = -1;
2387d10d5a6Sdrh   pExpr->pTab = 0;
239ebb6a65dSdrh   ExprSetVVAProperty(pExpr, EP_NoReduce);
2407d10d5a6Sdrh 
2418f25d18bSdrh   /* Translate the schema name in zDb into a pointer to the corresponding
2428f25d18bSdrh   ** schema.  If not found, pSchema will remain NULL and nothing will match
2438f25d18bSdrh   ** resulting in an appropriate error message toward the end of this routine
2448f25d18bSdrh   */
2458f25d18bSdrh   if( zDb ){
2461e7d43c9Sdrh     testcase( pNC->ncFlags & NC_PartIdx );
2471e7d43c9Sdrh     testcase( pNC->ncFlags & NC_IsCheck );
2481e7d43c9Sdrh     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
24931e7147dSdrh       /* Silently ignore database qualifiers inside CHECK constraints and
25031e7147dSdrh       ** partial indices.  Do not raise errors because that might break
25131e7147dSdrh       ** legacy and because it does not hurt anything to just ignore the
25231e7147dSdrh       ** database name. */
2531e7d43c9Sdrh       zDb = 0;
2541e7d43c9Sdrh     }else{
2558f25d18bSdrh       for(i=0; i<db->nDb; i++){
2568f25d18bSdrh         assert( db->aDb[i].zName );
2578f25d18bSdrh         if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
2588f25d18bSdrh           pSchema = db->aDb[i].pSchema;
2598f25d18bSdrh           break;
2608f25d18bSdrh         }
2618f25d18bSdrh       }
2628f25d18bSdrh     }
2631e7d43c9Sdrh   }
2648f25d18bSdrh 
2657d10d5a6Sdrh   /* Start at the inner-most context and move outward until a match is found */
2667d10d5a6Sdrh   while( pNC && cnt==0 ){
2677d10d5a6Sdrh     ExprList *pEList;
2687d10d5a6Sdrh     SrcList *pSrcList = pNC->pSrcList;
2697d10d5a6Sdrh 
2707d10d5a6Sdrh     if( pSrcList ){
2717d10d5a6Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
2727d10d5a6Sdrh         pTab = pItem->pTab;
273f436620eSdrh         assert( pTab!=0 && pTab->zName!=0 );
2747d10d5a6Sdrh         assert( pTab->nCol>0 );
2758f25d18bSdrh         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
2768f25d18bSdrh           int hit = 0;
277928d9c62Sdrh           pEList = pItem->pSelect->pEList;
2788f25d18bSdrh           for(j=0; j<pEList->nExpr; j++){
2793e3f1a5bSdrh             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
2808f25d18bSdrh               cnt++;
2818f25d18bSdrh               cntTab = 2;
2828f25d18bSdrh               pMatch = pItem;
2838f25d18bSdrh               pExpr->iColumn = j;
28438b384a0Sdrh               hit = 1;
2858f25d18bSdrh             }
2868f25d18bSdrh           }
2878f25d18bSdrh           if( hit || zTab==0 ) continue;
2888f25d18bSdrh         }
289c75e09c7Sdrh         if( zDb && pTab->pSchema!=pSchema ){
290c75e09c7Sdrh           continue;
291c75e09c7Sdrh         }
2927d10d5a6Sdrh         if( zTab ){
2938f25d18bSdrh           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
2948f25d18bSdrh           assert( zTabName!=0 );
2958f25d18bSdrh           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
29673c0fdc7Sdrh             continue;
29773c0fdc7Sdrh           }
2987d10d5a6Sdrh         }
2997d10d5a6Sdrh         if( 0==(cntTab++) ){
3007d10d5a6Sdrh           pMatch = pItem;
3017d10d5a6Sdrh         }
3027d10d5a6Sdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
3037d10d5a6Sdrh           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
304e802c5daSdrh             /* If there has been exactly one prior match and this match
305e802c5daSdrh             ** is for the right-hand table of a NATURAL JOIN or is in a
306e802c5daSdrh             ** USING clause, then skip this match.
307e802c5daSdrh             */
308e802c5daSdrh             if( cnt==1 ){
3098a48b9c0Sdrh               if( pItem->fg.jointype & JT_NATURAL ) continue;
310e802c5daSdrh               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
311e802c5daSdrh             }
3127d10d5a6Sdrh             cnt++;
3137d10d5a6Sdrh             pMatch = pItem;
3147d10d5a6Sdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
315cf697396Sshane             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
3167d10d5a6Sdrh             break;
3177d10d5a6Sdrh           }
3187d10d5a6Sdrh         }
3197d10d5a6Sdrh       }
3208f25d18bSdrh       if( pMatch ){
3218f25d18bSdrh         pExpr->iTable = pMatch->iCursor;
3228f25d18bSdrh         pExpr->pTab = pMatch->pTab;
32331e7147dSdrh         /* RIGHT JOIN not (yet) supported */
3248a48b9c0Sdrh         assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
3258a48b9c0Sdrh         if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
32672673a24Sdrh           ExprSetProperty(pExpr, EP_CanBeNull);
32772673a24Sdrh         }
3288f25d18bSdrh         pSchema = pExpr->pTab->pSchema;
3297d10d5a6Sdrh       }
3308f25d18bSdrh     } /* if( pSrcList ) */
3317d10d5a6Sdrh 
3327d10d5a6Sdrh #ifndef SQLITE_OMIT_TRIGGER
3337d10d5a6Sdrh     /* If we have not already resolved the name, then maybe
3347d10d5a6Sdrh     ** it is a new.* or old.* trigger argument reference
3357d10d5a6Sdrh     */
33611f9b033Sdrh     if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
33765a7cd16Sdan       int op = pParse->eTriggerOp;
33865a7cd16Sdan       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
33965a7cd16Sdan       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
340165921a7Sdan         pExpr->iTable = 1;
341165921a7Sdan         pTab = pParse->pTriggerTab;
34265a7cd16Sdan       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
343165921a7Sdan         pExpr->iTable = 0;
344165921a7Sdan         pTab = pParse->pTriggerTab;
3459d42cc99Smistachkin       }else{
3469d42cc99Smistachkin         pTab = 0;
3477d10d5a6Sdrh       }
3487d10d5a6Sdrh 
3497d10d5a6Sdrh       if( pTab ){
3507d10d5a6Sdrh         int iCol;
3517d10d5a6Sdrh         pSchema = pTab->pSchema;
3527d10d5a6Sdrh         cntTab++;
353511717c6Sdrh         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
3547d10d5a6Sdrh           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
3552bd93516Sdan             if( iCol==pTab->iPKey ){
3562bd93516Sdan               iCol = -1;
3572bd93516Sdan             }
3587d10d5a6Sdrh             break;
3597d10d5a6Sdrh           }
3607d10d5a6Sdrh         }
361fccda8a1Sdrh         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
362e8a537eeSdrh           /* IMP: R-51414-32910 */
363bbbb0e80Sdrh           /* IMP: R-44911-55124 */
364bbbb0e80Sdrh           iCol = -1;
3657d10d5a6Sdrh         }
3662bd93516Sdan         if( iCol<pTab->nCol ){
3672bd93516Sdan           cnt++;
3682bd93516Sdan           if( iCol<0 ){
3692bd93516Sdan             pExpr->affinity = SQLITE_AFF_INTEGER;
3702832ad42Sdan           }else if( pExpr->iTable==0 ){
3712832ad42Sdan             testcase( iCol==31 );
3722832ad42Sdan             testcase( iCol==32 );
3732832ad42Sdan             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
374bb5f168fSdan           }else{
375bb5f168fSdan             testcase( iCol==31 );
376bb5f168fSdan             testcase( iCol==32 );
377bb5f168fSdan             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
3782bd93516Sdan           }
379cea72b2dSshane           pExpr->iColumn = (i16)iCol;
3802bd93516Sdan           pExpr->pTab = pTab;
3812bd93516Sdan           isTrigger = 1;
3822bd93516Sdan         }
3832bd93516Sdan       }
3847d10d5a6Sdrh     }
3857d10d5a6Sdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
3867d10d5a6Sdrh 
3877d10d5a6Sdrh     /*
3887d10d5a6Sdrh     ** Perhaps the name is a reference to the ROWID
3897d10d5a6Sdrh     */
390784156f8Sdrh     if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
391fccda8a1Sdrh      && VisibleRowid(pMatch->pTab) ){
3927d10d5a6Sdrh       cnt = 1;
393c79c761fSdrh       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
3947d10d5a6Sdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
3957d10d5a6Sdrh     }
3967d10d5a6Sdrh 
3977d10d5a6Sdrh     /*
3987d10d5a6Sdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
3997d10d5a6Sdrh     ** might refer to an result-set alias.  This happens, for example, when
4007d10d5a6Sdrh     ** we are resolving names in the WHERE clause of the following command:
4017d10d5a6Sdrh     **
4027d10d5a6Sdrh     **     SELECT a+b AS x FROM table WHERE x<10;
4037d10d5a6Sdrh     **
4047d10d5a6Sdrh     ** In cases like this, replace pExpr with a copy of the expression that
4057d10d5a6Sdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
4067d10d5a6Sdrh     ** Note that the expression in the result set should have already been
4077d10d5a6Sdrh     ** resolved by the time the WHERE clause is resolved.
408e35463b3Sdrh     **
409e35463b3Sdrh     ** The ability to use an output result-set column in the WHERE, GROUP BY,
410e35463b3Sdrh     ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
411e35463b3Sdrh     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
412e35463b3Sdrh     ** is supported for backwards compatibility only.  TO DO: Issue a warning
413e35463b3Sdrh     ** on sqlite3_log() whenever the capability is used.
4147d10d5a6Sdrh     */
415a3a5bd9bSdrh     if( (pEList = pNC->pEList)!=0
416a3a5bd9bSdrh      && zTab==0
417e35463b3Sdrh      && cnt==0
418a3a5bd9bSdrh     ){
4197d10d5a6Sdrh       for(j=0; j<pEList->nExpr; j++){
4207d10d5a6Sdrh         char *zAs = pEList->a[j].zName;
4217d10d5a6Sdrh         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
4228b213899Sdrh           Expr *pOrig;
4237d10d5a6Sdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
4246ab3a2ecSdanielk1977           assert( pExpr->x.pList==0 );
4256ab3a2ecSdanielk1977           assert( pExpr->x.pSelect==0 );
4267d10d5a6Sdrh           pOrig = pEList->a[j].pExpr;
427a51009b2Sdrh           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
4287d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
429f7828b5cSdrh             return WRC_Abort;
4307d10d5a6Sdrh           }
431ed551b95Sdrh           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
4327d10d5a6Sdrh           cnt = 1;
4337d10d5a6Sdrh           pMatch = 0;
4347d10d5a6Sdrh           assert( zTab==0 && zDb==0 );
435b7916a78Sdrh           goto lookupname_end;
4367d10d5a6Sdrh         }
4377d10d5a6Sdrh       }
4387d10d5a6Sdrh     }
4397d10d5a6Sdrh 
4407d10d5a6Sdrh     /* Advance to the next name context.  The loop will exit when either
4417d10d5a6Sdrh     ** we have a match (cnt>0) or when we run out of name contexts.
4427d10d5a6Sdrh     */
4437d10d5a6Sdrh     if( cnt==0 ){
4447d10d5a6Sdrh       pNC = pNC->pNext;
445ed551b95Sdrh       nSubquery++;
4467d10d5a6Sdrh     }
4477d10d5a6Sdrh   }
4487d10d5a6Sdrh 
4497d10d5a6Sdrh   /*
4507d10d5a6Sdrh   ** If X and Y are NULL (in other words if only the column name Z is
4517d10d5a6Sdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
4527d10d5a6Sdrh   ** Z is a string literal if it doesn't match any column names.  In that
4537d10d5a6Sdrh   ** case, we need to return right away and not make any changes to
4547d10d5a6Sdrh   ** pExpr.
4557d10d5a6Sdrh   **
4567d10d5a6Sdrh   ** Because no reference was made to outer contexts, the pNC->nRef
4577d10d5a6Sdrh   ** fields are not changed in any context.
4587d10d5a6Sdrh   */
45924fb627aSdrh   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
4607d10d5a6Sdrh     pExpr->op = TK_STRING;
4611885d1c2Sdrh     pExpr->pTab = 0;
462f7828b5cSdrh     return WRC_Prune;
4637d10d5a6Sdrh   }
4647d10d5a6Sdrh 
4657d10d5a6Sdrh   /*
4667d10d5a6Sdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
4677d10d5a6Sdrh   ** more matches.  Either way, we have an error.
4687d10d5a6Sdrh   */
4697d10d5a6Sdrh   if( cnt!=1 ){
4707d10d5a6Sdrh     const char *zErr;
4717d10d5a6Sdrh     zErr = cnt==0 ? "no such column" : "ambiguous column name";
4727d10d5a6Sdrh     if( zDb ){
4737d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
4747d10d5a6Sdrh     }else if( zTab ){
4757d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
4767d10d5a6Sdrh     }else{
4777d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
4787d10d5a6Sdrh     }
4791db95106Sdan     pParse->checkSchema = 1;
4807d10d5a6Sdrh     pTopNC->nErr++;
4817d10d5a6Sdrh   }
4827d10d5a6Sdrh 
4837d10d5a6Sdrh   /* If a column from a table in pSrcList is referenced, then record
4847d10d5a6Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
4857d10d5a6Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
4867d10d5a6Sdrh   ** column number is greater than the number of bits in the bitmask
4877d10d5a6Sdrh   ** then set the high-order bit of the bitmask.
4887d10d5a6Sdrh   */
4892d2e7bd3Sdanielk1977   if( pExpr->iColumn>=0 && pMatch!=0 ){
4907d10d5a6Sdrh     int n = pExpr->iColumn;
49100e13613Sdanielk1977     testcase( n==BMS-1 );
49200e13613Sdanielk1977     if( n>=BMS ){
49300e13613Sdanielk1977       n = BMS-1;
4947d10d5a6Sdrh     }
4957d10d5a6Sdrh     assert( pMatch->iCursor==pExpr->iTable );
4967d10d5a6Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
4977d10d5a6Sdrh   }
4987d10d5a6Sdrh 
4997d10d5a6Sdrh   /* Clean up and return
5007d10d5a6Sdrh   */
5017d10d5a6Sdrh   sqlite3ExprDelete(db, pExpr->pLeft);
5027d10d5a6Sdrh   pExpr->pLeft = 0;
5037d10d5a6Sdrh   sqlite3ExprDelete(db, pExpr->pRight);
5047d10d5a6Sdrh   pExpr->pRight = 0;
5052bd93516Sdan   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
506b7916a78Sdrh lookupname_end:
5077d10d5a6Sdrh   if( cnt==1 ){
5087d10d5a6Sdrh     assert( pNC!=0 );
509a3a5bd9bSdrh     if( pExpr->op!=TK_AS ){
5107d10d5a6Sdrh       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
511a3a5bd9bSdrh     }
5127d10d5a6Sdrh     /* Increment the nRef value on all name contexts from TopNC up to
5137d10d5a6Sdrh     ** the point where the name matched. */
5147d10d5a6Sdrh     for(;;){
5157d10d5a6Sdrh       assert( pTopNC!=0 );
5167d10d5a6Sdrh       pTopNC->nRef++;
5177d10d5a6Sdrh       if( pTopNC==pNC ) break;
5187d10d5a6Sdrh       pTopNC = pTopNC->pNext;
5197d10d5a6Sdrh     }
520f7828b5cSdrh     return WRC_Prune;
5217d10d5a6Sdrh   } else {
522f7828b5cSdrh     return WRC_Abort;
5237d10d5a6Sdrh   }
5247d10d5a6Sdrh }
5257d10d5a6Sdrh 
5267d10d5a6Sdrh /*
527f7b0b0adSdan ** Allocate and return a pointer to an expression to load the column iCol
5289e48165bSdrh ** from datasource iSrc in SrcList pSrc.
529f7b0b0adSdan */
530f7b0b0adSdan Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
531f7b0b0adSdan   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
532f7b0b0adSdan   if( p ){
533f7b0b0adSdan     struct SrcList_item *pItem = &pSrc->a[iSrc];
534f7b0b0adSdan     p->pTab = pItem->pTab;
535f7b0b0adSdan     p->iTable = pItem->iCursor;
536f7b0b0adSdan     if( p->pTab->iPKey==iCol ){
537f7b0b0adSdan       p->iColumn = -1;
538f7b0b0adSdan     }else{
5398677d308Sdrh       p->iColumn = (ynVar)iCol;
5407caba669Sdrh       testcase( iCol==BMS );
5417caba669Sdrh       testcase( iCol==BMS-1 );
542f7b0b0adSdan       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
543f7b0b0adSdan     }
544f7b0b0adSdan     ExprSetProperty(p, EP_Resolved);
545f7b0b0adSdan   }
546f7b0b0adSdan   return p;
547f7b0b0adSdan }
548f7b0b0adSdan 
549f7b0b0adSdan /*
550*a514b8ebSdrh ** Report an error that an expression is not valid for some set of
551*a514b8ebSdrh ** pNC->ncFlags values determined by validMask.  If
5523780be11Sdrh */
553*a514b8ebSdrh static void notValid(
5543780be11Sdrh   Parse *pParse,       /* Leave error message here */
5553780be11Sdrh   NameContext *pNC,    /* The name context */
556*a514b8ebSdrh   const char *zMsg,    /* Type of error */
557*a514b8ebSdrh   int validMask,       /* Set of contexts for which prohibited */
558*a514b8ebSdrh   int okForInit        /* No error if pParse->db->init.busy is true */
5593780be11Sdrh ){
560*a514b8ebSdrh   assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
561*a514b8ebSdrh   if( (pNC->ncFlags & validMask)!=0
562*a514b8ebSdrh    && (pParse->db->init.busy==0 || !okForInit)
563*a514b8ebSdrh   ){
564*a514b8ebSdrh     const char *zIn = "partial index WHERE clauses";
565*a514b8ebSdrh     if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
5663780be11Sdrh #ifndef SQLITE_OMIT_CHECK
567*a514b8ebSdrh     else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
5683780be11Sdrh #endif
569*a514b8ebSdrh     sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
570*a514b8ebSdrh   }
571*a514b8ebSdrh }
5723780be11Sdrh 
573cca9f3d2Sdrh /*
574cca9f3d2Sdrh ** Expression p should encode a floating point value between 1.0 and 0.0.
575cca9f3d2Sdrh ** Return 1024 times this value.  Or return -1 if p is not a floating point
576cca9f3d2Sdrh ** value between 1.0 and 0.0.
577cca9f3d2Sdrh */
578cca9f3d2Sdrh static int exprProbability(Expr *p){
579cca9f3d2Sdrh   double r = -1.0;
580cca9f3d2Sdrh   if( p->op!=TK_FLOAT ) return -1;
581cca9f3d2Sdrh   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
58209328c00Sdrh   assert( r>=0.0 );
58309328c00Sdrh   if( r>1.0 ) return -1;
584d05ab6aaSdrh   return (int)(r*134217728.0);
585cca9f3d2Sdrh }
5863780be11Sdrh 
5873780be11Sdrh /*
5887d10d5a6Sdrh ** This routine is callback for sqlite3WalkExpr().
5897d10d5a6Sdrh **
5907d10d5a6Sdrh ** Resolve symbolic names into TK_COLUMN operators for the current
5917d10d5a6Sdrh ** node in the expression tree.  Return 0 to continue the search down
5927d10d5a6Sdrh ** the tree or 2 to abort the tree walk.
5937d10d5a6Sdrh **
5947d10d5a6Sdrh ** This routine also does error checking and name resolution for
5957d10d5a6Sdrh ** function names.  The operator for aggregate functions is changed
5967d10d5a6Sdrh ** to TK_AGG_FUNCTION.
5977d10d5a6Sdrh */
5987d10d5a6Sdrh static int resolveExprStep(Walker *pWalker, Expr *pExpr){
5997d10d5a6Sdrh   NameContext *pNC;
6007d10d5a6Sdrh   Parse *pParse;
6017d10d5a6Sdrh 
6027d10d5a6Sdrh   pNC = pWalker->u.pNC;
6037d10d5a6Sdrh   assert( pNC!=0 );
6047d10d5a6Sdrh   pParse = pNC->pParse;
6057d10d5a6Sdrh   assert( pParse==pWalker->pParse );
6067d10d5a6Sdrh 
607c5cd1249Sdrh   if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
6087d10d5a6Sdrh   ExprSetProperty(pExpr, EP_Resolved);
6097d10d5a6Sdrh #ifndef NDEBUG
6107d10d5a6Sdrh   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
6117d10d5a6Sdrh     SrcList *pSrcList = pNC->pSrcList;
6127d10d5a6Sdrh     int i;
6137d10d5a6Sdrh     for(i=0; i<pNC->pSrcList->nSrc; i++){
6147d10d5a6Sdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
6157d10d5a6Sdrh     }
6167d10d5a6Sdrh   }
6177d10d5a6Sdrh #endif
6187d10d5a6Sdrh   switch( pExpr->op ){
61941204f1fSdrh 
620273f619bSshane #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
62141204f1fSdrh     /* The special operator TK_ROW means use the rowid for the first
62241204f1fSdrh     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
62341204f1fSdrh     ** clause processing on UPDATE and DELETE statements.
62441204f1fSdrh     */
62541204f1fSdrh     case TK_ROW: {
62641204f1fSdrh       SrcList *pSrcList = pNC->pSrcList;
62741204f1fSdrh       struct SrcList_item *pItem;
62841204f1fSdrh       assert( pSrcList && pSrcList->nSrc==1 );
62941204f1fSdrh       pItem = pSrcList->a;
63041204f1fSdrh       pExpr->op = TK_COLUMN;
63141204f1fSdrh       pExpr->pTab = pItem->pTab;
63241204f1fSdrh       pExpr->iTable = pItem->iCursor;
63341204f1fSdrh       pExpr->iColumn = -1;
63441204f1fSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
63541204f1fSdrh       break;
63641204f1fSdrh     }
63731e7147dSdrh #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
63831e7147dSdrh           && !defined(SQLITE_OMIT_SUBQUERY) */
63941204f1fSdrh 
6407d10d5a6Sdrh     /* A lone identifier is the name of a column.
6417d10d5a6Sdrh     */
6427d10d5a6Sdrh     case TK_ID: {
643f7828b5cSdrh       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
6447d10d5a6Sdrh     }
6457d10d5a6Sdrh 
6467d10d5a6Sdrh     /* A table name and column name:     ID.ID
6477d10d5a6Sdrh     ** Or a database, table and column:  ID.ID.ID
6487d10d5a6Sdrh     */
6497d10d5a6Sdrh     case TK_DOT: {
650b7916a78Sdrh       const char *zColumn;
651b7916a78Sdrh       const char *zTable;
652b7916a78Sdrh       const char *zDb;
6537d10d5a6Sdrh       Expr *pRight;
6547d10d5a6Sdrh 
6557d10d5a6Sdrh       /* if( pSrcList==0 ) break; */
656*a514b8ebSdrh       notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr, 0);
657*a514b8ebSdrh       notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);
6587d10d5a6Sdrh       pRight = pExpr->pRight;
6597d10d5a6Sdrh       if( pRight->op==TK_ID ){
660b7916a78Sdrh         zDb = 0;
66133e619fcSdrh         zTable = pExpr->pLeft->u.zToken;
66233e619fcSdrh         zColumn = pRight->u.zToken;
6637d10d5a6Sdrh       }else{
6647d10d5a6Sdrh         assert( pRight->op==TK_DOT );
66533e619fcSdrh         zDb = pExpr->pLeft->u.zToken;
66633e619fcSdrh         zTable = pRight->pLeft->u.zToken;
66733e619fcSdrh         zColumn = pRight->pRight->u.zToken;
6687d10d5a6Sdrh       }
669f7828b5cSdrh       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
6707d10d5a6Sdrh     }
6717d10d5a6Sdrh 
6727d10d5a6Sdrh     /* Resolve function names
6737d10d5a6Sdrh     */
6747d10d5a6Sdrh     case TK_FUNCTION: {
6756ab3a2ecSdanielk1977       ExprList *pList = pExpr->x.pList;    /* The argument list */
6767d10d5a6Sdrh       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
6777d10d5a6Sdrh       int no_such_func = 0;       /* True if no such function exists */
6787d10d5a6Sdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
6797d10d5a6Sdrh       int is_agg = 0;             /* True if is an aggregate function */
6807d10d5a6Sdrh       int auth;                   /* Authorization to use the function */
6817d10d5a6Sdrh       int nId;                    /* Number of characters in function name */
6827d10d5a6Sdrh       const char *zId;            /* The function name. */
6837d10d5a6Sdrh       FuncDef *pDef;              /* Information about the function */
684ea678832Sdrh       u8 enc = ENC(pParse->db);   /* The database encoding */
6857d10d5a6Sdrh 
6866ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
687*a514b8ebSdrh       notValid(pParse, pNC, "functions", NC_PartIdx, 0);
68833e619fcSdrh       zId = pExpr->u.zToken;
689b7916a78Sdrh       nId = sqlite3Strlen30(zId);
6907d10d5a6Sdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
6917d10d5a6Sdrh       if( pDef==0 ){
69289d5d6a2Sdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
6937d10d5a6Sdrh         if( pDef==0 ){
6947d10d5a6Sdrh           no_such_func = 1;
6957d10d5a6Sdrh         }else{
6967d10d5a6Sdrh           wrong_num_args = 1;
6977d10d5a6Sdrh         }
6987d10d5a6Sdrh       }else{
6997d10d5a6Sdrh         is_agg = pDef->xFunc==0;
700cca9f3d2Sdrh         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
701a4c3c87eSdrh           ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
702cca9f3d2Sdrh           if( n==2 ){
703cca9f3d2Sdrh             pExpr->iTable = exprProbability(pList->a[1].pExpr);
704cca9f3d2Sdrh             if( pExpr->iTable<0 ){
70531e7147dSdrh               sqlite3ErrorMsg(pParse,
70631e7147dSdrh                 "second argument to likelihood() must be a "
707aae0f9e4Sdrh                 "constant between 0.0 and 1.0");
708cca9f3d2Sdrh               pNC->nErr++;
709cca9f3d2Sdrh             }
710cca9f3d2Sdrh           }else{
71131e7147dSdrh             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
71231e7147dSdrh             ** equivalent to likelihood(X, 0.0625).
71331e7147dSdrh             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
71431e7147dSdrh             ** short-hand for likelihood(X,0.0625).
71531e7147dSdrh             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
71631e7147dSdrh             ** for likelihood(X,0.9375).
71731e7147dSdrh             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
71831e7147dSdrh             ** to likelihood(X,0.9375). */
71903202a97Sdrh             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
720d05ab6aaSdrh             pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
721cca9f3d2Sdrh           }
722cca9f3d2Sdrh         }
7237d10d5a6Sdrh #ifndef SQLITE_OMIT_AUTHORIZATION
7247d10d5a6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
7257d10d5a6Sdrh         if( auth!=SQLITE_OK ){
7267d10d5a6Sdrh           if( auth==SQLITE_DENY ){
7277d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
7287d10d5a6Sdrh                                     pDef->zName);
7297d10d5a6Sdrh             pNC->nErr++;
7307d10d5a6Sdrh           }
7317d10d5a6Sdrh           pExpr->op = TK_NULL;
7327d10d5a6Sdrh           return WRC_Prune;
7337d10d5a6Sdrh         }
7349588ad95Sdrh #endif
73531e7147dSdrh         if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ){
73663f84573Sdrh           ExprSetProperty(pExpr,EP_ConstFunc);
737*a514b8ebSdrh         }else{
738*a514b8ebSdrh           notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr, 0);
73931e7147dSdrh         }
7407d10d5a6Sdrh       }
741a51009b2Sdrh       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
7427d10d5a6Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
7437d10d5a6Sdrh         pNC->nErr++;
7447d10d5a6Sdrh         is_agg = 0;
745ddd1fc72Sdrh       }else if( no_such_func && pParse->db->init.busy==0 ){
7467d10d5a6Sdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
7477d10d5a6Sdrh         pNC->nErr++;
7487d10d5a6Sdrh       }else if( wrong_num_args ){
7497d10d5a6Sdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
7507d10d5a6Sdrh              nId, zId);
7517d10d5a6Sdrh         pNC->nErr++;
7527d10d5a6Sdrh       }
753a51009b2Sdrh       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
7547d10d5a6Sdrh       sqlite3WalkExprList(pWalker, pList);
755030796dfSdrh       if( is_agg ){
756030796dfSdrh         NameContext *pNC2 = pNC;
757030796dfSdrh         pExpr->op = TK_AGG_FUNCTION;
758030796dfSdrh         pExpr->op2 = 0;
759030796dfSdrh         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
760030796dfSdrh           pExpr->op2++;
761030796dfSdrh           pNC2 = pNC2->pNext;
762030796dfSdrh         }
7639588ad95Sdrh         assert( pDef!=0 );
7649588ad95Sdrh         if( pNC2 ){
7659588ad95Sdrh           assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
7669588ad95Sdrh           testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
7679588ad95Sdrh           pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
7689588ad95Sdrh 
7699588ad95Sdrh         }
770030796dfSdrh         pNC->ncFlags |= NC_AllowAgg;
771030796dfSdrh       }
7727d10d5a6Sdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
7737d10d5a6Sdrh       ** type of the function
7747d10d5a6Sdrh       */
7757d10d5a6Sdrh       return WRC_Prune;
7767d10d5a6Sdrh     }
7777d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
7787d10d5a6Sdrh     case TK_SELECT:
77973c0fdc7Sdrh     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
7807d10d5a6Sdrh #endif
7817d10d5a6Sdrh     case TK_IN: {
78273c0fdc7Sdrh       testcase( pExpr->op==TK_IN );
7836ab3a2ecSdanielk1977       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
7847d10d5a6Sdrh         int nRef = pNC->nRef;
785*a514b8ebSdrh         notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr,0);
7866ab3a2ecSdanielk1977         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
7877d10d5a6Sdrh         assert( pNC->nRef>=nRef );
7887d10d5a6Sdrh         if( nRef!=pNC->nRef ){
7897d10d5a6Sdrh           ExprSetProperty(pExpr, EP_VarSelect);
7907d10d5a6Sdrh         }
7917d10d5a6Sdrh       }
7927d10d5a6Sdrh       break;
7937d10d5a6Sdrh     }
7947d10d5a6Sdrh     case TK_VARIABLE: {
795*a514b8ebSdrh       notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr, 0);
7967d10d5a6Sdrh       break;
7977d10d5a6Sdrh     }
7987d10d5a6Sdrh   }
7997d10d5a6Sdrh   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
8007d10d5a6Sdrh }
8017d10d5a6Sdrh 
8027d10d5a6Sdrh /*
8037d10d5a6Sdrh ** pEList is a list of expressions which are really the result set of the
8047d10d5a6Sdrh ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
8057d10d5a6Sdrh ** This routine checks to see if pE is a simple identifier which corresponds
8067d10d5a6Sdrh ** to the AS-name of one of the terms of the expression list.  If it is,
8077d10d5a6Sdrh ** this routine return an integer between 1 and N where N is the number of
8087d10d5a6Sdrh ** elements in pEList, corresponding to the matching entry.  If there is
8097d10d5a6Sdrh ** no match, or if pE is not a simple identifier, then this routine
8107d10d5a6Sdrh ** return 0.
8117d10d5a6Sdrh **
8127d10d5a6Sdrh ** pEList has been resolved.  pE has not.
8137d10d5a6Sdrh */
8147d10d5a6Sdrh static int resolveAsName(
8157d10d5a6Sdrh   Parse *pParse,     /* Parsing context for error messages */
8167d10d5a6Sdrh   ExprList *pEList,  /* List of expressions to scan */
8177d10d5a6Sdrh   Expr *pE           /* Expression we are trying to match */
8187d10d5a6Sdrh ){
8197d10d5a6Sdrh   int i;             /* Loop counter */
8207d10d5a6Sdrh 
821cf697396Sshane   UNUSED_PARAMETER(pParse);
822cf697396Sshane 
82373c0fdc7Sdrh   if( pE->op==TK_ID ){
82433e619fcSdrh     char *zCol = pE->u.zToken;
8257d10d5a6Sdrh     for(i=0; i<pEList->nExpr; i++){
8267d10d5a6Sdrh       char *zAs = pEList->a[i].zName;
8277d10d5a6Sdrh       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
8287d10d5a6Sdrh         return i+1;
8297d10d5a6Sdrh       }
8307d10d5a6Sdrh     }
8317d10d5a6Sdrh   }
8327d10d5a6Sdrh   return 0;
8337d10d5a6Sdrh }
8347d10d5a6Sdrh 
8357d10d5a6Sdrh /*
8367d10d5a6Sdrh ** pE is a pointer to an expression which is a single term in the
8377d10d5a6Sdrh ** ORDER BY of a compound SELECT.  The expression has not been
8387d10d5a6Sdrh ** name resolved.
8397d10d5a6Sdrh **
8407d10d5a6Sdrh ** At the point this routine is called, we already know that the
8417d10d5a6Sdrh ** ORDER BY term is not an integer index into the result set.  That
8427d10d5a6Sdrh ** case is handled by the calling routine.
8437d10d5a6Sdrh **
8447d10d5a6Sdrh ** Attempt to match pE against result set columns in the left-most
8457d10d5a6Sdrh ** SELECT statement.  Return the index i of the matching column,
8467d10d5a6Sdrh ** as an indication to the caller that it should sort by the i-th column.
8477d10d5a6Sdrh ** The left-most column is 1.  In other words, the value returned is the
8487d10d5a6Sdrh ** same integer value that would be used in the SQL statement to indicate
8497d10d5a6Sdrh ** the column.
8507d10d5a6Sdrh **
8517d10d5a6Sdrh ** If there is no match, return 0.  Return -1 if an error occurs.
8527d10d5a6Sdrh */
8537d10d5a6Sdrh static int resolveOrderByTermToExprList(
8547d10d5a6Sdrh   Parse *pParse,     /* Parsing context for error messages */
8557d10d5a6Sdrh   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
8567d10d5a6Sdrh   Expr *pE           /* The specific ORDER BY term */
8577d10d5a6Sdrh ){
8587d10d5a6Sdrh   int i;             /* Loop counter */
8597d10d5a6Sdrh   ExprList *pEList;  /* The columns of the result set */
8607d10d5a6Sdrh   NameContext nc;    /* Name context for resolving pE */
861a7564663Sdrh   sqlite3 *db;       /* Database connection */
862a7564663Sdrh   int rc;            /* Return code from subprocedures */
863a7564663Sdrh   u8 savedSuppErr;   /* Saved value of db->suppressErr */
8647d10d5a6Sdrh 
8657d10d5a6Sdrh   assert( sqlite3ExprIsInteger(pE, &i)==0 );
8667d10d5a6Sdrh   pEList = pSelect->pEList;
8677d10d5a6Sdrh 
8687d10d5a6Sdrh   /* Resolve all names in the ORDER BY term expression
8697d10d5a6Sdrh   */
8707d10d5a6Sdrh   memset(&nc, 0, sizeof(nc));
8717d10d5a6Sdrh   nc.pParse = pParse;
8727d10d5a6Sdrh   nc.pSrcList = pSelect->pSrc;
8737d10d5a6Sdrh   nc.pEList = pEList;
874a51009b2Sdrh   nc.ncFlags = NC_AllowAgg;
8757d10d5a6Sdrh   nc.nErr = 0;
876a7564663Sdrh   db = pParse->db;
877a7564663Sdrh   savedSuppErr = db->suppressErr;
878a7564663Sdrh   db->suppressErr = 1;
879a7564663Sdrh   rc = sqlite3ResolveExprNames(&nc, pE);
880a7564663Sdrh   db->suppressErr = savedSuppErr;
881a7564663Sdrh   if( rc ) return 0;
8827d10d5a6Sdrh 
8837d10d5a6Sdrh   /* Try to match the ORDER BY expression against an expression
8847d10d5a6Sdrh   ** in the result set.  Return an 1-based index of the matching
8857d10d5a6Sdrh   ** result-set entry.
8867d10d5a6Sdrh   */
8877d10d5a6Sdrh   for(i=0; i<pEList->nExpr; i++){
888619a1305Sdrh     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
8897d10d5a6Sdrh       return i+1;
8907d10d5a6Sdrh     }
8917d10d5a6Sdrh   }
8927d10d5a6Sdrh 
8937d10d5a6Sdrh   /* If no match, return 0. */
8947d10d5a6Sdrh   return 0;
8957d10d5a6Sdrh }
8967d10d5a6Sdrh 
8977d10d5a6Sdrh /*
8987d10d5a6Sdrh ** Generate an ORDER BY or GROUP BY term out-of-range error.
8997d10d5a6Sdrh */
9007d10d5a6Sdrh static void resolveOutOfRangeError(
9017d10d5a6Sdrh   Parse *pParse,         /* The error context into which to write the error */
9027d10d5a6Sdrh   const char *zType,     /* "ORDER" or "GROUP" */
9037d10d5a6Sdrh   int i,                 /* The index (1-based) of the term out of range */
9047d10d5a6Sdrh   int mx                 /* Largest permissible value of i */
9057d10d5a6Sdrh ){
9067d10d5a6Sdrh   sqlite3ErrorMsg(pParse,
9077d10d5a6Sdrh     "%r %s BY term out of range - should be "
9087d10d5a6Sdrh     "between 1 and %d", i, zType, mx);
9097d10d5a6Sdrh }
9107d10d5a6Sdrh 
9117d10d5a6Sdrh /*
9127d10d5a6Sdrh ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
9137d10d5a6Sdrh ** each term of the ORDER BY clause is a constant integer between 1
9147d10d5a6Sdrh ** and N where N is the number of columns in the compound SELECT.
9157d10d5a6Sdrh **
9167d10d5a6Sdrh ** ORDER BY terms that are already an integer between 1 and N are
9177d10d5a6Sdrh ** unmodified.  ORDER BY terms that are integers outside the range of
9187d10d5a6Sdrh ** 1 through N generate an error.  ORDER BY terms that are expressions
9197d10d5a6Sdrh ** are matched against result set expressions of compound SELECT
9207d10d5a6Sdrh ** beginning with the left-most SELECT and working toward the right.
9217d10d5a6Sdrh ** At the first match, the ORDER BY expression is transformed into
9227d10d5a6Sdrh ** the integer column number.
9237d10d5a6Sdrh **
9247d10d5a6Sdrh ** Return the number of errors seen.
9257d10d5a6Sdrh */
9267d10d5a6Sdrh static int resolveCompoundOrderBy(
9277d10d5a6Sdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
9287d10d5a6Sdrh   Select *pSelect       /* The SELECT statement containing the ORDER BY */
9297d10d5a6Sdrh ){
9307d10d5a6Sdrh   int i;
9317d10d5a6Sdrh   ExprList *pOrderBy;
9327d10d5a6Sdrh   ExprList *pEList;
9337d10d5a6Sdrh   sqlite3 *db;
9347d10d5a6Sdrh   int moreToDo = 1;
9357d10d5a6Sdrh 
9367d10d5a6Sdrh   pOrderBy = pSelect->pOrderBy;
9377d10d5a6Sdrh   if( pOrderBy==0 ) return 0;
9387d10d5a6Sdrh   db = pParse->db;
9397d10d5a6Sdrh #if SQLITE_MAX_COLUMN
9407d10d5a6Sdrh   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
9417d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
9427d10d5a6Sdrh     return 1;
9437d10d5a6Sdrh   }
9447d10d5a6Sdrh #endif
9457d10d5a6Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
9467d10d5a6Sdrh     pOrderBy->a[i].done = 0;
9477d10d5a6Sdrh   }
9487d10d5a6Sdrh   pSelect->pNext = 0;
9497d10d5a6Sdrh   while( pSelect->pPrior ){
9507d10d5a6Sdrh     pSelect->pPrior->pNext = pSelect;
9517d10d5a6Sdrh     pSelect = pSelect->pPrior;
9527d10d5a6Sdrh   }
9537d10d5a6Sdrh   while( pSelect && moreToDo ){
9547d10d5a6Sdrh     struct ExprList_item *pItem;
9557d10d5a6Sdrh     moreToDo = 0;
9567d10d5a6Sdrh     pEList = pSelect->pEList;
9570a846f96Sdrh     assert( pEList!=0 );
9587d10d5a6Sdrh     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
9597d10d5a6Sdrh       int iCol = -1;
9607d10d5a6Sdrh       Expr *pE, *pDup;
9617d10d5a6Sdrh       if( pItem->done ) continue;
962bd13d34bSdrh       pE = sqlite3ExprSkipCollate(pItem->pExpr);
9637d10d5a6Sdrh       if( sqlite3ExprIsInteger(pE, &iCol) ){
96473c0fdc7Sdrh         if( iCol<=0 || iCol>pEList->nExpr ){
9657d10d5a6Sdrh           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
9667d10d5a6Sdrh           return 1;
9677d10d5a6Sdrh         }
9687d10d5a6Sdrh       }else{
9697d10d5a6Sdrh         iCol = resolveAsName(pParse, pEList, pE);
9707d10d5a6Sdrh         if( iCol==0 ){
9716ab3a2ecSdanielk1977           pDup = sqlite3ExprDup(db, pE, 0);
9727d10d5a6Sdrh           if( !db->mallocFailed ){
9737d10d5a6Sdrh             assert(pDup);
9747d10d5a6Sdrh             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
9757d10d5a6Sdrh           }
9767d10d5a6Sdrh           sqlite3ExprDelete(db, pDup);
9777d10d5a6Sdrh         }
9787d10d5a6Sdrh       }
9797d10d5a6Sdrh       if( iCol>0 ){
980bd13d34bSdrh         /* Convert the ORDER BY term into an integer column number iCol,
981bd13d34bSdrh         ** taking care to preserve the COLLATE clause if it exists */
982bd13d34bSdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
983bd13d34bSdrh         if( pNew==0 ) return 1;
984bd13d34bSdrh         pNew->flags |= EP_IntValue;
985bd13d34bSdrh         pNew->u.iValue = iCol;
986bd13d34bSdrh         if( pItem->pExpr==pE ){
987bd13d34bSdrh           pItem->pExpr = pNew;
988bd13d34bSdrh         }else{
9896456b771Sdrh           Expr *pParent = pItem->pExpr;
9906456b771Sdrh           assert( pParent->op==TK_COLLATE );
9916456b771Sdrh           while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
9926456b771Sdrh           assert( pParent->pLeft==pE );
9936456b771Sdrh           pParent->pLeft = pNew;
994bd13d34bSdrh         }
9957d10d5a6Sdrh         sqlite3ExprDelete(db, pE);
996c2acc4e4Sdrh         pItem->u.x.iOrderByCol = (u16)iCol;
9977d10d5a6Sdrh         pItem->done = 1;
9987d10d5a6Sdrh       }else{
9997d10d5a6Sdrh         moreToDo = 1;
10007d10d5a6Sdrh       }
10017d10d5a6Sdrh     }
10027d10d5a6Sdrh     pSelect = pSelect->pNext;
10037d10d5a6Sdrh   }
10047d10d5a6Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
10057d10d5a6Sdrh     if( pOrderBy->a[i].done==0 ){
10067d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
10077d10d5a6Sdrh             "column in the result set", i+1);
10087d10d5a6Sdrh       return 1;
10097d10d5a6Sdrh     }
10107d10d5a6Sdrh   }
10117d10d5a6Sdrh   return 0;
10127d10d5a6Sdrh }
10137d10d5a6Sdrh 
10147d10d5a6Sdrh /*
10157d10d5a6Sdrh ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
10167d10d5a6Sdrh ** the SELECT statement pSelect.  If any term is reference to a
1017c2acc4e4Sdrh ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1018c2acc4e4Sdrh ** field) then convert that term into a copy of the corresponding result set
10197d10d5a6Sdrh ** column.
10207d10d5a6Sdrh **
10217d10d5a6Sdrh ** If any errors are detected, add an error message to pParse and
10227d10d5a6Sdrh ** return non-zero.  Return zero if no errors are seen.
10237d10d5a6Sdrh */
10247d10d5a6Sdrh int sqlite3ResolveOrderGroupBy(
10257d10d5a6Sdrh   Parse *pParse,        /* Parsing context.  Leave error messages here */
10267d10d5a6Sdrh   Select *pSelect,      /* The SELECT statement containing the clause */
10277d10d5a6Sdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
10287d10d5a6Sdrh   const char *zType     /* "ORDER" or "GROUP" */
10297d10d5a6Sdrh ){
10307d10d5a6Sdrh   int i;
10317d10d5a6Sdrh   sqlite3 *db = pParse->db;
10327d10d5a6Sdrh   ExprList *pEList;
10337d10d5a6Sdrh   struct ExprList_item *pItem;
10347d10d5a6Sdrh 
10357d10d5a6Sdrh   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
10367d10d5a6Sdrh #if SQLITE_MAX_COLUMN
10377d10d5a6Sdrh   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
10387d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
10397d10d5a6Sdrh     return 1;
10407d10d5a6Sdrh   }
10417d10d5a6Sdrh #endif
10427d10d5a6Sdrh   pEList = pSelect->pEList;
10430a846f96Sdrh   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
10447d10d5a6Sdrh   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1045c2acc4e4Sdrh     if( pItem->u.x.iOrderByCol ){
1046c2acc4e4Sdrh       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
10477d10d5a6Sdrh         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
10487d10d5a6Sdrh         return 1;
10497d10d5a6Sdrh       }
105031e7147dSdrh       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
105131e7147dSdrh                    zType,0);
10527d10d5a6Sdrh     }
10537d10d5a6Sdrh   }
10547d10d5a6Sdrh   return 0;
10557d10d5a6Sdrh }
10567d10d5a6Sdrh 
10577d10d5a6Sdrh /*
10587d10d5a6Sdrh ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
10597d10d5a6Sdrh ** The Name context of the SELECT statement is pNC.  zType is either
10607d10d5a6Sdrh ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
10617d10d5a6Sdrh **
10627d10d5a6Sdrh ** This routine resolves each term of the clause into an expression.
10637d10d5a6Sdrh ** If the order-by term is an integer I between 1 and N (where N is the
10647d10d5a6Sdrh ** number of columns in the result set of the SELECT) then the expression
10657d10d5a6Sdrh ** in the resolution is a copy of the I-th result-set expression.  If
106626080d92Sdrh ** the order-by term is an identifier that corresponds to the AS-name of
10677d10d5a6Sdrh ** a result-set expression, then the term resolves to a copy of the
10687d10d5a6Sdrh ** result-set expression.  Otherwise, the expression is resolved in
10697d10d5a6Sdrh ** the usual way - using sqlite3ResolveExprNames().
10707d10d5a6Sdrh **
10717d10d5a6Sdrh ** This routine returns the number of errors.  If errors occur, then
10727d10d5a6Sdrh ** an appropriate error message might be left in pParse.  (OOM errors
10737d10d5a6Sdrh ** excepted.)
10747d10d5a6Sdrh */
10757d10d5a6Sdrh static int resolveOrderGroupBy(
10767d10d5a6Sdrh   NameContext *pNC,     /* The name context of the SELECT statement */
10777d10d5a6Sdrh   Select *pSelect,      /* The SELECT statement holding pOrderBy */
10787d10d5a6Sdrh   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
10797d10d5a6Sdrh   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
10807d10d5a6Sdrh ){
108170331cd7Sdrh   int i, j;                      /* Loop counters */
10827d10d5a6Sdrh   int iCol;                      /* Column number */
10837d10d5a6Sdrh   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
10847d10d5a6Sdrh   Parse *pParse;                 /* Parsing context */
10857d10d5a6Sdrh   int nResult;                   /* Number of terms in the result set */
10867d10d5a6Sdrh 
10877d10d5a6Sdrh   if( pOrderBy==0 ) return 0;
10887d10d5a6Sdrh   nResult = pSelect->pEList->nExpr;
10897d10d5a6Sdrh   pParse = pNC->pParse;
10907d10d5a6Sdrh   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
10917d10d5a6Sdrh     Expr *pE = pItem->pExpr;
1092e35463b3Sdrh     Expr *pE2 = sqlite3ExprSkipCollate(pE);
10930af16ab2Sdrh     if( zType[0]!='G' ){
1094e35463b3Sdrh       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
10957d10d5a6Sdrh       if( iCol>0 ){
10967d10d5a6Sdrh         /* If an AS-name match is found, mark this ORDER BY column as being
10977d10d5a6Sdrh         ** a copy of the iCol-th result-set column.  The subsequent call to
10987d10d5a6Sdrh         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
10997d10d5a6Sdrh         ** copy of the iCol-th result-set expression. */
1100c2acc4e4Sdrh         pItem->u.x.iOrderByCol = (u16)iCol;
11017d10d5a6Sdrh         continue;
11027d10d5a6Sdrh       }
11030af16ab2Sdrh     }
1104e35463b3Sdrh     if( sqlite3ExprIsInteger(pE2, &iCol) ){
11057d10d5a6Sdrh       /* The ORDER BY term is an integer constant.  Again, set the column
11067d10d5a6Sdrh       ** number so that sqlite3ResolveOrderGroupBy() will convert the
11077d10d5a6Sdrh       ** order-by term to a copy of the result-set expression */
110885d641f9Sdrh       if( iCol<1 || iCol>0xffff ){
11097d10d5a6Sdrh         resolveOutOfRangeError(pParse, zType, i+1, nResult);
11107d10d5a6Sdrh         return 1;
11117d10d5a6Sdrh       }
1112c2acc4e4Sdrh       pItem->u.x.iOrderByCol = (u16)iCol;
11137d10d5a6Sdrh       continue;
11147d10d5a6Sdrh     }
11157d10d5a6Sdrh 
11167d10d5a6Sdrh     /* Otherwise, treat the ORDER BY term as an ordinary expression */
1117c2acc4e4Sdrh     pItem->u.x.iOrderByCol = 0;
11187d10d5a6Sdrh     if( sqlite3ResolveExprNames(pNC, pE) ){
11197d10d5a6Sdrh       return 1;
11207d10d5a6Sdrh     }
112170331cd7Sdrh     for(j=0; j<pSelect->pEList->nExpr; j++){
1122619a1305Sdrh       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
1123c2acc4e4Sdrh         pItem->u.x.iOrderByCol = j+1;
112470331cd7Sdrh       }
112570331cd7Sdrh     }
11267d10d5a6Sdrh   }
11277d10d5a6Sdrh   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
11287d10d5a6Sdrh }
11297d10d5a6Sdrh 
11307d10d5a6Sdrh /*
113160ec914cSpeter.d.reid ** Resolve names in the SELECT statement p and all of its descendants.
11327d10d5a6Sdrh */
11337d10d5a6Sdrh static int resolveSelectStep(Walker *pWalker, Select *p){
11347d10d5a6Sdrh   NameContext *pOuterNC;  /* Context that contains this SELECT */
11357d10d5a6Sdrh   NameContext sNC;        /* Name context of this SELECT */
11367d10d5a6Sdrh   int isCompound;         /* True if p is a compound select */
11377d10d5a6Sdrh   int nCompound;          /* Number of compound terms processed so far */
11387d10d5a6Sdrh   Parse *pParse;          /* Parsing context */
11397d10d5a6Sdrh   int i;                  /* Loop counter */
11407d10d5a6Sdrh   ExprList *pGroupBy;     /* The GROUP BY clause */
11417d10d5a6Sdrh   Select *pLeftmost;      /* Left-most of SELECT of a compound */
11427d10d5a6Sdrh   sqlite3 *db;            /* Database connection */
11437d10d5a6Sdrh 
11447d10d5a6Sdrh 
11450a846f96Sdrh   assert( p!=0 );
11467d10d5a6Sdrh   if( p->selFlags & SF_Resolved ){
11477d10d5a6Sdrh     return WRC_Prune;
11487d10d5a6Sdrh   }
11497d10d5a6Sdrh   pOuterNC = pWalker->u.pNC;
11507d10d5a6Sdrh   pParse = pWalker->pParse;
11517d10d5a6Sdrh   db = pParse->db;
11527d10d5a6Sdrh 
11537d10d5a6Sdrh   /* Normally sqlite3SelectExpand() will be called first and will have
11547d10d5a6Sdrh   ** already expanded this SELECT.  However, if this is a subquery within
11557d10d5a6Sdrh   ** an expression, sqlite3ResolveExprNames() will be called without a
11567d10d5a6Sdrh   ** prior call to sqlite3SelectExpand().  When that happens, let
11577d10d5a6Sdrh   ** sqlite3SelectPrep() do all of the processing for this SELECT.
11587d10d5a6Sdrh   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
11597d10d5a6Sdrh   ** this routine in the correct order.
11607d10d5a6Sdrh   */
11617d10d5a6Sdrh   if( (p->selFlags & SF_Expanded)==0 ){
11627d10d5a6Sdrh     sqlite3SelectPrep(pParse, p, pOuterNC);
11637d10d5a6Sdrh     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
11647d10d5a6Sdrh   }
11657d10d5a6Sdrh 
11667d10d5a6Sdrh   isCompound = p->pPrior!=0;
11677d10d5a6Sdrh   nCompound = 0;
11687d10d5a6Sdrh   pLeftmost = p;
11697d10d5a6Sdrh   while( p ){
11707d10d5a6Sdrh     assert( (p->selFlags & SF_Expanded)!=0 );
11717d10d5a6Sdrh     assert( (p->selFlags & SF_Resolved)==0 );
11727d10d5a6Sdrh     p->selFlags |= SF_Resolved;
11737d10d5a6Sdrh 
11747d10d5a6Sdrh     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
11757d10d5a6Sdrh     ** are not allowed to refer to any names, so pass an empty NameContext.
11767d10d5a6Sdrh     */
11777d10d5a6Sdrh     memset(&sNC, 0, sizeof(sNC));
11787d10d5a6Sdrh     sNC.pParse = pParse;
11797d10d5a6Sdrh     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
11807d10d5a6Sdrh         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
11817d10d5a6Sdrh       return WRC_Abort;
11827d10d5a6Sdrh     }
11837d10d5a6Sdrh 
1184b33c50f2Sdan     /* If the SF_Converted flags is set, then this Select object was
1185b33c50f2Sdan     ** was created by the convertCompoundSelectToSubquery() function.
1186b33c50f2Sdan     ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1187b33c50f2Sdan     ** as if it were part of the sub-query, not the parent. This block
1188b33c50f2Sdan     ** moves the pOrderBy down to the sub-query. It will be moved back
1189b33c50f2Sdan     ** after the names have been resolved.  */
1190b33c50f2Sdan     if( p->selFlags & SF_Converted ){
1191b33c50f2Sdan       Select *pSub = p->pSrc->a[0].pSelect;
1192a43f02efSdrh       assert( p->pSrc->nSrc==1 && p->pOrderBy );
1193b33c50f2Sdan       assert( pSub->pPrior && pSub->pOrderBy==0 );
1194b33c50f2Sdan       pSub->pOrderBy = p->pOrderBy;
1195b33c50f2Sdan       p->pOrderBy = 0;
1196b33c50f2Sdan     }
1197b33c50f2Sdan 
11987d10d5a6Sdrh     /* Recursively resolve names in all subqueries
11997d10d5a6Sdrh     */
12007d10d5a6Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
12017d10d5a6Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
12027d10d5a6Sdrh       if( pItem->pSelect ){
1203da79cf0cSdan         NameContext *pNC;         /* Used to iterate name contexts */
1204da79cf0cSdan         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
12057d10d5a6Sdrh         const char *zSavedContext = pParse->zAuthContext;
1206da79cf0cSdan 
1207da79cf0cSdan         /* Count the total number of references to pOuterNC and all of its
1208da79cf0cSdan         ** parent contexts. After resolving references to expressions in
1209da79cf0cSdan         ** pItem->pSelect, check if this value has changed. If so, then
1210da79cf0cSdan         ** SELECT statement pItem->pSelect must be correlated. Set the
12118a48b9c0Sdrh         ** pItem->fg.isCorrelated flag if this is the case. */
1212da79cf0cSdan         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1213da79cf0cSdan 
12147d10d5a6Sdrh         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1215cd2b5613Sdrh         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
12167d10d5a6Sdrh         pParse->zAuthContext = zSavedContext;
12177d10d5a6Sdrh         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
1218da79cf0cSdan 
1219da79cf0cSdan         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
12208a48b9c0Sdrh         assert( pItem->fg.isCorrelated==0 && nRef<=0 );
12218a48b9c0Sdrh         pItem->fg.isCorrelated = (nRef!=0);
12227d10d5a6Sdrh       }
12237d10d5a6Sdrh     }
12247d10d5a6Sdrh 
122592689d28Sdrh     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
122692689d28Sdrh     ** resolve the result-set expression list.
122792689d28Sdrh     */
122892689d28Sdrh     sNC.ncFlags = NC_AllowAgg;
122992689d28Sdrh     sNC.pSrcList = p->pSrc;
123092689d28Sdrh     sNC.pNext = pOuterNC;
123192689d28Sdrh 
123292689d28Sdrh     /* Resolve names in the result set. */
123301d230ceSdrh     if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
123492689d28Sdrh 
12357d10d5a6Sdrh     /* If there are no aggregate functions in the result-set, and no GROUP BY
12367d10d5a6Sdrh     ** expression, do not allow aggregates in any of the other expressions.
12377d10d5a6Sdrh     */
12387d10d5a6Sdrh     assert( (p->selFlags & SF_Aggregate)==0 );
12397d10d5a6Sdrh     pGroupBy = p->pGroupBy;
1240a51009b2Sdrh     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
12419588ad95Sdrh       assert( NC_MinMaxAgg==SF_MinMaxAgg );
12429588ad95Sdrh       p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
12437d10d5a6Sdrh     }else{
1244a51009b2Sdrh       sNC.ncFlags &= ~NC_AllowAgg;
12457d10d5a6Sdrh     }
12467d10d5a6Sdrh 
12477d10d5a6Sdrh     /* If a HAVING clause is present, then there must be a GROUP BY clause.
12487d10d5a6Sdrh     */
12497d10d5a6Sdrh     if( p->pHaving && !pGroupBy ){
12507d10d5a6Sdrh       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
12517d10d5a6Sdrh       return WRC_Abort;
12527d10d5a6Sdrh     }
12537d10d5a6Sdrh 
125426080d92Sdrh     /* Add the output column list to the name-context before parsing the
12557d10d5a6Sdrh     ** other expressions in the SELECT statement. This is so that
12567d10d5a6Sdrh     ** expressions in the WHERE clause (etc.) can refer to expressions by
12577d10d5a6Sdrh     ** aliases in the result set.
12587d10d5a6Sdrh     **
12597d10d5a6Sdrh     ** Minor point: If this is the case, then the expression will be
12607d10d5a6Sdrh     ** re-evaluated for each reference to it.
12617d10d5a6Sdrh     */
12627d10d5a6Sdrh     sNC.pEList = p->pEList;
126358a450c0Sdrh     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1264a3a5bd9bSdrh     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
12657d10d5a6Sdrh 
126601d230ceSdrh     /* Resolve names in table-valued-function arguments */
126701d230ceSdrh     for(i=0; i<p->pSrc->nSrc; i++){
126801d230ceSdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
126901d230ceSdrh       if( pItem->fg.isTabFunc
127001d230ceSdrh        && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
127101d230ceSdrh       ){
127201d230ceSdrh         return WRC_Abort;
127301d230ceSdrh       }
127401d230ceSdrh     }
127501d230ceSdrh 
12767d10d5a6Sdrh     /* The ORDER BY and GROUP BY clauses may not refer to terms in
12777d10d5a6Sdrh     ** outer queries
12787d10d5a6Sdrh     */
12797d10d5a6Sdrh     sNC.pNext = 0;
1280a51009b2Sdrh     sNC.ncFlags |= NC_AllowAgg;
12817d10d5a6Sdrh 
1282b33c50f2Sdan     /* If this is a converted compound query, move the ORDER BY clause from
1283b33c50f2Sdan     ** the sub-query back to the parent query. At this point each term
1284b33c50f2Sdan     ** within the ORDER BY clause has been transformed to an integer value.
1285b33c50f2Sdan     ** These integers will be replaced by copies of the corresponding result
1286b33c50f2Sdan     ** set expressions by the call to resolveOrderGroupBy() below.  */
1287b33c50f2Sdan     if( p->selFlags & SF_Converted ){
1288b33c50f2Sdan       Select *pSub = p->pSrc->a[0].pSelect;
1289b33c50f2Sdan       p->pOrderBy = pSub->pOrderBy;
1290b33c50f2Sdan       pSub->pOrderBy = 0;
1291b33c50f2Sdan     }
1292b33c50f2Sdan 
12937d10d5a6Sdrh     /* Process the ORDER BY clause for singleton SELECT statements.
12947d10d5a6Sdrh     ** The ORDER BY clause for compounds SELECT statements is handled
12957d10d5a6Sdrh     ** below, after all of the result-sets for all of the elements of
12967d10d5a6Sdrh     ** the compound have been resolved.
12977b4da150Sdrh     **
12987b4da150Sdrh     ** If there is an ORDER BY clause on a term of a compound-select other
12997b4da150Sdrh     ** than the right-most term, then that is a syntax error.  But the error
13007b4da150Sdrh     ** is not detected until much later, and so we need to go ahead and
13017b4da150Sdrh     ** resolve those symbols on the incorrect ORDER BY for consistency.
13027d10d5a6Sdrh     */
13037b4da150Sdrh     if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
13047b4da150Sdrh      && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
13057b4da150Sdrh     ){
13067d10d5a6Sdrh       return WRC_Abort;
13077d10d5a6Sdrh     }
13087d10d5a6Sdrh     if( db->mallocFailed ){
13097d10d5a6Sdrh       return WRC_Abort;
13107d10d5a6Sdrh     }
13117d10d5a6Sdrh 
13127d10d5a6Sdrh     /* Resolve the GROUP BY clause.  At the same time, make sure
13137d10d5a6Sdrh     ** the GROUP BY clause does not contain aggregate functions.
13147d10d5a6Sdrh     */
13157d10d5a6Sdrh     if( pGroupBy ){
13167d10d5a6Sdrh       struct ExprList_item *pItem;
13177d10d5a6Sdrh 
13187d10d5a6Sdrh       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
13197d10d5a6Sdrh         return WRC_Abort;
13207d10d5a6Sdrh       }
13217d10d5a6Sdrh       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
13227d10d5a6Sdrh         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
13237d10d5a6Sdrh           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
13247d10d5a6Sdrh               "the GROUP BY clause");
13257d10d5a6Sdrh           return WRC_Abort;
13267d10d5a6Sdrh         }
13277d10d5a6Sdrh       }
13287d10d5a6Sdrh     }
13297d10d5a6Sdrh 
1330923cadb1Sdan     /* If this is part of a compound SELECT, check that it has the right
1331923cadb1Sdan     ** number of expressions in the select list. */
1332923cadb1Sdan     if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
1333923cadb1Sdan       sqlite3SelectWrongNumTermsError(pParse, p->pNext);
1334923cadb1Sdan       return WRC_Abort;
1335923cadb1Sdan     }
1336923cadb1Sdan 
13377d10d5a6Sdrh     /* Advance to the next term of the compound
13387d10d5a6Sdrh     */
13397d10d5a6Sdrh     p = p->pPrior;
13407d10d5a6Sdrh     nCompound++;
13417d10d5a6Sdrh   }
13427d10d5a6Sdrh 
13437d10d5a6Sdrh   /* Resolve the ORDER BY on a compound SELECT after all terms of
13447d10d5a6Sdrh   ** the compound have been resolved.
13457d10d5a6Sdrh   */
13467d10d5a6Sdrh   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
13477d10d5a6Sdrh     return WRC_Abort;
13487d10d5a6Sdrh   }
13497d10d5a6Sdrh 
13507d10d5a6Sdrh   return WRC_Prune;
13517d10d5a6Sdrh }
13527d10d5a6Sdrh 
13537d10d5a6Sdrh /*
13547d10d5a6Sdrh ** This routine walks an expression tree and resolves references to
13557d10d5a6Sdrh ** table columns and result-set columns.  At the same time, do error
13567d10d5a6Sdrh ** checking on function usage and set a flag if any aggregate functions
13577d10d5a6Sdrh ** are seen.
13587d10d5a6Sdrh **
13597d10d5a6Sdrh ** To resolve table columns references we look for nodes (or subtrees) of the
13607d10d5a6Sdrh ** form X.Y.Z or Y.Z or just Z where
13617d10d5a6Sdrh **
13627d10d5a6Sdrh **      X:   The name of a database.  Ex:  "main" or "temp" or
13637d10d5a6Sdrh **           the symbolic name assigned to an ATTACH-ed database.
13647d10d5a6Sdrh **
13657d10d5a6Sdrh **      Y:   The name of a table in a FROM clause.  Or in a trigger
13667d10d5a6Sdrh **           one of the special names "old" or "new".
13677d10d5a6Sdrh **
13687d10d5a6Sdrh **      Z:   The name of a column in table Y.
13697d10d5a6Sdrh **
13707d10d5a6Sdrh ** The node at the root of the subtree is modified as follows:
13717d10d5a6Sdrh **
13727d10d5a6Sdrh **    Expr.op        Changed to TK_COLUMN
13737d10d5a6Sdrh **    Expr.pTab      Points to the Table object for X.Y
13747d10d5a6Sdrh **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
13757d10d5a6Sdrh **    Expr.iTable    The VDBE cursor number for X.Y
13767d10d5a6Sdrh **
13777d10d5a6Sdrh **
13787d10d5a6Sdrh ** To resolve result-set references, look for expression nodes of the
13797d10d5a6Sdrh ** form Z (with no X and Y prefix) where the Z matches the right-hand
13807d10d5a6Sdrh ** size of an AS clause in the result-set of a SELECT.  The Z expression
13817d10d5a6Sdrh ** is replaced by a copy of the left-hand side of the result-set expression.
13827d10d5a6Sdrh ** Table-name and function resolution occurs on the substituted expression
13837d10d5a6Sdrh ** tree.  For example, in:
13847d10d5a6Sdrh **
13857d10d5a6Sdrh **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
13867d10d5a6Sdrh **
13877d10d5a6Sdrh ** The "x" term of the order by is replaced by "a+b" to render:
13887d10d5a6Sdrh **
13897d10d5a6Sdrh **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
13907d10d5a6Sdrh **
13917d10d5a6Sdrh ** Function calls are checked to make sure that the function is
13927d10d5a6Sdrh ** defined and that the correct number of arguments are specified.
1393a51009b2Sdrh ** If the function is an aggregate function, then the NC_HasAgg flag is
13947d10d5a6Sdrh ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
13957d10d5a6Sdrh ** If an expression contains aggregate functions then the EP_Agg
13967d10d5a6Sdrh ** property on the expression is set.
13977d10d5a6Sdrh **
13987d10d5a6Sdrh ** An error message is left in pParse if anything is amiss.  The number
13997d10d5a6Sdrh ** if errors is returned.
14007d10d5a6Sdrh */
14017d10d5a6Sdrh int sqlite3ResolveExprNames(
14027d10d5a6Sdrh   NameContext *pNC,       /* Namespace to resolve expressions in. */
14037d10d5a6Sdrh   Expr *pExpr             /* The expression to be analyzed. */
14047d10d5a6Sdrh ){
14059588ad95Sdrh   u16 savedHasAgg;
14067d10d5a6Sdrh   Walker w;
14077d10d5a6Sdrh 
14087d10d5a6Sdrh   if( pExpr==0 ) return 0;
14097d10d5a6Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
14107d10d5a6Sdrh   {
14117d10d5a6Sdrh     Parse *pParse = pNC->pParse;
14127d10d5a6Sdrh     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
14137d10d5a6Sdrh       return 1;
14147d10d5a6Sdrh     }
14157d10d5a6Sdrh     pParse->nHeight += pExpr->nHeight;
14167d10d5a6Sdrh   }
14177d10d5a6Sdrh #endif
14189588ad95Sdrh   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
14199588ad95Sdrh   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
1420aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
14217d10d5a6Sdrh   w.xExprCallback = resolveExprStep;
14227d10d5a6Sdrh   w.xSelectCallback = resolveSelectStep;
14237d10d5a6Sdrh   w.pParse = pNC->pParse;
14247d10d5a6Sdrh   w.u.pNC = pNC;
14257d10d5a6Sdrh   sqlite3WalkExpr(&w, pExpr);
14267d10d5a6Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
14277d10d5a6Sdrh   pNC->pParse->nHeight -= pExpr->nHeight;
14287d10d5a6Sdrh #endif
1429fd773cf9Sdrh   if( pNC->nErr>0 || w.pParse->nErr>0 ){
14307d10d5a6Sdrh     ExprSetProperty(pExpr, EP_Error);
14317d10d5a6Sdrh   }
1432a51009b2Sdrh   if( pNC->ncFlags & NC_HasAgg ){
14337d10d5a6Sdrh     ExprSetProperty(pExpr, EP_Agg);
14347d10d5a6Sdrh   }
14359588ad95Sdrh   pNC->ncFlags |= savedHasAgg;
14367d10d5a6Sdrh   return ExprHasProperty(pExpr, EP_Error);
14377d10d5a6Sdrh }
14387d10d5a6Sdrh 
143901d230ceSdrh /*
144001d230ceSdrh ** Resolve all names for all expression in an expression list.  This is
144101d230ceSdrh ** just like sqlite3ResolveExprNames() except that it works for an expression
144201d230ceSdrh ** list rather than a single expression.
144301d230ceSdrh */
144401d230ceSdrh int sqlite3ResolveExprListNames(
144501d230ceSdrh   NameContext *pNC,       /* Namespace to resolve expressions in. */
144601d230ceSdrh   ExprList *pList         /* The expression list to be analyzed. */
144701d230ceSdrh ){
144801d230ceSdrh   int i;
1449c743579eSdrh   assert( pList!=0 );
145001d230ceSdrh   for(i=0; i<pList->nExpr; i++){
145101d230ceSdrh     if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
145201d230ceSdrh   }
145301d230ceSdrh   return WRC_Continue;
145401d230ceSdrh }
14557d10d5a6Sdrh 
14567d10d5a6Sdrh /*
14577d10d5a6Sdrh ** Resolve all names in all expressions of a SELECT and in all
14587d10d5a6Sdrh ** decendents of the SELECT, including compounds off of p->pPrior,
14597d10d5a6Sdrh ** subqueries in expressions, and subqueries used as FROM clause
14607d10d5a6Sdrh ** terms.
14617d10d5a6Sdrh **
14627d10d5a6Sdrh ** See sqlite3ResolveExprNames() for a description of the kinds of
14637d10d5a6Sdrh ** transformations that occur.
14647d10d5a6Sdrh **
14657d10d5a6Sdrh ** All SELECT statements should have been expanded using
14667d10d5a6Sdrh ** sqlite3SelectExpand() prior to invoking this routine.
14677d10d5a6Sdrh */
14687d10d5a6Sdrh void sqlite3ResolveSelectNames(
14697d10d5a6Sdrh   Parse *pParse,         /* The parser context */
14707d10d5a6Sdrh   Select *p,             /* The SELECT statement being coded. */
14717d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for parent SELECT statement */
14727d10d5a6Sdrh ){
14737d10d5a6Sdrh   Walker w;
14747d10d5a6Sdrh 
14750a846f96Sdrh   assert( p!=0 );
1476aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
14777d10d5a6Sdrh   w.xExprCallback = resolveExprStep;
14787d10d5a6Sdrh   w.xSelectCallback = resolveSelectStep;
14797d10d5a6Sdrh   w.pParse = pParse;
14807d10d5a6Sdrh   w.u.pNC = pOuterNC;
14817d10d5a6Sdrh   sqlite3WalkSelect(&w, p);
14827d10d5a6Sdrh }
14833780be11Sdrh 
14843780be11Sdrh /*
14853780be11Sdrh ** Resolve names in expressions that can only reference a single table:
14863780be11Sdrh **
14873780be11Sdrh **    *   CHECK constraints
14883780be11Sdrh **    *   WHERE clauses on partial indices
14893780be11Sdrh **
14903780be11Sdrh ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
14913780be11Sdrh ** is set to -1 and the Expr.iColumn value is set to the column number.
14923780be11Sdrh **
14933780be11Sdrh ** Any errors cause an error message to be set in pParse.
14943780be11Sdrh */
14953780be11Sdrh void sqlite3ResolveSelfReference(
14963780be11Sdrh   Parse *pParse,      /* Parsing context */
14973780be11Sdrh   Table *pTab,        /* The table being referenced */
1498*a514b8ebSdrh   int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
14993780be11Sdrh   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
15003780be11Sdrh   ExprList *pList     /* Expression list to resolve.  May be NUL. */
15013780be11Sdrh ){
15023780be11Sdrh   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
15033780be11Sdrh   NameContext sNC;                /* Name context for pParse->pNewTable */
15043780be11Sdrh 
1505*a514b8ebSdrh   assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
15063780be11Sdrh   memset(&sNC, 0, sizeof(sNC));
15073780be11Sdrh   memset(&sSrc, 0, sizeof(sSrc));
15083780be11Sdrh   sSrc.nSrc = 1;
15093780be11Sdrh   sSrc.a[0].zName = pTab->zName;
15103780be11Sdrh   sSrc.a[0].pTab = pTab;
15113780be11Sdrh   sSrc.a[0].iCursor = -1;
15123780be11Sdrh   sNC.pParse = pParse;
15133780be11Sdrh   sNC.pSrcList = &sSrc;
15143780be11Sdrh   sNC.ncFlags = type;
15153780be11Sdrh   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
1516fea870beSdrh   if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
15173780be11Sdrh }
1518