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.402 2008/11/12 08:07:12 danielk1977 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_SELECT ){
00039     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
00040   }
00041 #ifndef SQLITE_OMIT_CAST
00042   if( op==TK_CAST ){
00043     return sqlite3AffinityType(&pExpr->token);
00044   }
00045 #endif
00046   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
00047    && pExpr->pTab!=0
00048   ){
00049     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
00050     ** a TK_COLUMN but was previously evaluated and cached in a register */
00051     int j = pExpr->iColumn;
00052     if( j<0 ) return SQLITE_AFF_INTEGER;
00053     assert( pExpr->pTab && j<pExpr->pTab->nCol );
00054     return pExpr->pTab->aCol[j].affinity;
00055   }
00056   return pExpr->affinity;
00057 }
00058 
00059 /*
00060 ** Set the collating sequence for expression pExpr to be the collating
00061 ** sequence named by pToken.   Return a pointer to the revised expression.
00062 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
00063 ** flag.  An explicit collating sequence will override implicit
00064 ** collating sequences.
00065 */
00066 Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
00067   char *zColl = 0;            /* Dequoted name of collation sequence */
00068   CollSeq *pColl;
00069   sqlite3 *db = pParse->db;
00070   zColl = sqlite3NameFromToken(db, pCollName);
00071   if( pExpr && zColl ){
00072     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
00073     if( pColl ){
00074       pExpr->pColl = pColl;
00075       pExpr->flags |= EP_ExpCollate;
00076     }
00077   }
00078   sqlite3DbFree(db, zColl);
00079   return pExpr;
00080 }
00081 
00082 /*
00083 ** Return the default collation sequence for the expression pExpr. If
00084 ** there is no default collation type, return 0.
00085 */
00086 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
00087   CollSeq *pColl = 0;
00088   Expr *p = pExpr;
00089   while( p ){
00090     int op;
00091     pColl = p->pColl;
00092     if( pColl ) break;
00093     op = p->op;
00094     if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
00095       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
00096       ** a TK_COLUMN but was previously evaluated and cached in a register */
00097       const char *zColl;
00098       int j = p->iColumn;
00099       if( j>=0 ){
00100         sqlite3 *db = pParse->db;
00101         zColl = p->pTab->aCol[j].zColl;
00102         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
00103         pExpr->pColl = pColl;
00104       }
00105       break;
00106     }
00107     if( op!=TK_CAST && op!=TK_UPLUS ){
00108       break;
00109     }
00110     p = p->pLeft;
00111   }
00112   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
00113     pColl = 0;
00114   }
00115   return pColl;
00116 }
00117 
00118 /*
00119 ** pExpr is an operand of a comparison operator.  aff2 is the
00120 ** type affinity of the other operand.  This routine returns the
00121 ** type affinity that should be used for the comparison operator.
00122 */
00123 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
00124   char aff1 = sqlite3ExprAffinity(pExpr);
00125   if( aff1 && aff2 ){
00126     /* Both sides of the comparison are columns. If one has numeric
00127     ** affinity, use that. Otherwise use no affinity.
00128     */
00129     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
00130       return SQLITE_AFF_NUMERIC;
00131     }else{
00132       return SQLITE_AFF_NONE;
00133     }
00134   }else if( !aff1 && !aff2 ){
00135     /* Neither side of the comparison is a column.  Compare the
00136     ** results directly.
00137     */
00138     return SQLITE_AFF_NONE;
00139   }else{
00140     /* One side is a column, the other is not. Use the columns affinity. */
00141     assert( aff1==0 || aff2==0 );
00142     return (aff1 + aff2);
00143   }
00144 }
00145 
00146 /*
00147 ** pExpr is a comparison operator.  Return the type affinity that should
00148 ** be applied to both operands prior to doing the comparison.
00149 */
00150 static char comparisonAffinity(Expr *pExpr){
00151   char aff;
00152   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
00153           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
00154           pExpr->op==TK_NE );
00155   assert( pExpr->pLeft );
00156   aff = sqlite3ExprAffinity(pExpr->pLeft);
00157   if( pExpr->pRight ){
00158     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
00159   }
00160   else if( pExpr->pSelect ){
00161     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
00162   }
00163   else if( !aff ){
00164     aff = SQLITE_AFF_NONE;
00165   }
00166   return aff;
00167 }
00168 
00169 /*
00170 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
00171 ** idx_affinity is the affinity of an indexed column. Return true
00172 ** if the index with affinity idx_affinity may be used to implement
00173 ** the comparison in pExpr.
00174 */
00175 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
00176   char aff = comparisonAffinity(pExpr);
00177   switch( aff ){
00178     case SQLITE_AFF_NONE:
00179       return 1;
00180     case SQLITE_AFF_TEXT:
00181       return idx_affinity==SQLITE_AFF_TEXT;
00182     default:
00183       return sqlite3IsNumericAffinity(idx_affinity);
00184   }
00185 }
00186 
00187 /*
00188 ** Return the P5 value that should be used for a binary comparison
00189 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
00190 */
00191 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
00192   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
00193   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
00194   return aff;
00195 }
00196 
00197 /*
00198 ** Return a pointer to the collation sequence that should be used by
00199 ** a binary comparison operator comparing pLeft and pRight.
00200 **
00201 ** If the left hand expression has a collating sequence type, then it is
00202 ** used. Otherwise the collation sequence for the right hand expression
00203 ** is used, or the default (BINARY) if neither expression has a collating
00204 ** type.
00205 **
00206 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
00207 ** it is not considered.
00208 */
00209 CollSeq *sqlite3BinaryCompareCollSeq(
00210   Parse *pParse, 
00211   Expr *pLeft, 
00212   Expr *pRight
00213 ){
00214   CollSeq *pColl;
00215   assert( pLeft );
00216   if( pLeft->flags & EP_ExpCollate ){
00217     assert( pLeft->pColl );
00218     pColl = pLeft->pColl;
00219   }else if( pRight && pRight->flags & EP_ExpCollate ){
00220     assert( pRight->pColl );
00221     pColl = pRight->pColl;
00222   }else{
00223     pColl = sqlite3ExprCollSeq(pParse, pLeft);
00224     if( !pColl ){
00225       pColl = sqlite3ExprCollSeq(pParse, pRight);
00226     }
00227   }
00228   return pColl;
00229 }
00230 
00231 /*
00232 ** Generate the operands for a comparison operation.  Before
00233 ** generating the code for each operand, set the EP_AnyAff
00234 ** flag on the expression so that it will be able to used a
00235 ** cached column value that has previously undergone an
00236 ** affinity change.
00237 */
00238 static void codeCompareOperands(
00239   Parse *pParse,    /* Parsing and code generating context */
00240   Expr *pLeft,      /* The left operand */
00241   int *pRegLeft,    /* Register where left operand is stored */
00242   int *pFreeLeft,   /* Free this register when done */
00243   Expr *pRight,     /* The right operand */
00244   int *pRegRight,   /* Register where right operand is stored */
00245   int *pFreeRight   /* Write temp register for right operand there */
00246 ){
00247   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
00248   pLeft->flags |= EP_AnyAff;
00249   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
00250   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
00251   pRight->flags |= EP_AnyAff;
00252   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
00253 }
00254 
00255 /*
00256 ** Generate code for a comparison operator.
00257 */
00258 static int codeCompare(
00259   Parse *pParse,    /* The parsing (and code generating) context */
00260   Expr *pLeft,      /* The left operand */
00261   Expr *pRight,     /* The right operand */
00262   int opcode,       /* The comparison opcode */
00263   int in1, int in2, /* Register holding operands */
00264   int dest,         /* Jump here if true.  */
00265   int jumpIfNull    /* If true, jump if either operand is NULL */
00266 ){
00267   int p5;
00268   int addr;
00269   CollSeq *p4;
00270 
00271   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
00272   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
00273   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
00274                            (void*)p4, P4_COLLSEQ);
00275   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
00276   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
00277     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
00278     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
00279   }
00280   return addr;
00281 }
00282 
00283 #if SQLITE_MAX_EXPR_DEPTH>0
00284 /*
00285 ** Check that argument nHeight is less than or equal to the maximum
00286 ** expression depth allowed. If it is not, leave an error message in
00287 ** pParse.
00288 */
00289 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
00290   int rc = SQLITE_OK;
00291   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
00292   if( nHeight>mxHeight ){
00293     sqlite3ErrorMsg(pParse, 
00294        "Expression tree is too large (maximum depth %d)", mxHeight
00295     );
00296     rc = SQLITE_ERROR;
00297   }
00298   return rc;
00299 }
00300 
00301 /* The following three functions, heightOfExpr(), heightOfExprList()
00302 ** and heightOfSelect(), are used to determine the maximum height
00303 ** of any expression tree referenced by the structure passed as the
00304 ** first argument.
00305 **
00306 ** If this maximum height is greater than the current value pointed
00307 ** to by pnHeight, the second parameter, then set *pnHeight to that
00308 ** value.
00309 */
00310 static void heightOfExpr(Expr *p, int *pnHeight){
00311   if( p ){
00312     if( p->nHeight>*pnHeight ){
00313       *pnHeight = p->nHeight;
00314     }
00315   }
00316 }
00317 static void heightOfExprList(ExprList *p, int *pnHeight){
00318   if( p ){
00319     int i;
00320     for(i=0; i<p->nExpr; i++){
00321       heightOfExpr(p->a[i].pExpr, pnHeight);
00322     }
00323   }
00324 }
00325 static void heightOfSelect(Select *p, int *pnHeight){
00326   if( p ){
00327     heightOfExpr(p->pWhere, pnHeight);
00328     heightOfExpr(p->pHaving, pnHeight);
00329     heightOfExpr(p->pLimit, pnHeight);
00330     heightOfExpr(p->pOffset, pnHeight);
00331     heightOfExprList(p->pEList, pnHeight);
00332     heightOfExprList(p->pGroupBy, pnHeight);
00333     heightOfExprList(p->pOrderBy, pnHeight);
00334     heightOfSelect(p->pPrior, pnHeight);
00335   }
00336 }
00337 
00338 /*
00339 ** Set the Expr.nHeight variable in the structure passed as an 
00340 ** argument. An expression with no children, Expr.pList or 
00341 ** Expr.pSelect member has a height of 1. Any other expression
00342 ** has a height equal to the maximum height of any other 
00343 ** referenced Expr plus one.
00344 */
00345 static void exprSetHeight(Expr *p){
00346   int nHeight = 0;
00347   heightOfExpr(p->pLeft, &nHeight);
00348   heightOfExpr(p->pRight, &nHeight);
00349   heightOfExprList(p->pList, &nHeight);
00350   heightOfSelect(p->pSelect, &nHeight);
00351   p->nHeight = nHeight + 1;
00352 }
00353 
00354 /*
00355 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
00356 ** the height is greater than the maximum allowed expression depth,
00357 ** leave an error in pParse.
00358 */
00359 void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
00360   exprSetHeight(p);
00361   sqlite3ExprCheckHeight(pParse, p->nHeight);
00362 }
00363 
00364 /*
00365 ** Return the maximum height of any expression tree referenced
00366 ** by the select statement passed as an argument.
00367 */
00368 int sqlite3SelectExprHeight(Select *p){
00369   int nHeight = 0;
00370   heightOfSelect(p, &nHeight);
00371   return nHeight;
00372 }
00373 #else
00374   #define exprSetHeight(y)
00375 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
00376 
00377 /*
00378 ** Construct a new expression node and return a pointer to it.  Memory
00379 ** for this node is obtained from sqlite3_malloc().  The calling function
00380 ** is responsible for making sure the node eventually gets freed.
00381 */
00382 Expr *sqlite3Expr(
00383   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
00384   int op,                 /* Expression opcode */
00385   Expr *pLeft,            /* Left operand */
00386   Expr *pRight,           /* Right operand */
00387   const Token *pToken     /* Argument token */
00388 ){
00389   Expr *pNew;
00390   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
00391   if( pNew==0 ){
00392     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
00393     ** this function must always be allocated with sqlite3Expr() for this 
00394     ** reason. 
00395     */
00396     sqlite3ExprDelete(db, pLeft);
00397     sqlite3ExprDelete(db, pRight);
00398     return 0;
00399   }
00400   pNew->op = op;
00401   pNew->pLeft = pLeft;
00402   pNew->pRight = pRight;
00403   pNew->iAgg = -1;
00404   pNew->span.z = (u8*)"";
00405   if( pToken ){
00406     assert( pToken->dyn==0 );
00407     pNew->span = pNew->token = *pToken;
00408   }else if( pLeft ){
00409     if( pRight ){
00410       if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
00411         sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
00412       }
00413       if( pRight->flags & EP_ExpCollate ){
00414         pNew->flags |= EP_ExpCollate;
00415         pNew->pColl = pRight->pColl;
00416       }
00417     }
00418     if( pLeft->flags & EP_ExpCollate ){
00419       pNew->flags |= EP_ExpCollate;
00420       pNew->pColl = pLeft->pColl;
00421     }
00422   }
00423 
00424   exprSetHeight(pNew);
00425   return pNew;
00426 }
00427 
00428 /*
00429 ** Works like sqlite3Expr() except that it takes an extra Parse*
00430 ** argument and notifies the associated connection object if malloc fails.
00431 */
00432 Expr *sqlite3PExpr(
00433   Parse *pParse,          /* Parsing context */
00434   int op,                 /* Expression opcode */
00435   Expr *pLeft,            /* Left operand */
00436   Expr *pRight,           /* Right operand */
00437   const Token *pToken     /* Argument token */
00438 ){
00439   Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
00440   if( p ){
00441     sqlite3ExprCheckHeight(pParse, p->nHeight);
00442   }
00443   return p;
00444 }
00445 
00446 /*
00447 ** When doing a nested parse, you can include terms in an expression
00448 ** that look like this:   #1 #2 ...  These terms refer to registers
00449 ** in the virtual machine.  #N is the N-th register.
00450 **
00451 ** This routine is called by the parser to deal with on of those terms.
00452 ** It immediately generates code to store the value in a memory location.
00453 ** The returns an expression that will code to extract the value from
00454 ** that memory location as needed.
00455 */
00456 Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
00457   Vdbe *v = pParse->pVdbe;
00458   Expr *p;
00459   if( pParse->nested==0 ){
00460     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
00461     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
00462   }
00463   if( v==0 ) return 0;
00464   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
00465   if( p==0 ){
00466     return 0;  /* Malloc failed */
00467   }
00468   p->iTable = atoi((char*)&pToken->z[1]);
00469   return p;
00470 }
00471 
00472 /*
00473 ** Join two expressions using an AND operator.  If either expression is
00474 ** NULL, then just return the other expression.
00475 */
00476 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
00477   if( pLeft==0 ){
00478     return pRight;
00479   }else if( pRight==0 ){
00480     return pLeft;
00481   }else{
00482     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
00483   }
00484 }
00485 
00486 /*
00487 ** Set the Expr.span field of the given expression to span all
00488 ** text between the two given tokens.  Both tokens must be pointing
00489 ** at the same string.
00490 */
00491 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
00492   assert( pRight!=0 );
00493   assert( pLeft!=0 );
00494   if( pExpr ){
00495     pExpr->span.z = pLeft->z;
00496     pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
00497   }
00498 }
00499 
00500 /*
00501 ** Construct a new expression node for a function with multiple
00502 ** arguments.
00503 */
00504 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
00505   Expr *pNew;
00506   sqlite3 *db = pParse->db;
00507   assert( pToken );
00508   pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
00509   if( pNew==0 ){
00510     sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
00511     return 0;
00512   }
00513   pNew->op = TK_FUNCTION;
00514   pNew->pList = pList;
00515   assert( pToken->dyn==0 );
00516   pNew->token = *pToken;
00517   pNew->span = pNew->token;
00518 
00519   sqlite3ExprSetHeight(pParse, pNew);
00520   return pNew;
00521 }
00522 
00523 /*
00524 ** Assign a variable number to an expression that encodes a wildcard
00525 ** in the original SQL statement.  
00526 **
00527 ** Wildcards consisting of a single "?" are assigned the next sequential
00528 ** variable number.
00529 **
00530 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
00531 ** sure "nnn" is not too be to avoid a denial of service attack when
00532 ** the SQL statement comes from an external source.
00533 **
00534 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
00535 ** as the previous instance of the same wildcard.  Or if this is the first
00536 ** instance of the wildcard, the next sequenial variable number is
00537 ** assigned.
00538 */
00539 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
00540   Token *pToken;
00541   sqlite3 *db = pParse->db;
00542 
00543   if( pExpr==0 ) return;
00544   pToken = &pExpr->token;
00545   assert( pToken->n>=1 );
00546   assert( pToken->z!=0 );
00547   assert( pToken->z[0]!=0 );
00548   if( pToken->n==1 ){
00549     /* Wildcard of the form "?".  Assign the next variable number */
00550     pExpr->iTable = ++pParse->nVar;
00551   }else if( pToken->z[0]=='?' ){
00552     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
00553     ** use it as the variable number */
00554     int i;
00555     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
00556     testcase( i==0 );
00557     testcase( i==1 );
00558     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
00559     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
00560     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
00561       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
00562           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
00563     }
00564     if( i>pParse->nVar ){
00565       pParse->nVar = i;
00566     }
00567   }else{
00568     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
00569     ** number as the prior appearance of the same name, or if the name
00570     ** has never appeared before, reuse the same variable number
00571     */
00572     int i, n;
00573     n = pToken->n;
00574     for(i=0; i<pParse->nVarExpr; i++){
00575       Expr *pE;
00576       if( (pE = pParse->apVarExpr[i])!=0
00577           && pE->token.n==n
00578           && memcmp(pE->token.z, pToken->z, n)==0 ){
00579         pExpr->iTable = pE->iTable;
00580         break;
00581       }
00582     }
00583     if( i>=pParse->nVarExpr ){
00584       pExpr->iTable = ++pParse->nVar;
00585       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
00586         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
00587         pParse->apVarExpr =
00588             sqlite3DbReallocOrFree(
00589               db,
00590               pParse->apVarExpr,
00591               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
00592             );
00593       }
00594       if( !db->mallocFailed ){
00595         assert( pParse->apVarExpr!=0 );
00596         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
00597       }
00598     }
00599   } 
00600   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
00601     sqlite3ErrorMsg(pParse, "too many SQL variables");
00602   }
00603 }
00604 
00605 /*
00606 ** Clear an expression structure without deleting the structure itself.
00607 ** Substructure is deleted.
00608 */
00609 void sqlite3ExprClear(sqlite3 *db, Expr *p){
00610   if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
00611   if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
00612   sqlite3ExprDelete(db, p->pLeft);
00613   sqlite3ExprDelete(db, p->pRight);
00614   sqlite3ExprListDelete(db, p->pList);
00615   sqlite3SelectDelete(db, p->pSelect);
00616 }
00617 
00618 /*
00619 ** Recursively delete an expression tree.
00620 */
00621 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
00622   if( p==0 ) return;
00623   sqlite3ExprClear(db, p);
00624   sqlite3DbFree(db, p);
00625 }
00626 
00627 /*
00628 ** The Expr.token field might be a string literal that is quoted.
00629 ** If so, remove the quotation marks.
00630 */
00631 void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
00632   if( ExprHasAnyProperty(p, EP_Dequoted) ){
00633     return;
00634   }
00635   ExprSetProperty(p, EP_Dequoted);
00636   if( p->token.dyn==0 ){
00637     sqlite3TokenCopy(db, &p->token, &p->token);
00638   }
00639   sqlite3Dequote((char*)p->token.z);
00640 }
00641 
00642 /*
00643 ** The following group of routines make deep copies of expressions,
00644 ** expression lists, ID lists, and select statements.  The copies can
00645 ** be deleted (by being passed to their respective ...Delete() routines)
00646 ** without effecting the originals.
00647 **
00648 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
00649 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
00650 ** by subsequent calls to sqlite*ListAppend() routines.
00651 **
00652 ** Any tables that the SrcList might point to are not duplicated.
00653 */
00654 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
00655   Expr *pNew;
00656   if( p==0 ) return 0;
00657   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
00658   if( pNew==0 ) return 0;
00659   memcpy(pNew, p, sizeof(*pNew));
00660   if( p->token.z!=0 ){
00661     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
00662     pNew->token.dyn = 1;
00663   }else{
00664     assert( pNew->token.z==0 );
00665   }
00666   pNew->span.z = 0;
00667   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
00668   pNew->pRight = sqlite3ExprDup(db, p->pRight);
00669   pNew->pList = sqlite3ExprListDup(db, p->pList);
00670   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
00671   return pNew;
00672 }
00673 void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
00674   if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
00675   if( pFrom->z ){
00676     pTo->n = pFrom->n;
00677     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
00678     pTo->dyn = 1;
00679   }else{
00680     pTo->z = 0;
00681   }
00682 }
00683 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
00684   ExprList *pNew;
00685   struct ExprList_item *pItem, *pOldItem;
00686   int i;
00687   if( p==0 ) return 0;
00688   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
00689   if( pNew==0 ) return 0;
00690   pNew->iECursor = 0;
00691   pNew->nExpr = pNew->nAlloc = p->nExpr;
00692   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
00693   if( pItem==0 ){
00694     sqlite3DbFree(db, pNew);
00695     return 0;
00696   } 
00697   pOldItem = p->a;
00698   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
00699     Expr *pNewExpr, *pOldExpr;
00700     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
00701     if( pOldExpr->span.z!=0 && pNewExpr ){
00702       /* Always make a copy of the span for top-level expressions in the
00703       ** expression list.  The logic in SELECT processing that determines
00704       ** the names of columns in the result set needs this information */
00705       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
00706     }
00707     assert( pNewExpr==0 || pNewExpr->span.z!=0 
00708             || pOldExpr->span.z==0
00709             || db->mallocFailed );
00710     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
00711     pItem->sortOrder = pOldItem->sortOrder;
00712     pItem->done = 0;
00713     pItem->iCol = pOldItem->iCol;
00714     pItem->iAlias = pOldItem->iAlias;
00715   }
00716   return pNew;
00717 }
00718 
00719 /*
00720 ** If cursors, triggers, views and subqueries are all omitted from
00721 ** the build, then none of the following routines, except for 
00722 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
00723 ** called with a NULL argument.
00724 */
00725 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
00726  || !defined(SQLITE_OMIT_SUBQUERY)
00727 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
00728   SrcList *pNew;
00729   int i;
00730   int nByte;
00731   if( p==0 ) return 0;
00732   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
00733   pNew = sqlite3DbMallocRaw(db, nByte );
00734   if( pNew==0 ) return 0;
00735   pNew->nSrc = pNew->nAlloc = p->nSrc;
00736   for(i=0; i<p->nSrc; i++){
00737     struct SrcList_item *pNewItem = &pNew->a[i];
00738     struct SrcList_item *pOldItem = &p->a[i];
00739     Table *pTab;
00740     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
00741     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
00742     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
00743     pNewItem->jointype = pOldItem->jointype;
00744     pNewItem->iCursor = pOldItem->iCursor;
00745     pNewItem->isPopulated = pOldItem->isPopulated;
00746     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
00747     pNewItem->notIndexed = pOldItem->notIndexed;
00748     pNewItem->pIndex = pOldItem->pIndex;
00749     pTab = pNewItem->pTab = pOldItem->pTab;
00750     if( pTab ){
00751       pTab->nRef++;
00752     }
00753     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
00754     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
00755     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
00756     pNewItem->colUsed = pOldItem->colUsed;
00757   }
00758   return pNew;
00759 }
00760 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
00761   IdList *pNew;
00762   int i;
00763   if( p==0 ) return 0;
00764   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
00765   if( pNew==0 ) return 0;
00766   pNew->nId = pNew->nAlloc = p->nId;
00767   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
00768   if( pNew->a==0 ){
00769     sqlite3DbFree(db, pNew);
00770     return 0;
00771   }
00772   for(i=0; i<p->nId; i++){
00773     struct IdList_item *pNewItem = &pNew->a[i];
00774     struct IdList_item *pOldItem = &p->a[i];
00775     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
00776     pNewItem->idx = pOldItem->idx;
00777   }
00778   return pNew;
00779 }
00780 Select *sqlite3SelectDup(sqlite3 *db, Select *p){
00781   Select *pNew;
00782   if( p==0 ) return 0;
00783   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
00784   if( pNew==0 ) return 0;
00785   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
00786   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
00787   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
00788   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
00789   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
00790   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
00791   pNew->op = p->op;
00792   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
00793   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
00794   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
00795   pNew->iLimit = 0;
00796   pNew->iOffset = 0;
00797   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
00798   pNew->pRightmost = 0;
00799   pNew->addrOpenEphm[0] = -1;
00800   pNew->addrOpenEphm[1] = -1;
00801   pNew->addrOpenEphm[2] = -1;
00802   return pNew;
00803 }
00804 #else
00805 Select *sqlite3SelectDup(sqlite3 *db, Select *p){
00806   assert( p==0 );
00807   return 0;
00808 }
00809 #endif
00810 
00811 
00812 /*
00813 ** Add a new element to the end of an expression list.  If pList is
00814 ** initially NULL, then create a new expression list.
00815 */
00816 ExprList *sqlite3ExprListAppend(
00817   Parse *pParse,          /* Parsing context */
00818   ExprList *pList,        /* List to which to append. Might be NULL */
00819   Expr *pExpr,            /* Expression to be appended */
00820   Token *pName            /* AS keyword for the expression */
00821 ){
00822   sqlite3 *db = pParse->db;
00823   if( pList==0 ){
00824     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
00825     if( pList==0 ){
00826       goto no_mem;
00827     }
00828     assert( pList->nAlloc==0 );
00829   }
00830   if( pList->nAlloc<=pList->nExpr ){
00831     struct ExprList_item *a;
00832     int n = pList->nAlloc*2 + 4;
00833     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
00834     if( a==0 ){
00835       goto no_mem;
00836     }
00837     pList->a = a;
00838     pList->nAlloc = n;
00839   }
00840   assert( pList->a!=0 );
00841   if( pExpr || pName ){
00842     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
00843     memset(pItem, 0, sizeof(*pItem));
00844     pItem->zName = sqlite3NameFromToken(db, pName);
00845     pItem->pExpr = pExpr;
00846     pItem->iAlias = 0;
00847   }
00848   return pList;
00849 
00850 no_mem:     
00851   /* Avoid leaking memory if malloc has failed. */
00852   sqlite3ExprDelete(db, pExpr);
00853   sqlite3ExprListDelete(db, pList);
00854   return 0;
00855 }
00856 
00857 /*
00858 ** If the expression list pEList contains more than iLimit elements,
00859 ** leave an error message in pParse.
00860 */
00861 void sqlite3ExprListCheckLength(
00862   Parse *pParse,
00863   ExprList *pEList,
00864   const char *zObject
00865 ){
00866   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
00867   testcase( pEList && pEList->nExpr==mx );
00868   testcase( pEList && pEList->nExpr==mx+1 );
00869   if( pEList && pEList->nExpr>mx ){
00870     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
00871   }
00872 }
00873 
00874 /*
00875 ** Delete an entire expression list.
00876 */
00877 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
00878   int i;
00879   struct ExprList_item *pItem;
00880   if( pList==0 ) return;
00881   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
00882   assert( pList->nExpr<=pList->nAlloc );
00883   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
00884     sqlite3ExprDelete(db, pItem->pExpr);
00885     sqlite3DbFree(db, pItem->zName);
00886   }
00887   sqlite3DbFree(db, pList->a);
00888   sqlite3DbFree(db, pList);
00889 }
00890 
00891 /*
00892 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
00893 ** to an integer.  These routines are checking an expression to see
00894 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
00895 ** not constant.
00896 **
00897 ** These callback routines are used to implement the following:
00898 **
00899 **     sqlite3ExprIsConstant()
00900 **     sqlite3ExprIsConstantNotJoin()
00901 **     sqlite3ExprIsConstantOrFunction()
00902 **
00903 */
00904 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
00905 
00906   /* If pWalker->u.i is 3 then any term of the expression that comes from
00907   ** the ON or USING clauses of a join disqualifies the expression
00908   ** from being considered constant. */
00909   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
00910     pWalker->u.i = 0;
00911     return WRC_Abort;
00912   }
00913 
00914   switch( pExpr->op ){
00915     /* Consider functions to be constant if all their arguments are constant
00916     ** and pWalker->u.i==2 */
00917     case TK_FUNCTION:
00918       if( pWalker->u.i==2 ) return 0;
00919       /* Fall through */
00920     case TK_ID:
00921     case TK_COLUMN:
00922     case TK_DOT:
00923     case TK_AGG_FUNCTION:
00924     case TK_AGG_COLUMN:
00925 #ifndef SQLITE_OMIT_SUBQUERY
00926     case TK_SELECT:
00927     case TK_EXISTS:
00928       testcase( pExpr->op==TK_SELECT );
00929       testcase( pExpr->op==TK_EXISTS );
00930 #endif
00931       testcase( pExpr->op==TK_ID );
00932       testcase( pExpr->op==TK_COLUMN );
00933       testcase( pExpr->op==TK_DOT );
00934       testcase( pExpr->op==TK_AGG_FUNCTION );
00935       testcase( pExpr->op==TK_AGG_COLUMN );
00936       pWalker->u.i = 0;
00937       return WRC_Abort;
00938     default:
00939       return WRC_Continue;
00940   }
00941 }
00942 static int selectNodeIsConstant(Walker *pWalker, Select *pSelect){
00943   pWalker->u.i = 0;
00944   return WRC_Abort;
00945 }
00946 static int exprIsConst(Expr *p, int initFlag){
00947   Walker w;
00948   w.u.i = initFlag;
00949   w.xExprCallback = exprNodeIsConstant;
00950   w.xSelectCallback = selectNodeIsConstant;
00951   sqlite3WalkExpr(&w, p);
00952   return w.u.i;
00953 }
00954 
00955 /*
00956 ** Walk an expression tree.  Return 1 if the expression is constant
00957 ** and 0 if it involves variables or function calls.
00958 **
00959 ** For the purposes of this function, a double-quoted string (ex: "abc")
00960 ** is considered a variable but a single-quoted string (ex: 'abc') is
00961 ** a constant.
00962 */
00963 int sqlite3ExprIsConstant(Expr *p){
00964   return exprIsConst(p, 1);
00965 }
00966 
00967 /*
00968 ** Walk an expression tree.  Return 1 if the expression is constant
00969 ** that does no originate from the ON or USING clauses of a join.
00970 ** Return 0 if it involves variables or function calls or terms from
00971 ** an ON or USING clause.
00972 */
00973 int sqlite3ExprIsConstantNotJoin(Expr *p){
00974   return exprIsConst(p, 3);
00975 }
00976 
00977 /*
00978 ** Walk an expression tree.  Return 1 if the expression is constant
00979 ** or a function call with constant arguments.  Return and 0 if there
00980 ** are any variables.
00981 **
00982 ** For the purposes of this function, a double-quoted string (ex: "abc")
00983 ** is considered a variable but a single-quoted string (ex: 'abc') is
00984 ** a constant.
00985 */
00986 int sqlite3ExprIsConstantOrFunction(Expr *p){
00987   return exprIsConst(p, 2);
00988 }
00989 
00990 /*
00991 ** If the expression p codes a constant integer that is small enough
00992 ** to fit in a 32-bit integer, return 1 and put the value of the integer
00993 ** in *pValue.  If the expression is not an integer or if it is too big
00994 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
00995 */
00996 int sqlite3ExprIsInteger(Expr *p, int *pValue){
00997   int rc = 0;
00998   if( p->flags & EP_IntValue ){
00999     *pValue = p->iTable;
01000     return 1;
01001   }
01002   switch( p->op ){
01003     case TK_INTEGER: {
01004       rc = sqlite3GetInt32((char*)p->token.z, pValue);
01005       break;
01006     }
01007     case TK_UPLUS: {
01008       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
01009       break;
01010     }
01011     case TK_UMINUS: {
01012       int v;
01013       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
01014         *pValue = -v;
01015         rc = 1;
01016       }
01017       break;
01018     }
01019     default: break;
01020   }
01021   if( rc ){
01022     p->op = TK_INTEGER;
01023     p->flags |= EP_IntValue;
01024     p->iTable = *pValue;
01025   }
01026   return rc;
01027 }
01028 
01029 /*
01030 ** Return TRUE if the given string is a row-id column name.
01031 */
01032 int sqlite3IsRowid(const char *z){
01033   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
01034   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
01035   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
01036   return 0;
01037 }
01038 
01039 #ifdef SQLITE_TEST
01040   int sqlite3_enable_in_opt = 1;
01041 #else
01042   #define sqlite3_enable_in_opt 1
01043 #endif
01044 
01045 /*
01046 ** Return true if the IN operator optimization is enabled and
01047 ** the SELECT statement p exists and is of the
01048 ** simple form:
01049 **
01050 **     SELECT <column> FROM <table>
01051 **
01052 ** If this is the case, it may be possible to use an existing table
01053 ** or index instead of generating an epheremal table.
01054 */
01055 #ifndef SQLITE_OMIT_SUBQUERY
01056 static int isCandidateForInOpt(Select *p){
01057   SrcList *pSrc;
01058   ExprList *pEList;
01059   Table *pTab;
01060   if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
01061   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
01062   if( p->pPrior ) return 0;              /* Not a compound SELECT */
01063   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
01064       return 0; /* No DISTINCT keyword and no aggregate functions */
01065   }
01066   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
01067   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
01068   if( p->pOffset ) return 0;
01069   if( p->pWhere ) return 0;              /* Has no WHERE clause */
01070   pSrc = p->pSrc;
01071   if( pSrc==0 ) return 0;                /* A single table in the FROM clause */
01072   if( pSrc->nSrc!=1 ) return 0;
01073   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
01074   pTab = pSrc->a[0].pTab;
01075   if( pTab==0 ) return 0;
01076   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
01077   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
01078   pEList = p->pEList;
01079   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
01080   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
01081   return 1;
01082 }
01083 #endif /* SQLITE_OMIT_SUBQUERY */
01084 
01085 /*
01086 ** This function is used by the implementation of the IN (...) operator.
01087 ** It's job is to find or create a b-tree structure that may be used
01088 ** either to test for membership of the (...) set or to iterate through
01089 ** its members, skipping duplicates.
01090 **
01091 ** The cursor opened on the structure (database table, database index 
01092 ** or ephermal table) is stored in pX->iTable before this function returns.
01093 ** The returned value indicates the structure type, as follows:
01094 **
01095 **   IN_INDEX_ROWID - The cursor was opened on a database table.
01096 **   IN_INDEX_INDEX - The cursor was opened on a database index.
01097 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
01098 **                    populated epheremal table.
01099 **
01100 ** An existing structure may only be used if the SELECT is of the simple
01101 ** form:
01102 **
01103 **     SELECT <column> FROM <table>
01104 **
01105 ** If prNotFound parameter is 0, then the structure will be used to iterate
01106 ** through the set members, skipping any duplicates. In this case an
01107 ** epheremal table must be used unless the selected <column> is guaranteed
01108 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
01109 ** is unique by virtue of a constraint or implicit index.
01110 **
01111 ** If the prNotFound parameter is not 0, then the structure will be used 
01112 ** for fast set membership tests. In this case an epheremal table must 
01113 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
01114 ** be found with <column> as its left-most column.
01115 **
01116 ** When the structure is being used for set membership tests, the user
01117 ** needs to know whether or not the structure contains an SQL NULL 
01118 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
01119 ** If there is a chance that the structure may contain a NULL value at
01120 ** runtime, then a register is allocated and the register number written
01121 ** to *prNotFound. If there is no chance that the structure contains a
01122 ** NULL value, then *prNotFound is left unchanged.
01123 **
01124 ** If a register is allocated and its location stored in *prNotFound, then
01125 ** its initial value is NULL. If the structure does not remain constant
01126 ** for the duration of the query (i.e. the set is a correlated sub-select), 
01127 ** the value of the allocated register is reset to NULL each time the 
01128 ** structure is repopulated. This allows the caller to use vdbe code 
01129 ** equivalent to the following:
01130 **
01131 **   if( register==NULL ){
01132 **     has_null = <test if data structure contains null>
01133 **     register = 1
01134 **   }
01135 **
01136 ** in order to avoid running the <test if data structure contains null>
01137 ** test more often than is necessary.
01138 */
01139 #ifndef SQLITE_OMIT_SUBQUERY
01140 int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
01141   Select *p;
01142   int eType = 0;
01143   int iTab = pParse->nTab++;
01144   int mustBeUnique = !prNotFound;
01145 
01146   /* The follwing if(...) expression is true if the SELECT is of the 
01147   ** simple form:
01148   **
01149   **     SELECT <column> FROM <table>
01150   **
01151   ** If this is the case, it may be possible to use an existing table
01152   ** or index instead of generating an epheremal table.
01153   */
01154   p = pX->pSelect;
01155   if( isCandidateForInOpt(p) ){
01156     sqlite3 *db = pParse->db;
01157     Index *pIdx;
01158     Expr *pExpr = p->pEList->a[0].pExpr;
01159     int iCol = pExpr->iColumn;
01160     Vdbe *v = sqlite3GetVdbe(pParse);
01161 
01162     /* This function is only called from two places. In both cases the vdbe
01163     ** has already been allocated. So assume sqlite3GetVdbe() is always
01164     ** successful here.
01165     */
01166     assert(v);
01167     if( iCol<0 ){
01168       int iMem = ++pParse->nMem;
01169       int iAddr;
01170       Table *pTab = p->pSrc->a[0].pTab;
01171       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
01172       sqlite3VdbeUsesBtree(v, iDb);
01173 
01174       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
01175       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
01176 
01177       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
01178       eType = IN_INDEX_ROWID;
01179 
01180       sqlite3VdbeJumpHere(v, iAddr);
01181     }else{
01182       /* The collation sequence used by the comparison. If an index is to 
01183       ** be used in place of a temp-table, it must be ordered according
01184       ** to this collation sequence.
01185       */
01186       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
01187 
01188       /* Check that the affinity that will be used to perform the 
01189       ** comparison is the same as the affinity of the column. If
01190       ** it is not, it is not possible to use any index.
01191       */
01192       Table *pTab = p->pSrc->a[0].pTab;
01193       char aff = comparisonAffinity(pX);
01194       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
01195 
01196       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
01197         if( (pIdx->aiColumn[0]==iCol)
01198          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
01199          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
01200         ){
01201           int iDb;
01202           int iMem = ++pParse->nMem;
01203           int iAddr;
01204           char *pKey;
01205   
01206           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
01207           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
01208           sqlite3VdbeUsesBtree(v, iDb);
01209 
01210           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
01211           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
01212   
01213           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
01214           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
01215                                pKey,P4_KEYINFO_HANDOFF);
01216           VdbeComment((v, "%s", pIdx->zName));
01217           eType = IN_INDEX_INDEX;
01218 
01219           sqlite3VdbeJumpHere(v, iAddr);
01220           if( prNotFound && !pTab->aCol[iCol].notNull ){
01221             *prNotFound = ++pParse->nMem;
01222           }
01223         }
01224       }
01225     }
01226   }
01227 
01228   if( eType==0 ){
01229     int rMayHaveNull = 0;
01230     eType = IN_INDEX_EPH;
01231     if( prNotFound ){
01232       *prNotFound = rMayHaveNull = ++pParse->nMem;
01233     }else if( pX->pLeft->iColumn<0 && pX->pSelect==0 ){
01234       eType = IN_INDEX_ROWID;
01235     }
01236     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
01237   }else{
01238     pX->iTable = iTab;
01239   }
01240   return eType;
01241 }
01242 #endif
01243 
01244 /*
01245 ** Generate code for scalar subqueries used as an expression
01246 ** and IN operators.  Examples:
01247 **
01248 **     (SELECT a FROM b)          -- subquery
01249 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
01250 **     x IN (4,5,11)              -- IN operator with list on right-hand side
01251 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
01252 **
01253 ** The pExpr parameter describes the expression that contains the IN
01254 ** operator or subquery.
01255 **
01256 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
01257 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
01258 ** to some integer key column of a table B-Tree. In this case, use an
01259 ** intkey B-Tree to store the set of IN(...) values instead of the usual
01260 ** (slower) variable length keys B-Tree.
01261 */
01262 #ifndef SQLITE_OMIT_SUBQUERY
01263 void sqlite3CodeSubselect(
01264   Parse *pParse, 
01265   Expr *pExpr, 
01266   int rMayHaveNull,
01267   int isRowid
01268 ){
01269   int testAddr = 0;                       /* One-time test address */
01270   Vdbe *v = sqlite3GetVdbe(pParse);
01271   if( v==0 ) return;
01272 
01273 
01274   /* This code must be run in its entirety every time it is encountered
01275   ** if any of the following is true:
01276   **
01277   **    *  The right-hand side is a correlated subquery
01278   **    *  The right-hand side is an expression list containing variables
01279   **    *  We are inside a trigger
01280   **
01281   ** If all of the above are false, then we can run this code just once
01282   ** save the results, and reuse the same result on subsequent invocations.
01283   */
01284   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
01285     int mem = ++pParse->nMem;
01286     sqlite3VdbeAddOp1(v, OP_If, mem);
01287     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
01288     assert( testAddr>0 || pParse->db->mallocFailed );
01289   }
01290 
01291   switch( pExpr->op ){
01292     case TK_IN: {
01293       char affinity;
01294       KeyInfo keyInfo;
01295       int addr;        /* Address of OP_OpenEphemeral instruction */
01296       Expr *pLeft = pExpr->pLeft;
01297 
01298       if( rMayHaveNull ){
01299         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
01300       }
01301 
01302       affinity = sqlite3ExprAffinity(pLeft);
01303 
01304       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
01305       ** expression it is handled the same way. A virtual table is 
01306       ** filled with single-field index keys representing the results
01307       ** from the SELECT or the <exprlist>.
01308       **
01309       ** If the 'x' expression is a column value, or the SELECT...
01310       ** statement returns a column value, then the affinity of that
01311       ** column is used to build the index keys. If both 'x' and the
01312       ** SELECT... statement are columns, then numeric affinity is used
01313       ** if either column has NUMERIC or INTEGER affinity. If neither
01314       ** 'x' nor the SELECT... statement are columns, then numeric affinity
01315       ** is used.
01316       */
01317       pExpr->iTable = pParse->nTab++;
01318       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
01319       memset(&keyInfo, 0, sizeof(keyInfo));
01320       keyInfo.nField = 1;
01321 
01322       if( pExpr->pSelect ){
01323         /* Case 1:     expr IN (SELECT ...)
01324         **
01325         ** Generate code to write the results of the select into the temporary
01326         ** table allocated and opened above.
01327         */
01328         SelectDest dest;
01329         ExprList *pEList;
01330 
01331         assert( !isRowid );
01332         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
01333         dest.affinity = (int)affinity;
01334         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
01335         if( sqlite3Select(pParse, pExpr->pSelect, &dest) ){
01336           return;
01337         }
01338         pEList = pExpr->pSelect->pEList;
01339         if( pEList && pEList->nExpr>0 ){ 
01340           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
01341               pEList->a[0].pExpr);
01342         }
01343       }else if( pExpr->pList ){
01344         /* Case 2:     expr IN (exprlist)
01345         **
01346         ** For each expression, build an index key from the evaluation and
01347         ** store it in the temporary table. If <expr> is a column, then use
01348         ** that columns affinity when building index keys. If <expr> is not
01349         ** a column, use numeric affinity.
01350         */
01351         int i;
01352         ExprList *pList = pExpr->pList;
01353         struct ExprList_item *pItem;
01354         int r1, r2, r3;
01355 
01356         if( !affinity ){
01357           affinity = SQLITE_AFF_NONE;
01358         }
01359         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
01360 
01361         /* Loop through each expression in <exprlist>. */
01362         r1 = sqlite3GetTempReg(pParse);
01363         r2 = sqlite3GetTempReg(pParse);
01364         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
01365         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
01366           Expr *pE2 = pItem->pExpr;
01367 
01368           /* If the expression is not constant then we will need to
01369           ** disable the test that was generated above that makes sure
01370           ** this code only executes once.  Because for a non-constant
01371           ** expression we need to rerun this code each time.
01372           */
01373           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
01374             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
01375             testAddr = 0;
01376           }
01377 
01378           /* Evaluate the expression and insert it into the temp table */
01379           pParse->disableColCache++;
01380           r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
01381           assert( pParse->disableColCache>0 );
01382           pParse->disableColCache--;
01383 
01384           if( isRowid ){
01385             sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
01386             sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
01387           }else{
01388             sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
01389             sqlite3ExprCacheAffinityChange(pParse, r3, 1);
01390             sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
01391           }
01392         }
01393         sqlite3ReleaseTempReg(pParse, r1);
01394         sqlite3ReleaseTempReg(pParse, r2);
01395       }
01396       if( !isRowid ){
01397         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
01398       }
01399       break;
01400     }
01401 
01402     case TK_EXISTS:
01403     case TK_SELECT: {
01404       /* This has to be a scalar SELECT.  Generate code to put the
01405       ** value of this select in a memory cell and record the number
01406       ** of the memory cell in iColumn.
01407       */
01408       static const Token one = { (u8*)"1", 0, 1 };
01409       Select *pSel;
01410       SelectDest dest;
01411 
01412       pSel = pExpr->pSelect;
01413       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
01414       if( pExpr->op==TK_SELECT ){
01415         dest.eDest = SRT_Mem;
01416         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
01417         VdbeComment((v, "Init subquery result"));
01418       }else{
01419         dest.eDest = SRT_Exists;
01420         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
01421         VdbeComment((v, "Init EXISTS result"));
01422       }
01423       sqlite3ExprDelete(pParse->db, pSel->pLimit);
01424       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
01425       if( sqlite3Select(pParse, pSel, &dest) ){
01426         return;
01427       }
01428       pExpr->iColumn = dest.iParm;
01429       break;
01430     }
01431   }
01432 
01433   if( testAddr ){
01434     sqlite3VdbeJumpHere(v, testAddr-1);
01435   }
01436 
01437   return;
01438 }
01439 #endif /* SQLITE_OMIT_SUBQUERY */
01440 
01441 /*
01442 ** Duplicate an 8-byte value
01443 */
01444 static char *dup8bytes(Vdbe *v, const char *in){
01445   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
01446   if( out ){
01447     memcpy(out, in, 8);
01448   }
01449   return out;
01450 }
01451 
01452 /*
01453 ** Generate an instruction that will put the floating point
01454 ** value described by z[0..n-1] into register iMem.
01455 **
01456 ** The z[] string will probably not be zero-terminated.  But the 
01457 ** z[n] character is guaranteed to be something that does not look
01458 ** like the continuation of the number.
01459 */
01460 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
01461   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
01462   if( z ){
01463     double value;
01464     char *zV;
01465     assert( !isdigit(z[n]) );
01466     sqlite3AtoF(z, &value);
01467     if( sqlite3IsNaN(value) ){
01468       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
01469     }else{
01470       if( negateFlag ) value = -value;
01471       zV = dup8bytes(v, (char*)&value);
01472       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
01473     }
01474   }
01475 }
01476 
01477 
01478 /*
01479 ** Generate an instruction that will put the integer describe by
01480 ** text z[0..n-1] into register iMem.
01481 **
01482 ** The z[] string will probably not be zero-terminated.  But the 
01483 ** z[n] character is guaranteed to be something that does not look
01484 ** like the continuation of the number.
01485 */
01486 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
01487   const char *z;
01488   if( pExpr->flags & EP_IntValue ){
01489     int i = pExpr->iTable;
01490     if( negFlag ) i = -i;
01491     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
01492   }else if( (z = (char*)pExpr->token.z)!=0 ){
01493     int i;
01494     int n = pExpr->token.n;
01495     assert( !isdigit(z[n]) );
01496     if( sqlite3GetInt32(z, &i) ){
01497       if( negFlag ) i = -i;
01498       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
01499     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
01500       i64 value;
01501       char *zV;
01502       sqlite3Atoi64(z, &value);
01503       if( negFlag ) value = -value;
01504       zV = dup8bytes(v, (char*)&value);
01505       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
01506     }else{
01507       codeReal(v, z, n, negFlag, iMem);
01508     }
01509   }
01510 }
01511 
01512 
01513 /*
01514 ** Generate code that will extract the iColumn-th column from
01515 ** table pTab and store the column value in a register.  An effort
01516 ** is made to store the column value in register iReg, but this is
01517 ** not guaranteed.  The location of the column value is returned.
01518 **
01519 ** There must be an open cursor to pTab in iTable when this routine
01520 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
01521 **
01522 ** This routine might attempt to reuse the value of the column that
01523 ** has already been loaded into a register.  The value will always
01524 ** be used if it has not undergone any affinity changes.  But if
01525 ** an affinity change has occurred, then the cached value will only be
01526 ** used if allowAffChng is true.
01527 */
01528 int sqlite3ExprCodeGetColumn(
01529   Parse *pParse,   /* Parsing and code generating context */
01530   Table *pTab,     /* Description of the table we are reading from */
01531   int iColumn,     /* Index of the table column */
01532   int iTable,      /* The cursor pointing to the table */
01533   int iReg,        /* Store results here */
01534   int allowAffChng /* True if prior affinity changes are OK */
01535 ){
01536   Vdbe *v = pParse->pVdbe;
01537   int i;
01538   struct yColCache *p;
01539 
01540   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
01541     if( p->iTable==iTable && p->iColumn==iColumn
01542            && (!p->affChange || allowAffChng) ){
01543 #if 0
01544       sqlite3VdbeAddOp0(v, OP_Noop);
01545       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
01546 #endif
01547       return p->iReg;
01548     }
01549   }  
01550   assert( v!=0 );
01551   if( iColumn<0 ){
01552     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
01553     sqlite3VdbeAddOp2(v, op, iTable, iReg);
01554   }else if( pTab==0 ){
01555     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
01556   }else{
01557     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
01558     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
01559     sqlite3ColumnDefault(v, pTab, iColumn);
01560 #ifndef SQLITE_OMIT_FLOATING_POINT
01561     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
01562       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
01563     }
01564 #endif
01565   }
01566   if( pParse->disableColCache==0 ){
01567     i = pParse->iColCache;
01568     p = &pParse->aColCache[i];
01569     p->iTable = iTable;
01570     p->iColumn = iColumn;
01571     p->iReg = iReg;
01572     p->affChange = 0;
01573     i++;
01574     if( i>=ArraySize(pParse->aColCache) ) i = 0;
01575     if( i>pParse->nColCache ) pParse->nColCache = i;
01576     pParse->iColCache = i;
01577   }
01578   return iReg;
01579 }
01580 
01581 /*
01582 ** Clear all column cache entries associated with the vdbe
01583 ** cursor with cursor number iTable.
01584 */
01585 void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
01586   if( iTable<0 ){
01587     pParse->nColCache = 0;
01588     pParse->iColCache = 0;
01589   }else{
01590     int i;
01591     for(i=0; i<pParse->nColCache; i++){
01592       if( pParse->aColCache[i].iTable==iTable ){
01593         testcase( i==pParse->nColCache-1 );
01594         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
01595         pParse->iColCache = pParse->nColCache;
01596       }
01597     }
01598   }
01599 }
01600 
01601 /*
01602 ** Record the fact that an affinity change has occurred on iCount
01603 ** registers starting with iStart.
01604 */
01605 void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
01606   int iEnd = iStart + iCount - 1;
01607   int i;
01608   for(i=0; i<pParse->nColCache; i++){
01609     int r = pParse->aColCache[i].iReg;
01610     if( r>=iStart && r<=iEnd ){
01611       pParse->aColCache[i].affChange = 1;
01612     }
01613   }
01614 }
01615 
01616 /*
01617 ** Generate code to move content from registers iFrom...iFrom+nReg-1
01618 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
01619 */
01620 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
01621   int i;
01622   if( iFrom==iTo ) return;
01623   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
01624   for(i=0; i<pParse->nColCache; i++){
01625     int x = pParse->aColCache[i].iReg;
01626     if( x>=iFrom && x<iFrom+nReg ){
01627       pParse->aColCache[i].iReg += iTo-iFrom;
01628     }
01629   }
01630 }
01631 
01632 /*
01633 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
01634 ** over to iTo..iTo+nReg-1.
01635 */
01636 void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
01637   int i;
01638   if( iFrom==iTo ) return;
01639   for(i=0; i<nReg; i++){
01640     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
01641   }
01642 }
01643 
01644 /*
01645 ** Return true if any register in the range iFrom..iTo (inclusive)
01646 ** is used as part of the column cache.
01647 */
01648 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
01649   int i;
01650   for(i=0; i<pParse->nColCache; i++){
01651     int r = pParse->aColCache[i].iReg;
01652     if( r>=iFrom && r<=iTo ) return 1;
01653   }
01654   return 0;
01655 }
01656 
01657 /*
01658 ** Theres is a value in register iCurrent.  We ultimately want
01659 ** the value to be in register iTarget.  It might be that
01660 ** iCurrent and iTarget are the same register.
01661 **
01662 ** We are going to modify the value, so we need to make sure it
01663 ** is not a cached register.  If iCurrent is a cached register,
01664 ** then try to move the value over to iTarget.  If iTarget is a
01665 ** cached register, then clear the corresponding cache line.
01666 **
01667 ** Return the register that the value ends up in.
01668 */
01669 int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
01670   int i;
01671   assert( pParse->pVdbe!=0 );
01672   if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
01673     return iCurrent;
01674   }
01675   if( iCurrent!=iTarget ){
01676     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
01677   }
01678   for(i=0; i<pParse->nColCache; i++){
01679     if( pParse->aColCache[i].iReg==iTarget ){
01680       pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
01681       pParse->iColCache = pParse->nColCache;
01682     }
01683   }
01684   return iTarget;
01685 }
01686 
01687 /*
01688 ** If the last instruction coded is an ephemeral copy of any of
01689 ** the registers in the nReg registers beginning with iReg, then
01690 ** convert the last instruction from OP_SCopy to OP_Copy.
01691 */
01692 void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
01693   int addr;
01694   VdbeOp *pOp;
01695   Vdbe *v;
01696 
01697   v = pParse->pVdbe;
01698   addr = sqlite3VdbeCurrentAddr(v);
01699   pOp = sqlite3VdbeGetOp(v, addr-1);
01700   assert( pOp || pParse->db->mallocFailed );
01701   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
01702     pOp->opcode = OP_Copy;
01703   }
01704 }
01705 
01706 /*
01707 ** Generate code to store the value of the iAlias-th alias in register
01708 ** target.  The first time this is called, pExpr is evaluated to compute
01709 ** the value of the alias.  The value is stored in an auxiliary register
01710 ** and the number of that register is returned.  On subsequent calls,
01711 ** the register number is returned without generating any code.
01712 **
01713 ** Note that in order for this to work, code must be generated in the
01714 ** same order that it is executed.
01715 **
01716 ** Aliases are numbered starting with 1.  So iAlias is in the range
01717 ** of 1 to pParse->nAlias inclusive.  
01718 **
01719 ** pParse->aAlias[iAlias-1] records the register number where the value
01720 ** of the iAlias-th alias is stored.  If zero, that means that the
01721 ** alias has not yet been computed.
01722 */
01723 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
01724   sqlite3 *db = pParse->db;
01725   int iReg;
01726   if( pParse->aAlias==0 ){
01727     pParse->aAlias = sqlite3DbMallocZero(db, 
01728                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
01729     if( db->mallocFailed ) return 0;
01730   }
01731   assert( iAlias>0 && iAlias<=pParse->nAlias );
01732   iReg = pParse->aAlias[iAlias-1];
01733   if( iReg==0 ){
01734     if( pParse->disableColCache ){
01735       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
01736     }else{
01737       iReg = ++pParse->nMem;
01738       sqlite3ExprCode(pParse, pExpr, iReg);
01739       pParse->aAlias[iAlias-1] = iReg;
01740     }
01741   }
01742   return iReg;
01743 }
01744 
01745 /*
01746 ** Generate code into the current Vdbe to evaluate the given
01747 ** expression.  Attempt to store the results in register "target".
01748 ** Return the register where results are stored.
01749 **
01750 ** With this routine, there is no guarantee that results will
01751 ** be stored in target.  The result might be stored in some other
01752 ** register if it is convenient to do so.  The calling function
01753 ** must check the return code and move the results to the desired
01754 ** register.
01755 */
01756 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
01757   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
01758   int op;                   /* The opcode being coded */
01759   int inReg = target;       /* Results stored in register inReg */
01760   int regFree1 = 0;         /* If non-zero free this temporary register */
01761   int regFree2 = 0;         /* If non-zero free this temporary register */
01762   int r1, r2, r3, r4;       /* Various register numbers */
01763   sqlite3 *db;
01764 
01765   db = pParse->db;
01766   assert( v!=0 || db->mallocFailed );
01767   assert( target>0 && target<=pParse->nMem );
01768   if( v==0 ) return 0;
01769 
01770   if( pExpr==0 ){
01771     op = TK_NULL;
01772   }else{
01773     op = pExpr->op;
01774   }
01775   switch( op ){
01776     case TK_AGG_COLUMN: {
01777       AggInfo *pAggInfo = pExpr->pAggInfo;
01778       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
01779       if( !pAggInfo->directMode ){
01780         assert( pCol->iMem>0 );
01781         inReg = pCol->iMem;
01782         break;
01783       }else if( pAggInfo->useSortingIdx ){
01784         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
01785                               pCol->iSorterColumn, target);
01786         break;
01787       }
01788       /* Otherwise, fall thru into the TK_COLUMN case */
01789     }
01790     case TK_COLUMN: {
01791       if( pExpr->iTable<0 ){
01792         /* This only happens when coding check constraints */
01793         assert( pParse->ckBase>0 );
01794         inReg = pExpr->iColumn + pParse->ckBase;
01795       }else{
01796         testcase( (pExpr->flags & EP_AnyAff)!=0 );
01797         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
01798                                  pExpr->iColumn, pExpr->iTable, target,
01799                                  pExpr->flags & EP_AnyAff);
01800       }
01801       break;
01802     }
01803     case TK_INTEGER: {
01804       codeInteger(v, pExpr, 0, target);
01805       break;
01806     }
01807     case TK_FLOAT: {
01808       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
01809       break;
01810     }
01811     case TK_STRING: {
01812       sqlite3DequoteExpr(db, pExpr);
01813       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
01814                         (char*)pExpr->token.z, pExpr->token.n);
01815       break;
01816     }
01817     case TK_NULL: {
01818       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
01819       break;
01820     }
01821 #ifndef SQLITE_OMIT_BLOB_LITERAL
01822     case TK_BLOB: {
01823       int n;
01824       const char *z;
01825       char *zBlob;
01826       assert( pExpr->token.n>=3 );
01827       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
01828       assert( pExpr->token.z[1]=='\'' );
01829       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
01830       n = pExpr->token.n - 3;
01831       z = (char*)pExpr->token.z + 2;
01832       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
01833       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
01834       break;
01835     }
01836 #endif
01837     case TK_VARIABLE: {
01838       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
01839       if( pExpr->token.n>1 ){
01840         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
01841       }
01842       break;
01843     }
01844     case TK_REGISTER: {
01845       inReg = pExpr->iTable;
01846       break;
01847     }
01848     case TK_AS: {
01849       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
01850       break;
01851     }
01852 #ifndef SQLITE_OMIT_CAST
01853     case TK_CAST: {
01854       /* Expressions of the form:   CAST(pLeft AS token) */
01855       int aff, to_op;
01856       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
01857       aff = sqlite3AffinityType(&pExpr->token);
01858       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
01859       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
01860       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
01861       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
01862       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
01863       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
01864       testcase( to_op==OP_ToText );
01865       testcase( to_op==OP_ToBlob );
01866       testcase( to_op==OP_ToNumeric );
01867       testcase( to_op==OP_ToInt );
01868       testcase( to_op==OP_ToReal );
01869       if( inReg!=target ){
01870         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
01871         inReg = target;
01872       }
01873       sqlite3VdbeAddOp1(v, to_op, inReg);
01874       testcase( usedAsColumnCache(pParse, inReg, inReg) );
01875       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
01876       break;
01877     }
01878 #endif /* SQLITE_OMIT_CAST */
01879     case TK_LT:
01880     case TK_LE:
01881     case TK_GT:
01882     case TK_GE:
01883     case TK_NE:
01884     case TK_EQ: {
01885       assert( TK_LT==OP_Lt );
01886       assert( TK_LE==OP_Le );
01887       assert( TK_GT==OP_Gt );
01888       assert( TK_GE==OP_Ge );
01889       assert( TK_EQ==OP_Eq );
01890       assert( TK_NE==OP_Ne );
01891       testcase( op==TK_LT );
01892       testcase( op==TK_LE );
01893       testcase( op==TK_GT );
01894       testcase( op==TK_GE );
01895       testcase( op==TK_EQ );
01896       testcase( op==TK_NE );
01897       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
01898                                   pExpr->pRight, &r2, &regFree2);
01899       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
01900                   r1, r2, inReg, SQLITE_STOREP2);
01901       testcase( regFree1==0 );
01902       testcase( regFree2==0 );
01903       break;
01904     }
01905     case TK_AND:
01906     case TK_OR:
01907     case TK_PLUS:
01908     case TK_STAR:
01909     case TK_MINUS:
01910     case TK_REM:
01911     case TK_BITAND:
01912     case TK_BITOR:
01913     case TK_SLASH:
01914     case TK_LSHIFT:
01915     case TK_RSHIFT: 
01916     case TK_CONCAT: {
01917       assert( TK_AND==OP_And );
01918       assert( TK_OR==OP_Or );
01919       assert( TK_PLUS==OP_Add );
01920       assert( TK_MINUS==OP_Subtract );
01921       assert( TK_REM==OP_Remainder );
01922       assert( TK_BITAND==OP_BitAnd );
01923       assert( TK_BITOR==OP_BitOr );
01924       assert( TK_SLASH==OP_Divide );
01925       assert( TK_LSHIFT==OP_ShiftLeft );
01926       assert( TK_RSHIFT==OP_ShiftRight );
01927       assert( TK_CONCAT==OP_Concat );
01928       testcase( op==TK_AND );
01929       testcase( op==TK_OR );
01930       testcase( op==TK_PLUS );
01931       testcase( op==TK_MINUS );
01932       testcase( op==TK_REM );
01933       testcase( op==TK_BITAND );
01934       testcase( op==TK_BITOR );
01935       testcase( op==TK_SLASH );
01936       testcase( op==TK_LSHIFT );
01937       testcase( op==TK_RSHIFT );
01938       testcase( op==TK_CONCAT );
01939       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
01940       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
01941       sqlite3VdbeAddOp3(v, op, r2, r1, target);
01942       testcase( regFree1==0 );
01943       testcase( regFree2==0 );
01944       break;
01945     }
01946     case TK_UMINUS: {
01947       Expr *pLeft = pExpr->pLeft;
01948       assert( pLeft );
01949       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
01950         if( pLeft->op==TK_FLOAT ){
01951           codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
01952         }else{
01953           codeInteger(v, pLeft, 1, target);
01954         }
01955       }else{
01956         regFree1 = r1 = sqlite3GetTempReg(pParse);
01957         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
01958         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
01959         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
01960         testcase( regFree2==0 );
01961       }
01962       inReg = target;
01963       break;
01964     }
01965     case TK_BITNOT:
01966     case TK_NOT: {
01967       assert( TK_BITNOT==OP_BitNot );
01968       assert( TK_NOT==OP_Not );
01969       testcase( op==TK_BITNOT );
01970       testcase( op==TK_NOT );
01971       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
01972       testcase( inReg==target );
01973       testcase( usedAsColumnCache(pParse, inReg, inReg) );
01974       inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
01975       sqlite3VdbeAddOp1(v, op, inReg);
01976       break;
01977     }
01978     case TK_ISNULL:
01979     case TK_NOTNULL: {
01980       int addr;
01981       assert( TK_ISNULL==OP_IsNull );
01982       assert( TK_NOTNULL==OP_NotNull );
01983       testcase( op==TK_ISNULL );
01984       testcase( op==TK_NOTNULL );
01985       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
01986       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
01987       testcase( regFree1==0 );
01988       addr = sqlite3VdbeAddOp1(v, op, r1);
01989       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
01990       sqlite3VdbeJumpHere(v, addr);
01991       break;
01992     }
01993     case TK_AGG_FUNCTION: {
01994       AggInfo *pInfo = pExpr->pAggInfo;
01995       if( pInfo==0 ){
01996         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
01997             &pExpr->span);
01998       }else{
01999         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
02000       }
02001       break;
02002     }
02003     case TK_CONST_FUNC:
02004     case TK_FUNCTION: {
02005       ExprList *pList = pExpr->pList;
02006       int nExpr = pList ? pList->nExpr : 0;
02007       FuncDef *pDef;
02008       int nId;
02009       const char *zId;
02010       int constMask = 0;
02011       int i;
02012       u8 enc = ENC(db);
02013       CollSeq *pColl = 0;
02014 
02015       testcase( op==TK_CONST_FUNC );
02016       testcase( op==TK_FUNCTION );
02017       zId = (char*)pExpr->token.z;
02018       nId = pExpr->token.n;
02019       pDef = sqlite3FindFunction(db, zId, nId, nExpr, enc, 0);
02020       assert( pDef!=0 );
02021       if( pList ){
02022         nExpr = pList->nExpr;
02023         r1 = sqlite3GetTempRange(pParse, nExpr);
02024         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
02025       }else{
02026         nExpr = r1 = 0;
02027       }
02028 #ifndef SQLITE_OMIT_VIRTUALTABLE
02029       /* Possibly overload the function if the first argument is
02030       ** a virtual table column.
02031       **
02032       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
02033       ** second argument, not the first, as the argument to test to
02034       ** see if it is a column in a virtual table.  This is done because
02035       ** the left operand of infix functions (the operand we want to
02036       ** control overloading) ends up as the second argument to the
02037       ** function.  The expression "A glob B" is equivalent to 
02038       ** "glob(B,A).  We want to use the A in "A glob B" to test
02039       ** for function overloading.  But we use the B term in "glob(B,A)".
02040       */
02041       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
02042         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
02043       }else if( nExpr>0 ){
02044         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
02045       }
02046 #endif
02047       for(i=0; i<nExpr && i<32; i++){
02048         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
02049           constMask |= (1<<i);
02050         }
02051         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
02052           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
02053         }
02054       }
02055       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
02056         if( !pColl ) pColl = db->pDfltColl; 
02057         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
02058       }
02059       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
02060                         (char*)pDef, P4_FUNCDEF);
02061       sqlite3VdbeChangeP5(v, nExpr);
02062       if( nExpr ){
02063         sqlite3ReleaseTempRange(pParse, r1, nExpr);
02064       }
02065       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
02066       break;
02067     }
02068 #ifndef SQLITE_OMIT_SUBQUERY
02069     case TK_EXISTS:
02070     case TK_SELECT: {
02071       testcase( op==TK_EXISTS );
02072       testcase( op==TK_SELECT );
02073       if( pExpr->iColumn==0 ){
02074         sqlite3CodeSubselect(pParse, pExpr, 0, 0);
02075       }
02076       inReg = pExpr->iColumn;
02077       break;
02078     }
02079     case TK_IN: {
02080       int rNotFound = 0;
02081       int rMayHaveNull = 0;
02082       int j2, j3, j4, j5;
02083       char affinity;
02084       int eType;
02085 
02086       VdbeNoopComment((v, "begin IN expr r%d", target));
02087       eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
02088       if( rMayHaveNull ){
02089         rNotFound = ++pParse->nMem;
02090       }
02091 
02092       /* Figure out the affinity to use to create a key from the results
02093       ** of the expression. affinityStr stores a static string suitable for
02094       ** P4 of OP_MakeRecord.
02095       */
02096       affinity = comparisonAffinity(pExpr);
02097 
02098 
02099       /* Code the <expr> from "<expr> IN (...)". The temporary table
02100       ** pExpr->iTable contains the values that make up the (...) set.
02101       */
02102       pParse->disableColCache++;
02103       sqlite3ExprCode(pParse, pExpr->pLeft, target);
02104       pParse->disableColCache--;
02105       j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
02106       if( eType==IN_INDEX_ROWID ){
02107         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
02108         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
02109         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
02110         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
02111         sqlite3VdbeJumpHere(v, j3);
02112         sqlite3VdbeJumpHere(v, j4);
02113         sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
02114       }else{
02115         r2 = regFree2 = sqlite3GetTempReg(pParse);
02116 
02117         /* Create a record and test for set membership. If the set contains
02118         ** the value, then jump to the end of the test code. The target
02119         ** register still contains the true (1) value written to it earlier.
02120         */
02121         sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
02122         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
02123         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
02124 
02125         /* If the set membership test fails, then the result of the 
02126         ** "x IN (...)" expression must be either 0 or NULL. If the set
02127         ** contains no NULL values, then the result is 0. If the set 
02128         ** contains one or more NULL values, then the result of the
02129         ** expression is also NULL.
02130         */
02131         if( rNotFound==0 ){
02132           /* This branch runs if it is known at compile time (now) that 
02133           ** the set contains no NULL values. This happens as the result
02134           ** of a "NOT NULL" constraint in the database schema. No need
02135           ** to test the data structure at runtime in this case.
02136           */
02137           sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
02138         }else{
02139           /* This block populates the rNotFound register with either NULL
02140           ** or 0 (an integer value). If the data structure contains one
02141           ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
02142           ** to 0. If register rMayHaveNull is already set to some value
02143           ** other than NULL, then the test has already been run and 
02144           ** rNotFound is already populated.
02145           */
02146           static const char nullRecord[] = { 0x02, 0x00 };
02147           j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
02148           sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
02149           sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, 
02150                              nullRecord, P4_STATIC);
02151           j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
02152           sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
02153           sqlite3VdbeJumpHere(v, j4);
02154           sqlite3VdbeJumpHere(v, j3);
02155 
02156           /* Copy the value of register rNotFound (which is either NULL or 0)
02157           ** into the target register. This will be the result of the
02158           ** expression.
02159           */
02160           sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
02161         }
02162       }
02163       sqlite3VdbeJumpHere(v, j2);
02164       sqlite3VdbeJumpHere(v, j5);
02165       VdbeComment((v, "end IN expr r%d", target));
02166       break;
02167     }
02168 #endif
02169     /*
02170     **    x BETWEEN y AND z
02171     **
02172     ** This is equivalent to
02173     **
02174     **    x>=y AND x<=z
02175     **
02176     ** X is stored in pExpr->pLeft.
02177     ** Y is stored in pExpr->pList->a[0].pExpr.
02178     ** Z is stored in pExpr->pList->a[1].pExpr.
02179     */
02180     case TK_BETWEEN: {
02181       Expr *pLeft = pExpr->pLeft;
02182       struct ExprList_item *pLItem = pExpr->pList->a;
02183       Expr *pRight = pLItem->pExpr;
02184 
02185       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
02186                                   pRight, &r2, &regFree2);
02187       testcase( regFree1==0 );
02188       testcase( regFree2==0 );
02189       r3 = sqlite3GetTempReg(pParse);
02190       r4 = sqlite3GetTempReg(pParse);
02191       codeCompare(pParse, pLeft, pRight, OP_Ge,
02192                   r1, r2, r3, SQLITE_STOREP2);
02193       pLItem++;
02194       pRight = pLItem->pExpr;
02195       sqlite3ReleaseTempReg(pParse, regFree2);
02196       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
02197       testcase( regFree2==0 );
02198       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
02199       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
02200       sqlite3ReleaseTempReg(pParse, r3);
02201       sqlite3ReleaseTempReg(pParse, r4);
02202       break;
02203     }
02204     case TK_UPLUS: {
02205       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
02206       break;
02207     }
02208 
02209     /*
02210     ** Form A:
02211     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
02212     **
02213     ** Form B:
02214     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
02215     **
02216     ** Form A is can be transformed into the equivalent form B as follows:
02217     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
02218     **        WHEN x=eN THEN rN ELSE y END
02219     **
02220     ** X (if it exists) is in pExpr->pLeft.
02221     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
02222     ** ELSE clause and no other term matches, then the result of the
02223     ** exprssion is NULL.
02224     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
02225     **
02226     ** The result of the expression is the Ri for the first matching Ei,
02227     ** or if there is no matching Ei, the ELSE term Y, or if there is
02228     ** no ELSE term, NULL.
02229     */
02230     case TK_CASE: {
02231       int endLabel;                     /* GOTO label for end of CASE stmt */
02232       int nextCase;                     /* GOTO label for next WHEN clause */
02233       int nExpr;                        /* 2x number of WHEN terms */
02234       int i;                            /* Loop counter */
02235       ExprList *pEList;                 /* List of WHEN terms */
02236       struct ExprList_item *aListelem;  /* Array of WHEN terms */
02237       Expr opCompare;                   /* The X==Ei expression */
02238       Expr cacheX;                      /* Cached expression X */
02239       Expr *pX;                         /* The X expression */
02240       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
02241 
02242       assert(pExpr->pList);
02243       assert((pExpr->pList->nExpr % 2) == 0);
02244       assert(pExpr->pList->nExpr > 0);
02245       pEList = pExpr->pList;
02246       aListelem = pEList->a;
02247       nExpr = pEList->nExpr;
02248       endLabel = sqlite3VdbeMakeLabel(v);
02249       if( (pX = pExpr->pLeft)!=0 ){
02250         cacheX = *pX;
02251         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
02252         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
02253         testcase( regFree1==0 );
02254         cacheX.op = TK_REGISTER;
02255         opCompare.op = TK_EQ;
02256         opCompare.pLeft = &cacheX;
02257         pTest = &opCompare;
02258       }
02259       pParse->disableColCache++;
02260       for(i=0; i<nExpr; i=i+2){
02261         if( pX ){
02262           opCompare.pRight = aListelem[i].pExpr;
02263         }else{
02264           pTest = aListelem[i].pExpr;
02265         }
02266         nextCase = sqlite3VdbeMakeLabel(v);
02267         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
02268         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
02269         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
02270         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
02271         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
02272         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
02273         sqlite3VdbeResolveLabel(v, nextCase);
02274       }
02275       if( pExpr->pRight ){
02276         sqlite3ExprCode(pParse, pExpr->pRight, target);
02277       }else{
02278         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
02279       }
02280       sqlite3VdbeResolveLabel(v, endLabel);
02281       assert( pParse->disableColCache>0 );
02282       pParse->disableColCache--;
02283       break;
02284     }
02285 #ifndef SQLITE_OMIT_TRIGGER
02286     case TK_RAISE: {
02287       if( !pParse->trigStack ){
02288         sqlite3ErrorMsg(pParse,
02289                        "RAISE() may only be used within a trigger-program");
02290         return 0;
02291       }
02292       if( pExpr->iColumn!=OE_Ignore ){
02293          assert( pExpr->iColumn==OE_Rollback ||
02294                  pExpr->iColumn == OE_Abort ||
02295                  pExpr->iColumn == OE_Fail );
02296          sqlite3DequoteExpr(db, pExpr);
02297          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
02298                         (char*)pExpr->token.z, pExpr->token.n);
02299       } else {
02300          assert( pExpr->iColumn == OE_Ignore );
02301          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
02302          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
02303          VdbeComment((v, "raise(IGNORE)"));
02304       }
02305       break;
02306     }
02307 #endif
02308   }
02309   sqlite3ReleaseTempReg(pParse, regFree1);
02310   sqlite3ReleaseTempReg(pParse, regFree2);
02311   return inReg;
02312 }
02313 
02314 /*
02315 ** Generate code to evaluate an expression and store the results
02316 ** into a register.  Return the register number where the results
02317 ** are stored.
02318 **
02319 ** If the register is a temporary register that can be deallocated,
02320 ** then write its number into *pReg.  If the result register is not
02321 ** a temporary, then set *pReg to zero.
02322 */
02323 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
02324   int r1 = sqlite3GetTempReg(pParse);
02325   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
02326   if( r2==r1 ){
02327     *pReg = r1;
02328   }else{
02329     sqlite3ReleaseTempReg(pParse, r1);
02330     *pReg = 0;
02331   }
02332   return r2;
02333 }
02334 
02335 /*
02336 ** Generate code that will evaluate expression pExpr and store the
02337 ** results in register target.  The results are guaranteed to appear
02338 ** in register target.
02339 */
02340 int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
02341   int inReg;
02342 
02343   assert( target>0 && target<=pParse->nMem );
02344   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
02345   assert( pParse->pVdbe || pParse->db->mallocFailed );
02346   if( inReg!=target && pParse->pVdbe ){
02347     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
02348   }
02349   return target;
02350 }
02351 
02352 /*
02353 ** Generate code that evalutes the given expression and puts the result
02354 ** in register target.
02355 **
02356 ** Also make a copy of the expression results into another "cache" register
02357 ** and modify the expression so that the next time it is evaluated,
02358 ** the result is a copy of the cache register.
02359 **
02360 ** This routine is used for expressions that are used multiple 
02361 ** times.  They are evaluated once and the results of the expression
02362 ** are reused.
02363 */
02364 int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
02365   Vdbe *v = pParse->pVdbe;
02366   int inReg;
02367   inReg = sqlite3ExprCode(pParse, pExpr, target);
02368   assert( target>0 );
02369   if( pExpr->op!=TK_REGISTER ){  
02370     int iMem;
02371     iMem = ++pParse->nMem;
02372     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
02373     pExpr->iTable = iMem;
02374     pExpr->op = TK_REGISTER;
02375   }
02376   return inReg;
02377 }
02378 
02379 /*
02380 ** Return TRUE if pExpr is an constant expression that is appropriate
02381 ** for factoring out of a loop.  Appropriate expressions are:
02382 **
02383 **    *  Any expression that evaluates to two or more opcodes.
02384 **
02385 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
02386 **       or OP_Variable that does not need to be placed in a 
02387 **       specific register.
02388 **
02389 ** There is no point in factoring out single-instruction constant
02390 ** expressions that need to be placed in a particular register.  
02391 ** We could factor them out, but then we would end up adding an
02392 ** OP_SCopy instruction to move the value into the correct register
02393 ** later.  We might as well just use the original instruction and
02394 ** avoid the OP_SCopy.
02395 */
02396 static int isAppropriateForFactoring(Expr *p){
02397   if( !sqlite3ExprIsConstantNotJoin(p) ){
02398     return 0;  /* Only constant expressions are appropriate for factoring */
02399   }
02400   if( (p->flags & EP_FixedDest)==0 ){
02401     return 1;  /* Any constant without a fixed destination is appropriate */
02402   }
02403   while( p->op==TK_UPLUS ) p = p->pLeft;
02404   switch( p->op ){
02405 #ifndef SQLITE_OMIT_BLOB_LITERAL
02406     case TK_BLOB:
02407 #endif
02408     case TK_VARIABLE:
02409     case TK_INTEGER:
02410     case TK_FLOAT:
02411     case TK_NULL:
02412     case TK_STRING: {
02413       testcase( p->op==TK_BLOB );
02414       testcase( p->op==TK_VARIABLE );
02415       testcase( p->op==TK_INTEGER );
02416       testcase( p->op==TK_FLOAT );
02417       testcase( p->op==TK_NULL );
02418       testcase( p->op==TK_STRING );
02419       /* Single-instruction constants with a fixed destination are
02420       ** better done in-line.  If we factor them, they will just end
02421       ** up generating an OP_SCopy to move the value to the destination
02422       ** register. */
02423       return 0;
02424     }
02425     case TK_UMINUS: {
02426        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
02427          return 0;
02428        }
02429        break;
02430     }
02431     default: {
02432       break;
02433     }
02434   }
02435   return 1;
02436 }
02437 
02438 /*
02439 ** If pExpr is a constant expression that is appropriate for
02440 ** factoring out of a loop, then evaluate the expression
02441 ** into a register and convert the expression into a TK_REGISTER
02442 ** expression.
02443 */
02444 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
02445   Parse *pParse = pWalker->pParse;
02446   switch( pExpr->op ){
02447     case TK_REGISTER: {
02448       return 1;
02449     }
02450     case TK_FUNCTION:
02451     case TK_AGG_FUNCTION:
02452     case TK_CONST_FUNC: {
02453       /* The arguments to a function have a fixed destination.
02454       ** Mark them this way to avoid generated unneeded OP_SCopy
02455       ** instructions. 
02456       */
02457       ExprList *pList = pExpr->pList;
02458       if( pList ){
02459         int i = pList->nExpr;
02460         struct ExprList_item *pItem = pList->a;
02461         for(; i>0; i--, pItem++){
02462           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
02463         }
02464       }
02465       break;
02466     }
02467   }
02468   if( isAppropriateForFactoring(pExpr) ){
02469     int r1 = ++pParse->nMem;
02470     int r2;
02471     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
02472     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
02473     pExpr->op = TK_REGISTER;
02474     pExpr->iTable = r2;
02475     return WRC_Prune;
02476   }
02477   return WRC_Continue;
02478 }
02479 
02480 /*
02481 ** Preevaluate constant subexpressions within pExpr and store the
02482 ** results in registers.  Modify pExpr so that the constant subexpresions
02483 ** are TK_REGISTER opcodes that refer to the precomputed values.
02484 */
02485 void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
02486   Walker w;
02487   w.xExprCallback = evalConstExpr;
02488   w.xSelectCallback = 0;
02489   w.pParse = pParse;
02490   sqlite3WalkExpr(&w, pExpr);
02491 }
02492 
02493 
02494 /*
02495 ** Generate code that pushes the value of every element of the given
02496 ** expression list into a sequence of registers beginning at target.
02497 **
02498 ** Return the number of elements evaluated.
02499 */
02500 int sqlite3ExprCodeExprList(
02501   Parse *pParse,     /* Parsing context */
02502   ExprList *pList,   /* The expression list to be coded */
02503   int target,        /* Where to write results */
02504   int doHardCopy     /* Make a hard copy of every element */
02505 ){
02506   struct ExprList_item *pItem;
02507   int i, n;
02508   assert( pList!=0 );
02509   assert( target>0 );
02510   n = pList->nExpr;
02511   for(pItem=pList->a, i=0; i<n; i++, pItem++){
02512     if( pItem->iAlias ){
02513       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
02514       Vdbe *v = sqlite3GetVdbe(pParse);
02515       if( iReg!=target+i ){
02516         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
02517       }
02518     }else{
02519       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
02520     }
02521     if( doHardCopy ){
02522       sqlite3ExprHardCopy(pParse, target, n);
02523     }
02524   }
02525   return n;
02526 }
02527 
02528 /*
02529 ** Generate code for a boolean expression such that a jump is made
02530 ** to the label "dest" if the expression is true but execution
02531 ** continues straight thru if the expression is false.
02532 **
02533 ** If the expression evaluates to NULL (neither true nor false), then
02534 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
02535 **
02536 ** This code depends on the fact that certain token values (ex: TK_EQ)
02537 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
02538 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
02539 ** the make process cause these values to align.  Assert()s in the code
02540 ** below verify that the numbers are aligned correctly.
02541 */
02542 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
02543   Vdbe *v = pParse->pVdbe;
02544   int op = 0;
02545   int regFree1 = 0;
02546   int regFree2 = 0;
02547   int r1, r2;
02548 
02549   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
02550   if( v==0 || pExpr==0 ) return;
02551   op = pExpr->op;
02552   switch( op ){
02553     case TK_AND: {
02554       int d2 = sqlite3VdbeMakeLabel(v);
02555       testcase( jumpIfNull==0 );
02556       testcase( pParse->disableColCache==0 );
02557       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
02558       pParse->disableColCache++;
02559       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
02560       assert( pParse->disableColCache>0 );
02561       pParse->disableColCache--;
02562       sqlite3VdbeResolveLabel(v, d2);
02563       break;
02564     }
02565     case TK_OR: {
02566       testcase( jumpIfNull==0 );
02567       testcase( pParse->disableColCache==0 );
02568       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
02569       pParse->disableColCache++;
02570       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
02571       assert( pParse->disableColCache>0 );
02572       pParse->disableColCache--;
02573       break;
02574     }
02575     case TK_NOT: {
02576       testcase( jumpIfNull==0 );
02577       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
02578       break;
02579     }
02580     case TK_LT:
02581     case TK_LE:
02582     case TK_GT:
02583     case TK_GE:
02584     case TK_NE:
02585     case TK_EQ: {
02586       assert( TK_LT==OP_Lt );
02587       assert( TK_LE==OP_Le );
02588       assert( TK_GT==OP_Gt );
02589       assert( TK_GE==OP_Ge );
02590       assert( TK_EQ==OP_Eq );
02591       assert( TK_NE==OP_Ne );
02592       testcase( op==TK_LT );
02593       testcase( op==TK_LE );
02594       testcase( op==TK_GT );
02595       testcase( op==TK_GE );
02596       testcase( op==TK_EQ );
02597       testcase( op==TK_NE );
02598       testcase( jumpIfNull==0 );
02599       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
02600                                   pExpr->pRight, &r2, &regFree2);
02601       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
02602                   r1, r2, dest, jumpIfNull);
02603       testcase( regFree1==0 );
02604       testcase( regFree2==0 );
02605       break;
02606     }
02607     case TK_ISNULL:
02608     case TK_NOTNULL: {
02609       assert( TK_ISNULL==OP_IsNull );
02610       assert( TK_NOTNULL==OP_NotNull );
02611       testcase( op==TK_ISNULL );
02612       testcase( op==TK_NOTNULL );
02613       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
02614       sqlite3VdbeAddOp2(v, op, r1, dest);
02615       testcase( regFree1==0 );
02616       break;
02617     }
02618     case TK_BETWEEN: {
02619       /*    x BETWEEN y AND z
02620       **
02621       ** Is equivalent to 
02622       **
02623       **    x>=y AND x<=z
02624       **
02625       ** Code it as such, taking care to do the common subexpression
02626       ** elementation of x.
02627       */
02628       Expr exprAnd;
02629       Expr compLeft;
02630       Expr compRight;
02631       Expr exprX;
02632 
02633       exprX = *pExpr->pLeft;
02634       exprAnd.op = TK_AND;
02635       exprAnd.pLeft = &compLeft;
02636       exprAnd.pRight = &compRight;
02637       compLeft.op = TK_GE;
02638       compLeft.pLeft = &exprX;
02639       compLeft.pRight = pExpr->pList->a[0].pExpr;
02640       compRight.op = TK_LE;
02641       compRight.pLeft = &exprX;
02642       compRight.pRight = pExpr->pList->a[1].pExpr;
02643       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
02644       testcase( regFree1==0 );
02645       exprX.op = TK_REGISTER;
02646       testcase( jumpIfNull==0 );
02647       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
02648       break;
02649     }
02650     default: {
02651       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
02652       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
02653       testcase( regFree1==0 );
02654       testcase( jumpIfNull==0 );
02655       break;
02656     }
02657   }
02658   sqlite3ReleaseTempReg(pParse, regFree1);
02659   sqlite3ReleaseTempReg(pParse, regFree2);  
02660 }
02661 
02662 /*
02663 ** Generate code for a boolean expression such that a jump is made
02664 ** to the label "dest" if the expression is false but execution
02665 ** continues straight thru if the expression is true.
02666 **
02667 ** If the expression evaluates to NULL (neither true nor false) then
02668 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
02669 ** is 0.
02670 */
02671 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
02672   Vdbe *v = pParse->pVdbe;
02673   int op = 0;
02674   int regFree1 = 0;
02675   int regFree2 = 0;
02676   int r1, r2;
02677 
02678   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
02679   if( v==0 || pExpr==0 ) return;
02680 
02681   /* The value of pExpr->op and op are related as follows:
02682   **
02683   **       pExpr->op            op
02684   **       ---------          ----------
02685   **       TK_ISNULL          OP_NotNull
02686   **       TK_NOTNULL         OP_IsNull
02687   **       TK_NE              OP_Eq
02688   **       TK_EQ              OP_Ne
02689   **       TK_GT              OP_Le
02690   **       TK_LE              OP_Gt
02691   **       TK_GE              OP_Lt
02692   **       TK_LT              OP_Ge
02693   **
02694   ** For other values of pExpr->op, op is undefined and unused.
02695   ** The value of TK_ and OP_ constants are arranged such that we
02696   ** can compute the mapping above using the following expression.
02697   ** Assert()s verify that the computation is correct.
02698   */
02699   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
02700 
02701   /* Verify correct alignment of TK_ and OP_ constants
02702   */
02703   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
02704   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
02705   assert( pExpr->op!=TK_NE || op==OP_Eq );
02706   assert( pExpr->op!=TK_EQ || op==OP_Ne );
02707   assert( pExpr->op!=TK_LT || op==OP_Ge );
02708   assert( pExpr->op!=TK_LE || op==OP_Gt );
02709   assert( pExpr->op!=TK_GT || op==OP_Le );
02710   assert( pExpr->op!=TK_GE || op==OP_Lt );
02711 
02712   switch( pExpr->op ){
02713     case TK_AND: {
02714       testcase( jumpIfNull==0 );
02715       testcase( pParse->disableColCache==0 );
02716       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
02717       pParse->disableColCache++;
02718       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
02719       assert( pParse->disableColCache>0 );
02720       pParse->disableColCache--;
02721       break;
02722     }
02723     case TK_OR: {
02724       int d2 = sqlite3VdbeMakeLabel(v);
02725       testcase( jumpIfNull==0 );
02726       testcase( pParse->disableColCache==0 );
02727       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
02728       pParse->disableColCache++;
02729       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
02730       assert( pParse->disableColCache>0 );
02731       pParse->disableColCache--;
02732       sqlite3VdbeResolveLabel(v, d2);
02733       break;
02734     }
02735     case TK_NOT: {
02736       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
02737       break;
02738     }
02739     case TK_LT:
02740     case TK_LE:
02741     case TK_GT:
02742     case TK_GE:
02743     case TK_NE:
02744     case TK_EQ: {
02745       testcase( op==TK_LT );
02746       testcase( op==TK_LE );
02747       testcase( op==TK_GT );
02748       testcase( op==TK_GE );
02749       testcase( op==TK_EQ );
02750       testcase( op==TK_NE );
02751       testcase( jumpIfNull==0 );
02752       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
02753                                   pExpr->pRight, &r2, &regFree2);
02754       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
02755                   r1, r2, dest, jumpIfNull);
02756       testcase( regFree1==0 );
02757       testcase( regFree2==0 );
02758       break;
02759     }
02760     case TK_ISNULL:
02761     case TK_NOTNULL: {
02762       testcase( op==TK_ISNULL );
02763       testcase( op==TK_NOTNULL );
02764       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
02765       sqlite3VdbeAddOp2(v, op, r1, dest);
02766       testcase( regFree1==0 );
02767       break;
02768     }
02769     case TK_BETWEEN: {
02770       /*    x BETWEEN y AND z
02771       **
02772       ** Is equivalent to 
02773       **
02774       **    x>=y AND x<=z
02775       **
02776       ** Code it as such, taking care to do the common subexpression
02777       ** elementation of x.
02778       */
02779       Expr exprAnd;
02780       Expr compLeft;
02781       Expr compRight;
02782       Expr exprX;
02783 
02784       exprX = *pExpr->pLeft;
02785       exprAnd.op = TK_AND;
02786       exprAnd.pLeft = &compLeft;
02787       exprAnd.pRight = &compRight;
02788       compLeft.op = TK_GE;
02789       compLeft.pLeft = &exprX;
02790       compLeft.pRight = pExpr->pList->a[0].pExpr;
02791       compRight.op = TK_LE;
02792       compRight.pLeft = &exprX;
02793       compRight.pRight = pExpr->pList->a[1].pExpr;
02794       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
02795       testcase( regFree1==0 );
02796       exprX.op = TK_REGISTER;
02797       testcase( jumpIfNull==0 );
02798       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
02799       break;
02800     }
02801     default: {
02802       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
02803       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
02804       testcase( regFree1==0 );
02805       testcase( jumpIfNull==0 );
02806       break;
02807     }
02808   }
02809   sqlite3ReleaseTempReg(pParse, regFree1);
02810   sqlite3ReleaseTempReg(pParse, regFree2);
02811 }
02812 
02813 /*
02814 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
02815 ** if they are identical and return FALSE if they differ in any way.
02816 **
02817 ** Sometimes this routine will return FALSE even if the two expressions
02818 ** really are equivalent.  If we cannot prove that the expressions are
02819 ** identical, we return FALSE just to be safe.  So if this routine
02820 ** returns false, then you do not really know for certain if the two
02821 ** expressions are the same.  But if you get a TRUE return, then you
02822 ** can be sure the expressions are the same.  In the places where
02823 ** this routine is used, it does not hurt to get an extra FALSE - that
02824 ** just might result in some slightly slower code.  But returning
02825 ** an incorrect TRUE could lead to a malfunction.
02826 */
02827 int sqlite3ExprCompare(Expr *pA, Expr *pB){
02828   int i;
02829   if( pA==0||pB==0 ){
02830     return pB==pA;
02831   }
02832   if( pA->op!=pB->op ) return 0;
02833   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
02834   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
02835   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
02836   if( pA->pList ){
02837     if( pB->pList==0 ) return 0;
02838     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
02839     for(i=0; i<pA->pList->nExpr; i++){
02840       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
02841         return 0;
02842       }
02843     }
02844   }else if( pB->pList ){
02845     return 0;
02846   }
02847   if( pA->pSelect || pB->pSelect ) return 0;
02848   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
02849   if( pA->op!=TK_COLUMN && pA->token.z ){
02850     if( pB->token.z==0 ) return 0;
02851     if( pB->token.n!=pA->token.n ) return 0;
02852     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
02853       return 0;
02854     }
02855   }
02856   return 1;
02857 }
02858 
02859 
02860 /*
02861 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
02862 ** the new element.  Return a negative number if malloc fails.
02863 */
02864 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
02865   int i;
02866   pInfo->aCol = sqlite3ArrayAllocate(
02867        db,
02868        pInfo->aCol,
02869        sizeof(pInfo->aCol[0]),
02870        3,
02871        &pInfo->nColumn,
02872        &pInfo->nColumnAlloc,
02873        &i
02874   );
02875   return i;
02876 }    
02877 
02878 /*
02879 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
02880 ** the new element.  Return a negative number if malloc fails.
02881 */
02882 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
02883   int i;
02884   pInfo->aFunc = sqlite3ArrayAllocate(
02885        db, 
02886        pInfo->aFunc,
02887        sizeof(pInfo->aFunc[0]),
02888        3,
02889        &pInfo->nFunc,
02890        &pInfo->nFuncAlloc,
02891        &i
02892   );
02893   return i;
02894 }    
02895 
02896 /*
02897 ** This is the xExprCallback for a tree walker.  It is used to
02898 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
02899 ** for additional information.
02900 */
02901 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
02902   int i;
02903   NameContext *pNC = pWalker->u.pNC;
02904   Parse *pParse = pNC->pParse;
02905   SrcList *pSrcList = pNC->pSrcList;
02906   AggInfo *pAggInfo = pNC->pAggInfo;
02907 
02908   switch( pExpr->op ){
02909     case TK_AGG_COLUMN:
02910     case TK_COLUMN: {
02911       testcase( pExpr->op==TK_AGG_COLUMN );
02912       testcase( pExpr->op==TK_COLUMN );
02913       /* Check to see if the column is in one of the tables in the FROM
02914       ** clause of the aggregate query */
02915       if( pSrcList ){
02916         struct SrcList_item *pItem = pSrcList->a;
02917         for(i=0; i<pSrcList->nSrc; i++, pItem++){
02918           struct AggInfo_col *pCol;
02919           if( pExpr->iTable==pItem->iCursor ){
02920             /* If we reach this point, it means that pExpr refers to a table
02921             ** that is in the FROM clause of the aggregate query.  
02922             **
02923             ** Make an entry for the column in pAggInfo->aCol[] if there
02924             ** is not an entry there already.
02925             */
02926             int k;
02927             pCol = pAggInfo->aCol;
02928             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
02929               if( pCol->iTable==pExpr->iTable &&
02930                   pCol->iColumn==pExpr->iColumn ){
02931                 break;
02932               }
02933             }
02934             if( (k>=pAggInfo->nColumn)
02935              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
02936             ){
02937               pCol = &pAggInfo->aCol[k];
02938               pCol->pTab = pExpr->pTab;
02939               pCol->iTable = pExpr->iTable;
02940               pCol->iColumn = pExpr->iColumn;
02941               pCol->iMem = ++pParse->nMem;
02942               pCol->iSorterColumn = -1;
02943               pCol->pExpr = pExpr;
02944               if( pAggInfo->pGroupBy ){
02945                 int j, n;
02946                 ExprList *pGB = pAggInfo->pGroupBy;
02947                 struct ExprList_item *pTerm = pGB->a;
02948                 n = pGB->nExpr;
02949                 for(j=0; j<n; j++, pTerm++){
02950                   Expr *pE = pTerm->pExpr;
02951                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
02952                       pE->iColumn==pExpr->iColumn ){
02953                     pCol->iSorterColumn = j;
02954                     break;
02955                   }
02956                 }
02957               }
02958               if( pCol->iSorterColumn<0 ){
02959                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
02960               }
02961             }
02962             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
02963             ** because it was there before or because we just created it).
02964             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
02965             ** pAggInfo->aCol[] entry.
02966             */
02967             pExpr->pAggInfo = pAggInfo;
02968             pExpr->op = TK_AGG_COLUMN;
02969             pExpr->iAgg = k;
02970             break;
02971           } /* endif pExpr->iTable==pItem->iCursor */
02972         } /* end loop over pSrcList */
02973       }
02974       return WRC_Prune;
02975     }
02976     case TK_AGG_FUNCTION: {
02977       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
02978       ** to be ignored */
02979       if( pNC->nDepth==0 ){
02980         /* Check to see if pExpr is a duplicate of another aggregate 
02981         ** function that is already in the pAggInfo structure
02982         */
02983         struct AggInfo_func *pItem = pAggInfo->aFunc;
02984         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
02985           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
02986             break;
02987           }
02988         }
02989         if( i>=pAggInfo->nFunc ){
02990           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
02991           */
02992           u8 enc = ENC(pParse->db);
02993           i = addAggInfoFunc(pParse->db, pAggInfo);
02994           if( i>=0 ){
02995             pItem = &pAggInfo->aFunc[i];
02996             pItem->pExpr = pExpr;
02997             pItem->iMem = ++pParse->nMem;
02998             pItem->pFunc = sqlite3FindFunction(pParse->db,
02999                    (char*)pExpr->token.z, pExpr->token.n,
03000                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
03001             if( pExpr->flags & EP_Distinct ){
03002               pItem->iDistinct = pParse->nTab++;
03003             }else{
03004               pItem->iDistinct = -1;
03005             }
03006           }
03007         }
03008         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
03009         */
03010         pExpr->iAgg = i;
03011         pExpr->pAggInfo = pAggInfo;
03012         return WRC_Prune;
03013       }
03014     }
03015   }
03016   return WRC_Continue;
03017 }
03018 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
03019   NameContext *pNC = pWalker->u.pNC;
03020   if( pNC->nDepth==0 ){
03021     pNC->nDepth++;
03022     sqlite3WalkSelect(pWalker, pSelect);
03023     pNC->nDepth--;
03024     return WRC_Prune;
03025   }else{
03026     return WRC_Continue;
03027   }
03028 }
03029 
03030 /*
03031 ** Analyze the given expression looking for aggregate functions and
03032 ** for variables that need to be added to the pParse->aAgg[] array.
03033 ** Make additional entries to the pParse->aAgg[] array as necessary.
03034 **
03035 ** This routine should only be called after the expression has been
03036 ** analyzed by sqlite3ResolveExprNames().
03037 */
03038 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
03039   Walker w;
03040   w.xExprCallback = analyzeAggregate;
03041   w.xSelectCallback = analyzeAggregatesInSelect;
03042   w.u.pNC = pNC;
03043   sqlite3WalkExpr(&w, pExpr);
03044 }
03045 
03046 /*
03047 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
03048 ** expression list.  Return the number of errors.
03049 **
03050 ** If an error is found, the analysis is cut short.
03051 */
03052 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
03053   struct ExprList_item *pItem;
03054   int i;
03055   if( pList ){
03056     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
03057       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
03058     }
03059   }
03060 }
03061 
03062 /*
03063 ** Allocate or deallocate temporary use registers during code generation.
03064 */
03065 int sqlite3GetTempReg(Parse *pParse){
03066   if( pParse->nTempReg==0 ){
03067     return ++pParse->nMem;
03068   }
03069   return pParse->aTempReg[--pParse->nTempReg];
03070 }
03071 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
03072   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
03073     sqlite3ExprWritableRegister(pParse, iReg, iReg);
03074     pParse->aTempReg[pParse->nTempReg++] = iReg;
03075   }
03076 }
03077 
03078 /*
03079 ** Allocate or deallocate a block of nReg consecutive registers
03080 */
03081 int sqlite3GetTempRange(Parse *pParse, int nReg){
03082   int i, n;
03083   i = pParse->iRangeReg;
03084   n = pParse->nRangeReg;
03085   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
03086     pParse->iRangeReg += nReg;
03087     pParse->nRangeReg -= nReg;
03088   }else{
03089     i = pParse->nMem+1;
03090     pParse->nMem += nReg;
03091   }
03092   return i;
03093 }
03094 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
03095   if( nReg>pParse->nRangeReg ){
03096     pParse->nRangeReg = nReg;
03097     pParse->iRangeReg = iReg;
03098   }
03099 }

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:53 2011 by Doxygen 1.6.1