Back to index

lightning-sunbird  0.9+nobinonly
expr.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains routines used for analyzing expressions and
00013 ** for generating VDBE code that evaluates expressions in SQLite.
00014 **
00015 ** $Id: expr.c,v 1.257 2006/03/17 13:56:34 drh Exp $
00016 */
00017 #include "sqliteInt.h"
00018 #include <ctype.h>
00019 
00020 /*
00021 ** Return the 'affinity' of the expression pExpr if any.
00022 **
00023 ** If pExpr is a column, a reference to a column via an 'AS' alias,
00024 ** or a sub-select with a column as the return value, then the 
00025 ** affinity of that column is returned. Otherwise, 0x00 is returned,
00026 ** indicating no affinity for the expression.
00027 **
00028 ** i.e. the WHERE clause expresssions in the following statements all
00029 ** have an affinity:
00030 **
00031 ** CREATE TABLE t1(a);
00032 ** SELECT * FROM t1 WHERE a;
00033 ** SELECT a AS b FROM t1 WHERE b;
00034 ** SELECT * FROM t1 WHERE (select a from t1);
00035 */
00036 char sqlite3ExprAffinity(Expr *pExpr){
00037   int op = pExpr->op;
00038   if( op==TK_AS ){
00039     return sqlite3ExprAffinity(pExpr->pLeft);
00040   }
00041   if( op==TK_SELECT ){
00042     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
00043   }
00044 #ifndef SQLITE_OMIT_CAST
00045   if( op==TK_CAST ){
00046     return sqlite3AffinityType(&pExpr->token);
00047   }
00048 #endif
00049   return pExpr->affinity;
00050 }
00051 
00052 /*
00053 ** Return the default collation sequence for the expression pExpr. If
00054 ** there is no default collation type, return 0.
00055 */
00056 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
00057   CollSeq *pColl = 0;
00058   if( pExpr ){
00059     pColl = pExpr->pColl;
00060     if( (pExpr->op==TK_AS || pExpr->op==TK_CAST) && !pColl ){
00061       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
00062     }
00063   }
00064   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
00065     pColl = 0;
00066   }
00067   return pColl;
00068 }
00069 
00070 /*
00071 ** pExpr is an operand of a comparison operator.  aff2 is the
00072 ** type affinity of the other operand.  This routine returns the
00073 ** type affinity that should be used for the comparison operator.
00074 */
00075 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
00076   char aff1 = sqlite3ExprAffinity(pExpr);
00077   if( aff1 && aff2 ){
00078     /* Both sides of the comparison are columns. If one has numeric
00079     ** affinity, use that. Otherwise use no affinity.
00080     */
00081     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
00082       return SQLITE_AFF_NUMERIC;
00083     }else{
00084       return SQLITE_AFF_NONE;
00085     }
00086   }else if( !aff1 && !aff2 ){
00087     /* Neither side of the comparison is a column.  Compare the
00088     ** results directly.
00089     */
00090     return SQLITE_AFF_NONE;
00091   }else{
00092     /* One side is a column, the other is not. Use the columns affinity. */
00093     assert( aff1==0 || aff2==0 );
00094     return (aff1 + aff2);
00095   }
00096 }
00097 
00098 /*
00099 ** pExpr is a comparison operator.  Return the type affinity that should
00100 ** be applied to both operands prior to doing the comparison.
00101 */
00102 static char comparisonAffinity(Expr *pExpr){
00103   char aff;
00104   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
00105           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
00106           pExpr->op==TK_NE );
00107   assert( pExpr->pLeft );
00108   aff = sqlite3ExprAffinity(pExpr->pLeft);
00109   if( pExpr->pRight ){
00110     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
00111   }
00112   else if( pExpr->pSelect ){
00113     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
00114   }
00115   else if( !aff ){
00116     aff = SQLITE_AFF_NUMERIC;
00117   }
00118   return aff;
00119 }
00120 
00121 /*
00122 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
00123 ** idx_affinity is the affinity of an indexed column. Return true
00124 ** if the index with affinity idx_affinity may be used to implement
00125 ** the comparison in pExpr.
00126 */
00127 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
00128   char aff = comparisonAffinity(pExpr);
00129   switch( aff ){
00130     case SQLITE_AFF_NONE:
00131       return 1;
00132     case SQLITE_AFF_TEXT:
00133       return idx_affinity==SQLITE_AFF_TEXT;
00134     default:
00135       return sqlite3IsNumericAffinity(idx_affinity);
00136   }
00137 }
00138 
00139 /*
00140 ** Return the P1 value that should be used for a binary comparison
00141 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
00142 ** If jumpIfNull is true, then set the low byte of the returned
00143 ** P1 value to tell the opcode to jump if either expression
00144 ** evaluates to NULL.
00145 */
00146 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
00147   char aff = sqlite3ExprAffinity(pExpr2);
00148   return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
00149 }
00150 
00151 /*
00152 ** Return a pointer to the collation sequence that should be used by
00153 ** a binary comparison operator comparing pLeft and pRight.
00154 **
00155 ** If the left hand expression has a collating sequence type, then it is
00156 ** used. Otherwise the collation sequence for the right hand expression
00157 ** is used, or the default (BINARY) if neither expression has a collating
00158 ** type.
00159 */
00160 static CollSeq* binaryCompareCollSeq(Parse *pParse, Expr *pLeft, Expr *pRight){
00161   CollSeq *pColl = sqlite3ExprCollSeq(pParse, pLeft);
00162   if( !pColl ){
00163     pColl = sqlite3ExprCollSeq(pParse, pRight);
00164   }
00165   return pColl;
00166 }
00167 
00168 /*
00169 ** Generate code for a comparison operator.
00170 */
00171 static int codeCompare(
00172   Parse *pParse,    /* The parsing (and code generating) context */
00173   Expr *pLeft,      /* The left operand */
00174   Expr *pRight,     /* The right operand */
00175   int opcode,       /* The comparison opcode */
00176   int dest,         /* Jump here if true.  */
00177   int jumpIfNull    /* If true, jump if either operand is NULL */
00178 ){
00179   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
00180   CollSeq *p3 = binaryCompareCollSeq(pParse, pLeft, pRight);
00181   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
00182 }
00183 
00184 /*
00185 ** Construct a new expression node and return a pointer to it.  Memory
00186 ** for this node is obtained from sqliteMalloc().  The calling function
00187 ** is responsible for making sure the node eventually gets freed.
00188 */
00189 Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
00190   Expr *pNew;
00191   pNew = sqliteMalloc( sizeof(Expr) );
00192   if( pNew==0 ){
00193     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
00194     ** this function must always be allocated with sqlite3Expr() for this 
00195     ** reason. 
00196     */
00197     sqlite3ExprDelete(pLeft);
00198     sqlite3ExprDelete(pRight);
00199     return 0;
00200   }
00201   pNew->op = op;
00202   pNew->pLeft = pLeft;
00203   pNew->pRight = pRight;
00204   pNew->iAgg = -1;
00205   if( pToken ){
00206     assert( pToken->dyn==0 );
00207     pNew->span = pNew->token = *pToken;
00208   }else if( pLeft && pRight ){
00209     sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
00210   }
00211   return pNew;
00212 }
00213 
00214 /*
00215 ** When doing a nested parse, you can include terms in an expression
00216 ** that look like this:   #0 #1 #2 ...  These terms refer to elements
00217 ** on the stack.  "#0" means the top of the stack.
00218 ** "#1" means the next down on the stack.  And so forth.
00219 **
00220 ** This routine is called by the parser to deal with on of those terms.
00221 ** It immediately generates code to store the value in a memory location.
00222 ** The returns an expression that will code to extract the value from
00223 ** that memory location as needed.
00224 */
00225 Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
00226   Vdbe *v = pParse->pVdbe;
00227   Expr *p;
00228   int depth;
00229   if( pParse->nested==0 ){
00230     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
00231     return 0;
00232   }
00233   if( v==0 ) return 0;
00234   p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
00235   if( p==0 ){
00236     return 0;  /* Malloc failed */
00237   }
00238   depth = atoi((char*)&pToken->z[1]);
00239   p->iTable = pParse->nMem++;
00240   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
00241   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
00242   return p;
00243 }
00244 
00245 /*
00246 ** Join two expressions using an AND operator.  If either expression is
00247 ** NULL, then just return the other expression.
00248 */
00249 Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
00250   if( pLeft==0 ){
00251     return pRight;
00252   }else if( pRight==0 ){
00253     return pLeft;
00254   }else{
00255     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
00256   }
00257 }
00258 
00259 /*
00260 ** Set the Expr.span field of the given expression to span all
00261 ** text between the two given tokens.
00262 */
00263 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
00264   assert( pRight!=0 );
00265   assert( pLeft!=0 );
00266   if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
00267     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
00268     if( pLeft->dyn==0 && pRight->dyn==0 ){
00269       pExpr->span.z = pLeft->z;
00270       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
00271     }else{
00272       pExpr->span.z = 0;
00273     }
00274   }
00275 }
00276 
00277 /*
00278 ** Construct a new expression node for a function with multiple
00279 ** arguments.
00280 */
00281 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
00282   Expr *pNew;
00283   assert( pToken );
00284   pNew = sqliteMalloc( sizeof(Expr) );
00285   if( pNew==0 ){
00286     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
00287     return 0;
00288   }
00289   pNew->op = TK_FUNCTION;
00290   pNew->pList = pList;
00291   assert( pToken->dyn==0 );
00292   pNew->token = *pToken;
00293   pNew->span = pNew->token;
00294   return pNew;
00295 }
00296 
00297 /*
00298 ** Assign a variable number to an expression that encodes a wildcard
00299 ** in the original SQL statement.  
00300 **
00301 ** Wildcards consisting of a single "?" are assigned the next sequential
00302 ** variable number.
00303 **
00304 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
00305 ** sure "nnn" is not too be to avoid a denial of service attack when
00306 ** the SQL statement comes from an external source.
00307 **
00308 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
00309 ** as the previous instance of the same wildcard.  Or if this is the first
00310 ** instance of the wildcard, the next sequenial variable number is
00311 ** assigned.
00312 */
00313 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
00314   Token *pToken;
00315   if( pExpr==0 ) return;
00316   pToken = &pExpr->token;
00317   assert( pToken->n>=1 );
00318   assert( pToken->z!=0 );
00319   assert( pToken->z[0]!=0 );
00320   if( pToken->n==1 ){
00321     /* Wildcard of the form "?".  Assign the next variable number */
00322     pExpr->iTable = ++pParse->nVar;
00323   }else if( pToken->z[0]=='?' ){
00324     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
00325     ** use it as the variable number */
00326     int i;
00327     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
00328     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
00329       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
00330           SQLITE_MAX_VARIABLE_NUMBER);
00331     }
00332     if( i>pParse->nVar ){
00333       pParse->nVar = i;
00334     }
00335   }else{
00336     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
00337     ** number as the prior appearance of the same name, or if the name
00338     ** has never appeared before, reuse the same variable number
00339     */
00340     int i, n;
00341     n = pToken->n;
00342     for(i=0; i<pParse->nVarExpr; i++){
00343       Expr *pE;
00344       if( (pE = pParse->apVarExpr[i])!=0
00345           && pE->token.n==n
00346           && memcmp(pE->token.z, pToken->z, n)==0 ){
00347         pExpr->iTable = pE->iTable;
00348         break;
00349       }
00350     }
00351     if( i>=pParse->nVarExpr ){
00352       pExpr->iTable = ++pParse->nVar;
00353       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
00354         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
00355         sqliteReallocOrFree((void**)&pParse->apVarExpr,
00356                        pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
00357       }
00358       if( !sqlite3MallocFailed() ){
00359         assert( pParse->apVarExpr!=0 );
00360         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
00361       }
00362     }
00363   } 
00364 }
00365 
00366 /*
00367 ** Recursively delete an expression tree.
00368 */
00369 void sqlite3ExprDelete(Expr *p){
00370   if( p==0 ) return;
00371   if( p->span.dyn ) sqliteFree((char*)p->span.z);
00372   if( p->token.dyn ) sqliteFree((char*)p->token.z);
00373   sqlite3ExprDelete(p->pLeft);
00374   sqlite3ExprDelete(p->pRight);
00375   sqlite3ExprListDelete(p->pList);
00376   sqlite3SelectDelete(p->pSelect);
00377   sqliteFree(p);
00378 }
00379 
00380 /*
00381 ** The Expr.token field might be a string literal that is quoted.
00382 ** If so, remove the quotation marks.
00383 */
00384 void sqlite3DequoteExpr(Expr *p){
00385   if( ExprHasAnyProperty(p, EP_Dequoted) ){
00386     return;
00387   }
00388   ExprSetProperty(p, EP_Dequoted);
00389   if( p->token.dyn==0 ){
00390     sqlite3TokenCopy(&p->token, &p->token);
00391   }
00392   sqlite3Dequote((char*)p->token.z);
00393 }
00394 
00395 
00396 /*
00397 ** The following group of routines make deep copies of expressions,
00398 ** expression lists, ID lists, and select statements.  The copies can
00399 ** be deleted (by being passed to their respective ...Delete() routines)
00400 ** without effecting the originals.
00401 **
00402 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
00403 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
00404 ** by subsequent calls to sqlite*ListAppend() routines.
00405 **
00406 ** Any tables that the SrcList might point to are not duplicated.
00407 */
00408 Expr *sqlite3ExprDup(Expr *p){
00409   Expr *pNew;
00410   if( p==0 ) return 0;
00411   pNew = sqliteMallocRaw( sizeof(*p) );
00412   if( pNew==0 ) return 0;
00413   memcpy(pNew, p, sizeof(*pNew));
00414   if( p->token.z!=0 ){
00415     pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
00416     pNew->token.dyn = 1;
00417   }else{
00418     assert( pNew->token.z==0 );
00419   }
00420   pNew->span.z = 0;
00421   pNew->pLeft = sqlite3ExprDup(p->pLeft);
00422   pNew->pRight = sqlite3ExprDup(p->pRight);
00423   pNew->pList = sqlite3ExprListDup(p->pList);
00424   pNew->pSelect = sqlite3SelectDup(p->pSelect);
00425   pNew->pTab = p->pTab;
00426   return pNew;
00427 }
00428 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
00429   if( pTo->dyn ) sqliteFree((char*)pTo->z);
00430   if( pFrom->z ){
00431     pTo->n = pFrom->n;
00432     pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
00433     pTo->dyn = 1;
00434   }else{
00435     pTo->z = 0;
00436   }
00437 }
00438 ExprList *sqlite3ExprListDup(ExprList *p){
00439   ExprList *pNew;
00440   struct ExprList_item *pItem, *pOldItem;
00441   int i;
00442   if( p==0 ) return 0;
00443   pNew = sqliteMalloc( sizeof(*pNew) );
00444   if( pNew==0 ) return 0;
00445   pNew->nExpr = pNew->nAlloc = p->nExpr;
00446   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
00447   if( pItem==0 ){
00448     sqliteFree(pNew);
00449     return 0;
00450   } 
00451   pOldItem = p->a;
00452   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
00453     Expr *pNewExpr, *pOldExpr;
00454     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
00455     if( pOldExpr->span.z!=0 && pNewExpr ){
00456       /* Always make a copy of the span for top-level expressions in the
00457       ** expression list.  The logic in SELECT processing that determines
00458       ** the names of columns in the result set needs this information */
00459       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
00460     }
00461     assert( pNewExpr==0 || pNewExpr->span.z!=0 
00462             || pOldExpr->span.z==0
00463             || sqlite3MallocFailed() );
00464     pItem->zName = sqliteStrDup(pOldItem->zName);
00465     pItem->sortOrder = pOldItem->sortOrder;
00466     pItem->isAgg = pOldItem->isAgg;
00467     pItem->done = 0;
00468   }
00469   return pNew;
00470 }
00471 
00472 /*
00473 ** If cursors, triggers, views and subqueries are all omitted from
00474 ** the build, then none of the following routines, except for 
00475 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
00476 ** called with a NULL argument.
00477 */
00478 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
00479  || !defined(SQLITE_OMIT_SUBQUERY)
00480 SrcList *sqlite3SrcListDup(SrcList *p){
00481   SrcList *pNew;
00482   int i;
00483   int nByte;
00484   if( p==0 ) return 0;
00485   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
00486   pNew = sqliteMallocRaw( nByte );
00487   if( pNew==0 ) return 0;
00488   pNew->nSrc = pNew->nAlloc = p->nSrc;
00489   for(i=0; i<p->nSrc; i++){
00490     struct SrcList_item *pNewItem = &pNew->a[i];
00491     struct SrcList_item *pOldItem = &p->a[i];
00492     Table *pTab;
00493     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
00494     pNewItem->zName = sqliteStrDup(pOldItem->zName);
00495     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
00496     pNewItem->jointype = pOldItem->jointype;
00497     pNewItem->iCursor = pOldItem->iCursor;
00498     pNewItem->isPopulated = pOldItem->isPopulated;
00499     pTab = pNewItem->pTab = pOldItem->pTab;
00500     if( pTab ){
00501       pTab->nRef++;
00502     }
00503     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
00504     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
00505     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
00506     pNewItem->colUsed = pOldItem->colUsed;
00507   }
00508   return pNew;
00509 }
00510 IdList *sqlite3IdListDup(IdList *p){
00511   IdList *pNew;
00512   int i;
00513   if( p==0 ) return 0;
00514   pNew = sqliteMallocRaw( sizeof(*pNew) );
00515   if( pNew==0 ) return 0;
00516   pNew->nId = pNew->nAlloc = p->nId;
00517   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
00518   if( pNew->a==0 ){
00519     sqliteFree(pNew);
00520     return 0;
00521   }
00522   for(i=0; i<p->nId; i++){
00523     struct IdList_item *pNewItem = &pNew->a[i];
00524     struct IdList_item *pOldItem = &p->a[i];
00525     pNewItem->zName = sqliteStrDup(pOldItem->zName);
00526     pNewItem->idx = pOldItem->idx;
00527   }
00528   return pNew;
00529 }
00530 Select *sqlite3SelectDup(Select *p){
00531   Select *pNew;
00532   if( p==0 ) return 0;
00533   pNew = sqliteMallocRaw( sizeof(*p) );
00534   if( pNew==0 ) return 0;
00535   pNew->isDistinct = p->isDistinct;
00536   pNew->pEList = sqlite3ExprListDup(p->pEList);
00537   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
00538   pNew->pWhere = sqlite3ExprDup(p->pWhere);
00539   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
00540   pNew->pHaving = sqlite3ExprDup(p->pHaving);
00541   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
00542   pNew->op = p->op;
00543   pNew->pPrior = sqlite3SelectDup(p->pPrior);
00544   pNew->pLimit = sqlite3ExprDup(p->pLimit);
00545   pNew->pOffset = sqlite3ExprDup(p->pOffset);
00546   pNew->iLimit = -1;
00547   pNew->iOffset = -1;
00548   pNew->isResolved = p->isResolved;
00549   pNew->isAgg = p->isAgg;
00550   pNew->usesVirt = 0;
00551   pNew->disallowOrderBy = 0;
00552   pNew->pRightmost = 0;
00553   pNew->addrOpenVirt[0] = -1;
00554   pNew->addrOpenVirt[1] = -1;
00555   pNew->addrOpenVirt[2] = -1;
00556   return pNew;
00557 }
00558 #else
00559 Select *sqlite3SelectDup(Select *p){
00560   assert( p==0 );
00561   return 0;
00562 }
00563 #endif
00564 
00565 
00566 /*
00567 ** Add a new element to the end of an expression list.  If pList is
00568 ** initially NULL, then create a new expression list.
00569 */
00570 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
00571   if( pList==0 ){
00572     pList = sqliteMalloc( sizeof(ExprList) );
00573     if( pList==0 ){
00574       goto no_mem;
00575     }
00576     assert( pList->nAlloc==0 );
00577   }
00578   if( pList->nAlloc<=pList->nExpr ){
00579     struct ExprList_item *a;
00580     int n = pList->nAlloc*2 + 4;
00581     a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
00582     if( a==0 ){
00583       goto no_mem;
00584     }
00585     pList->a = a;
00586     pList->nAlloc = n;
00587   }
00588   assert( pList->a!=0 );
00589   if( pExpr || pName ){
00590     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
00591     memset(pItem, 0, sizeof(*pItem));
00592     pItem->zName = sqlite3NameFromToken(pName);
00593     pItem->pExpr = pExpr;
00594   }
00595   return pList;
00596 
00597 no_mem:     
00598   /* Avoid leaking memory if malloc has failed. */
00599   sqlite3ExprDelete(pExpr);
00600   sqlite3ExprListDelete(pList);
00601   return 0;
00602 }
00603 
00604 /*
00605 ** Delete an entire expression list.
00606 */
00607 void sqlite3ExprListDelete(ExprList *pList){
00608   int i;
00609   struct ExprList_item *pItem;
00610   if( pList==0 ) return;
00611   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
00612   assert( pList->nExpr<=pList->nAlloc );
00613   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
00614     sqlite3ExprDelete(pItem->pExpr);
00615     sqliteFree(pItem->zName);
00616   }
00617   sqliteFree(pList->a);
00618   sqliteFree(pList);
00619 }
00620 
00621 /*
00622 ** Walk an expression tree.  Call xFunc for each node visited.
00623 **
00624 ** The return value from xFunc determines whether the tree walk continues.
00625 ** 0 means continue walking the tree.  1 means do not walk children
00626 ** of the current node but continue with siblings.  2 means abandon
00627 ** the tree walk completely.
00628 **
00629 ** The return value from this routine is 1 to abandon the tree walk
00630 ** and 0 to continue.
00631 **
00632 ** NOTICE:  This routine does *not* descend into subqueries.
00633 */
00634 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
00635 static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
00636   int rc;
00637   if( pExpr==0 ) return 0;
00638   rc = (*xFunc)(pArg, pExpr);
00639   if( rc==0 ){
00640     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
00641     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
00642     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
00643   }
00644   return rc>1;
00645 }
00646 
00647 /*
00648 ** Call walkExprTree() for every expression in list p.
00649 */
00650 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
00651   int i;
00652   struct ExprList_item *pItem;
00653   if( !p ) return 0;
00654   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
00655     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
00656   }
00657   return 0;
00658 }
00659 
00660 /*
00661 ** Call walkExprTree() for every expression in Select p, not including
00662 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
00663 ** or OFFSET expressions..
00664 */
00665 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
00666   walkExprList(p->pEList, xFunc, pArg);
00667   walkExprTree(p->pWhere, xFunc, pArg);
00668   walkExprList(p->pGroupBy, xFunc, pArg);
00669   walkExprTree(p->pHaving, xFunc, pArg);
00670   walkExprList(p->pOrderBy, xFunc, pArg);
00671   return 0;
00672 }
00673 
00674 
00675 /*
00676 ** This routine is designed as an xFunc for walkExprTree().
00677 **
00678 ** pArg is really a pointer to an integer.  If we can tell by looking
00679 ** at pExpr that the expression that contains pExpr is not a constant
00680 ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
00681 ** If pExpr does does not disqualify the expression from being a constant
00682 ** then do nothing.
00683 **
00684 ** After walking the whole tree, if no nodes are found that disqualify
00685 ** the expression as constant, then we assume the whole expression
00686 ** is constant.  See sqlite3ExprIsConstant() for additional information.
00687 */
00688 static int exprNodeIsConstant(void *pArg, Expr *pExpr){
00689   switch( pExpr->op ){
00690     /* Consider functions to be constant if all their arguments are constant
00691     ** and *pArg==2 */
00692     case TK_FUNCTION:
00693       if( *((int*)pArg)==2 ) return 0;
00694       /* Fall through */
00695     case TK_ID:
00696     case TK_COLUMN:
00697     case TK_DOT:
00698     case TK_AGG_FUNCTION:
00699     case TK_AGG_COLUMN:
00700 #ifndef SQLITE_OMIT_SUBQUERY
00701     case TK_SELECT:
00702     case TK_EXISTS:
00703 #endif
00704       *((int*)pArg) = 0;
00705       return 2;
00706     case TK_IN:
00707       if( pExpr->pSelect ){
00708         *((int*)pArg) = 0;
00709         return 2;
00710       }
00711     default:
00712       return 0;
00713   }
00714 }
00715 
00716 /*
00717 ** Walk an expression tree.  Return 1 if the expression is constant
00718 ** and 0 if it involves variables or function calls.
00719 **
00720 ** For the purposes of this function, a double-quoted string (ex: "abc")
00721 ** is considered a variable but a single-quoted string (ex: 'abc') is
00722 ** a constant.
00723 */
00724 int sqlite3ExprIsConstant(Expr *p){
00725   int isConst = 1;
00726   walkExprTree(p, exprNodeIsConstant, &isConst);
00727   return isConst;
00728 }
00729 
00730 /*
00731 ** Walk an expression tree.  Return 1 if the expression is constant
00732 ** or a function call with constant arguments.  Return and 0 if there
00733 ** are any variables.
00734 **
00735 ** For the purposes of this function, a double-quoted string (ex: "abc")
00736 ** is considered a variable but a single-quoted string (ex: 'abc') is
00737 ** a constant.
00738 */
00739 int sqlite3ExprIsConstantOrFunction(Expr *p){
00740   int isConst = 2;
00741   walkExprTree(p, exprNodeIsConstant, &isConst);
00742   return isConst!=0;
00743 }
00744 
00745 /*
00746 ** If the expression p codes a constant integer that is small enough
00747 ** to fit in a 32-bit integer, return 1 and put the value of the integer
00748 ** in *pValue.  If the expression is not an integer or if it is too big
00749 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
00750 */
00751 int sqlite3ExprIsInteger(Expr *p, int *pValue){
00752   switch( p->op ){
00753     case TK_INTEGER: {
00754       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
00755         return 1;
00756       }
00757       break;
00758     }
00759     case TK_UPLUS: {
00760       return sqlite3ExprIsInteger(p->pLeft, pValue);
00761     }
00762     case TK_UMINUS: {
00763       int v;
00764       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
00765         *pValue = -v;
00766         return 1;
00767       }
00768       break;
00769     }
00770     default: break;
00771   }
00772   return 0;
00773 }
00774 
00775 /*
00776 ** Return TRUE if the given string is a row-id column name.
00777 */
00778 int sqlite3IsRowid(const char *z){
00779   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
00780   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
00781   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
00782   return 0;
00783 }
00784 
00785 /*
00786 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
00787 ** that name in the set of source tables in pSrcList and make the pExpr 
00788 ** expression node refer back to that source column.  The following changes
00789 ** are made to pExpr:
00790 **
00791 **    pExpr->iDb           Set the index in db->aDb[] of the database holding
00792 **                         the table.
00793 **    pExpr->iTable        Set to the cursor number for the table obtained
00794 **                         from pSrcList.
00795 **    pExpr->iColumn       Set to the column number within the table.
00796 **    pExpr->op            Set to TK_COLUMN.
00797 **    pExpr->pLeft         Any expression this points to is deleted
00798 **    pExpr->pRight        Any expression this points to is deleted.
00799 **
00800 ** The pDbToken is the name of the database (the "X").  This value may be
00801 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
00802 ** can be used.  The pTableToken is the name of the table (the "Y").  This
00803 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
00804 ** means that the form of the name is Z and that columns from any table
00805 ** can be used.
00806 **
00807 ** If the name cannot be resolved unambiguously, leave an error message
00808 ** in pParse and return non-zero.  Return zero on success.
00809 */
00810 static int lookupName(
00811   Parse *pParse,       /* The parsing context */
00812   Token *pDbToken,     /* Name of the database containing table, or NULL */
00813   Token *pTableToken,  /* Name of table containing column, or NULL */
00814   Token *pColumnToken, /* Name of the column. */
00815   NameContext *pNC,    /* The name context used to resolve the name */
00816   Expr *pExpr          /* Make this EXPR node point to the selected column */
00817 ){
00818   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
00819   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
00820   char *zCol = 0;      /* Name of the column.  The "Z" */
00821   int i, j;            /* Loop counters */
00822   int cnt = 0;         /* Number of matching column names */
00823   int cntTab = 0;      /* Number of matching table names */
00824   sqlite3 *db = pParse->db;  /* The database */
00825   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
00826   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
00827   NameContext *pTopNC = pNC;        /* First namecontext in the list */
00828 
00829   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
00830   zDb = sqlite3NameFromToken(pDbToken);
00831   zTab = sqlite3NameFromToken(pTableToken);
00832   zCol = sqlite3NameFromToken(pColumnToken);
00833   if( sqlite3MallocFailed() ){
00834     goto lookupname_end;
00835   }
00836 
00837   pExpr->iTable = -1;
00838   while( pNC && cnt==0 ){
00839     ExprList *pEList;
00840     SrcList *pSrcList = pNC->pSrcList;
00841 
00842     if( pSrcList ){
00843       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
00844         Table *pTab;
00845         int iDb;
00846         Column *pCol;
00847   
00848         pTab = pItem->pTab;
00849         assert( pTab!=0 );
00850         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
00851         assert( pTab->nCol>0 );
00852         if( zTab ){
00853           if( pItem->zAlias ){
00854             char *zTabName = pItem->zAlias;
00855             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
00856           }else{
00857             char *zTabName = pTab->zName;
00858             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
00859             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
00860               continue;
00861             }
00862           }
00863         }
00864         if( 0==(cntTab++) ){
00865           pExpr->iTable = pItem->iCursor;
00866           pExpr->pSchema = pTab->pSchema;
00867           pMatch = pItem;
00868         }
00869         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
00870           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
00871             const char *zColl = pTab->aCol[j].zColl;
00872             IdList *pUsing;
00873             cnt++;
00874             pExpr->iTable = pItem->iCursor;
00875             pMatch = pItem;
00876             pExpr->pSchema = pTab->pSchema;
00877             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
00878             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
00879             pExpr->affinity = pTab->aCol[j].affinity;
00880             pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
00881             if( pItem->jointype & JT_NATURAL ){
00882               /* If this match occurred in the left table of a natural join,
00883               ** then skip the right table to avoid a duplicate match */
00884               pItem++;
00885               i++;
00886             }
00887             if( (pUsing = pItem->pUsing)!=0 ){
00888               /* If this match occurs on a column that is in the USING clause
00889               ** of a join, skip the search of the right table of the join
00890               ** to avoid a duplicate match there. */
00891               int k;
00892               for(k=0; k<pUsing->nId; k++){
00893                 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
00894                   pItem++;
00895                   i++;
00896                   break;
00897                 }
00898               }
00899             }
00900             break;
00901           }
00902         }
00903       }
00904     }
00905 
00906 #ifndef SQLITE_OMIT_TRIGGER
00907     /* If we have not already resolved the name, then maybe 
00908     ** it is a new.* or old.* trigger argument reference
00909     */
00910     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
00911       TriggerStack *pTriggerStack = pParse->trigStack;
00912       Table *pTab = 0;
00913       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
00914         pExpr->iTable = pTriggerStack->newIdx;
00915         assert( pTriggerStack->pTab );
00916         pTab = pTriggerStack->pTab;
00917       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
00918         pExpr->iTable = pTriggerStack->oldIdx;
00919         assert( pTriggerStack->pTab );
00920         pTab = pTriggerStack->pTab;
00921       }
00922 
00923       if( pTab ){ 
00924         int iCol;
00925         Column *pCol = pTab->aCol;
00926 
00927         pExpr->pSchema = pTab->pSchema;
00928         cntTab++;
00929         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
00930           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
00931             const char *zColl = pTab->aCol[iCol].zColl;
00932             cnt++;
00933             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
00934             pExpr->affinity = pTab->aCol[iCol].affinity;
00935             pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
00936             pExpr->pTab = pTab;
00937             break;
00938           }
00939         }
00940       }
00941     }
00942 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
00943 
00944     /*
00945     ** Perhaps the name is a reference to the ROWID
00946     */
00947     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
00948       cnt = 1;
00949       pExpr->iColumn = -1;
00950       pExpr->affinity = SQLITE_AFF_INTEGER;
00951     }
00952 
00953     /*
00954     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
00955     ** might refer to an result-set alias.  This happens, for example, when
00956     ** we are resolving names in the WHERE clause of the following command:
00957     **
00958     **     SELECT a+b AS x FROM table WHERE x<10;
00959     **
00960     ** In cases like this, replace pExpr with a copy of the expression that
00961     ** forms the result set entry ("a+b" in the example) and return immediately.
00962     ** Note that the expression in the result set should have already been
00963     ** resolved by the time the WHERE clause is resolved.
00964     */
00965     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
00966       for(j=0; j<pEList->nExpr; j++){
00967         char *zAs = pEList->a[j].zName;
00968         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
00969           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
00970           pExpr->op = TK_AS;
00971           pExpr->iColumn = j;
00972           pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
00973           cnt = 1;
00974           assert( zTab==0 && zDb==0 );
00975           goto lookupname_end_2;
00976         }
00977       } 
00978     }
00979 
00980     /* Advance to the next name context.  The loop will exit when either
00981     ** we have a match (cnt>0) or when we run out of name contexts.
00982     */
00983     if( cnt==0 ){
00984       pNC = pNC->pNext;
00985     }
00986   }
00987 
00988   /*
00989   ** If X and Y are NULL (in other words if only the column name Z is
00990   ** supplied) and the value of Z is enclosed in double-quotes, then
00991   ** Z is a string literal if it doesn't match any column names.  In that
00992   ** case, we need to return right away and not make any changes to
00993   ** pExpr.
00994   **
00995   ** Because no reference was made to outer contexts, the pNC->nRef
00996   ** fields are not changed in any context.
00997   */
00998   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
00999     sqliteFree(zCol);
01000     return 0;
01001   }
01002 
01003   /*
01004   ** cnt==0 means there was not match.  cnt>1 means there were two or
01005   ** more matches.  Either way, we have an error.
01006   */
01007   if( cnt!=1 ){
01008     char *z = 0;
01009     char *zErr;
01010     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
01011     if( zDb ){
01012       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
01013     }else if( zTab ){
01014       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
01015     }else{
01016       z = sqliteStrDup(zCol);
01017     }
01018     sqlite3ErrorMsg(pParse, zErr, z);
01019     sqliteFree(z);
01020     pTopNC->nErr++;
01021   }
01022 
01023   /* If a column from a table in pSrcList is referenced, then record
01024   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
01025   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
01026   ** column number is greater than the number of bits in the bitmask
01027   ** then set the high-order bit of the bitmask.
01028   */
01029   if( pExpr->iColumn>=0 && pMatch!=0 ){
01030     int n = pExpr->iColumn;
01031     if( n>=sizeof(Bitmask)*8 ){
01032       n = sizeof(Bitmask)*8-1;
01033     }
01034     assert( pMatch->iCursor==pExpr->iTable );
01035     pMatch->colUsed |= 1<<n;
01036   }
01037 
01038 lookupname_end:
01039   /* Clean up and return
01040   */
01041   sqliteFree(zDb);
01042   sqliteFree(zTab);
01043   sqlite3ExprDelete(pExpr->pLeft);
01044   pExpr->pLeft = 0;
01045   sqlite3ExprDelete(pExpr->pRight);
01046   pExpr->pRight = 0;
01047   pExpr->op = TK_COLUMN;
01048 lookupname_end_2:
01049   sqliteFree(zCol);
01050   if( cnt==1 ){
01051     assert( pNC!=0 );
01052     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
01053     if( pMatch && !pMatch->pSelect ){
01054       pExpr->pTab = pMatch->pTab;
01055     }
01056     /* Increment the nRef value on all name contexts from TopNC up to
01057     ** the point where the name matched. */
01058     for(;;){
01059       assert( pTopNC!=0 );
01060       pTopNC->nRef++;
01061       if( pTopNC==pNC ) break;
01062       pTopNC = pTopNC->pNext;
01063     }
01064     return 0;
01065   } else {
01066     return 1;
01067   }
01068 }
01069 
01070 /*
01071 ** This routine is designed as an xFunc for walkExprTree().
01072 **
01073 ** Resolve symbolic names into TK_COLUMN operators for the current
01074 ** node in the expression tree.  Return 0 to continue the search down
01075 ** the tree or 2 to abort the tree walk.
01076 **
01077 ** This routine also does error checking and name resolution for
01078 ** function names.  The operator for aggregate functions is changed
01079 ** to TK_AGG_FUNCTION.
01080 */
01081 static int nameResolverStep(void *pArg, Expr *pExpr){
01082   NameContext *pNC = (NameContext*)pArg;
01083   Parse *pParse;
01084 
01085   if( pExpr==0 ) return 1;
01086   assert( pNC!=0 );
01087   pParse = pNC->pParse;
01088 
01089   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
01090   ExprSetProperty(pExpr, EP_Resolved);
01091 #ifndef NDEBUG
01092   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
01093     SrcList *pSrcList = pNC->pSrcList;
01094     int i;
01095     for(i=0; i<pNC->pSrcList->nSrc; i++){
01096       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
01097     }
01098   }
01099 #endif
01100   switch( pExpr->op ){
01101     /* Double-quoted strings (ex: "abc") are used as identifiers if
01102     ** possible.  Otherwise they remain as strings.  Single-quoted
01103     ** strings (ex: 'abc') are always string literals.
01104     */
01105     case TK_STRING: {
01106       if( pExpr->token.z[0]=='\'' ) break;
01107       /* Fall thru into the TK_ID case if this is a double-quoted string */
01108     }
01109     /* A lone identifier is the name of a column.
01110     */
01111     case TK_ID: {
01112       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
01113       return 1;
01114     }
01115   
01116     /* A table name and column name:     ID.ID
01117     ** Or a database, table and column:  ID.ID.ID
01118     */
01119     case TK_DOT: {
01120       Token *pColumn;
01121       Token *pTable;
01122       Token *pDb;
01123       Expr *pRight;
01124 
01125       /* if( pSrcList==0 ) break; */
01126       pRight = pExpr->pRight;
01127       if( pRight->op==TK_ID ){
01128         pDb = 0;
01129         pTable = &pExpr->pLeft->token;
01130         pColumn = &pRight->token;
01131       }else{
01132         assert( pRight->op==TK_DOT );
01133         pDb = &pExpr->pLeft->token;
01134         pTable = &pRight->pLeft->token;
01135         pColumn = &pRight->pRight->token;
01136       }
01137       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
01138       return 1;
01139     }
01140 
01141     /* Resolve function names
01142     */
01143     case TK_CONST_FUNC:
01144     case TK_FUNCTION: {
01145       ExprList *pList = pExpr->pList;    /* The argument list */
01146       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
01147       int no_such_func = 0;       /* True if no such function exists */
01148       int wrong_num_args = 0;     /* True if wrong number of arguments */
01149       int is_agg = 0;             /* True if is an aggregate function */
01150       int i;
01151       int nId;                    /* Number of characters in function name */
01152       const char *zId;            /* The function name. */
01153       FuncDef *pDef;              /* Information about the function */
01154       int enc = ENC(pParse->db);  /* The database encoding */
01155 
01156       zId = (char*)pExpr->token.z;
01157       nId = pExpr->token.n;
01158       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
01159       if( pDef==0 ){
01160         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
01161         if( pDef==0 ){
01162           no_such_func = 1;
01163         }else{
01164           wrong_num_args = 1;
01165         }
01166       }else{
01167         is_agg = pDef->xFunc==0;
01168       }
01169       if( is_agg && !pNC->allowAgg ){
01170         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
01171         pNC->nErr++;
01172         is_agg = 0;
01173       }else if( no_such_func ){
01174         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
01175         pNC->nErr++;
01176       }else if( wrong_num_args ){
01177         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
01178              nId, zId);
01179         pNC->nErr++;
01180       }
01181       if( is_agg ){
01182         pExpr->op = TK_AGG_FUNCTION;
01183         pNC->hasAgg = 1;
01184       }
01185       if( is_agg ) pNC->allowAgg = 0;
01186       for(i=0; pNC->nErr==0 && i<n; i++){
01187         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
01188       }
01189       if( is_agg ) pNC->allowAgg = 1;
01190       /* FIX ME:  Compute pExpr->affinity based on the expected return
01191       ** type of the function 
01192       */
01193       return is_agg;
01194     }
01195 #ifndef SQLITE_OMIT_SUBQUERY
01196     case TK_SELECT:
01197     case TK_EXISTS:
01198 #endif
01199     case TK_IN: {
01200       if( pExpr->pSelect ){
01201         int nRef = pNC->nRef;
01202 #ifndef SQLITE_OMIT_CHECK
01203         if( pNC->isCheck ){
01204           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
01205         }
01206 #endif
01207         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
01208         assert( pNC->nRef>=nRef );
01209         if( nRef!=pNC->nRef ){
01210           ExprSetProperty(pExpr, EP_VarSelect);
01211         }
01212       }
01213       break;
01214     }
01215 #ifndef SQLITE_OMIT_CHECK
01216     case TK_VARIABLE: {
01217       if( pNC->isCheck ){
01218         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
01219       }
01220       break;
01221     }
01222 #endif
01223   }
01224   return 0;
01225 }
01226 
01227 /*
01228 ** This routine walks an expression tree and resolves references to
01229 ** table columns.  Nodes of the form ID.ID or ID resolve into an
01230 ** index to the table in the table list and a column offset.  The 
01231 ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
01232 ** value is changed to the index of the referenced table in pTabList
01233 ** plus the "base" value.  The base value will ultimately become the
01234 ** VDBE cursor number for a cursor that is pointing into the referenced
01235 ** table.  The Expr.iColumn value is changed to the index of the column 
01236 ** of the referenced table.  The Expr.iColumn value for the special
01237 ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
01238 ** alias for ROWID.
01239 **
01240 ** Also resolve function names and check the functions for proper
01241 ** usage.  Make sure all function names are recognized and all functions
01242 ** have the correct number of arguments.  Leave an error message
01243 ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
01244 **
01245 ** If the expression contains aggregate functions then set the EP_Agg
01246 ** property on the expression.
01247 */
01248 int sqlite3ExprResolveNames(
01249   NameContext *pNC,       /* Namespace to resolve expressions in. */
01250   Expr *pExpr             /* The expression to be analyzed. */
01251 ){
01252   int savedHasAgg;
01253   if( pExpr==0 ) return 0;
01254   savedHasAgg = pNC->hasAgg;
01255   pNC->hasAgg = 0;
01256   walkExprTree(pExpr, nameResolverStep, pNC);
01257   if( pNC->nErr>0 ){
01258     ExprSetProperty(pExpr, EP_Error);
01259   }
01260   if( pNC->hasAgg ){
01261     ExprSetProperty(pExpr, EP_Agg);
01262   }else if( savedHasAgg ){
01263     pNC->hasAgg = 1;
01264   }
01265   return ExprHasProperty(pExpr, EP_Error);
01266 }
01267 
01268 /*
01269 ** A pointer instance of this structure is used to pass information
01270 ** through walkExprTree into codeSubqueryStep().
01271 */
01272 typedef struct QueryCoder QueryCoder;
01273 struct QueryCoder {
01274   Parse *pParse;       /* The parsing context */
01275   NameContext *pNC;    /* Namespace of first enclosing query */
01276 };
01277 
01278 
01279 /*
01280 ** Generate code for scalar subqueries used as an expression
01281 ** and IN operators.  Examples:
01282 **
01283 **     (SELECT a FROM b)          -- subquery
01284 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
01285 **     x IN (4,5,11)              -- IN operator with list on right-hand side
01286 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
01287 **
01288 ** The pExpr parameter describes the expression that contains the IN
01289 ** operator or subquery.
01290 */
01291 #ifndef SQLITE_OMIT_SUBQUERY
01292 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
01293   int testAddr = 0;                       /* One-time test address */
01294   Vdbe *v = sqlite3GetVdbe(pParse);
01295   if( v==0 ) return;
01296 
01297   /* This code must be run in its entirety every time it is encountered
01298   ** if any of the following is true:
01299   **
01300   **    *  The right-hand side is a correlated subquery
01301   **    *  The right-hand side is an expression list containing variables
01302   **    *  We are inside a trigger
01303   **
01304   ** If all of the above are false, then we can run this code just once
01305   ** save the results, and reuse the same result on subsequent invocations.
01306   */
01307   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
01308     int mem = pParse->nMem++;
01309     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
01310     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
01311     assert( testAddr>0 || sqlite3MallocFailed() );
01312     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
01313   }
01314 
01315   switch( pExpr->op ){
01316     case TK_IN: {
01317       char affinity;
01318       KeyInfo keyInfo;
01319       int addr;        /* Address of OP_OpenVirtual instruction */
01320 
01321       affinity = sqlite3ExprAffinity(pExpr->pLeft);
01322 
01323       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
01324       ** expression it is handled the same way. A virtual table is 
01325       ** filled with single-field index keys representing the results
01326       ** from the SELECT or the <exprlist>.
01327       **
01328       ** If the 'x' expression is a column value, or the SELECT...
01329       ** statement returns a column value, then the affinity of that
01330       ** column is used to build the index keys. If both 'x' and the
01331       ** SELECT... statement are columns, then numeric affinity is used
01332       ** if either column has NUMERIC or INTEGER affinity. If neither
01333       ** 'x' nor the SELECT... statement are columns, then numeric affinity
01334       ** is used.
01335       */
01336       pExpr->iTable = pParse->nTab++;
01337       addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, pExpr->iTable, 0);
01338       memset(&keyInfo, 0, sizeof(keyInfo));
01339       keyInfo.nField = 1;
01340       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
01341 
01342       if( pExpr->pSelect ){
01343         /* Case 1:     expr IN (SELECT ...)
01344         **
01345         ** Generate code to write the results of the select into the temporary
01346         ** table allocated and opened above.
01347         */
01348         int iParm = pExpr->iTable +  (((int)affinity)<<16);
01349         ExprList *pEList;
01350         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
01351         sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
01352         pEList = pExpr->pSelect->pEList;
01353         if( pEList && pEList->nExpr>0 ){ 
01354           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
01355               pEList->a[0].pExpr);
01356         }
01357       }else if( pExpr->pList ){
01358         /* Case 2:     expr IN (exprlist)
01359         **
01360        ** For each expression, build an index key from the evaluation and
01361         ** store it in the temporary table. If <expr> is a column, then use
01362         ** that columns affinity when building index keys. If <expr> is not
01363         ** a column, use numeric affinity.
01364         */
01365         int i;
01366         ExprList *pList = pExpr->pList;
01367         struct ExprList_item *pItem;
01368 
01369         if( !affinity ){
01370           affinity = SQLITE_AFF_NUMERIC;
01371         }
01372         keyInfo.aColl[0] = pExpr->pLeft->pColl;
01373 
01374         /* Loop through each expression in <exprlist>. */
01375         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
01376           Expr *pE2 = pItem->pExpr;
01377 
01378           /* If the expression is not constant then we will need to
01379           ** disable the test that was generated above that makes sure
01380           ** this code only executes once.  Because for a non-constant
01381           ** expression we need to rerun this code each time.
01382           */
01383           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
01384             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
01385             testAddr = 0;
01386           }
01387 
01388           /* Evaluate the expression and insert it into the temp table */
01389           sqlite3ExprCode(pParse, pE2);
01390           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
01391           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
01392         }
01393       }
01394       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
01395       break;
01396     }
01397 
01398     case TK_EXISTS:
01399     case TK_SELECT: {
01400       /* This has to be a scalar SELECT.  Generate code to put the
01401       ** value of this select in a memory cell and record the number
01402       ** of the memory cell in iColumn.
01403       */
01404       static const Token one = { (u8*)"1", 0, 1 };
01405       Select *pSel;
01406       int iMem;
01407       int sop;
01408 
01409       pExpr->iColumn = iMem = pParse->nMem++;
01410       pSel = pExpr->pSelect;
01411       if( pExpr->op==TK_SELECT ){
01412         sop = SRT_Mem;
01413         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
01414         VdbeComment((v, "# Init subquery result"));
01415       }else{
01416         sop = SRT_Exists;
01417         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
01418         VdbeComment((v, "# Init EXISTS result"));
01419       }
01420       sqlite3ExprDelete(pSel->pLimit);
01421       pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
01422       sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0);
01423       break;
01424     }
01425   }
01426 
01427   if( testAddr ){
01428     sqlite3VdbeJumpHere(v, testAddr);
01429   }
01430   return;
01431 }
01432 #endif /* SQLITE_OMIT_SUBQUERY */
01433 
01434 /*
01435 ** Generate an instruction that will put the integer describe by
01436 ** text z[0..n-1] on the stack.
01437 */
01438 static void codeInteger(Vdbe *v, const char *z, int n){
01439   int i;
01440   if( sqlite3GetInt32(z, &i) ){
01441     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
01442   }else if( sqlite3FitsIn64Bits(z) ){
01443     sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
01444   }else{
01445     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
01446   }
01447 }
01448 
01449 /*
01450 ** Generate code into the current Vdbe to evaluate the given
01451 ** expression and leave the result on the top of stack.
01452 **
01453 ** This code depends on the fact that certain token values (ex: TK_EQ)
01454 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
01455 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
01456 ** the make process cause these values to align.  Assert()s in the code
01457 ** below verify that the numbers are aligned correctly.
01458 */
01459 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
01460   Vdbe *v = pParse->pVdbe;
01461   int op;
01462   int stackChng = 1;    /* Amount of change to stack depth */
01463 
01464   if( v==0 ) return;
01465   if( pExpr==0 ){
01466     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
01467     return;
01468   }
01469   op = pExpr->op;
01470   switch( op ){
01471     case TK_AGG_COLUMN: {
01472       AggInfo *pAggInfo = pExpr->pAggInfo;
01473       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
01474       if( !pAggInfo->directMode ){
01475         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
01476         break;
01477       }else if( pAggInfo->useSortingIdx ){
01478         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
01479                               pCol->iSorterColumn);
01480         break;
01481       }
01482       /* Otherwise, fall thru into the TK_COLUMN case */
01483     }
01484     case TK_COLUMN: {
01485       if( pExpr->iTable<0 ){
01486         /* This only happens when coding check constraints */
01487         assert( pParse->ckOffset>0 );
01488         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
01489       }else if( pExpr->iColumn>=0 ){
01490         Table *pTab = pExpr->pTab;
01491         int iCol = pExpr->iColumn;
01492         sqlite3VdbeAddOp(v, OP_Column, pExpr->iTable, iCol);
01493         sqlite3ColumnDefault(v, pTab, iCol);
01494 #ifndef SQLITE_OMIT_FLOATING_POINT
01495         if( pTab && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
01496           sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
01497         }
01498 #endif
01499       }else{
01500         sqlite3VdbeAddOp(v, OP_Rowid, pExpr->iTable, 0);
01501       }
01502       break;
01503     }
01504     case TK_INTEGER: {
01505       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
01506       break;
01507     }
01508     case TK_FLOAT:
01509     case TK_STRING: {
01510       assert( TK_FLOAT==OP_Real );
01511       assert( TK_STRING==OP_String8 );
01512       sqlite3DequoteExpr(pExpr);
01513       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
01514       break;
01515     }
01516     case TK_NULL: {
01517       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
01518       break;
01519     }
01520 #ifndef SQLITE_OMIT_BLOB_LITERAL
01521     case TK_BLOB: {
01522       int n;
01523       const char *z;
01524       assert( TK_BLOB==OP_HexBlob );
01525       n = pExpr->token.n - 3;
01526       z = (char*)pExpr->token.z + 2;
01527       assert( n>=0 );
01528       if( n==0 ){
01529         z = "";
01530       }
01531       sqlite3VdbeOp3(v, op, 0, 0, z, n);
01532       break;
01533     }
01534 #endif
01535     case TK_VARIABLE: {
01536       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
01537       if( pExpr->token.n>1 ){
01538         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
01539       }
01540       break;
01541     }
01542     case TK_REGISTER: {
01543       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
01544       break;
01545     }
01546 #ifndef SQLITE_OMIT_CAST
01547     case TK_CAST: {
01548       /* Expressions of the form:   CAST(pLeft AS token) */
01549       int aff, to_op;
01550       sqlite3ExprCode(pParse, pExpr->pLeft);
01551       aff = sqlite3AffinityType(&pExpr->token);
01552       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
01553       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
01554       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
01555       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
01556       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
01557       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
01558       sqlite3VdbeAddOp(v, to_op, 0, 0);
01559       stackChng = 0;
01560       break;
01561     }
01562 #endif /* SQLITE_OMIT_CAST */
01563     case TK_LT:
01564     case TK_LE:
01565     case TK_GT:
01566     case TK_GE:
01567     case TK_NE:
01568     case TK_EQ: {
01569       assert( TK_LT==OP_Lt );
01570       assert( TK_LE==OP_Le );
01571       assert( TK_GT==OP_Gt );
01572       assert( TK_GE==OP_Ge );
01573       assert( TK_EQ==OP_Eq );
01574       assert( TK_NE==OP_Ne );
01575       sqlite3ExprCode(pParse, pExpr->pLeft);
01576       sqlite3ExprCode(pParse, pExpr->pRight);
01577       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
01578       stackChng = -1;
01579       break;
01580     }
01581     case TK_AND:
01582     case TK_OR:
01583     case TK_PLUS:
01584     case TK_STAR:
01585     case TK_MINUS:
01586     case TK_REM:
01587     case TK_BITAND:
01588     case TK_BITOR:
01589     case TK_SLASH:
01590     case TK_LSHIFT:
01591     case TK_RSHIFT: 
01592     case TK_CONCAT: {
01593       assert( TK_AND==OP_And );
01594       assert( TK_OR==OP_Or );
01595       assert( TK_PLUS==OP_Add );
01596       assert( TK_MINUS==OP_Subtract );
01597       assert( TK_REM==OP_Remainder );
01598       assert( TK_BITAND==OP_BitAnd );
01599       assert( TK_BITOR==OP_BitOr );
01600       assert( TK_SLASH==OP_Divide );
01601       assert( TK_LSHIFT==OP_ShiftLeft );
01602       assert( TK_RSHIFT==OP_ShiftRight );
01603       assert( TK_CONCAT==OP_Concat );
01604       sqlite3ExprCode(pParse, pExpr->pLeft);
01605       sqlite3ExprCode(pParse, pExpr->pRight);
01606       sqlite3VdbeAddOp(v, op, 0, 0);
01607       stackChng = -1;
01608       break;
01609     }
01610     case TK_UMINUS: {
01611       Expr *pLeft = pExpr->pLeft;
01612       assert( pLeft );
01613       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
01614         Token *p = &pLeft->token;
01615         char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
01616         if( pLeft->op==TK_FLOAT ){
01617           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
01618         }else{
01619           codeInteger(v, z, p->n+1);
01620         }
01621         sqliteFree(z);
01622         break;
01623       }
01624       /* Fall through into TK_NOT */
01625     }
01626     case TK_BITNOT:
01627     case TK_NOT: {
01628       assert( TK_BITNOT==OP_BitNot );
01629       assert( TK_NOT==OP_Not );
01630       sqlite3ExprCode(pParse, pExpr->pLeft);
01631       sqlite3VdbeAddOp(v, op, 0, 0);
01632       stackChng = 0;
01633       break;
01634     }
01635     case TK_ISNULL:
01636     case TK_NOTNULL: {
01637       int dest;
01638       assert( TK_ISNULL==OP_IsNull );
01639       assert( TK_NOTNULL==OP_NotNull );
01640       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
01641       sqlite3ExprCode(pParse, pExpr->pLeft);
01642       dest = sqlite3VdbeCurrentAddr(v) + 2;
01643       sqlite3VdbeAddOp(v, op, 1, dest);
01644       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
01645       stackChng = 0;
01646       break;
01647     }
01648     case TK_AGG_FUNCTION: {
01649       AggInfo *pInfo = pExpr->pAggInfo;
01650       if( pInfo==0 ){
01651         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
01652             &pExpr->span);
01653       }else{
01654         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
01655       }
01656       break;
01657     }
01658     case TK_CONST_FUNC:
01659     case TK_FUNCTION: {
01660       ExprList *pList = pExpr->pList;
01661       int nExpr = pList ? pList->nExpr : 0;
01662       FuncDef *pDef;
01663       int nId;
01664       const char *zId;
01665       int constMask = 0;
01666       int i;
01667       u8 enc = ENC(pParse->db);
01668       CollSeq *pColl = 0;
01669       zId = (char*)pExpr->token.z;
01670       nId = pExpr->token.n;
01671       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
01672       assert( pDef!=0 );
01673       nExpr = sqlite3ExprCodeExprList(pParse, pList);
01674       for(i=0; i<nExpr && i<32; i++){
01675         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
01676           constMask |= (1<<i);
01677         }
01678         if( pDef->needCollSeq && !pColl ){
01679           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
01680         }
01681       }
01682       if( pDef->needCollSeq ){
01683         if( !pColl ) pColl = pParse->db->pDfltColl; 
01684         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
01685       }
01686       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
01687       stackChng = 1-nExpr;
01688       break;
01689     }
01690 #ifndef SQLITE_OMIT_SUBQUERY
01691     case TK_EXISTS:
01692     case TK_SELECT: {
01693       if( pExpr->iColumn==0 ){
01694         sqlite3CodeSubselect(pParse, pExpr);
01695       }
01696       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
01697       VdbeComment((v, "# load subquery result"));
01698       break;
01699     }
01700     case TK_IN: {
01701       int addr;
01702       char affinity;
01703       int ckOffset = pParse->ckOffset;
01704       sqlite3CodeSubselect(pParse, pExpr);
01705 
01706       /* Figure out the affinity to use to create a key from the results
01707       ** of the expression. affinityStr stores a static string suitable for
01708       ** P3 of OP_MakeRecord.
01709       */
01710       affinity = comparisonAffinity(pExpr);
01711 
01712       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
01713       pParse->ckOffset = ckOffset+1;
01714 
01715       /* Code the <expr> from "<expr> IN (...)". The temporary table
01716       ** pExpr->iTable contains the values that make up the (...) set.
01717       */
01718       sqlite3ExprCode(pParse, pExpr->pLeft);
01719       addr = sqlite3VdbeCurrentAddr(v);
01720       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
01721       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
01722       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
01723       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
01724       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
01725       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
01726       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
01727 
01728       break;
01729     }
01730 #endif
01731     case TK_BETWEEN: {
01732       Expr *pLeft = pExpr->pLeft;
01733       struct ExprList_item *pLItem = pExpr->pList->a;
01734       Expr *pRight = pLItem->pExpr;
01735       sqlite3ExprCode(pParse, pLeft);
01736       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
01737       sqlite3ExprCode(pParse, pRight);
01738       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
01739       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
01740       pLItem++;
01741       pRight = pLItem->pExpr;
01742       sqlite3ExprCode(pParse, pRight);
01743       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
01744       sqlite3VdbeAddOp(v, OP_And, 0, 0);
01745       break;
01746     }
01747     case TK_UPLUS:
01748     case TK_AS: {
01749       sqlite3ExprCode(pParse, pExpr->pLeft);
01750       stackChng = 0;
01751       break;
01752     }
01753     case TK_CASE: {
01754       int expr_end_label;
01755       int jumpInst;
01756       int nExpr;
01757       int i;
01758       ExprList *pEList;
01759       struct ExprList_item *aListelem;
01760 
01761       assert(pExpr->pList);
01762       assert((pExpr->pList->nExpr % 2) == 0);
01763       assert(pExpr->pList->nExpr > 0);
01764       pEList = pExpr->pList;
01765       aListelem = pEList->a;
01766       nExpr = pEList->nExpr;
01767       expr_end_label = sqlite3VdbeMakeLabel(v);
01768       if( pExpr->pLeft ){
01769         sqlite3ExprCode(pParse, pExpr->pLeft);
01770       }
01771       for(i=0; i<nExpr; i=i+2){
01772         sqlite3ExprCode(pParse, aListelem[i].pExpr);
01773         if( pExpr->pLeft ){
01774           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
01775           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
01776                                  OP_Ne, 0, 1);
01777           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
01778         }else{
01779           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
01780         }
01781         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
01782         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
01783         sqlite3VdbeJumpHere(v, jumpInst);
01784       }
01785       if( pExpr->pLeft ){
01786         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
01787       }
01788       if( pExpr->pRight ){
01789         sqlite3ExprCode(pParse, pExpr->pRight);
01790       }else{
01791         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
01792       }
01793       sqlite3VdbeResolveLabel(v, expr_end_label);
01794       break;
01795     }
01796 #ifndef SQLITE_OMIT_TRIGGER
01797     case TK_RAISE: {
01798       if( !pParse->trigStack ){
01799         sqlite3ErrorMsg(pParse,
01800                        "RAISE() may only be used within a trigger-program");
01801        return;
01802       }
01803       if( pExpr->iColumn!=OE_Ignore ){
01804          assert( pExpr->iColumn==OE_Rollback ||
01805                  pExpr->iColumn == OE_Abort ||
01806                  pExpr->iColumn == OE_Fail );
01807          sqlite3DequoteExpr(pExpr);
01808          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
01809                         (char*)pExpr->token.z, pExpr->token.n);
01810       } else {
01811          assert( pExpr->iColumn == OE_Ignore );
01812          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
01813          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
01814          VdbeComment((v, "# raise(IGNORE)"));
01815       }
01816       stackChng = 0;
01817       break;
01818     }
01819 #endif
01820   }
01821 
01822   if( pParse->ckOffset ){
01823     pParse->ckOffset += stackChng;
01824     assert( pParse->ckOffset );
01825   }
01826 }
01827 
01828 #ifndef SQLITE_OMIT_TRIGGER
01829 /*
01830 ** Generate code that evalutes the given expression and leaves the result
01831 ** on the stack.  See also sqlite3ExprCode().
01832 **
01833 ** This routine might also cache the result and modify the pExpr tree
01834 ** so that it will make use of the cached result on subsequent evaluations
01835 ** rather than evaluate the whole expression again.  Trivial expressions are
01836 ** not cached.  If the expression is cached, its result is stored in a 
01837 ** memory location.
01838 */
01839 void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
01840   Vdbe *v = pParse->pVdbe;
01841   int iMem;
01842   int addr1, addr2;
01843   if( v==0 ) return;
01844   addr1 = sqlite3VdbeCurrentAddr(v);
01845   sqlite3ExprCode(pParse, pExpr);
01846   addr2 = sqlite3VdbeCurrentAddr(v);
01847   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
01848     iMem = pExpr->iTable = pParse->nMem++;
01849     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
01850     pExpr->op = TK_REGISTER;
01851   }
01852 }
01853 #endif
01854 
01855 /*
01856 ** Generate code that pushes the value of every element of the given
01857 ** expression list onto the stack.
01858 **
01859 ** Return the number of elements pushed onto the stack.
01860 */
01861 int sqlite3ExprCodeExprList(
01862   Parse *pParse,     /* Parsing context */
01863   ExprList *pList    /* The expression list to be coded */
01864 ){
01865   struct ExprList_item *pItem;
01866   int i, n;
01867   if( pList==0 ) return 0;
01868   n = pList->nExpr;
01869   for(pItem=pList->a, i=n; i>0; i--, pItem++){
01870     sqlite3ExprCode(pParse, pItem->pExpr);
01871   }
01872   return n;
01873 }
01874 
01875 /*
01876 ** Generate code for a boolean expression such that a jump is made
01877 ** to the label "dest" if the expression is true but execution
01878 ** continues straight thru if the expression is false.
01879 **
01880 ** If the expression evaluates to NULL (neither true nor false), then
01881 ** take the jump if the jumpIfNull flag is true.
01882 **
01883 ** This code depends on the fact that certain token values (ex: TK_EQ)
01884 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
01885 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
01886 ** the make process cause these values to align.  Assert()s in the code
01887 ** below verify that the numbers are aligned correctly.
01888 */
01889 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
01890   Vdbe *v = pParse->pVdbe;
01891   int op = 0;
01892   int ckOffset = pParse->ckOffset;
01893   if( v==0 || pExpr==0 ) return;
01894   op = pExpr->op;
01895   switch( op ){
01896     case TK_AND: {
01897       int d2 = sqlite3VdbeMakeLabel(v);
01898       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
01899       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
01900       sqlite3VdbeResolveLabel(v, d2);
01901       break;
01902     }
01903     case TK_OR: {
01904       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
01905       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
01906       break;
01907     }
01908     case TK_NOT: {
01909       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
01910       break;
01911     }
01912     case TK_LT:
01913     case TK_LE:
01914     case TK_GT:
01915     case TK_GE:
01916     case TK_NE:
01917     case TK_EQ: {
01918       assert( TK_LT==OP_Lt );
01919       assert( TK_LE==OP_Le );
01920       assert( TK_GT==OP_Gt );
01921       assert( TK_GE==OP_Ge );
01922       assert( TK_EQ==OP_Eq );
01923       assert( TK_NE==OP_Ne );
01924       sqlite3ExprCode(pParse, pExpr->pLeft);
01925       sqlite3ExprCode(pParse, pExpr->pRight);
01926       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
01927       break;
01928     }
01929     case TK_ISNULL:
01930     case TK_NOTNULL: {
01931       assert( TK_ISNULL==OP_IsNull );
01932       assert( TK_NOTNULL==OP_NotNull );
01933       sqlite3ExprCode(pParse, pExpr->pLeft);
01934       sqlite3VdbeAddOp(v, op, 1, dest);
01935       break;
01936     }
01937     case TK_BETWEEN: {
01938       /* The expression "x BETWEEN y AND z" is implemented as:
01939       **
01940       ** 1 IF (x < y) GOTO 3
01941       ** 2 IF (x <= z) GOTO <dest>
01942       ** 3 ...
01943       */
01944       int addr;
01945       Expr *pLeft = pExpr->pLeft;
01946       Expr *pRight = pExpr->pList->a[0].pExpr;
01947       sqlite3ExprCode(pParse, pLeft);
01948       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
01949       sqlite3ExprCode(pParse, pRight);
01950       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
01951 
01952       pRight = pExpr->pList->a[1].pExpr;
01953       sqlite3ExprCode(pParse, pRight);
01954       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
01955 
01956       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
01957       sqlite3VdbeJumpHere(v, addr);
01958       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
01959       break;
01960     }
01961     default: {
01962       sqlite3ExprCode(pParse, pExpr);
01963       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
01964       break;
01965     }
01966   }
01967   pParse->ckOffset = ckOffset;
01968 }
01969 
01970 /*
01971 ** Generate code for a boolean expression such that a jump is made
01972 ** to the label "dest" if the expression is false but execution
01973 ** continues straight thru if the expression is true.
01974 **
01975 ** If the expression evaluates to NULL (neither true nor false) then
01976 ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
01977 */
01978 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
01979   Vdbe *v = pParse->pVdbe;
01980   int op = 0;
01981   int ckOffset = pParse->ckOffset;
01982   if( v==0 || pExpr==0 ) return;
01983 
01984   /* The value of pExpr->op and op are related as follows:
01985   **
01986   **       pExpr->op            op
01987   **       ---------          ----------
01988   **       TK_ISNULL          OP_NotNull
01989   **       TK_NOTNULL         OP_IsNull
01990   **       TK_NE              OP_Eq
01991   **       TK_EQ              OP_Ne
01992   **       TK_GT              OP_Le
01993   **       TK_LE              OP_Gt
01994   **       TK_GE              OP_Lt
01995   **       TK_LT              OP_Ge
01996   **
01997   ** For other values of pExpr->op, op is undefined and unused.
01998   ** The value of TK_ and OP_ constants are arranged such that we
01999   ** can compute the mapping above using the following expression.
02000   ** Assert()s verify that the computation is correct.
02001   */
02002   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
02003 
02004   /* Verify correct alignment of TK_ and OP_ constants
02005   */
02006   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
02007   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
02008   assert( pExpr->op!=TK_NE || op==OP_Eq );
02009   assert( pExpr->op!=TK_EQ || op==OP_Ne );
02010   assert( pExpr->op!=TK_LT || op==OP_Ge );
02011   assert( pExpr->op!=TK_LE || op==OP_Gt );
02012   assert( pExpr->op!=TK_GT || op==OP_Le );
02013   assert( pExpr->op!=TK_GE || op==OP_Lt );
02014 
02015   switch( pExpr->op ){
02016     case TK_AND: {
02017       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
02018       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
02019       break;
02020     }
02021     case TK_OR: {
02022       int d2 = sqlite3VdbeMakeLabel(v);
02023       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
02024       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
02025       sqlite3VdbeResolveLabel(v, d2);
02026       break;
02027     }
02028     case TK_NOT: {
02029       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
02030       break;
02031     }
02032     case TK_LT:
02033     case TK_LE:
02034     case TK_GT:
02035     case TK_GE:
02036     case TK_NE:
02037     case TK_EQ: {
02038       sqlite3ExprCode(pParse, pExpr->pLeft);
02039       sqlite3ExprCode(pParse, pExpr->pRight);
02040       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
02041       break;
02042     }
02043     case TK_ISNULL:
02044     case TK_NOTNULL: {
02045       sqlite3ExprCode(pParse, pExpr->pLeft);
02046       sqlite3VdbeAddOp(v, op, 1, dest);
02047       break;
02048     }
02049     case TK_BETWEEN: {
02050       /* The expression is "x BETWEEN y AND z". It is implemented as:
02051       **
02052       ** 1 IF (x >= y) GOTO 3
02053       ** 2 GOTO <dest>
02054       ** 3 IF (x > z) GOTO <dest>
02055       */
02056       int addr;
02057       Expr *pLeft = pExpr->pLeft;
02058       Expr *pRight = pExpr->pList->a[0].pExpr;
02059       sqlite3ExprCode(pParse, pLeft);
02060       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
02061       sqlite3ExprCode(pParse, pRight);
02062       addr = sqlite3VdbeCurrentAddr(v);
02063       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
02064 
02065       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
02066       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
02067       pRight = pExpr->pList->a[1].pExpr;
02068       sqlite3ExprCode(pParse, pRight);
02069       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
02070       break;
02071     }
02072     default: {
02073       sqlite3ExprCode(pParse, pExpr);
02074       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
02075       break;
02076     }
02077   }
02078   pParse->ckOffset = ckOffset;
02079 }
02080 
02081 /*
02082 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
02083 ** if they are identical and return FALSE if they differ in any way.
02084 */
02085 int sqlite3ExprCompare(Expr *pA, Expr *pB){
02086   int i;
02087   if( pA==0||pB==0 ){
02088     return pB==pA;
02089   }
02090   if( pA->op!=pB->op ) return 0;
02091   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
02092   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
02093   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
02094   if( pA->pList ){
02095     if( pB->pList==0 ) return 0;
02096     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
02097     for(i=0; i<pA->pList->nExpr; i++){
02098       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
02099         return 0;
02100       }
02101     }
02102   }else if( pB->pList ){
02103     return 0;
02104   }
02105   if( pA->pSelect || pB->pSelect ) return 0;
02106   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
02107   if( pA->token.z ){
02108     if( pB->token.z==0 ) return 0;
02109     if( pB->token.n!=pA->token.n ) return 0;
02110     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
02111       return 0;
02112     }
02113   }
02114   return 1;
02115 }
02116 
02117 
02118 /*
02119 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
02120 ** the new element.  Return a negative number if malloc fails.
02121 */
02122 static int addAggInfoColumn(AggInfo *pInfo){
02123   int i;
02124   i = sqlite3ArrayAllocate((void**)&pInfo->aCol, sizeof(pInfo->aCol[0]), 3);
02125   if( i<0 ){
02126     return -1;
02127   }
02128   return i;
02129 }    
02130 
02131 /*
02132 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
02133 ** the new element.  Return a negative number if malloc fails.
02134 */
02135 static int addAggInfoFunc(AggInfo *pInfo){
02136   int i;
02137   i = sqlite3ArrayAllocate((void**)&pInfo->aFunc, sizeof(pInfo->aFunc[0]), 2);
02138   if( i<0 ){
02139     return -1;
02140   }
02141   return i;
02142 }    
02143 
02144 /*
02145 ** This is an xFunc for walkExprTree() used to implement 
02146 ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
02147 ** for additional information.
02148 **
02149 ** This routine analyzes the aggregate function at pExpr.
02150 */
02151 static int analyzeAggregate(void *pArg, Expr *pExpr){
02152   int i;
02153   NameContext *pNC = (NameContext *)pArg;
02154   Parse *pParse = pNC->pParse;
02155   SrcList *pSrcList = pNC->pSrcList;
02156   AggInfo *pAggInfo = pNC->pAggInfo;
02157   
02158 
02159   switch( pExpr->op ){
02160     case TK_COLUMN: {
02161       /* Check to see if the column is in one of the tables in the FROM
02162       ** clause of the aggregate query */
02163       if( pSrcList ){
02164         struct SrcList_item *pItem = pSrcList->a;
02165         for(i=0; i<pSrcList->nSrc; i++, pItem++){
02166           struct AggInfo_col *pCol;
02167           if( pExpr->iTable==pItem->iCursor ){
02168             /* If we reach this point, it means that pExpr refers to a table
02169             ** that is in the FROM clause of the aggregate query.  
02170             **
02171             ** Make an entry for the column in pAggInfo->aCol[] if there
02172             ** is not an entry there already.
02173             */
02174             pCol = pAggInfo->aCol;
02175             for(i=0; i<pAggInfo->nColumn; i++, pCol++){
02176               if( pCol->iTable==pExpr->iTable &&
02177                   pCol->iColumn==pExpr->iColumn ){
02178                 break;
02179               }
02180             }
02181             if( i>=pAggInfo->nColumn && (i = addAggInfoColumn(pAggInfo))>=0 ){
02182               pCol = &pAggInfo->aCol[i];
02183               pCol->iTable = pExpr->iTable;
02184               pCol->iColumn = pExpr->iColumn;
02185               pCol->iMem = pParse->nMem++;
02186               pCol->iSorterColumn = -1;
02187               pCol->pExpr = pExpr;
02188               if( pAggInfo->pGroupBy ){
02189                 int j, n;
02190                 ExprList *pGB = pAggInfo->pGroupBy;
02191                 struct ExprList_item *pTerm = pGB->a;
02192                 n = pGB->nExpr;
02193                 for(j=0; j<n; j++, pTerm++){
02194                   Expr *pE = pTerm->pExpr;
02195                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
02196                       pE->iColumn==pExpr->iColumn ){
02197                     pCol->iSorterColumn = j;
02198                     break;
02199                   }
02200                 }
02201               }
02202               if( pCol->iSorterColumn<0 ){
02203                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
02204               }
02205             }
02206             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
02207             ** because it was there before or because we just created it).
02208             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
02209             ** pAggInfo->aCol[] entry.
02210             */
02211             pExpr->pAggInfo = pAggInfo;
02212             pExpr->op = TK_AGG_COLUMN;
02213             pExpr->iAgg = i;
02214             break;
02215           } /* endif pExpr->iTable==pItem->iCursor */
02216         } /* end loop over pSrcList */
02217       }
02218       return 1;
02219     }
02220     case TK_AGG_FUNCTION: {
02221       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
02222       ** to be ignored */
02223       if( pNC->nDepth==0 ){
02224         /* Check to see if pExpr is a duplicate of another aggregate 
02225         ** function that is already in the pAggInfo structure
02226         */
02227         struct AggInfo_func *pItem = pAggInfo->aFunc;
02228         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
02229           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
02230             break;
02231           }
02232         }
02233         if( i>=pAggInfo->nFunc ){
02234           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
02235           */
02236           u8 enc = ENC(pParse->db);
02237           i = addAggInfoFunc(pAggInfo);
02238           if( i>=0 ){
02239             pItem = &pAggInfo->aFunc[i];
02240             pItem->pExpr = pExpr;
02241             pItem->iMem = pParse->nMem++;
02242             pItem->pFunc = sqlite3FindFunction(pParse->db,
02243                    (char*)pExpr->token.z, pExpr->token.n,
02244                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
02245             if( pExpr->flags & EP_Distinct ){
02246               pItem->iDistinct = pParse->nTab++;
02247             }else{
02248               pItem->iDistinct = -1;
02249             }
02250           }
02251         }
02252         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
02253         */
02254         pExpr->iAgg = i;
02255         pExpr->pAggInfo = pAggInfo;
02256         return 1;
02257       }
02258     }
02259   }
02260 
02261   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
02262   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
02263   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
02264   */
02265   if( pExpr->pSelect ){
02266     pNC->nDepth++;
02267     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
02268     pNC->nDepth--;
02269   }
02270   return 0;
02271 }
02272 
02273 /*
02274 ** Analyze the given expression looking for aggregate functions and
02275 ** for variables that need to be added to the pParse->aAgg[] array.
02276 ** Make additional entries to the pParse->aAgg[] array as necessary.
02277 **
02278 ** This routine should only be called after the expression has been
02279 ** analyzed by sqlite3ExprResolveNames().
02280 **
02281 ** If errors are seen, leave an error message in zErrMsg and return
02282 ** the number of errors.
02283 */
02284 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
02285   int nErr = pNC->pParse->nErr;
02286   walkExprTree(pExpr, analyzeAggregate, pNC);
02287   return pNC->pParse->nErr - nErr;
02288 }
02289 
02290 /*
02291 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
02292 ** expression list.  Return the number of errors.
02293 **
02294 ** If an error is found, the analysis is cut short.
02295 */
02296 int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
02297   struct ExprList_item *pItem;
02298   int i;
02299   int nErr = 0;
02300   if( pList ){
02301     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
02302       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
02303     }
02304   }
02305   return nErr;
02306 }