persistentstorage/sqlite3api/SQLite/expr.c
changeset 0 08ec8eefde2f
equal deleted inserted replaced
-1:000000000000 0:08ec8eefde2f
       
     1 /*
       
     2 ** 2001 September 15
       
     3 **
       
     4 ** The author disclaims copyright to this source code.  In place of
       
     5 ** a legal notice, here is a blessing:
       
     6 **
       
     7 **    May you do good and not evil.
       
     8 **    May you find forgiveness for yourself and forgive others.
       
     9 **    May you share freely, never taking more than you give.
       
    10 **
       
    11 *************************************************************************
       
    12 ** This file contains routines used for analyzing expressions and
       
    13 ** for generating VDBE code that evaluates expressions in SQLite.
       
    14 **
       
    15 ** $Id: expr.c,v 1.395 2008/10/02 13:50:56 danielk1977 Exp $
       
    16 */
       
    17 #include "sqliteInt.h"
       
    18 #include <ctype.h>
       
    19 
       
    20 /*
       
    21 ** Return the 'affinity' of the expression pExpr if any.
       
    22 **
       
    23 ** If pExpr is a column, a reference to a column via an 'AS' alias,
       
    24 ** or a sub-select with a column as the return value, then the 
       
    25 ** affinity of that column is returned. Otherwise, 0x00 is returned,
       
    26 ** indicating no affinity for the expression.
       
    27 **
       
    28 ** i.e. the WHERE clause expresssions in the following statements all
       
    29 ** have an affinity:
       
    30 **
       
    31 ** CREATE TABLE t1(a);
       
    32 ** SELECT * FROM t1 WHERE a;
       
    33 ** SELECT a AS b FROM t1 WHERE b;
       
    34 ** SELECT * FROM t1 WHERE (select a from t1);
       
    35 */
       
    36 char sqlite3ExprAffinity(Expr *pExpr){
       
    37   int op = pExpr->op;
       
    38   if( op==TK_SELECT ){
       
    39     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
       
    40   }
       
    41 #ifndef SQLITE_OMIT_CAST
       
    42   if( op==TK_CAST ){
       
    43     return sqlite3AffinityType(&pExpr->token);
       
    44   }
       
    45 #endif
       
    46   if( (op==TK_COLUMN || op==TK_REGISTER) && pExpr->pTab!=0 ){
       
    47     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
       
    48     ** a TK_COLUMN but was previously evaluated and cached in a register */
       
    49     int j = pExpr->iColumn;
       
    50     if( j<0 ) return SQLITE_AFF_INTEGER;
       
    51     assert( pExpr->pTab && j<pExpr->pTab->nCol );
       
    52     return pExpr->pTab->aCol[j].affinity;
       
    53   }
       
    54   return pExpr->affinity;
       
    55 }
       
    56 
       
    57 /*
       
    58 ** Set the collating sequence for expression pExpr to be the collating
       
    59 ** sequence named by pToken.   Return a pointer to the revised expression.
       
    60 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
       
    61 ** flag.  An explicit collating sequence will override implicit
       
    62 ** collating sequences.
       
    63 */
       
    64 Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
       
    65   char *zColl = 0;            /* Dequoted name of collation sequence */
       
    66   CollSeq *pColl;
       
    67   sqlite3 *db = pParse->db;
       
    68   zColl = sqlite3NameFromToken(db, pCollName);
       
    69   if( pExpr && zColl ){
       
    70     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
       
    71     if( pColl ){
       
    72       pExpr->pColl = pColl;
       
    73       pExpr->flags |= EP_ExpCollate;
       
    74     }
       
    75   }
       
    76   sqlite3DbFree(db, zColl);
       
    77   return pExpr;
       
    78 }
       
    79 
       
    80 /*
       
    81 ** Return the default collation sequence for the expression pExpr. If
       
    82 ** there is no default collation type, return 0.
       
    83 */
       
    84 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
       
    85   CollSeq *pColl = 0;
       
    86   Expr *p = pExpr;
       
    87   while( p ){
       
    88     int op;
       
    89     pColl = p->pColl;
       
    90     if( pColl ) break;
       
    91     op = p->op;
       
    92     if( (op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
       
    93       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
       
    94       ** a TK_COLUMN but was previously evaluated and cached in a register */
       
    95       const char *zColl;
       
    96       int j = p->iColumn;
       
    97       if( j>=0 ){
       
    98         sqlite3 *db = pParse->db;
       
    99         zColl = p->pTab->aCol[j].zColl;
       
   100         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
       
   101         pExpr->pColl = pColl;
       
   102       }
       
   103       break;
       
   104     }
       
   105     if( op!=TK_CAST && op!=TK_UPLUS ){
       
   106       break;
       
   107     }
       
   108     p = p->pLeft;
       
   109   }
       
   110   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
       
   111     pColl = 0;
       
   112   }
       
   113   return pColl;
       
   114 }
       
   115 
       
   116 /*
       
   117 ** pExpr is an operand of a comparison operator.  aff2 is the
       
   118 ** type affinity of the other operand.  This routine returns the
       
   119 ** type affinity that should be used for the comparison operator.
       
   120 */
       
   121 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
       
   122   char aff1 = sqlite3ExprAffinity(pExpr);
       
   123   if( aff1 && aff2 ){
       
   124     /* Both sides of the comparison are columns. If one has numeric
       
   125     ** affinity, use that. Otherwise use no affinity.
       
   126     */
       
   127     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
       
   128       return SQLITE_AFF_NUMERIC;
       
   129     }else{
       
   130       return SQLITE_AFF_NONE;
       
   131     }
       
   132   }else if( !aff1 && !aff2 ){
       
   133     /* Neither side of the comparison is a column.  Compare the
       
   134     ** results directly.
       
   135     */
       
   136     return SQLITE_AFF_NONE;
       
   137   }else{
       
   138     /* One side is a column, the other is not. Use the columns affinity. */
       
   139     assert( aff1==0 || aff2==0 );
       
   140     return (aff1 + aff2);
       
   141   }
       
   142 }
       
   143 
       
   144 /*
       
   145 ** pExpr is a comparison operator.  Return the type affinity that should
       
   146 ** be applied to both operands prior to doing the comparison.
       
   147 */
       
   148 static char comparisonAffinity(Expr *pExpr){
       
   149   char aff;
       
   150   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
       
   151           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
       
   152           pExpr->op==TK_NE );
       
   153   assert( pExpr->pLeft );
       
   154   aff = sqlite3ExprAffinity(pExpr->pLeft);
       
   155   if( pExpr->pRight ){
       
   156     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
       
   157   }
       
   158   else if( pExpr->pSelect ){
       
   159     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
       
   160   }
       
   161   else if( !aff ){
       
   162     aff = SQLITE_AFF_NONE;
       
   163   }
       
   164   return aff;
       
   165 }
       
   166 
       
   167 /*
       
   168 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
       
   169 ** idx_affinity is the affinity of an indexed column. Return true
       
   170 ** if the index with affinity idx_affinity may be used to implement
       
   171 ** the comparison in pExpr.
       
   172 */
       
   173 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
       
   174   char aff = comparisonAffinity(pExpr);
       
   175   switch( aff ){
       
   176     case SQLITE_AFF_NONE:
       
   177       return 1;
       
   178     case SQLITE_AFF_TEXT:
       
   179       return idx_affinity==SQLITE_AFF_TEXT;
       
   180     default:
       
   181       return sqlite3IsNumericAffinity(idx_affinity);
       
   182   }
       
   183 }
       
   184 
       
   185 /*
       
   186 ** Return the P5 value that should be used for a binary comparison
       
   187 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
       
   188 */
       
   189 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
       
   190   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
       
   191   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
       
   192   return aff;
       
   193 }
       
   194 
       
   195 /*
       
   196 ** Return a pointer to the collation sequence that should be used by
       
   197 ** a binary comparison operator comparing pLeft and pRight.
       
   198 **
       
   199 ** If the left hand expression has a collating sequence type, then it is
       
   200 ** used. Otherwise the collation sequence for the right hand expression
       
   201 ** is used, or the default (BINARY) if neither expression has a collating
       
   202 ** type.
       
   203 **
       
   204 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
       
   205 ** it is not considered.
       
   206 */
       
   207 CollSeq *sqlite3BinaryCompareCollSeq(
       
   208   Parse *pParse, 
       
   209   Expr *pLeft, 
       
   210   Expr *pRight
       
   211 ){
       
   212   CollSeq *pColl;
       
   213   assert( pLeft );
       
   214   if( pLeft->flags & EP_ExpCollate ){
       
   215     assert( pLeft->pColl );
       
   216     pColl = pLeft->pColl;
       
   217   }else if( pRight && pRight->flags & EP_ExpCollate ){
       
   218     assert( pRight->pColl );
       
   219     pColl = pRight->pColl;
       
   220   }else{
       
   221     pColl = sqlite3ExprCollSeq(pParse, pLeft);
       
   222     if( !pColl ){
       
   223       pColl = sqlite3ExprCollSeq(pParse, pRight);
       
   224     }
       
   225   }
       
   226   return pColl;
       
   227 }
       
   228 
       
   229 /*
       
   230 ** Generate the operands for a comparison operation.  Before
       
   231 ** generating the code for each operand, set the EP_AnyAff
       
   232 ** flag on the expression so that it will be able to used a
       
   233 ** cached column value that has previously undergone an
       
   234 ** affinity change.
       
   235 */
       
   236 static void codeCompareOperands(
       
   237   Parse *pParse,    /* Parsing and code generating context */
       
   238   Expr *pLeft,      /* The left operand */
       
   239   int *pRegLeft,    /* Register where left operand is stored */
       
   240   int *pFreeLeft,   /* Free this register when done */
       
   241   Expr *pRight,     /* The right operand */
       
   242   int *pRegRight,   /* Register where right operand is stored */
       
   243   int *pFreeRight   /* Write temp register for right operand there */
       
   244 ){
       
   245   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
       
   246   pLeft->flags |= EP_AnyAff;
       
   247   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
       
   248   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
       
   249   pRight->flags |= EP_AnyAff;
       
   250   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
       
   251 }
       
   252 
       
   253 /*
       
   254 ** Generate code for a comparison operator.
       
   255 */
       
   256 static int codeCompare(
       
   257   Parse *pParse,    /* The parsing (and code generating) context */
       
   258   Expr *pLeft,      /* The left operand */
       
   259   Expr *pRight,     /* The right operand */
       
   260   int opcode,       /* The comparison opcode */
       
   261   int in1, int in2, /* Register holding operands */
       
   262   int dest,         /* Jump here if true.  */
       
   263   int jumpIfNull    /* If true, jump if either operand is NULL */
       
   264 ){
       
   265   int p5;
       
   266   int addr;
       
   267   CollSeq *p4;
       
   268 
       
   269   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
       
   270   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
       
   271   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
       
   272                            (void*)p4, P4_COLLSEQ);
       
   273   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
       
   274   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
       
   275     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
       
   276     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
       
   277   }
       
   278   return addr;
       
   279 }
       
   280 
       
   281 #if SQLITE_MAX_EXPR_DEPTH>0
       
   282 /*
       
   283 ** Check that argument nHeight is less than or equal to the maximum
       
   284 ** expression depth allowed. If it is not, leave an error message in
       
   285 ** pParse.
       
   286 */
       
   287 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
       
   288   int rc = SQLITE_OK;
       
   289   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
       
   290   if( nHeight>mxHeight ){
       
   291     sqlite3ErrorMsg(pParse, 
       
   292        "Expression tree is too large (maximum depth %d)", mxHeight
       
   293     );
       
   294     rc = SQLITE_ERROR;
       
   295   }
       
   296   return rc;
       
   297 }
       
   298 
       
   299 /* The following three functions, heightOfExpr(), heightOfExprList()
       
   300 ** and heightOfSelect(), are used to determine the maximum height
       
   301 ** of any expression tree referenced by the structure passed as the
       
   302 ** first argument.
       
   303 **
       
   304 ** If this maximum height is greater than the current value pointed
       
   305 ** to by pnHeight, the second parameter, then set *pnHeight to that
       
   306 ** value.
       
   307 */
       
   308 static void heightOfExpr(Expr *p, int *pnHeight){
       
   309   if( p ){
       
   310     if( p->nHeight>*pnHeight ){
       
   311       *pnHeight = p->nHeight;
       
   312     }
       
   313   }
       
   314 }
       
   315 static void heightOfExprList(ExprList *p, int *pnHeight){
       
   316   if( p ){
       
   317     int i;
       
   318     for(i=0; i<p->nExpr; i++){
       
   319       heightOfExpr(p->a[i].pExpr, pnHeight);
       
   320     }
       
   321   }
       
   322 }
       
   323 static void heightOfSelect(Select *p, int *pnHeight){
       
   324   if( p ){
       
   325     heightOfExpr(p->pWhere, pnHeight);
       
   326     heightOfExpr(p->pHaving, pnHeight);
       
   327     heightOfExpr(p->pLimit, pnHeight);
       
   328     heightOfExpr(p->pOffset, pnHeight);
       
   329     heightOfExprList(p->pEList, pnHeight);
       
   330     heightOfExprList(p->pGroupBy, pnHeight);
       
   331     heightOfExprList(p->pOrderBy, pnHeight);
       
   332     heightOfSelect(p->pPrior, pnHeight);
       
   333   }
       
   334 }
       
   335 
       
   336 /*
       
   337 ** Set the Expr.nHeight variable in the structure passed as an 
       
   338 ** argument. An expression with no children, Expr.pList or 
       
   339 ** Expr.pSelect member has a height of 1. Any other expression
       
   340 ** has a height equal to the maximum height of any other 
       
   341 ** referenced Expr plus one.
       
   342 */
       
   343 static void exprSetHeight(Expr *p){
       
   344   int nHeight = 0;
       
   345   heightOfExpr(p->pLeft, &nHeight);
       
   346   heightOfExpr(p->pRight, &nHeight);
       
   347   heightOfExprList(p->pList, &nHeight);
       
   348   heightOfSelect(p->pSelect, &nHeight);
       
   349   p->nHeight = nHeight + 1;
       
   350 }
       
   351 
       
   352 /*
       
   353 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
       
   354 ** the height is greater than the maximum allowed expression depth,
       
   355 ** leave an error in pParse.
       
   356 */
       
   357 void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
       
   358   exprSetHeight(p);
       
   359   sqlite3ExprCheckHeight(pParse, p->nHeight);
       
   360 }
       
   361 
       
   362 /*
       
   363 ** Return the maximum height of any expression tree referenced
       
   364 ** by the select statement passed as an argument.
       
   365 */
       
   366 int sqlite3SelectExprHeight(Select *p){
       
   367   int nHeight = 0;
       
   368   heightOfSelect(p, &nHeight);
       
   369   return nHeight;
       
   370 }
       
   371 #else
       
   372   #define exprSetHeight(y)
       
   373 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
       
   374 
       
   375 /*
       
   376 ** Construct a new expression node and return a pointer to it.  Memory
       
   377 ** for this node is obtained from sqlite3_malloc().  The calling function
       
   378 ** is responsible for making sure the node eventually gets freed.
       
   379 */
       
   380 Expr *sqlite3Expr(
       
   381   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
       
   382   int op,                 /* Expression opcode */
       
   383   Expr *pLeft,            /* Left operand */
       
   384   Expr *pRight,           /* Right operand */
       
   385   const Token *pToken     /* Argument token */
       
   386 ){
       
   387   Expr *pNew;
       
   388   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
       
   389   if( pNew==0 ){
       
   390     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
       
   391     ** this function must always be allocated with sqlite3Expr() for this 
       
   392     ** reason. 
       
   393     */
       
   394     sqlite3ExprDelete(db, pLeft);
       
   395     sqlite3ExprDelete(db, pRight);
       
   396     return 0;
       
   397   }
       
   398   pNew->op = op;
       
   399   pNew->pLeft = pLeft;
       
   400   pNew->pRight = pRight;
       
   401   pNew->iAgg = -1;
       
   402   pNew->span.z = (u8*)"";
       
   403   if( pToken ){
       
   404     assert( pToken->dyn==0 );
       
   405     pNew->span = pNew->token = *pToken;
       
   406   }else if( pLeft ){
       
   407     if( pRight ){
       
   408       if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
       
   409         sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
       
   410       }
       
   411       if( pRight->flags & EP_ExpCollate ){
       
   412         pNew->flags |= EP_ExpCollate;
       
   413         pNew->pColl = pRight->pColl;
       
   414       }
       
   415     }
       
   416     if( pLeft->flags & EP_ExpCollate ){
       
   417       pNew->flags |= EP_ExpCollate;
       
   418       pNew->pColl = pLeft->pColl;
       
   419     }
       
   420   }
       
   421 
       
   422   exprSetHeight(pNew);
       
   423   return pNew;
       
   424 }
       
   425 
       
   426 /*
       
   427 ** Works like sqlite3Expr() except that it takes an extra Parse*
       
   428 ** argument and notifies the associated connection object if malloc fails.
       
   429 */
       
   430 Expr *sqlite3PExpr(
       
   431   Parse *pParse,          /* Parsing context */
       
   432   int op,                 /* Expression opcode */
       
   433   Expr *pLeft,            /* Left operand */
       
   434   Expr *pRight,           /* Right operand */
       
   435   const Token *pToken     /* Argument token */
       
   436 ){
       
   437   Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
       
   438   if( p ){
       
   439     sqlite3ExprCheckHeight(pParse, p->nHeight);
       
   440   }
       
   441   return p;
       
   442 }
       
   443 
       
   444 /*
       
   445 ** When doing a nested parse, you can include terms in an expression
       
   446 ** that look like this:   #1 #2 ...  These terms refer to registers
       
   447 ** in the virtual machine.  #N is the N-th register.
       
   448 **
       
   449 ** This routine is called by the parser to deal with on of those terms.
       
   450 ** It immediately generates code to store the value in a memory location.
       
   451 ** The returns an expression that will code to extract the value from
       
   452 ** that memory location as needed.
       
   453 */
       
   454 Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
       
   455   Vdbe *v = pParse->pVdbe;
       
   456   Expr *p;
       
   457   if( pParse->nested==0 ){
       
   458     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
       
   459     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
       
   460   }
       
   461   if( v==0 ) return 0;
       
   462   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
       
   463   if( p==0 ){
       
   464     return 0;  /* Malloc failed */
       
   465   }
       
   466   p->iTable = atoi((char*)&pToken->z[1]);
       
   467   return p;
       
   468 }
       
   469 
       
   470 /*
       
   471 ** Join two expressions using an AND operator.  If either expression is
       
   472 ** NULL, then just return the other expression.
       
   473 */
       
   474 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
       
   475   if( pLeft==0 ){
       
   476     return pRight;
       
   477   }else if( pRight==0 ){
       
   478     return pLeft;
       
   479   }else{
       
   480     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
       
   481   }
       
   482 }
       
   483 
       
   484 /*
       
   485 ** Set the Expr.span field of the given expression to span all
       
   486 ** text between the two given tokens.  Both tokens must be pointing
       
   487 ** at the same string.
       
   488 */
       
   489 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
       
   490   assert( pRight!=0 );
       
   491   assert( pLeft!=0 );
       
   492   if( pExpr ){
       
   493     pExpr->span.z = pLeft->z;
       
   494     pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
       
   495   }
       
   496 }
       
   497 
       
   498 /*
       
   499 ** Construct a new expression node for a function with multiple
       
   500 ** arguments.
       
   501 */
       
   502 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
       
   503   Expr *pNew;
       
   504   sqlite3 *db = pParse->db;
       
   505   assert( pToken );
       
   506   pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
       
   507   if( pNew==0 ){
       
   508     sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
       
   509     return 0;
       
   510   }
       
   511   pNew->op = TK_FUNCTION;
       
   512   pNew->pList = pList;
       
   513   assert( pToken->dyn==0 );
       
   514   pNew->token = *pToken;
       
   515   pNew->span = pNew->token;
       
   516 
       
   517   sqlite3ExprSetHeight(pParse, pNew);
       
   518   return pNew;
       
   519 }
       
   520 
       
   521 /*
       
   522 ** Assign a variable number to an expression that encodes a wildcard
       
   523 ** in the original SQL statement.  
       
   524 **
       
   525 ** Wildcards consisting of a single "?" are assigned the next sequential
       
   526 ** variable number.
       
   527 **
       
   528 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
       
   529 ** sure "nnn" is not too be to avoid a denial of service attack when
       
   530 ** the SQL statement comes from an external source.
       
   531 **
       
   532 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
       
   533 ** as the previous instance of the same wildcard.  Or if this is the first
       
   534 ** instance of the wildcard, the next sequenial variable number is
       
   535 ** assigned.
       
   536 */
       
   537 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
       
   538   Token *pToken;
       
   539   sqlite3 *db = pParse->db;
       
   540 
       
   541   if( pExpr==0 ) return;
       
   542   pToken = &pExpr->token;
       
   543   assert( pToken->n>=1 );
       
   544   assert( pToken->z!=0 );
       
   545   assert( pToken->z[0]!=0 );
       
   546   if( pToken->n==1 ){
       
   547     /* Wildcard of the form "?".  Assign the next variable number */
       
   548     pExpr->iTable = ++pParse->nVar;
       
   549   }else if( pToken->z[0]=='?' ){
       
   550     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
       
   551     ** use it as the variable number */
       
   552     int i;
       
   553     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
       
   554     testcase( i==0 );
       
   555     testcase( i==1 );
       
   556     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
       
   557     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
       
   558     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
       
   559       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
       
   560           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
       
   561     }
       
   562     if( i>pParse->nVar ){
       
   563       pParse->nVar = i;
       
   564     }
       
   565   }else{
       
   566     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
       
   567     ** number as the prior appearance of the same name, or if the name
       
   568     ** has never appeared before, reuse the same variable number
       
   569     */
       
   570     int i, n;
       
   571     n = pToken->n;
       
   572     for(i=0; i<pParse->nVarExpr; i++){
       
   573       Expr *pE;
       
   574       if( (pE = pParse->apVarExpr[i])!=0
       
   575           && pE->token.n==n
       
   576           && memcmp(pE->token.z, pToken->z, n)==0 ){
       
   577         pExpr->iTable = pE->iTable;
       
   578         break;
       
   579       }
       
   580     }
       
   581     if( i>=pParse->nVarExpr ){
       
   582       pExpr->iTable = ++pParse->nVar;
       
   583       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
       
   584         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
       
   585         pParse->apVarExpr =
       
   586             sqlite3DbReallocOrFree(
       
   587               db,
       
   588               pParse->apVarExpr,
       
   589               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
       
   590             );
       
   591       }
       
   592       if( !db->mallocFailed ){
       
   593         assert( pParse->apVarExpr!=0 );
       
   594         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
       
   595       }
       
   596     }
       
   597   } 
       
   598   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
       
   599     sqlite3ErrorMsg(pParse, "too many SQL variables");
       
   600   }
       
   601 }
       
   602 
       
   603 /*
       
   604 ** Recursively delete an expression tree.
       
   605 */
       
   606 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
       
   607   if( p==0 ) return;
       
   608   if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
       
   609   if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
       
   610   sqlite3ExprDelete(db, p->pLeft);
       
   611   sqlite3ExprDelete(db, p->pRight);
       
   612   sqlite3ExprListDelete(db, p->pList);
       
   613   sqlite3SelectDelete(db, p->pSelect);
       
   614   sqlite3DbFree(db, p);
       
   615 }
       
   616 
       
   617 /*
       
   618 ** The Expr.token field might be a string literal that is quoted.
       
   619 ** If so, remove the quotation marks.
       
   620 */
       
   621 void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
       
   622   if( ExprHasAnyProperty(p, EP_Dequoted) ){
       
   623     return;
       
   624   }
       
   625   ExprSetProperty(p, EP_Dequoted);
       
   626   if( p->token.dyn==0 ){
       
   627     sqlite3TokenCopy(db, &p->token, &p->token);
       
   628   }
       
   629   sqlite3Dequote((char*)p->token.z);
       
   630 }
       
   631 
       
   632 /*
       
   633 ** The following group of routines make deep copies of expressions,
       
   634 ** expression lists, ID lists, and select statements.  The copies can
       
   635 ** be deleted (by being passed to their respective ...Delete() routines)
       
   636 ** without effecting the originals.
       
   637 **
       
   638 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
       
   639 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
       
   640 ** by subsequent calls to sqlite*ListAppend() routines.
       
   641 **
       
   642 ** Any tables that the SrcList might point to are not duplicated.
       
   643 */
       
   644 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
       
   645   Expr *pNew;
       
   646   if( p==0 ) return 0;
       
   647   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
       
   648   if( pNew==0 ) return 0;
       
   649   memcpy(pNew, p, sizeof(*pNew));
       
   650   if( p->token.z!=0 ){
       
   651     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
       
   652     pNew->token.dyn = 1;
       
   653   }else{
       
   654     assert( pNew->token.z==0 );
       
   655   }
       
   656   pNew->span.z = 0;
       
   657   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
       
   658   pNew->pRight = sqlite3ExprDup(db, p->pRight);
       
   659   pNew->pList = sqlite3ExprListDup(db, p->pList);
       
   660   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
       
   661   return pNew;
       
   662 }
       
   663 void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
       
   664   if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
       
   665   if( pFrom->z ){
       
   666     pTo->n = pFrom->n;
       
   667     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
       
   668     pTo->dyn = 1;
       
   669   }else{
       
   670     pTo->z = 0;
       
   671   }
       
   672 }
       
   673 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
       
   674   ExprList *pNew;
       
   675   struct ExprList_item *pItem, *pOldItem;
       
   676   int i;
       
   677   if( p==0 ) return 0;
       
   678   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
       
   679   if( pNew==0 ) return 0;
       
   680   pNew->iECursor = 0;
       
   681   pNew->nExpr = pNew->nAlloc = p->nExpr;
       
   682   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
       
   683   if( pItem==0 ){
       
   684     sqlite3DbFree(db, pNew);
       
   685     return 0;
       
   686   } 
       
   687   pOldItem = p->a;
       
   688   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
       
   689     Expr *pNewExpr, *pOldExpr;
       
   690     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
       
   691     if( pOldExpr->span.z!=0 && pNewExpr ){
       
   692       /* Always make a copy of the span for top-level expressions in the
       
   693       ** expression list.  The logic in SELECT processing that determines
       
   694       ** the names of columns in the result set needs this information */
       
   695       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
       
   696     }
       
   697     assert( pNewExpr==0 || pNewExpr->span.z!=0 
       
   698             || pOldExpr->span.z==0
       
   699             || db->mallocFailed );
       
   700     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
       
   701     pItem->sortOrder = pOldItem->sortOrder;
       
   702     pItem->done = 0;
       
   703     pItem->iCol = pOldItem->iCol;
       
   704     pItem->iAlias = pOldItem->iAlias;
       
   705   }
       
   706   return pNew;
       
   707 }
       
   708 
       
   709 /*
       
   710 ** If cursors, triggers, views and subqueries are all omitted from
       
   711 ** the build, then none of the following routines, except for 
       
   712 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
       
   713 ** called with a NULL argument.
       
   714 */
       
   715 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
       
   716  || !defined(SQLITE_OMIT_SUBQUERY)
       
   717 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
       
   718   SrcList *pNew;
       
   719   int i;
       
   720   int nByte;
       
   721   if( p==0 ) return 0;
       
   722   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
       
   723   pNew = sqlite3DbMallocRaw(db, nByte );
       
   724   if( pNew==0 ) return 0;
       
   725   pNew->nSrc = pNew->nAlloc = p->nSrc;
       
   726   for(i=0; i<p->nSrc; i++){
       
   727     struct SrcList_item *pNewItem = &pNew->a[i];
       
   728     struct SrcList_item *pOldItem = &p->a[i];
       
   729     Table *pTab;
       
   730     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
       
   731     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
       
   732     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
       
   733     pNewItem->jointype = pOldItem->jointype;
       
   734     pNewItem->iCursor = pOldItem->iCursor;
       
   735     pNewItem->isPopulated = pOldItem->isPopulated;
       
   736     pTab = pNewItem->pTab = pOldItem->pTab;
       
   737     if( pTab ){
       
   738       pTab->nRef++;
       
   739     }
       
   740     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
       
   741     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
       
   742     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
       
   743     pNewItem->colUsed = pOldItem->colUsed;
       
   744   }
       
   745   return pNew;
       
   746 }
       
   747 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
       
   748   IdList *pNew;
       
   749   int i;
       
   750   if( p==0 ) return 0;
       
   751   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
       
   752   if( pNew==0 ) return 0;
       
   753   pNew->nId = pNew->nAlloc = p->nId;
       
   754   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
       
   755   if( pNew->a==0 ){
       
   756     sqlite3DbFree(db, pNew);
       
   757     return 0;
       
   758   }
       
   759   for(i=0; i<p->nId; i++){
       
   760     struct IdList_item *pNewItem = &pNew->a[i];
       
   761     struct IdList_item *pOldItem = &p->a[i];
       
   762     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
       
   763     pNewItem->idx = pOldItem->idx;
       
   764   }
       
   765   return pNew;
       
   766 }
       
   767 Select *sqlite3SelectDup(sqlite3 *db, Select *p){
       
   768   Select *pNew;
       
   769   if( p==0 ) return 0;
       
   770   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
       
   771   if( pNew==0 ) return 0;
       
   772   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
       
   773   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
       
   774   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
       
   775   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
       
   776   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
       
   777   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
       
   778   pNew->op = p->op;
       
   779   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
       
   780   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
       
   781   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
       
   782   pNew->iLimit = 0;
       
   783   pNew->iOffset = 0;
       
   784   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
       
   785   pNew->pRightmost = 0;
       
   786   pNew->addrOpenEphm[0] = -1;
       
   787   pNew->addrOpenEphm[1] = -1;
       
   788   pNew->addrOpenEphm[2] = -1;
       
   789   return pNew;
       
   790 }
       
   791 #else
       
   792 Select *sqlite3SelectDup(sqlite3 *db, Select *p){
       
   793   assert( p==0 );
       
   794   return 0;
       
   795 }
       
   796 #endif
       
   797 
       
   798 
       
   799 /*
       
   800 ** Add a new element to the end of an expression list.  If pList is
       
   801 ** initially NULL, then create a new expression list.
       
   802 */
       
   803 ExprList *sqlite3ExprListAppend(
       
   804   Parse *pParse,          /* Parsing context */
       
   805   ExprList *pList,        /* List to which to append. Might be NULL */
       
   806   Expr *pExpr,            /* Expression to be appended */
       
   807   Token *pName            /* AS keyword for the expression */
       
   808 ){
       
   809   sqlite3 *db = pParse->db;
       
   810   if( pList==0 ){
       
   811     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
       
   812     if( pList==0 ){
       
   813       goto no_mem;
       
   814     }
       
   815     assert( pList->nAlloc==0 );
       
   816   }
       
   817   if( pList->nAlloc<=pList->nExpr ){
       
   818     struct ExprList_item *a;
       
   819     int n = pList->nAlloc*2 + 4;
       
   820     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
       
   821     if( a==0 ){
       
   822       goto no_mem;
       
   823     }
       
   824     pList->a = a;
       
   825     pList->nAlloc = n;
       
   826   }
       
   827   assert( pList->a!=0 );
       
   828   if( pExpr || pName ){
       
   829     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
       
   830     memset(pItem, 0, sizeof(*pItem));
       
   831     pItem->zName = sqlite3NameFromToken(db, pName);
       
   832     pItem->pExpr = pExpr;
       
   833     pItem->iAlias = 0;
       
   834   }
       
   835   return pList;
       
   836 
       
   837 no_mem:     
       
   838   /* Avoid leaking memory if malloc has failed. */
       
   839   sqlite3ExprDelete(db, pExpr);
       
   840   sqlite3ExprListDelete(db, pList);
       
   841   return 0;
       
   842 }
       
   843 
       
   844 /*
       
   845 ** If the expression list pEList contains more than iLimit elements,
       
   846 ** leave an error message in pParse.
       
   847 */
       
   848 void sqlite3ExprListCheckLength(
       
   849   Parse *pParse,
       
   850   ExprList *pEList,
       
   851   const char *zObject
       
   852 ){
       
   853   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
       
   854   testcase( pEList && pEList->nExpr==mx );
       
   855   testcase( pEList && pEList->nExpr==mx+1 );
       
   856   if( pEList && pEList->nExpr>mx ){
       
   857     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
       
   858   }
       
   859 }
       
   860 
       
   861 /*
       
   862 ** Delete an entire expression list.
       
   863 */
       
   864 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
       
   865   int i;
       
   866   struct ExprList_item *pItem;
       
   867   if( pList==0 ) return;
       
   868   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
       
   869   assert( pList->nExpr<=pList->nAlloc );
       
   870   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
       
   871     sqlite3ExprDelete(db, pItem->pExpr);
       
   872     sqlite3DbFree(db, pItem->zName);
       
   873   }
       
   874   sqlite3DbFree(db, pList->a);
       
   875   sqlite3DbFree(db, pList);
       
   876 }
       
   877 
       
   878 /*
       
   879 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
       
   880 ** to an integer.  These routines are checking an expression to see
       
   881 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
       
   882 ** not constant.
       
   883 **
       
   884 ** These callback routines are used to implement the following:
       
   885 **
       
   886 **     sqlite3ExprIsConstant()
       
   887 **     sqlite3ExprIsConstantNotJoin()
       
   888 **     sqlite3ExprIsConstantOrFunction()
       
   889 **
       
   890 */
       
   891 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
       
   892 
       
   893   /* If pWalker->u.i is 3 then any term of the expression that comes from
       
   894   ** the ON or USING clauses of a join disqualifies the expression
       
   895   ** from being considered constant. */
       
   896   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
       
   897     pWalker->u.i = 0;
       
   898     return WRC_Abort;
       
   899   }
       
   900 
       
   901   switch( pExpr->op ){
       
   902     /* Consider functions to be constant if all their arguments are constant
       
   903     ** and pWalker->u.i==2 */
       
   904     case TK_FUNCTION:
       
   905       if( pWalker->u.i==2 ) return 0;
       
   906       /* Fall through */
       
   907     case TK_ID:
       
   908     case TK_COLUMN:
       
   909     case TK_DOT:
       
   910     case TK_AGG_FUNCTION:
       
   911     case TK_AGG_COLUMN:
       
   912 #ifndef SQLITE_OMIT_SUBQUERY
       
   913     case TK_SELECT:
       
   914     case TK_EXISTS:
       
   915       testcase( pExpr->op==TK_SELECT );
       
   916       testcase( pExpr->op==TK_EXISTS );
       
   917 #endif
       
   918       testcase( pExpr->op==TK_ID );
       
   919       testcase( pExpr->op==TK_COLUMN );
       
   920       testcase( pExpr->op==TK_DOT );
       
   921       testcase( pExpr->op==TK_AGG_FUNCTION );
       
   922       testcase( pExpr->op==TK_AGG_COLUMN );
       
   923       pWalker->u.i = 0;
       
   924       return WRC_Abort;
       
   925     default:
       
   926       return WRC_Continue;
       
   927   }
       
   928 }
       
   929 static int selectNodeIsConstant(Walker *pWalker, Select *pSelect){
       
   930   pWalker->u.i = 0;
       
   931   return WRC_Abort;
       
   932 }
       
   933 static int exprIsConst(Expr *p, int initFlag){
       
   934   Walker w;
       
   935   w.u.i = initFlag;
       
   936   w.xExprCallback = exprNodeIsConstant;
       
   937   w.xSelectCallback = selectNodeIsConstant;
       
   938   sqlite3WalkExpr(&w, p);
       
   939   return w.u.i;
       
   940 }
       
   941 
       
   942 /*
       
   943 ** Walk an expression tree.  Return 1 if the expression is constant
       
   944 ** and 0 if it involves variables or function calls.
       
   945 **
       
   946 ** For the purposes of this function, a double-quoted string (ex: "abc")
       
   947 ** is considered a variable but a single-quoted string (ex: 'abc') is
       
   948 ** a constant.
       
   949 */
       
   950 int sqlite3ExprIsConstant(Expr *p){
       
   951   return exprIsConst(p, 1);
       
   952 }
       
   953 
       
   954 /*
       
   955 ** Walk an expression tree.  Return 1 if the expression is constant
       
   956 ** that does no originate from the ON or USING clauses of a join.
       
   957 ** Return 0 if it involves variables or function calls or terms from
       
   958 ** an ON or USING clause.
       
   959 */
       
   960 int sqlite3ExprIsConstantNotJoin(Expr *p){
       
   961   return exprIsConst(p, 3);
       
   962 }
       
   963 
       
   964 /*
       
   965 ** Walk an expression tree.  Return 1 if the expression is constant
       
   966 ** or a function call with constant arguments.  Return and 0 if there
       
   967 ** are any variables.
       
   968 **
       
   969 ** For the purposes of this function, a double-quoted string (ex: "abc")
       
   970 ** is considered a variable but a single-quoted string (ex: 'abc') is
       
   971 ** a constant.
       
   972 */
       
   973 int sqlite3ExprIsConstantOrFunction(Expr *p){
       
   974   return exprIsConst(p, 2);
       
   975 }
       
   976 
       
   977 /*
       
   978 ** If the expression p codes a constant integer that is small enough
       
   979 ** to fit in a 32-bit integer, return 1 and put the value of the integer
       
   980 ** in *pValue.  If the expression is not an integer or if it is too big
       
   981 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
       
   982 */
       
   983 int sqlite3ExprIsInteger(Expr *p, int *pValue){
       
   984   int rc = 0;
       
   985   if( p->flags & EP_IntValue ){
       
   986     *pValue = p->iTable;
       
   987     return 1;
       
   988   }
       
   989   switch( p->op ){
       
   990     case TK_INTEGER: {
       
   991       rc = sqlite3GetInt32((char*)p->token.z, pValue);
       
   992       break;
       
   993     }
       
   994     case TK_UPLUS: {
       
   995       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
       
   996       break;
       
   997     }
       
   998     case TK_UMINUS: {
       
   999       int v;
       
  1000       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
       
  1001         *pValue = -v;
       
  1002         rc = 1;
       
  1003       }
       
  1004       break;
       
  1005     }
       
  1006     default: break;
       
  1007   }
       
  1008   if( rc ){
       
  1009     p->op = TK_INTEGER;
       
  1010     p->flags |= EP_IntValue;
       
  1011     p->iTable = *pValue;
       
  1012   }
       
  1013   return rc;
       
  1014 }
       
  1015 
       
  1016 /*
       
  1017 ** Return TRUE if the given string is a row-id column name.
       
  1018 */
       
  1019 int sqlite3IsRowid(const char *z){
       
  1020   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
       
  1021   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
       
  1022   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
       
  1023   return 0;
       
  1024 }
       
  1025 
       
  1026 #ifdef SQLITE_TEST
       
  1027   int sqlite3_enable_in_opt = 1;
       
  1028 #else
       
  1029   #define sqlite3_enable_in_opt 1
       
  1030 #endif
       
  1031 
       
  1032 /*
       
  1033 ** Return true if the IN operator optimization is enabled and
       
  1034 ** the SELECT statement p exists and is of the
       
  1035 ** simple form:
       
  1036 **
       
  1037 **     SELECT <column> FROM <table>
       
  1038 **
       
  1039 ** If this is the case, it may be possible to use an existing table
       
  1040 ** or index instead of generating an epheremal table.
       
  1041 */
       
  1042 #ifndef SQLITE_OMIT_SUBQUERY
       
  1043 static int isCandidateForInOpt(Select *p){
       
  1044   SrcList *pSrc;
       
  1045   ExprList *pEList;
       
  1046   Table *pTab;
       
  1047   if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
       
  1048   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
       
  1049   if( p->pPrior ) return 0;              /* Not a compound SELECT */
       
  1050   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
       
  1051       return 0; /* No DISTINCT keyword and no aggregate functions */
       
  1052   }
       
  1053   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
       
  1054   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
       
  1055   if( p->pOffset ) return 0;
       
  1056   if( p->pWhere ) return 0;              /* Has no WHERE clause */
       
  1057   pSrc = p->pSrc;
       
  1058   if( pSrc==0 ) return 0;                /* A single table in the FROM clause */
       
  1059   if( pSrc->nSrc!=1 ) return 0;
       
  1060   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
       
  1061   pTab = pSrc->a[0].pTab;
       
  1062   if( pTab==0 ) return 0;
       
  1063   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
       
  1064   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
       
  1065   pEList = p->pEList;
       
  1066   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
       
  1067   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
       
  1068   return 1;
       
  1069 }
       
  1070 #endif /* SQLITE_OMIT_SUBQUERY */
       
  1071 
       
  1072 /*
       
  1073 ** This function is used by the implementation of the IN (...) operator.
       
  1074 ** It's job is to find or create a b-tree structure that may be used
       
  1075 ** either to test for membership of the (...) set or to iterate through
       
  1076 ** its members, skipping duplicates.
       
  1077 **
       
  1078 ** The cursor opened on the structure (database table, database index 
       
  1079 ** or ephermal table) is stored in pX->iTable before this function returns.
       
  1080 ** The returned value indicates the structure type, as follows:
       
  1081 **
       
  1082 **   IN_INDEX_ROWID - The cursor was opened on a database table.
       
  1083 **   IN_INDEX_INDEX - The cursor was opened on a database index.
       
  1084 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
       
  1085 **                    populated epheremal table.
       
  1086 **
       
  1087 ** An existing structure may only be used if the SELECT is of the simple
       
  1088 ** form:
       
  1089 **
       
  1090 **     SELECT <column> FROM <table>
       
  1091 **
       
  1092 ** If prNotFound parameter is 0, then the structure will be used to iterate
       
  1093 ** through the set members, skipping any duplicates. In this case an
       
  1094 ** epheremal table must be used unless the selected <column> is guaranteed
       
  1095 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
       
  1096 ** is unique by virtue of a constraint or implicit index.
       
  1097 **
       
  1098 ** If the prNotFound parameter is not 0, then the structure will be used 
       
  1099 ** for fast set membership tests. In this case an epheremal table must 
       
  1100 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
       
  1101 ** be found with <column> as its left-most column.
       
  1102 **
       
  1103 ** When the structure is being used for set membership tests, the user
       
  1104 ** needs to know whether or not the structure contains an SQL NULL 
       
  1105 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
       
  1106 ** If there is a chance that the structure may contain a NULL value at
       
  1107 ** runtime, then a register is allocated and the register number written
       
  1108 ** to *prNotFound. If there is no chance that the structure contains a
       
  1109 ** NULL value, then *prNotFound is left unchanged.
       
  1110 **
       
  1111 ** If a register is allocated and its location stored in *prNotFound, then
       
  1112 ** its initial value is NULL. If the structure does not remain constant
       
  1113 ** for the duration of the query (i.e. the set is a correlated sub-select), 
       
  1114 ** the value of the allocated register is reset to NULL each time the 
       
  1115 ** structure is repopulated. This allows the caller to use vdbe code 
       
  1116 ** equivalent to the following:
       
  1117 **
       
  1118 **   if( register==NULL ){
       
  1119 **     has_null = <test if data structure contains null>
       
  1120 **     register = 1
       
  1121 **   }
       
  1122 **
       
  1123 ** in order to avoid running the <test if data structure contains null>
       
  1124 ** test more often than is necessary.
       
  1125 */
       
  1126 #ifndef SQLITE_OMIT_SUBQUERY
       
  1127 int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
       
  1128   Select *p;
       
  1129   int eType = 0;
       
  1130   int iTab = pParse->nTab++;
       
  1131   int mustBeUnique = !prNotFound;
       
  1132 
       
  1133   /* The follwing if(...) expression is true if the SELECT is of the 
       
  1134   ** simple form:
       
  1135   **
       
  1136   **     SELECT <column> FROM <table>
       
  1137   **
       
  1138   ** If this is the case, it may be possible to use an existing table
       
  1139   ** or index instead of generating an epheremal table.
       
  1140   */
       
  1141   p = pX->pSelect;
       
  1142   if( isCandidateForInOpt(p) ){
       
  1143     sqlite3 *db = pParse->db;
       
  1144     Index *pIdx;
       
  1145     Expr *pExpr = p->pEList->a[0].pExpr;
       
  1146     int iCol = pExpr->iColumn;
       
  1147     Vdbe *v = sqlite3GetVdbe(pParse);
       
  1148 
       
  1149     /* This function is only called from two places. In both cases the vdbe
       
  1150     ** has already been allocated. So assume sqlite3GetVdbe() is always
       
  1151     ** successful here.
       
  1152     */
       
  1153     assert(v);
       
  1154     if( iCol<0 ){
       
  1155       int iMem = ++pParse->nMem;
       
  1156       int iAddr;
       
  1157       Table *pTab = p->pSrc->a[0].pTab;
       
  1158       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
       
  1159       sqlite3VdbeUsesBtree(v, iDb);
       
  1160 
       
  1161       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
       
  1162       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
       
  1163 
       
  1164       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
       
  1165       eType = IN_INDEX_ROWID;
       
  1166 
       
  1167       sqlite3VdbeJumpHere(v, iAddr);
       
  1168     }else{
       
  1169       /* The collation sequence used by the comparison. If an index is to 
       
  1170       ** be used in place of a temp-table, it must be ordered according
       
  1171       ** to this collation sequence.
       
  1172       */
       
  1173       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
       
  1174 
       
  1175       /* Check that the affinity that will be used to perform the 
       
  1176       ** comparison is the same as the affinity of the column. If
       
  1177       ** it is not, it is not possible to use any index.
       
  1178       */
       
  1179       Table *pTab = p->pSrc->a[0].pTab;
       
  1180       char aff = comparisonAffinity(pX);
       
  1181       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
       
  1182 
       
  1183       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
       
  1184         if( (pIdx->aiColumn[0]==iCol)
       
  1185          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
       
  1186          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
       
  1187         ){
       
  1188           int iDb;
       
  1189           int iMem = ++pParse->nMem;
       
  1190           int iAddr;
       
  1191           char *pKey;
       
  1192   
       
  1193           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
       
  1194           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
       
  1195           sqlite3VdbeUsesBtree(v, iDb);
       
  1196 
       
  1197           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
       
  1198           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
       
  1199   
       
  1200           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
       
  1201           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
       
  1202                                pKey,P4_KEYINFO_HANDOFF);
       
  1203           VdbeComment((v, "%s", pIdx->zName));
       
  1204           eType = IN_INDEX_INDEX;
       
  1205 
       
  1206           sqlite3VdbeJumpHere(v, iAddr);
       
  1207           if( prNotFound && !pTab->aCol[iCol].notNull ){
       
  1208             *prNotFound = ++pParse->nMem;
       
  1209           }
       
  1210         }
       
  1211       }
       
  1212     }
       
  1213   }
       
  1214 
       
  1215   if( eType==0 ){
       
  1216     int rMayHaveNull = 0;
       
  1217     eType = IN_INDEX_EPH;
       
  1218     if( prNotFound ){
       
  1219       *prNotFound = rMayHaveNull = ++pParse->nMem;
       
  1220     }else if( pX->pLeft->iColumn<0 && pX->pSelect==0 ){
       
  1221       eType = IN_INDEX_ROWID;
       
  1222     }
       
  1223     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
       
  1224   }else{
       
  1225     pX->iTable = iTab;
       
  1226   }
       
  1227   return eType;
       
  1228 }
       
  1229 #endif
       
  1230 
       
  1231 /*
       
  1232 ** Generate code for scalar subqueries used as an expression
       
  1233 ** and IN operators.  Examples:
       
  1234 **
       
  1235 **     (SELECT a FROM b)          -- subquery
       
  1236 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
       
  1237 **     x IN (4,5,11)              -- IN operator with list on right-hand side
       
  1238 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
       
  1239 **
       
  1240 ** The pExpr parameter describes the expression that contains the IN
       
  1241 ** operator or subquery.
       
  1242 **
       
  1243 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
       
  1244 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
       
  1245 ** to some integer key column of a table B-Tree. In this case, use an
       
  1246 ** intkey B-Tree to store the set of IN(...) values instead of the usual
       
  1247 ** (slower) variable length keys B-Tree.
       
  1248 */
       
  1249 #ifndef SQLITE_OMIT_SUBQUERY
       
  1250 void sqlite3CodeSubselect(
       
  1251   Parse *pParse, 
       
  1252   Expr *pExpr, 
       
  1253   int rMayHaveNull,
       
  1254   int isRowid
       
  1255 ){
       
  1256   int testAddr = 0;                       /* One-time test address */
       
  1257   Vdbe *v = sqlite3GetVdbe(pParse);
       
  1258   if( v==0 ) return;
       
  1259 
       
  1260 
       
  1261   /* This code must be run in its entirety every time it is encountered
       
  1262   ** if any of the following is true:
       
  1263   **
       
  1264   **    *  The right-hand side is a correlated subquery
       
  1265   **    *  The right-hand side is an expression list containing variables
       
  1266   **    *  We are inside a trigger
       
  1267   **
       
  1268   ** If all of the above are false, then we can run this code just once
       
  1269   ** save the results, and reuse the same result on subsequent invocations.
       
  1270   */
       
  1271   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
       
  1272     int mem = ++pParse->nMem;
       
  1273     sqlite3VdbeAddOp1(v, OP_If, mem);
       
  1274     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
       
  1275     assert( testAddr>0 || pParse->db->mallocFailed );
       
  1276   }
       
  1277 
       
  1278   switch( pExpr->op ){
       
  1279     case TK_IN: {
       
  1280       char affinity;
       
  1281       KeyInfo keyInfo;
       
  1282       int addr;        /* Address of OP_OpenEphemeral instruction */
       
  1283       Expr *pLeft = pExpr->pLeft;
       
  1284 
       
  1285       if( rMayHaveNull ){
       
  1286         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
       
  1287       }
       
  1288 
       
  1289       affinity = sqlite3ExprAffinity(pLeft);
       
  1290 
       
  1291       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
       
  1292       ** expression it is handled the same way. A virtual table is 
       
  1293       ** filled with single-field index keys representing the results
       
  1294       ** from the SELECT or the <exprlist>.
       
  1295       **
       
  1296       ** If the 'x' expression is a column value, or the SELECT...
       
  1297       ** statement returns a column value, then the affinity of that
       
  1298       ** column is used to build the index keys. If both 'x' and the
       
  1299       ** SELECT... statement are columns, then numeric affinity is used
       
  1300       ** if either column has NUMERIC or INTEGER affinity. If neither
       
  1301       ** 'x' nor the SELECT... statement are columns, then numeric affinity
       
  1302       ** is used.
       
  1303       */
       
  1304       pExpr->iTable = pParse->nTab++;
       
  1305       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
       
  1306       memset(&keyInfo, 0, sizeof(keyInfo));
       
  1307       keyInfo.nField = 1;
       
  1308 
       
  1309       if( pExpr->pSelect ){
       
  1310         /* Case 1:     expr IN (SELECT ...)
       
  1311         **
       
  1312         ** Generate code to write the results of the select into the temporary
       
  1313         ** table allocated and opened above.
       
  1314         */
       
  1315         SelectDest dest;
       
  1316         ExprList *pEList;
       
  1317 
       
  1318         assert( !isRowid );
       
  1319         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
       
  1320         dest.affinity = (int)affinity;
       
  1321         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
       
  1322         if( sqlite3Select(pParse, pExpr->pSelect, &dest) ){
       
  1323           return;
       
  1324         }
       
  1325         pEList = pExpr->pSelect->pEList;
       
  1326         if( pEList && pEList->nExpr>0 ){ 
       
  1327           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
       
  1328               pEList->a[0].pExpr);
       
  1329         }
       
  1330       }else if( pExpr->pList ){
       
  1331         /* Case 2:     expr IN (exprlist)
       
  1332         **
       
  1333         ** For each expression, build an index key from the evaluation and
       
  1334         ** store it in the temporary table. If <expr> is a column, then use
       
  1335         ** that columns affinity when building index keys. If <expr> is not
       
  1336         ** a column, use numeric affinity.
       
  1337         */
       
  1338         int i;
       
  1339         ExprList *pList = pExpr->pList;
       
  1340         struct ExprList_item *pItem;
       
  1341         int r1, r2, r3;
       
  1342 
       
  1343         if( !affinity ){
       
  1344           affinity = SQLITE_AFF_NONE;
       
  1345         }
       
  1346         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
       
  1347 
       
  1348         /* Loop through each expression in <exprlist>. */
       
  1349         r1 = sqlite3GetTempReg(pParse);
       
  1350         r2 = sqlite3GetTempReg(pParse);
       
  1351         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
       
  1352           Expr *pE2 = pItem->pExpr;
       
  1353 
       
  1354           /* If the expression is not constant then we will need to
       
  1355           ** disable the test that was generated above that makes sure
       
  1356           ** this code only executes once.  Because for a non-constant
       
  1357           ** expression we need to rerun this code each time.
       
  1358           */
       
  1359           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
       
  1360             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
       
  1361             testAddr = 0;
       
  1362           }
       
  1363 
       
  1364           /* Evaluate the expression and insert it into the temp table */
       
  1365           pParse->disableColCache++;
       
  1366           r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
       
  1367           assert( pParse->disableColCache>0 );
       
  1368           pParse->disableColCache--;
       
  1369 
       
  1370           if( isRowid ){
       
  1371             sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
       
  1372             sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
       
  1373             sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
       
  1374           }else{
       
  1375             sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
       
  1376             sqlite3ExprCacheAffinityChange(pParse, r3, 1);
       
  1377             sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
       
  1378           }
       
  1379         }
       
  1380         sqlite3ReleaseTempReg(pParse, r1);
       
  1381         sqlite3ReleaseTempReg(pParse, r2);
       
  1382       }
       
  1383       if( !isRowid ){
       
  1384         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
       
  1385       }
       
  1386       break;
       
  1387     }
       
  1388 
       
  1389     case TK_EXISTS:
       
  1390     case TK_SELECT: {
       
  1391       /* This has to be a scalar SELECT.  Generate code to put the
       
  1392       ** value of this select in a memory cell and record the number
       
  1393       ** of the memory cell in iColumn.
       
  1394       */
       
  1395       static const Token one = { (u8*)"1", 0, 1 };
       
  1396       Select *pSel;
       
  1397       SelectDest dest;
       
  1398 
       
  1399       pSel = pExpr->pSelect;
       
  1400       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
       
  1401       if( pExpr->op==TK_SELECT ){
       
  1402         dest.eDest = SRT_Mem;
       
  1403         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
       
  1404         VdbeComment((v, "Init subquery result"));
       
  1405       }else{
       
  1406         dest.eDest = SRT_Exists;
       
  1407         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
       
  1408         VdbeComment((v, "Init EXISTS result"));
       
  1409       }
       
  1410       sqlite3ExprDelete(pParse->db, pSel->pLimit);
       
  1411       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
       
  1412       if( sqlite3Select(pParse, pSel, &dest) ){
       
  1413         return;
       
  1414       }
       
  1415       pExpr->iColumn = dest.iParm;
       
  1416       break;
       
  1417     }
       
  1418   }
       
  1419 
       
  1420   if( testAddr ){
       
  1421     sqlite3VdbeJumpHere(v, testAddr-1);
       
  1422   }
       
  1423 
       
  1424   return;
       
  1425 }
       
  1426 #endif /* SQLITE_OMIT_SUBQUERY */
       
  1427 
       
  1428 /*
       
  1429 ** Duplicate an 8-byte value
       
  1430 */
       
  1431 static char *dup8bytes(Vdbe *v, const char *in){
       
  1432   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
       
  1433   if( out ){
       
  1434     memcpy(out, in, 8);
       
  1435   }
       
  1436   return out;
       
  1437 }
       
  1438 
       
  1439 /*
       
  1440 ** Generate an instruction that will put the floating point
       
  1441 ** value described by z[0..n-1] into register iMem.
       
  1442 **
       
  1443 ** The z[] string will probably not be zero-terminated.  But the 
       
  1444 ** z[n] character is guaranteed to be something that does not look
       
  1445 ** like the continuation of the number.
       
  1446 */
       
  1447 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
       
  1448   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
       
  1449   if( z ){
       
  1450     double value;
       
  1451     char *zV;
       
  1452     assert( !isdigit(z[n]) );
       
  1453     sqlite3AtoF(z, &value);
       
  1454     if( sqlite3IsNaN(value) ){
       
  1455       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
       
  1456     }else{
       
  1457       if( negateFlag ) value = -value;
       
  1458       zV = dup8bytes(v, (char*)&value);
       
  1459       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
       
  1460     }
       
  1461   }
       
  1462 }
       
  1463 
       
  1464 
       
  1465 /*
       
  1466 ** Generate an instruction that will put the integer describe by
       
  1467 ** text z[0..n-1] into register iMem.
       
  1468 **
       
  1469 ** The z[] string will probably not be zero-terminated.  But the 
       
  1470 ** z[n] character is guaranteed to be something that does not look
       
  1471 ** like the continuation of the number.
       
  1472 */
       
  1473 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
       
  1474   const char *z;
       
  1475   if( pExpr->flags & EP_IntValue ){
       
  1476     int i = pExpr->iTable;
       
  1477     if( negFlag ) i = -i;
       
  1478     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
       
  1479   }else if( (z = (char*)pExpr->token.z)!=0 ){
       
  1480     int i;
       
  1481     int n = pExpr->token.n;
       
  1482     assert( !isdigit(z[n]) );
       
  1483     if( sqlite3GetInt32(z, &i) ){
       
  1484       if( negFlag ) i = -i;
       
  1485       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
       
  1486     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
       
  1487       i64 value;
       
  1488       char *zV;
       
  1489       sqlite3Atoi64(z, &value);
       
  1490       if( negFlag ) value = -value;
       
  1491       zV = dup8bytes(v, (char*)&value);
       
  1492       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
       
  1493     }else{
       
  1494       codeReal(v, z, n, negFlag, iMem);
       
  1495     }
       
  1496   }
       
  1497 }
       
  1498 
       
  1499 
       
  1500 /*
       
  1501 ** Generate code that will extract the iColumn-th column from
       
  1502 ** table pTab and store the column value in a register.  An effort
       
  1503 ** is made to store the column value in register iReg, but this is
       
  1504 ** not guaranteed.  The location of the column value is returned.
       
  1505 **
       
  1506 ** There must be an open cursor to pTab in iTable when this routine
       
  1507 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
       
  1508 **
       
  1509 ** This routine might attempt to reuse the value of the column that
       
  1510 ** has already been loaded into a register.  The value will always
       
  1511 ** be used if it has not undergone any affinity changes.  But if
       
  1512 ** an affinity change has occurred, then the cached value will only be
       
  1513 ** used if allowAffChng is true.
       
  1514 */
       
  1515 int sqlite3ExprCodeGetColumn(
       
  1516   Parse *pParse,   /* Parsing and code generating context */
       
  1517   Table *pTab,     /* Description of the table we are reading from */
       
  1518   int iColumn,     /* Index of the table column */
       
  1519   int iTable,      /* The cursor pointing to the table */
       
  1520   int iReg,        /* Store results here */
       
  1521   int allowAffChng /* True if prior affinity changes are OK */
       
  1522 ){
       
  1523   Vdbe *v = pParse->pVdbe;
       
  1524   int i;
       
  1525   struct yColCache *p;
       
  1526 
       
  1527   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
       
  1528     if( p->iTable==iTable && p->iColumn==iColumn
       
  1529            && (!p->affChange || allowAffChng) ){
       
  1530 #if 0
       
  1531       sqlite3VdbeAddOp0(v, OP_Noop);
       
  1532       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
       
  1533 #endif
       
  1534       return p->iReg;
       
  1535     }
       
  1536   }  
       
  1537   assert( v!=0 );
       
  1538   if( iColumn<0 ){
       
  1539     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
       
  1540     sqlite3VdbeAddOp2(v, op, iTable, iReg);
       
  1541   }else if( pTab==0 ){
       
  1542     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
       
  1543   }else{
       
  1544     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
       
  1545     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
       
  1546     sqlite3ColumnDefault(v, pTab, iColumn);
       
  1547 #ifndef SQLITE_OMIT_FLOATING_POINT
       
  1548     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
       
  1549       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
       
  1550     }
       
  1551 #endif
       
  1552   }
       
  1553   if( pParse->disableColCache==0 ){
       
  1554     i = pParse->iColCache;
       
  1555     p = &pParse->aColCache[i];
       
  1556     p->iTable = iTable;
       
  1557     p->iColumn = iColumn;
       
  1558     p->iReg = iReg;
       
  1559     p->affChange = 0;
       
  1560     i++;
       
  1561     if( i>=ArraySize(pParse->aColCache) ) i = 0;
       
  1562     if( i>pParse->nColCache ) pParse->nColCache = i;
       
  1563     pParse->iColCache = i;
       
  1564   }
       
  1565   return iReg;
       
  1566 }
       
  1567 
       
  1568 /*
       
  1569 ** Clear all column cache entries associated with the vdbe
       
  1570 ** cursor with cursor number iTable.
       
  1571 */
       
  1572 void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
       
  1573   if( iTable<0 ){
       
  1574     pParse->nColCache = 0;
       
  1575     pParse->iColCache = 0;
       
  1576   }else{
       
  1577     int i;
       
  1578     for(i=0; i<pParse->nColCache; i++){
       
  1579       if( pParse->aColCache[i].iTable==iTable ){
       
  1580         testcase( i==pParse->nColCache-1 );
       
  1581         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
       
  1582         pParse->iColCache = pParse->nColCache;
       
  1583       }
       
  1584     }
       
  1585   }
       
  1586 }
       
  1587 
       
  1588 /*
       
  1589 ** Record the fact that an affinity change has occurred on iCount
       
  1590 ** registers starting with iStart.
       
  1591 */
       
  1592 void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
       
  1593   int iEnd = iStart + iCount - 1;
       
  1594   int i;
       
  1595   for(i=0; i<pParse->nColCache; i++){
       
  1596     int r = pParse->aColCache[i].iReg;
       
  1597     if( r>=iStart && r<=iEnd ){
       
  1598       pParse->aColCache[i].affChange = 1;
       
  1599     }
       
  1600   }
       
  1601 }
       
  1602 
       
  1603 /*
       
  1604 ** Generate code to move content from registers iFrom...iFrom+nReg-1
       
  1605 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
       
  1606 */
       
  1607 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
       
  1608   int i;
       
  1609   if( iFrom==iTo ) return;
       
  1610   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
       
  1611   for(i=0; i<pParse->nColCache; i++){
       
  1612     int x = pParse->aColCache[i].iReg;
       
  1613     if( x>=iFrom && x<iFrom+nReg ){
       
  1614       pParse->aColCache[i].iReg += iTo-iFrom;
       
  1615     }
       
  1616   }
       
  1617 }
       
  1618 
       
  1619 /*
       
  1620 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
       
  1621 ** over to iTo..iTo+nReg-1.
       
  1622 */
       
  1623 void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
       
  1624   int i;
       
  1625   if( iFrom==iTo ) return;
       
  1626   for(i=0; i<nReg; i++){
       
  1627     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
       
  1628   }
       
  1629 }
       
  1630 
       
  1631 /*
       
  1632 ** Return true if any register in the range iFrom..iTo (inclusive)
       
  1633 ** is used as part of the column cache.
       
  1634 */
       
  1635 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
       
  1636   int i;
       
  1637   for(i=0; i<pParse->nColCache; i++){
       
  1638     int r = pParse->aColCache[i].iReg;
       
  1639     if( r>=iFrom && r<=iTo ) return 1;
       
  1640   }
       
  1641   return 0;
       
  1642 }
       
  1643 
       
  1644 /*
       
  1645 ** Theres is a value in register iCurrent.  We ultimately want
       
  1646 ** the value to be in register iTarget.  It might be that
       
  1647 ** iCurrent and iTarget are the same register.
       
  1648 **
       
  1649 ** We are going to modify the value, so we need to make sure it
       
  1650 ** is not a cached register.  If iCurrent is a cached register,
       
  1651 ** then try to move the value over to iTarget.  If iTarget is a
       
  1652 ** cached register, then clear the corresponding cache line.
       
  1653 **
       
  1654 ** Return the register that the value ends up in.
       
  1655 */
       
  1656 int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
       
  1657   int i;
       
  1658   assert( pParse->pVdbe!=0 );
       
  1659   if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
       
  1660     return iCurrent;
       
  1661   }
       
  1662   if( iCurrent!=iTarget ){
       
  1663     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
       
  1664   }
       
  1665   for(i=0; i<pParse->nColCache; i++){
       
  1666     if( pParse->aColCache[i].iReg==iTarget ){
       
  1667       pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
       
  1668       pParse->iColCache = pParse->nColCache;
       
  1669     }
       
  1670   }
       
  1671   return iTarget;
       
  1672 }
       
  1673 
       
  1674 /*
       
  1675 ** If the last instruction coded is an ephemeral copy of any of
       
  1676 ** the registers in the nReg registers beginning with iReg, then
       
  1677 ** convert the last instruction from OP_SCopy to OP_Copy.
       
  1678 */
       
  1679 void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
       
  1680   int addr;
       
  1681   VdbeOp *pOp;
       
  1682   Vdbe *v;
       
  1683 
       
  1684   v = pParse->pVdbe;
       
  1685   addr = sqlite3VdbeCurrentAddr(v);
       
  1686   pOp = sqlite3VdbeGetOp(v, addr-1);
       
  1687   assert( pOp || pParse->db->mallocFailed );
       
  1688   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
       
  1689     pOp->opcode = OP_Copy;
       
  1690   }
       
  1691 }
       
  1692 
       
  1693 /*
       
  1694 ** Generate code to store the value of the iAlias-th alias in register
       
  1695 ** target.  The first time this is called, pExpr is evaluated to compute
       
  1696 ** the value of the alias.  The value is stored in an auxiliary register
       
  1697 ** and the number of that register is returned.  On subsequent calls,
       
  1698 ** the register number is returned without generating any code.
       
  1699 **
       
  1700 ** Note that in order for this to work, code must be generated in the
       
  1701 ** same order that it is executed.
       
  1702 **
       
  1703 ** Aliases are numbered starting with 1.  So iAlias is in the range
       
  1704 ** of 1 to pParse->nAlias inclusive.  
       
  1705 **
       
  1706 ** pParse->aAlias[iAlias-1] records the register number where the value
       
  1707 ** of the iAlias-th alias is stored.  If zero, that means that the
       
  1708 ** alias has not yet been computed.
       
  1709 */
       
  1710 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr){
       
  1711   sqlite3 *db = pParse->db;
       
  1712   int iReg;
       
  1713   if( pParse->aAlias==0 ){
       
  1714     pParse->aAlias = sqlite3DbMallocZero(db, 
       
  1715                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
       
  1716     if( db->mallocFailed ) return 0;
       
  1717   }
       
  1718   assert( iAlias>0 && iAlias<=pParse->nAlias );
       
  1719   iReg = pParse->aAlias[iAlias-1];
       
  1720   if( iReg==0 ){
       
  1721     iReg = ++pParse->nMem;
       
  1722     sqlite3ExprCode(pParse, pExpr, iReg);
       
  1723     pParse->aAlias[iAlias-1] = iReg;
       
  1724   }
       
  1725   return iReg;
       
  1726 }
       
  1727 
       
  1728 /*
       
  1729 ** Generate code into the current Vdbe to evaluate the given
       
  1730 ** expression.  Attempt to store the results in register "target".
       
  1731 ** Return the register where results are stored.
       
  1732 **
       
  1733 ** With this routine, there is no guarantee that results will
       
  1734 ** be stored in target.  The result might be stored in some other
       
  1735 ** register if it is convenient to do so.  The calling function
       
  1736 ** must check the return code and move the results to the desired
       
  1737 ** register.
       
  1738 */
       
  1739 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
       
  1740   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
       
  1741   int op;                   /* The opcode being coded */
       
  1742   int inReg = target;       /* Results stored in register inReg */
       
  1743   int regFree1 = 0;         /* If non-zero free this temporary register */
       
  1744   int regFree2 = 0;         /* If non-zero free this temporary register */
       
  1745   int r1, r2, r3, r4;       /* Various register numbers */
       
  1746   sqlite3 *db;
       
  1747 
       
  1748   db = pParse->db;
       
  1749   assert( v!=0 || db->mallocFailed );
       
  1750   assert( target>0 && target<=pParse->nMem );
       
  1751   if( v==0 ) return 0;
       
  1752 
       
  1753   if( pExpr==0 ){
       
  1754     op = TK_NULL;
       
  1755   }else{
       
  1756     op = pExpr->op;
       
  1757   }
       
  1758   switch( op ){
       
  1759     case TK_AGG_COLUMN: {
       
  1760       AggInfo *pAggInfo = pExpr->pAggInfo;
       
  1761       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
       
  1762       if( !pAggInfo->directMode ){
       
  1763         assert( pCol->iMem>0 );
       
  1764         inReg = pCol->iMem;
       
  1765         break;
       
  1766       }else if( pAggInfo->useSortingIdx ){
       
  1767         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
       
  1768                               pCol->iSorterColumn, target);
       
  1769         break;
       
  1770       }
       
  1771       /* Otherwise, fall thru into the TK_COLUMN case */
       
  1772     }
       
  1773     case TK_COLUMN: {
       
  1774       if( pExpr->iTable<0 ){
       
  1775         /* This only happens when coding check constraints */
       
  1776         assert( pParse->ckBase>0 );
       
  1777         inReg = pExpr->iColumn + pParse->ckBase;
       
  1778       }else{
       
  1779         testcase( (pExpr->flags & EP_AnyAff)!=0 );
       
  1780         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
       
  1781                                  pExpr->iColumn, pExpr->iTable, target,
       
  1782                                  pExpr->flags & EP_AnyAff);
       
  1783       }
       
  1784       break;
       
  1785     }
       
  1786     case TK_INTEGER: {
       
  1787       codeInteger(v, pExpr, 0, target);
       
  1788       break;
       
  1789     }
       
  1790     case TK_FLOAT: {
       
  1791       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
       
  1792       break;
       
  1793     }
       
  1794     case TK_STRING: {
       
  1795       sqlite3DequoteExpr(db, pExpr);
       
  1796       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
       
  1797                         (char*)pExpr->token.z, pExpr->token.n);
       
  1798       break;
       
  1799     }
       
  1800     case TK_NULL: {
       
  1801       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
       
  1802       break;
       
  1803     }
       
  1804 #ifndef SQLITE_OMIT_BLOB_LITERAL
       
  1805     case TK_BLOB: {
       
  1806       int n;
       
  1807       const char *z;
       
  1808       char *zBlob;
       
  1809       assert( pExpr->token.n>=3 );
       
  1810       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
       
  1811       assert( pExpr->token.z[1]=='\'' );
       
  1812       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
       
  1813       n = pExpr->token.n - 3;
       
  1814       z = (char*)pExpr->token.z + 2;
       
  1815       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
       
  1816       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
       
  1817       break;
       
  1818     }
       
  1819 #endif
       
  1820     case TK_VARIABLE: {
       
  1821       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
       
  1822       if( pExpr->token.n>1 ){
       
  1823         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
       
  1824       }
       
  1825       break;
       
  1826     }
       
  1827     case TK_REGISTER: {
       
  1828       inReg = pExpr->iTable;
       
  1829       break;
       
  1830     }
       
  1831     case TK_AS: {
       
  1832       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft);
       
  1833       break;
       
  1834     }
       
  1835 #ifndef SQLITE_OMIT_CAST
       
  1836     case TK_CAST: {
       
  1837       /* Expressions of the form:   CAST(pLeft AS token) */
       
  1838       int aff, to_op;
       
  1839       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
       
  1840       aff = sqlite3AffinityType(&pExpr->token);
       
  1841       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
       
  1842       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
       
  1843       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
       
  1844       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
       
  1845       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
       
  1846       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
       
  1847       testcase( to_op==OP_ToText );
       
  1848       testcase( to_op==OP_ToBlob );
       
  1849       testcase( to_op==OP_ToNumeric );
       
  1850       testcase( to_op==OP_ToInt );
       
  1851       testcase( to_op==OP_ToReal );
       
  1852       sqlite3VdbeAddOp1(v, to_op, inReg);
       
  1853       testcase( usedAsColumnCache(pParse, inReg, inReg) );
       
  1854       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
       
  1855       break;
       
  1856     }
       
  1857 #endif /* SQLITE_OMIT_CAST */
       
  1858     case TK_LT:
       
  1859     case TK_LE:
       
  1860     case TK_GT:
       
  1861     case TK_GE:
       
  1862     case TK_NE:
       
  1863     case TK_EQ: {
       
  1864       assert( TK_LT==OP_Lt );
       
  1865       assert( TK_LE==OP_Le );
       
  1866       assert( TK_GT==OP_Gt );
       
  1867       assert( TK_GE==OP_Ge );
       
  1868       assert( TK_EQ==OP_Eq );
       
  1869       assert( TK_NE==OP_Ne );
       
  1870       testcase( op==TK_LT );
       
  1871       testcase( op==TK_LE );
       
  1872       testcase( op==TK_GT );
       
  1873       testcase( op==TK_GE );
       
  1874       testcase( op==TK_EQ );
       
  1875       testcase( op==TK_NE );
       
  1876       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
       
  1877                                   pExpr->pRight, &r2, &regFree2);
       
  1878       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
       
  1879                   r1, r2, inReg, SQLITE_STOREP2);
       
  1880       testcase( regFree1==0 );
       
  1881       testcase( regFree2==0 );
       
  1882       break;
       
  1883     }
       
  1884     case TK_AND:
       
  1885     case TK_OR:
       
  1886     case TK_PLUS:
       
  1887     case TK_STAR:
       
  1888     case TK_MINUS:
       
  1889     case TK_REM:
       
  1890     case TK_BITAND:
       
  1891     case TK_BITOR:
       
  1892     case TK_SLASH:
       
  1893     case TK_LSHIFT:
       
  1894     case TK_RSHIFT: 
       
  1895     case TK_CONCAT: {
       
  1896       assert( TK_AND==OP_And );
       
  1897       assert( TK_OR==OP_Or );
       
  1898       assert( TK_PLUS==OP_Add );
       
  1899       assert( TK_MINUS==OP_Subtract );
       
  1900       assert( TK_REM==OP_Remainder );
       
  1901       assert( TK_BITAND==OP_BitAnd );
       
  1902       assert( TK_BITOR==OP_BitOr );
       
  1903       assert( TK_SLASH==OP_Divide );
       
  1904       assert( TK_LSHIFT==OP_ShiftLeft );
       
  1905       assert( TK_RSHIFT==OP_ShiftRight );
       
  1906       assert( TK_CONCAT==OP_Concat );
       
  1907       testcase( op==TK_AND );
       
  1908       testcase( op==TK_OR );
       
  1909       testcase( op==TK_PLUS );
       
  1910       testcase( op==TK_MINUS );
       
  1911       testcase( op==TK_REM );
       
  1912       testcase( op==TK_BITAND );
       
  1913       testcase( op==TK_BITOR );
       
  1914       testcase( op==TK_SLASH );
       
  1915       testcase( op==TK_LSHIFT );
       
  1916       testcase( op==TK_RSHIFT );
       
  1917       testcase( op==TK_CONCAT );
       
  1918       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
       
  1919       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
       
  1920       sqlite3VdbeAddOp3(v, op, r2, r1, target);
       
  1921       testcase( regFree1==0 );
       
  1922       testcase( regFree2==0 );
       
  1923       break;
       
  1924     }
       
  1925     case TK_UMINUS: {
       
  1926       Expr *pLeft = pExpr->pLeft;
       
  1927       assert( pLeft );
       
  1928       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
       
  1929         if( pLeft->op==TK_FLOAT ){
       
  1930           codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
       
  1931         }else{
       
  1932           codeInteger(v, pLeft, 1, target);
       
  1933         }
       
  1934       }else{
       
  1935         regFree1 = r1 = sqlite3GetTempReg(pParse);
       
  1936         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
       
  1937         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
       
  1938         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
       
  1939         testcase( regFree2==0 );
       
  1940       }
       
  1941       inReg = target;
       
  1942       break;
       
  1943     }
       
  1944     case TK_BITNOT:
       
  1945     case TK_NOT: {
       
  1946       assert( TK_BITNOT==OP_BitNot );
       
  1947       assert( TK_NOT==OP_Not );
       
  1948       testcase( op==TK_BITNOT );
       
  1949       testcase( op==TK_NOT );
       
  1950       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
       
  1951       testcase( inReg==target );
       
  1952       testcase( usedAsColumnCache(pParse, inReg, inReg) );
       
  1953       inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
       
  1954       sqlite3VdbeAddOp1(v, op, inReg);
       
  1955       break;
       
  1956     }
       
  1957     case TK_ISNULL:
       
  1958     case TK_NOTNULL: {
       
  1959       int addr;
       
  1960       assert( TK_ISNULL==OP_IsNull );
       
  1961       assert( TK_NOTNULL==OP_NotNull );
       
  1962       testcase( op==TK_ISNULL );
       
  1963       testcase( op==TK_NOTNULL );
       
  1964       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
       
  1965       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
       
  1966       testcase( regFree1==0 );
       
  1967       addr = sqlite3VdbeAddOp1(v, op, r1);
       
  1968       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
       
  1969       sqlite3VdbeJumpHere(v, addr);
       
  1970       break;
       
  1971     }
       
  1972     case TK_AGG_FUNCTION: {
       
  1973       AggInfo *pInfo = pExpr->pAggInfo;
       
  1974       if( pInfo==0 ){
       
  1975         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
       
  1976             &pExpr->span);
       
  1977       }else{
       
  1978         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
       
  1979       }
       
  1980       break;
       
  1981     }
       
  1982     case TK_CONST_FUNC:
       
  1983     case TK_FUNCTION: {
       
  1984       ExprList *pList = pExpr->pList;
       
  1985       int nExpr = pList ? pList->nExpr : 0;
       
  1986       FuncDef *pDef;
       
  1987       int nId;
       
  1988       const char *zId;
       
  1989       int constMask = 0;
       
  1990       int i;
       
  1991       u8 enc = ENC(db);
       
  1992       CollSeq *pColl = 0;
       
  1993 
       
  1994       testcase( op==TK_CONST_FUNC );
       
  1995       testcase( op==TK_FUNCTION );
       
  1996       zId = (char*)pExpr->token.z;
       
  1997       nId = pExpr->token.n;
       
  1998       pDef = sqlite3FindFunction(db, zId, nId, nExpr, enc, 0);
       
  1999       assert( pDef!=0 );
       
  2000       if( pList ){
       
  2001         nExpr = pList->nExpr;
       
  2002         r1 = sqlite3GetTempRange(pParse, nExpr);
       
  2003         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
       
  2004       }else{
       
  2005         nExpr = r1 = 0;
       
  2006       }
       
  2007 #ifndef SQLITE_OMIT_VIRTUALTABLE
       
  2008       /* Possibly overload the function if the first argument is
       
  2009       ** a virtual table column.
       
  2010       **
       
  2011       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
       
  2012       ** second argument, not the first, as the argument to test to
       
  2013       ** see if it is a column in a virtual table.  This is done because
       
  2014       ** the left operand of infix functions (the operand we want to
       
  2015       ** control overloading) ends up as the second argument to the
       
  2016       ** function.  The expression "A glob B" is equivalent to 
       
  2017       ** "glob(B,A).  We want to use the A in "A glob B" to test
       
  2018       ** for function overloading.  But we use the B term in "glob(B,A)".
       
  2019       */
       
  2020       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
       
  2021         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
       
  2022       }else if( nExpr>0 ){
       
  2023         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
       
  2024       }
       
  2025 #endif
       
  2026       for(i=0; i<nExpr && i<32; i++){
       
  2027         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
       
  2028           constMask |= (1<<i);
       
  2029         }
       
  2030         if( pDef->needCollSeq && !pColl ){
       
  2031           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
       
  2032         }
       
  2033       }
       
  2034       if( pDef->needCollSeq ){
       
  2035         if( !pColl ) pColl = db->pDfltColl; 
       
  2036         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
       
  2037       }
       
  2038       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
       
  2039                         (char*)pDef, P4_FUNCDEF);
       
  2040       sqlite3VdbeChangeP5(v, nExpr);
       
  2041       if( nExpr ){
       
  2042         sqlite3ReleaseTempRange(pParse, r1, nExpr);
       
  2043       }
       
  2044       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
       
  2045       break;
       
  2046     }
       
  2047 #ifndef SQLITE_OMIT_SUBQUERY
       
  2048     case TK_EXISTS:
       
  2049     case TK_SELECT: {
       
  2050       testcase( op==TK_EXISTS );
       
  2051       testcase( op==TK_SELECT );
       
  2052       if( pExpr->iColumn==0 ){
       
  2053         sqlite3CodeSubselect(pParse, pExpr, 0, 0);
       
  2054       }
       
  2055       inReg = pExpr->iColumn;
       
  2056       break;
       
  2057     }
       
  2058     case TK_IN: {
       
  2059       int rNotFound = 0;
       
  2060       int rMayHaveNull = 0;
       
  2061       int j2, j3, j4, j5;
       
  2062       char affinity;
       
  2063       int eType;
       
  2064 
       
  2065       VdbeNoopComment((v, "begin IN expr r%d", target));
       
  2066       eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
       
  2067       if( rMayHaveNull ){
       
  2068         rNotFound = ++pParse->nMem;
       
  2069       }
       
  2070 
       
  2071       /* Figure out the affinity to use to create a key from the results
       
  2072       ** of the expression. affinityStr stores a static string suitable for
       
  2073       ** P4 of OP_MakeRecord.
       
  2074       */
       
  2075       affinity = comparisonAffinity(pExpr);
       
  2076 
       
  2077 
       
  2078       /* Code the <expr> from "<expr> IN (...)". The temporary table
       
  2079       ** pExpr->iTable contains the values that make up the (...) set.
       
  2080       */
       
  2081       pParse->disableColCache++;
       
  2082       sqlite3ExprCode(pParse, pExpr->pLeft, target);
       
  2083       pParse->disableColCache--;
       
  2084       j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
       
  2085       if( eType==IN_INDEX_ROWID ){
       
  2086         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
       
  2087         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
       
  2088         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
       
  2089         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
       
  2090         sqlite3VdbeJumpHere(v, j3);
       
  2091         sqlite3VdbeJumpHere(v, j4);
       
  2092         sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
       
  2093       }else{
       
  2094         r2 = regFree2 = sqlite3GetTempReg(pParse);
       
  2095 
       
  2096         /* Create a record and test for set membership. If the set contains
       
  2097         ** the value, then jump to the end of the test code. The target
       
  2098         ** register still contains the true (1) value written to it earlier.
       
  2099         */
       
  2100         sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
       
  2101         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
       
  2102         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
       
  2103 
       
  2104         /* If the set membership test fails, then the result of the 
       
  2105         ** "x IN (...)" expression must be either 0 or NULL. If the set
       
  2106         ** contains no NULL values, then the result is 0. If the set 
       
  2107         ** contains one or more NULL values, then the result of the
       
  2108         ** expression is also NULL.
       
  2109         */
       
  2110         if( rNotFound==0 ){
       
  2111           /* This branch runs if it is known at compile time (now) that 
       
  2112           ** the set contains no NULL values. This happens as the result
       
  2113           ** of a "NOT NULL" constraint in the database schema. No need
       
  2114           ** to test the data structure at runtime in this case.
       
  2115           */
       
  2116           sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
       
  2117         }else{
       
  2118           /* This block populates the rNotFound register with either NULL
       
  2119           ** or 0 (an integer value). If the data structure contains one
       
  2120           ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
       
  2121           ** to 0. If register rMayHaveNull is already set to some value
       
  2122           ** other than NULL, then the test has already been run and 
       
  2123           ** rNotFound is already populated.
       
  2124           */
       
  2125           static const char nullRecord[] = { 0x02, 0x00 };
       
  2126           j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
       
  2127           sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
       
  2128           sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, 
       
  2129                              nullRecord, P4_STATIC);
       
  2130           j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
       
  2131           sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
       
  2132           sqlite3VdbeJumpHere(v, j4);
       
  2133           sqlite3VdbeJumpHere(v, j3);
       
  2134 
       
  2135           /* Copy the value of register rNotFound (which is either NULL or 0)
       
  2136           ** into the target register. This will be the result of the
       
  2137           ** expression.
       
  2138           */
       
  2139           sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
       
  2140         }
       
  2141       }
       
  2142       sqlite3VdbeJumpHere(v, j2);
       
  2143       sqlite3VdbeJumpHere(v, j5);
       
  2144       VdbeComment((v, "end IN expr r%d", target));
       
  2145       break;
       
  2146     }
       
  2147 #endif
       
  2148     /*
       
  2149     **    x BETWEEN y AND z
       
  2150     **
       
  2151     ** This is equivalent to
       
  2152     **
       
  2153     **    x>=y AND x<=z
       
  2154     **
       
  2155     ** X is stored in pExpr->pLeft.
       
  2156     ** Y is stored in pExpr->pList->a[0].pExpr.
       
  2157     ** Z is stored in pExpr->pList->a[1].pExpr.
       
  2158     */
       
  2159     case TK_BETWEEN: {
       
  2160       Expr *pLeft = pExpr->pLeft;
       
  2161       struct ExprList_item *pLItem = pExpr->pList->a;
       
  2162       Expr *pRight = pLItem->pExpr;
       
  2163 
       
  2164       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
       
  2165                                   pRight, &r2, &regFree2);
       
  2166       testcase( regFree1==0 );
       
  2167       testcase( regFree2==0 );
       
  2168       r3 = sqlite3GetTempReg(pParse);
       
  2169       r4 = sqlite3GetTempReg(pParse);
       
  2170       codeCompare(pParse, pLeft, pRight, OP_Ge,
       
  2171                   r1, r2, r3, SQLITE_STOREP2);
       
  2172       pLItem++;
       
  2173       pRight = pLItem->pExpr;
       
  2174       sqlite3ReleaseTempReg(pParse, regFree2);
       
  2175       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
       
  2176       testcase( regFree2==0 );
       
  2177       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
       
  2178       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
       
  2179       sqlite3ReleaseTempReg(pParse, r3);
       
  2180       sqlite3ReleaseTempReg(pParse, r4);
       
  2181       break;
       
  2182     }
       
  2183     case TK_UPLUS: {
       
  2184       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
       
  2185       break;
       
  2186     }
       
  2187 
       
  2188     /*
       
  2189     ** Form A:
       
  2190     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
       
  2191     **
       
  2192     ** Form B:
       
  2193     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
       
  2194     **
       
  2195     ** Form A is can be transformed into the equivalent form B as follows:
       
  2196     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
       
  2197     **        WHEN x=eN THEN rN ELSE y END
       
  2198     **
       
  2199     ** X (if it exists) is in pExpr->pLeft.
       
  2200     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
       
  2201     ** ELSE clause and no other term matches, then the result of the
       
  2202     ** exprssion is NULL.
       
  2203     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
       
  2204     **
       
  2205     ** The result of the expression is the Ri for the first matching Ei,
       
  2206     ** or if there is no matching Ei, the ELSE term Y, or if there is
       
  2207     ** no ELSE term, NULL.
       
  2208     */
       
  2209     case TK_CASE: {
       
  2210       int endLabel;                     /* GOTO label for end of CASE stmt */
       
  2211       int nextCase;                     /* GOTO label for next WHEN clause */
       
  2212       int nExpr;                        /* 2x number of WHEN terms */
       
  2213       int i;                            /* Loop counter */
       
  2214       ExprList *pEList;                 /* List of WHEN terms */
       
  2215       struct ExprList_item *aListelem;  /* Array of WHEN terms */
       
  2216       Expr opCompare;                   /* The X==Ei expression */
       
  2217       Expr cacheX;                      /* Cached expression X */
       
  2218       Expr *pX;                         /* The X expression */
       
  2219       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
       
  2220 
       
  2221       assert(pExpr->pList);
       
  2222       assert((pExpr->pList->nExpr % 2) == 0);
       
  2223       assert(pExpr->pList->nExpr > 0);
       
  2224       pEList = pExpr->pList;
       
  2225       aListelem = pEList->a;
       
  2226       nExpr = pEList->nExpr;
       
  2227       endLabel = sqlite3VdbeMakeLabel(v);
       
  2228       if( (pX = pExpr->pLeft)!=0 ){
       
  2229         cacheX = *pX;
       
  2230         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
       
  2231         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
       
  2232         testcase( regFree1==0 );
       
  2233         cacheX.op = TK_REGISTER;
       
  2234         opCompare.op = TK_EQ;
       
  2235         opCompare.pLeft = &cacheX;
       
  2236         pTest = &opCompare;
       
  2237       }
       
  2238       pParse->disableColCache++;
       
  2239       for(i=0; i<nExpr; i=i+2){
       
  2240         if( pX ){
       
  2241           opCompare.pRight = aListelem[i].pExpr;
       
  2242         }else{
       
  2243           pTest = aListelem[i].pExpr;
       
  2244         }
       
  2245         nextCase = sqlite3VdbeMakeLabel(v);
       
  2246         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
       
  2247         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
       
  2248         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
       
  2249         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
       
  2250         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
       
  2251         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
       
  2252         sqlite3VdbeResolveLabel(v, nextCase);
       
  2253       }
       
  2254       if( pExpr->pRight ){
       
  2255         sqlite3ExprCode(pParse, pExpr->pRight, target);
       
  2256       }else{
       
  2257         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
       
  2258       }
       
  2259       sqlite3VdbeResolveLabel(v, endLabel);
       
  2260       assert( pParse->disableColCache>0 );
       
  2261       pParse->disableColCache--;
       
  2262       break;
       
  2263     }
       
  2264 #ifndef SQLITE_OMIT_TRIGGER
       
  2265     case TK_RAISE: {
       
  2266       if( !pParse->trigStack ){
       
  2267         sqlite3ErrorMsg(pParse,
       
  2268                        "RAISE() may only be used within a trigger-program");
       
  2269         return 0;
       
  2270       }
       
  2271       if( pExpr->iColumn!=OE_Ignore ){
       
  2272          assert( pExpr->iColumn==OE_Rollback ||
       
  2273                  pExpr->iColumn == OE_Abort ||
       
  2274                  pExpr->iColumn == OE_Fail );
       
  2275          sqlite3DequoteExpr(db, pExpr);
       
  2276          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
       
  2277                         (char*)pExpr->token.z, pExpr->token.n);
       
  2278       } else {
       
  2279          assert( pExpr->iColumn == OE_Ignore );
       
  2280          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
       
  2281          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
       
  2282          VdbeComment((v, "raise(IGNORE)"));
       
  2283       }
       
  2284       break;
       
  2285     }
       
  2286 #endif
       
  2287   }
       
  2288   sqlite3ReleaseTempReg(pParse, regFree1);
       
  2289   sqlite3ReleaseTempReg(pParse, regFree2);
       
  2290   return inReg;
       
  2291 }
       
  2292 
       
  2293 /*
       
  2294 ** Generate code to evaluate an expression and store the results
       
  2295 ** into a register.  Return the register number where the results
       
  2296 ** are stored.
       
  2297 **
       
  2298 ** If the register is a temporary register that can be deallocated,
       
  2299 ** then write its number into *pReg.  If the result register is not
       
  2300 ** a temporary, then set *pReg to zero.
       
  2301 */
       
  2302 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
       
  2303   int r1 = sqlite3GetTempReg(pParse);
       
  2304   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
       
  2305   if( r2==r1 ){
       
  2306     *pReg = r1;
       
  2307   }else{
       
  2308     sqlite3ReleaseTempReg(pParse, r1);
       
  2309     *pReg = 0;
       
  2310   }
       
  2311   return r2;
       
  2312 }
       
  2313 
       
  2314 /*
       
  2315 ** Generate code that will evaluate expression pExpr and store the
       
  2316 ** results in register target.  The results are guaranteed to appear
       
  2317 ** in register target.
       
  2318 */
       
  2319 int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
       
  2320   int inReg;
       
  2321 
       
  2322   assert( target>0 && target<=pParse->nMem );
       
  2323   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
       
  2324   assert( pParse->pVdbe || pParse->db->mallocFailed );
       
  2325   if( inReg!=target && pParse->pVdbe ){
       
  2326     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
       
  2327   }
       
  2328   return target;
       
  2329 }
       
  2330 
       
  2331 /*
       
  2332 ** Generate code that evalutes the given expression and puts the result
       
  2333 ** in register target.
       
  2334 **
       
  2335 ** Also make a copy of the expression results into another "cache" register
       
  2336 ** and modify the expression so that the next time it is evaluated,
       
  2337 ** the result is a copy of the cache register.
       
  2338 **
       
  2339 ** This routine is used for expressions that are used multiple 
       
  2340 ** times.  They are evaluated once and the results of the expression
       
  2341 ** are reused.
       
  2342 */
       
  2343 int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
       
  2344   Vdbe *v = pParse->pVdbe;
       
  2345   int inReg;
       
  2346   inReg = sqlite3ExprCode(pParse, pExpr, target);
       
  2347   assert( target>0 );
       
  2348   if( pExpr->op!=TK_REGISTER ){  
       
  2349     int iMem;
       
  2350     iMem = ++pParse->nMem;
       
  2351     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
       
  2352     pExpr->iTable = iMem;
       
  2353     pExpr->op = TK_REGISTER;
       
  2354   }
       
  2355   return inReg;
       
  2356 }
       
  2357 
       
  2358 /*
       
  2359 ** Return TRUE if pExpr is an constant expression that is appropriate
       
  2360 ** for factoring out of a loop.  Appropriate expressions are:
       
  2361 **
       
  2362 **    *  Any expression that evaluates to two or more opcodes.
       
  2363 **
       
  2364 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
       
  2365 **       or OP_Variable that does not need to be placed in a 
       
  2366 **       specific register.
       
  2367 **
       
  2368 ** There is no point in factoring out single-instruction constant
       
  2369 ** expressions that need to be placed in a particular register.  
       
  2370 ** We could factor them out, but then we would end up adding an
       
  2371 ** OP_SCopy instruction to move the value into the correct register
       
  2372 ** later.  We might as well just use the original instruction and
       
  2373 ** avoid the OP_SCopy.
       
  2374 */
       
  2375 static int isAppropriateForFactoring(Expr *p){
       
  2376   if( !sqlite3ExprIsConstantNotJoin(p) ){
       
  2377     return 0;  /* Only constant expressions are appropriate for factoring */
       
  2378   }
       
  2379   if( (p->flags & EP_FixedDest)==0 ){
       
  2380     return 1;  /* Any constant without a fixed destination is appropriate */
       
  2381   }
       
  2382   while( p->op==TK_UPLUS ) p = p->pLeft;
       
  2383   switch( p->op ){
       
  2384 #ifndef SQLITE_OMIT_BLOB_LITERAL
       
  2385     case TK_BLOB:
       
  2386 #endif
       
  2387     case TK_VARIABLE:
       
  2388     case TK_INTEGER:
       
  2389     case TK_FLOAT:
       
  2390     case TK_NULL:
       
  2391     case TK_STRING: {
       
  2392       testcase( p->op==TK_BLOB );
       
  2393       testcase( p->op==TK_VARIABLE );
       
  2394       testcase( p->op==TK_INTEGER );
       
  2395       testcase( p->op==TK_FLOAT );
       
  2396       testcase( p->op==TK_NULL );
       
  2397       testcase( p->op==TK_STRING );
       
  2398       /* Single-instruction constants with a fixed destination are
       
  2399       ** better done in-line.  If we factor them, they will just end
       
  2400       ** up generating an OP_SCopy to move the value to the destination
       
  2401       ** register. */
       
  2402       return 0;
       
  2403     }
       
  2404     case TK_UMINUS: {
       
  2405        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
       
  2406          return 0;
       
  2407        }
       
  2408        break;
       
  2409     }
       
  2410     default: {
       
  2411       break;
       
  2412     }
       
  2413   }
       
  2414   return 1;
       
  2415 }
       
  2416 
       
  2417 /*
       
  2418 ** If pExpr is a constant expression that is appropriate for
       
  2419 ** factoring out of a loop, then evaluate the expression
       
  2420 ** into a register and convert the expression into a TK_REGISTER
       
  2421 ** expression.
       
  2422 */
       
  2423 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
       
  2424   Parse *pParse = pWalker->pParse;
       
  2425   switch( pExpr->op ){
       
  2426     case TK_REGISTER: {
       
  2427       return 1;
       
  2428     }
       
  2429     case TK_FUNCTION:
       
  2430     case TK_AGG_FUNCTION:
       
  2431     case TK_CONST_FUNC: {
       
  2432       /* The arguments to a function have a fixed destination.
       
  2433       ** Mark them this way to avoid generated unneeded OP_SCopy
       
  2434       ** instructions. 
       
  2435       */
       
  2436       ExprList *pList = pExpr->pList;
       
  2437       if( pList ){
       
  2438         int i = pList->nExpr;
       
  2439         struct ExprList_item *pItem = pList->a;
       
  2440         for(; i>0; i--, pItem++){
       
  2441           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
       
  2442         }
       
  2443       }
       
  2444       break;
       
  2445     }
       
  2446   }
       
  2447   if( isAppropriateForFactoring(pExpr) ){
       
  2448     int r1 = ++pParse->nMem;
       
  2449     int r2;
       
  2450     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
       
  2451     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
       
  2452     pExpr->op = TK_REGISTER;
       
  2453     pExpr->iTable = r2;
       
  2454     return WRC_Prune;
       
  2455   }
       
  2456   return WRC_Continue;
       
  2457 }
       
  2458 
       
  2459 /*
       
  2460 ** Preevaluate constant subexpressions within pExpr and store the
       
  2461 ** results in registers.  Modify pExpr so that the constant subexpresions
       
  2462 ** are TK_REGISTER opcodes that refer to the precomputed values.
       
  2463 */
       
  2464 void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
       
  2465   Walker w;
       
  2466   w.xExprCallback = evalConstExpr;
       
  2467   w.xSelectCallback = 0;
       
  2468   w.pParse = pParse;
       
  2469   sqlite3WalkExpr(&w, pExpr);
       
  2470 }
       
  2471 
       
  2472 
       
  2473 /*
       
  2474 ** Generate code that pushes the value of every element of the given
       
  2475 ** expression list into a sequence of registers beginning at target.
       
  2476 **
       
  2477 ** Return the number of elements evaluated.
       
  2478 */
       
  2479 int sqlite3ExprCodeExprList(
       
  2480   Parse *pParse,     /* Parsing context */
       
  2481   ExprList *pList,   /* The expression list to be coded */
       
  2482   int target,        /* Where to write results */
       
  2483   int doHardCopy     /* Make a hard copy of every element */
       
  2484 ){
       
  2485   struct ExprList_item *pItem;
       
  2486   int i, n;
       
  2487   assert( pList!=0 );
       
  2488   assert( target>0 );
       
  2489   n = pList->nExpr;
       
  2490   for(pItem=pList->a, i=0; i<n; i++, pItem++){
       
  2491     if( pItem->iAlias ){
       
  2492       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr);
       
  2493       Vdbe *v = sqlite3GetVdbe(pParse);
       
  2494       sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
       
  2495     }else{
       
  2496       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
       
  2497     }
       
  2498     if( doHardCopy ){
       
  2499       sqlite3ExprHardCopy(pParse, target, n);
       
  2500     }
       
  2501   }
       
  2502   return n;
       
  2503 }
       
  2504 
       
  2505 /*
       
  2506 ** Generate code for a boolean expression such that a jump is made
       
  2507 ** to the label "dest" if the expression is true but execution
       
  2508 ** continues straight thru if the expression is false.
       
  2509 **
       
  2510 ** If the expression evaluates to NULL (neither true nor false), then
       
  2511 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
       
  2512 **
       
  2513 ** This code depends on the fact that certain token values (ex: TK_EQ)
       
  2514 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
       
  2515 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
       
  2516 ** the make process cause these values to align.  Assert()s in the code
       
  2517 ** below verify that the numbers are aligned correctly.
       
  2518 */
       
  2519 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
       
  2520   Vdbe *v = pParse->pVdbe;
       
  2521   int op = 0;
       
  2522   int regFree1 = 0;
       
  2523   int regFree2 = 0;
       
  2524   int r1, r2;
       
  2525 
       
  2526   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
       
  2527   if( v==0 || pExpr==0 ) return;
       
  2528   op = pExpr->op;
       
  2529   switch( op ){
       
  2530     case TK_AND: {
       
  2531       int d2 = sqlite3VdbeMakeLabel(v);
       
  2532       testcase( jumpIfNull==0 );
       
  2533       testcase( pParse->disableColCache==0 );
       
  2534       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
       
  2535       pParse->disableColCache++;
       
  2536       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
       
  2537       assert( pParse->disableColCache>0 );
       
  2538       pParse->disableColCache--;
       
  2539       sqlite3VdbeResolveLabel(v, d2);
       
  2540       break;
       
  2541     }
       
  2542     case TK_OR: {
       
  2543       testcase( jumpIfNull==0 );
       
  2544       testcase( pParse->disableColCache==0 );
       
  2545       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
       
  2546       pParse->disableColCache++;
       
  2547       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
       
  2548       assert( pParse->disableColCache>0 );
       
  2549       pParse->disableColCache--;
       
  2550       break;
       
  2551     }
       
  2552     case TK_NOT: {
       
  2553       testcase( jumpIfNull==0 );
       
  2554       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
       
  2555       break;
       
  2556     }
       
  2557     case TK_LT:
       
  2558     case TK_LE:
       
  2559     case TK_GT:
       
  2560     case TK_GE:
       
  2561     case TK_NE:
       
  2562     case TK_EQ: {
       
  2563       assert( TK_LT==OP_Lt );
       
  2564       assert( TK_LE==OP_Le );
       
  2565       assert( TK_GT==OP_Gt );
       
  2566       assert( TK_GE==OP_Ge );
       
  2567       assert( TK_EQ==OP_Eq );
       
  2568       assert( TK_NE==OP_Ne );
       
  2569       testcase( op==TK_LT );
       
  2570       testcase( op==TK_LE );
       
  2571       testcase( op==TK_GT );
       
  2572       testcase( op==TK_GE );
       
  2573       testcase( op==TK_EQ );
       
  2574       testcase( op==TK_NE );
       
  2575       testcase( jumpIfNull==0 );
       
  2576       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
       
  2577                                   pExpr->pRight, &r2, &regFree2);
       
  2578       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
       
  2579                   r1, r2, dest, jumpIfNull);
       
  2580       testcase( regFree1==0 );
       
  2581       testcase( regFree2==0 );
       
  2582       break;
       
  2583     }
       
  2584     case TK_ISNULL:
       
  2585     case TK_NOTNULL: {
       
  2586       assert( TK_ISNULL==OP_IsNull );
       
  2587       assert( TK_NOTNULL==OP_NotNull );
       
  2588       testcase( op==TK_ISNULL );
       
  2589       testcase( op==TK_NOTNULL );
       
  2590       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
       
  2591       sqlite3VdbeAddOp2(v, op, r1, dest);
       
  2592       testcase( regFree1==0 );
       
  2593       break;
       
  2594     }
       
  2595     case TK_BETWEEN: {
       
  2596       /*    x BETWEEN y AND z
       
  2597       **
       
  2598       ** Is equivalent to 
       
  2599       **
       
  2600       **    x>=y AND x<=z
       
  2601       **
       
  2602       ** Code it as such, taking care to do the common subexpression
       
  2603       ** elementation of x.
       
  2604       */
       
  2605       Expr exprAnd;
       
  2606       Expr compLeft;
       
  2607       Expr compRight;
       
  2608       Expr exprX;
       
  2609 
       
  2610       exprX = *pExpr->pLeft;
       
  2611       exprAnd.op = TK_AND;
       
  2612       exprAnd.pLeft = &compLeft;
       
  2613       exprAnd.pRight = &compRight;
       
  2614       compLeft.op = TK_GE;
       
  2615       compLeft.pLeft = &exprX;
       
  2616       compLeft.pRight = pExpr->pList->a[0].pExpr;
       
  2617       compRight.op = TK_LE;
       
  2618       compRight.pLeft = &exprX;
       
  2619       compRight.pRight = pExpr->pList->a[1].pExpr;
       
  2620       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
       
  2621       testcase( regFree1==0 );
       
  2622       exprX.op = TK_REGISTER;
       
  2623       testcase( jumpIfNull==0 );
       
  2624       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
       
  2625       break;
       
  2626     }
       
  2627     default: {
       
  2628       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
       
  2629       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
       
  2630       testcase( regFree1==0 );
       
  2631       testcase( jumpIfNull==0 );
       
  2632       break;
       
  2633     }
       
  2634   }
       
  2635   sqlite3ReleaseTempReg(pParse, regFree1);
       
  2636   sqlite3ReleaseTempReg(pParse, regFree2);  
       
  2637 }
       
  2638 
       
  2639 /*
       
  2640 ** Generate code for a boolean expression such that a jump is made
       
  2641 ** to the label "dest" if the expression is false but execution
       
  2642 ** continues straight thru if the expression is true.
       
  2643 **
       
  2644 ** If the expression evaluates to NULL (neither true nor false) then
       
  2645 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
       
  2646 ** is 0.
       
  2647 */
       
  2648 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
       
  2649   Vdbe *v = pParse->pVdbe;
       
  2650   int op = 0;
       
  2651   int regFree1 = 0;
       
  2652   int regFree2 = 0;
       
  2653   int r1, r2;
       
  2654 
       
  2655   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
       
  2656   if( v==0 || pExpr==0 ) return;
       
  2657 
       
  2658   /* The value of pExpr->op and op are related as follows:
       
  2659   **
       
  2660   **       pExpr->op            op
       
  2661   **       ---------          ----------
       
  2662   **       TK_ISNULL          OP_NotNull
       
  2663   **       TK_NOTNULL         OP_IsNull
       
  2664   **       TK_NE              OP_Eq
       
  2665   **       TK_EQ              OP_Ne
       
  2666   **       TK_GT              OP_Le
       
  2667   **       TK_LE              OP_Gt
       
  2668   **       TK_GE              OP_Lt
       
  2669   **       TK_LT              OP_Ge
       
  2670   **
       
  2671   ** For other values of pExpr->op, op is undefined and unused.
       
  2672   ** The value of TK_ and OP_ constants are arranged such that we
       
  2673   ** can compute the mapping above using the following expression.
       
  2674   ** Assert()s verify that the computation is correct.
       
  2675   */
       
  2676   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
       
  2677 
       
  2678   /* Verify correct alignment of TK_ and OP_ constants
       
  2679   */
       
  2680   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
       
  2681   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
       
  2682   assert( pExpr->op!=TK_NE || op==OP_Eq );
       
  2683   assert( pExpr->op!=TK_EQ || op==OP_Ne );
       
  2684   assert( pExpr->op!=TK_LT || op==OP_Ge );
       
  2685   assert( pExpr->op!=TK_LE || op==OP_Gt );
       
  2686   assert( pExpr->op!=TK_GT || op==OP_Le );
       
  2687   assert( pExpr->op!=TK_GE || op==OP_Lt );
       
  2688 
       
  2689   switch( pExpr->op ){
       
  2690     case TK_AND: {
       
  2691       testcase( jumpIfNull==0 );
       
  2692       testcase( pParse->disableColCache==0 );
       
  2693       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
       
  2694       pParse->disableColCache++;
       
  2695       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
       
  2696       assert( pParse->disableColCache>0 );
       
  2697       pParse->disableColCache--;
       
  2698       break;
       
  2699     }
       
  2700     case TK_OR: {
       
  2701       int d2 = sqlite3VdbeMakeLabel(v);
       
  2702       testcase( jumpIfNull==0 );
       
  2703       testcase( pParse->disableColCache==0 );
       
  2704       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
       
  2705       pParse->disableColCache++;
       
  2706       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
       
  2707       assert( pParse->disableColCache>0 );
       
  2708       pParse->disableColCache--;
       
  2709       sqlite3VdbeResolveLabel(v, d2);
       
  2710       break;
       
  2711     }
       
  2712     case TK_NOT: {
       
  2713       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
       
  2714       break;
       
  2715     }
       
  2716     case TK_LT:
       
  2717     case TK_LE:
       
  2718     case TK_GT:
       
  2719     case TK_GE:
       
  2720     case TK_NE:
       
  2721     case TK_EQ: {
       
  2722       testcase( op==TK_LT );
       
  2723       testcase( op==TK_LE );
       
  2724       testcase( op==TK_GT );
       
  2725       testcase( op==TK_GE );
       
  2726       testcase( op==TK_EQ );
       
  2727       testcase( op==TK_NE );
       
  2728       testcase( jumpIfNull==0 );
       
  2729       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
       
  2730                                   pExpr->pRight, &r2, &regFree2);
       
  2731       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
       
  2732                   r1, r2, dest, jumpIfNull);
       
  2733       testcase( regFree1==0 );
       
  2734       testcase( regFree2==0 );
       
  2735       break;
       
  2736     }
       
  2737     case TK_ISNULL:
       
  2738     case TK_NOTNULL: {
       
  2739       testcase( op==TK_ISNULL );
       
  2740       testcase( op==TK_NOTNULL );
       
  2741       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
       
  2742       sqlite3VdbeAddOp2(v, op, r1, dest);
       
  2743       testcase( regFree1==0 );
       
  2744       break;
       
  2745     }
       
  2746     case TK_BETWEEN: {
       
  2747       /*    x BETWEEN y AND z
       
  2748       **
       
  2749       ** Is equivalent to 
       
  2750       **
       
  2751       **    x>=y AND x<=z
       
  2752       **
       
  2753       ** Code it as such, taking care to do the common subexpression
       
  2754       ** elementation of x.
       
  2755       */
       
  2756       Expr exprAnd;
       
  2757       Expr compLeft;
       
  2758       Expr compRight;
       
  2759       Expr exprX;
       
  2760 
       
  2761       exprX = *pExpr->pLeft;
       
  2762       exprAnd.op = TK_AND;
       
  2763       exprAnd.pLeft = &compLeft;
       
  2764       exprAnd.pRight = &compRight;
       
  2765       compLeft.op = TK_GE;
       
  2766       compLeft.pLeft = &exprX;
       
  2767       compLeft.pRight = pExpr->pList->a[0].pExpr;
       
  2768       compRight.op = TK_LE;
       
  2769       compRight.pLeft = &exprX;
       
  2770       compRight.pRight = pExpr->pList->a[1].pExpr;
       
  2771       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
       
  2772       testcase( regFree1==0 );
       
  2773       exprX.op = TK_REGISTER;
       
  2774       testcase( jumpIfNull==0 );
       
  2775       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
       
  2776       break;
       
  2777     }
       
  2778     default: {
       
  2779       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
       
  2780       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
       
  2781       testcase( regFree1==0 );
       
  2782       testcase( jumpIfNull==0 );
       
  2783       break;
       
  2784     }
       
  2785   }
       
  2786   sqlite3ReleaseTempReg(pParse, regFree1);
       
  2787   sqlite3ReleaseTempReg(pParse, regFree2);
       
  2788 }
       
  2789 
       
  2790 /*
       
  2791 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
       
  2792 ** if they are identical and return FALSE if they differ in any way.
       
  2793 **
       
  2794 ** Sometimes this routine will return FALSE even if the two expressions
       
  2795 ** really are equivalent.  If we cannot prove that the expressions are
       
  2796 ** identical, we return FALSE just to be safe.  So if this routine
       
  2797 ** returns false, then you do not really know for certain if the two
       
  2798 ** expressions are the same.  But if you get a TRUE return, then you
       
  2799 ** can be sure the expressions are the same.  In the places where
       
  2800 ** this routine is used, it does not hurt to get an extra FALSE - that
       
  2801 ** just might result in some slightly slower code.  But returning
       
  2802 ** an incorrect TRUE could lead to a malfunction.
       
  2803 */
       
  2804 int sqlite3ExprCompare(Expr *pA, Expr *pB){
       
  2805   int i;
       
  2806   if( pA==0||pB==0 ){
       
  2807     return pB==pA;
       
  2808   }
       
  2809   if( pA->op!=pB->op ) return 0;
       
  2810   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
       
  2811   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
       
  2812   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
       
  2813   if( pA->pList ){
       
  2814     if( pB->pList==0 ) return 0;
       
  2815     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
       
  2816     for(i=0; i<pA->pList->nExpr; i++){
       
  2817       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
       
  2818         return 0;
       
  2819       }
       
  2820     }
       
  2821   }else if( pB->pList ){
       
  2822     return 0;
       
  2823   }
       
  2824   if( pA->pSelect || pB->pSelect ) return 0;
       
  2825   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
       
  2826   if( pA->op!=TK_COLUMN && pA->token.z ){
       
  2827     if( pB->token.z==0 ) return 0;
       
  2828     if( pB->token.n!=pA->token.n ) return 0;
       
  2829     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
       
  2830       return 0;
       
  2831     }
       
  2832   }
       
  2833   return 1;
       
  2834 }
       
  2835 
       
  2836 
       
  2837 /*
       
  2838 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
       
  2839 ** the new element.  Return a negative number if malloc fails.
       
  2840 */
       
  2841 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
       
  2842   int i;
       
  2843   pInfo->aCol = sqlite3ArrayAllocate(
       
  2844        db,
       
  2845        pInfo->aCol,
       
  2846        sizeof(pInfo->aCol[0]),
       
  2847        3,
       
  2848        &pInfo->nColumn,
       
  2849        &pInfo->nColumnAlloc,
       
  2850        &i
       
  2851   );
       
  2852   return i;
       
  2853 }    
       
  2854 
       
  2855 /*
       
  2856 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
       
  2857 ** the new element.  Return a negative number if malloc fails.
       
  2858 */
       
  2859 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
       
  2860   int i;
       
  2861   pInfo->aFunc = sqlite3ArrayAllocate(
       
  2862        db, 
       
  2863        pInfo->aFunc,
       
  2864        sizeof(pInfo->aFunc[0]),
       
  2865        3,
       
  2866        &pInfo->nFunc,
       
  2867        &pInfo->nFuncAlloc,
       
  2868        &i
       
  2869   );
       
  2870   return i;
       
  2871 }    
       
  2872 
       
  2873 /*
       
  2874 ** This is the xExprCallback for a tree walker.  It is used to
       
  2875 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
       
  2876 ** for additional information.
       
  2877 */
       
  2878 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
       
  2879   int i;
       
  2880   NameContext *pNC = pWalker->u.pNC;
       
  2881   Parse *pParse = pNC->pParse;
       
  2882   SrcList *pSrcList = pNC->pSrcList;
       
  2883   AggInfo *pAggInfo = pNC->pAggInfo;
       
  2884 
       
  2885   switch( pExpr->op ){
       
  2886     case TK_AGG_COLUMN:
       
  2887     case TK_COLUMN: {
       
  2888       testcase( pExpr->op==TK_AGG_COLUMN );
       
  2889       testcase( pExpr->op==TK_COLUMN );
       
  2890       /* Check to see if the column is in one of the tables in the FROM
       
  2891       ** clause of the aggregate query */
       
  2892       if( pSrcList ){
       
  2893         struct SrcList_item *pItem = pSrcList->a;
       
  2894         for(i=0; i<pSrcList->nSrc; i++, pItem++){
       
  2895           struct AggInfo_col *pCol;
       
  2896           if( pExpr->iTable==pItem->iCursor ){
       
  2897             /* If we reach this point, it means that pExpr refers to a table
       
  2898             ** that is in the FROM clause of the aggregate query.  
       
  2899             **
       
  2900             ** Make an entry for the column in pAggInfo->aCol[] if there
       
  2901             ** is not an entry there already.
       
  2902             */
       
  2903             int k;
       
  2904             pCol = pAggInfo->aCol;
       
  2905             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
       
  2906               if( pCol->iTable==pExpr->iTable &&
       
  2907                   pCol->iColumn==pExpr->iColumn ){
       
  2908                 break;
       
  2909               }
       
  2910             }
       
  2911             if( (k>=pAggInfo->nColumn)
       
  2912              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
       
  2913             ){
       
  2914               pCol = &pAggInfo->aCol[k];
       
  2915               pCol->pTab = pExpr->pTab;
       
  2916               pCol->iTable = pExpr->iTable;
       
  2917               pCol->iColumn = pExpr->iColumn;
       
  2918               pCol->iMem = ++pParse->nMem;
       
  2919               pCol->iSorterColumn = -1;
       
  2920               pCol->pExpr = pExpr;
       
  2921               if( pAggInfo->pGroupBy ){
       
  2922                 int j, n;
       
  2923                 ExprList *pGB = pAggInfo->pGroupBy;
       
  2924                 struct ExprList_item *pTerm = pGB->a;
       
  2925                 n = pGB->nExpr;
       
  2926                 for(j=0; j<n; j++, pTerm++){
       
  2927                   Expr *pE = pTerm->pExpr;
       
  2928                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
       
  2929                       pE->iColumn==pExpr->iColumn ){
       
  2930                     pCol->iSorterColumn = j;
       
  2931                     break;
       
  2932                   }
       
  2933                 }
       
  2934               }
       
  2935               if( pCol->iSorterColumn<0 ){
       
  2936                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
       
  2937               }
       
  2938             }
       
  2939             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
       
  2940             ** because it was there before or because we just created it).
       
  2941             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
       
  2942             ** pAggInfo->aCol[] entry.
       
  2943             */
       
  2944             pExpr->pAggInfo = pAggInfo;
       
  2945             pExpr->op = TK_AGG_COLUMN;
       
  2946             pExpr->iAgg = k;
       
  2947             break;
       
  2948           } /* endif pExpr->iTable==pItem->iCursor */
       
  2949         } /* end loop over pSrcList */
       
  2950       }
       
  2951       return WRC_Prune;
       
  2952     }
       
  2953     case TK_AGG_FUNCTION: {
       
  2954       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
       
  2955       ** to be ignored */
       
  2956       if( pNC->nDepth==0 ){
       
  2957         /* Check to see if pExpr is a duplicate of another aggregate 
       
  2958         ** function that is already in the pAggInfo structure
       
  2959         */
       
  2960         struct AggInfo_func *pItem = pAggInfo->aFunc;
       
  2961         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
       
  2962           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
       
  2963             break;
       
  2964           }
       
  2965         }
       
  2966         if( i>=pAggInfo->nFunc ){
       
  2967           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
       
  2968           */
       
  2969           u8 enc = ENC(pParse->db);
       
  2970           i = addAggInfoFunc(pParse->db, pAggInfo);
       
  2971           if( i>=0 ){
       
  2972             pItem = &pAggInfo->aFunc[i];
       
  2973             pItem->pExpr = pExpr;
       
  2974             pItem->iMem = ++pParse->nMem;
       
  2975             pItem->pFunc = sqlite3FindFunction(pParse->db,
       
  2976                    (char*)pExpr->token.z, pExpr->token.n,
       
  2977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
       
  2978             if( pExpr->flags & EP_Distinct ){
       
  2979               pItem->iDistinct = pParse->nTab++;
       
  2980             }else{
       
  2981               pItem->iDistinct = -1;
       
  2982             }
       
  2983           }
       
  2984         }
       
  2985         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
       
  2986         */
       
  2987         pExpr->iAgg = i;
       
  2988         pExpr->pAggInfo = pAggInfo;
       
  2989         return WRC_Prune;
       
  2990       }
       
  2991     }
       
  2992   }
       
  2993   return WRC_Continue;
       
  2994 }
       
  2995 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
       
  2996   NameContext *pNC = pWalker->u.pNC;
       
  2997   if( pNC->nDepth==0 ){
       
  2998     pNC->nDepth++;
       
  2999     sqlite3WalkSelect(pWalker, pSelect);
       
  3000     pNC->nDepth--;
       
  3001     return WRC_Prune;
       
  3002   }else{
       
  3003     return WRC_Continue;
       
  3004   }
       
  3005 }
       
  3006 
       
  3007 /*
       
  3008 ** Analyze the given expression looking for aggregate functions and
       
  3009 ** for variables that need to be added to the pParse->aAgg[] array.
       
  3010 ** Make additional entries to the pParse->aAgg[] array as necessary.
       
  3011 **
       
  3012 ** This routine should only be called after the expression has been
       
  3013 ** analyzed by sqlite3ResolveExprNames().
       
  3014 */
       
  3015 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
       
  3016   Walker w;
       
  3017   w.xExprCallback = analyzeAggregate;
       
  3018   w.xSelectCallback = analyzeAggregatesInSelect;
       
  3019   w.u.pNC = pNC;
       
  3020   sqlite3WalkExpr(&w, pExpr);
       
  3021 }
       
  3022 
       
  3023 /*
       
  3024 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
       
  3025 ** expression list.  Return the number of errors.
       
  3026 **
       
  3027 ** If an error is found, the analysis is cut short.
       
  3028 */
       
  3029 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
       
  3030   struct ExprList_item *pItem;
       
  3031   int i;
       
  3032   if( pList ){
       
  3033     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
       
  3034       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
       
  3035     }
       
  3036   }
       
  3037 }
       
  3038 
       
  3039 /*
       
  3040 ** Allocate or deallocate temporary use registers during code generation.
       
  3041 */
       
  3042 int sqlite3GetTempReg(Parse *pParse){
       
  3043   if( pParse->nTempReg==0 ){
       
  3044     return ++pParse->nMem;
       
  3045   }
       
  3046   return pParse->aTempReg[--pParse->nTempReg];
       
  3047 }
       
  3048 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
       
  3049   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
       
  3050     sqlite3ExprWritableRegister(pParse, iReg, iReg);
       
  3051     pParse->aTempReg[pParse->nTempReg++] = iReg;
       
  3052   }
       
  3053 }
       
  3054 
       
  3055 /*
       
  3056 ** Allocate or deallocate a block of nReg consecutive registers
       
  3057 */
       
  3058 int sqlite3GetTempRange(Parse *pParse, int nReg){
       
  3059   int i, n;
       
  3060   i = pParse->iRangeReg;
       
  3061   n = pParse->nRangeReg;
       
  3062   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
       
  3063     pParse->iRangeReg += nReg;
       
  3064     pParse->nRangeReg -= nReg;
       
  3065   }else{
       
  3066     i = pParse->nMem+1;
       
  3067     pParse->nMem += nReg;
       
  3068   }
       
  3069   return i;
       
  3070 }
       
  3071 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
       
  3072   if( nReg>pParse->nRangeReg ){
       
  3073     pParse->nRangeReg = nReg;
       
  3074     pParse->iRangeReg = iReg;
       
  3075   }
       
  3076 }