xref: /sqlite-3.40.0/src/expr.c (revision 06ae6792)
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 #include "sqliteInt.h"
16 
17 /*
18 ** Return the 'affinity' of the expression pExpr if any.
19 **
20 ** If pExpr is a column, a reference to a column via an 'AS' alias,
21 ** or a sub-select with a column as the return value, then the
22 ** affinity of that column is returned. Otherwise, 0x00 is returned,
23 ** indicating no affinity for the expression.
24 **
25 ** i.e. the WHERE clause expresssions in the following statements all
26 ** have an affinity:
27 **
28 ** CREATE TABLE t1(a);
29 ** SELECT * FROM t1 WHERE a;
30 ** SELECT a AS b FROM t1 WHERE b;
31 ** SELECT * FROM t1 WHERE (select a from t1);
32 */
33 char sqlite3ExprAffinity(Expr *pExpr){
34   int op = pExpr->op;
35   if( op==TK_SELECT ){
36     assert( pExpr->flags&EP_xIsSelect );
37     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
38   }
39 #ifndef SQLITE_OMIT_CAST
40   if( op==TK_CAST ){
41     assert( !ExprHasProperty(pExpr, EP_IntValue) );
42     return sqlite3AffinityType(pExpr->u.zToken);
43   }
44 #endif
45   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
46    && pExpr->pTab!=0
47   ){
48     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
49     ** a TK_COLUMN but was previously evaluated and cached in a register */
50     int j = pExpr->iColumn;
51     if( j<0 ) return SQLITE_AFF_INTEGER;
52     assert( pExpr->pTab && j<pExpr->pTab->nCol );
53     return pExpr->pTab->aCol[j].affinity;
54   }
55   return pExpr->affinity;
56 }
57 
58 /*
59 ** Set the explicit collating sequence for an expression to the
60 ** collating sequence supplied in the second argument.
61 */
62 Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
63   if( pExpr && pColl ){
64     pExpr->pColl = pColl;
65     pExpr->flags |= EP_ExpCollate;
66   }
67   return pExpr;
68 }
69 
70 /*
71 ** Set the collating sequence for expression pExpr to be the collating
72 ** sequence named by pToken.   Return a pointer to the revised expression.
73 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
74 ** flag.  An explicit collating sequence will override implicit
75 ** collating sequences.
76 */
77 Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
78   char *zColl = 0;            /* Dequoted name of collation sequence */
79   CollSeq *pColl;
80   sqlite3 *db = pParse->db;
81   zColl = sqlite3NameFromToken(db, pCollName);
82   pColl = sqlite3LocateCollSeq(pParse, zColl);
83   sqlite3ExprSetColl(pExpr, pColl);
84   sqlite3DbFree(db, zColl);
85   return pExpr;
86 }
87 
88 /*
89 ** Return the default collation sequence for the expression pExpr. If
90 ** there is no default collation type, return 0.
91 */
92 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
93   CollSeq *pColl = 0;
94   Expr *p = pExpr;
95   while( ALWAYS(p) ){
96     int op;
97     pColl = p->pColl;
98     if( pColl ) break;
99     op = p->op;
100     if( p->pTab!=0 && (
101         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
102     )){
103       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
104       ** a TK_COLUMN but was previously evaluated and cached in a register */
105       const char *zColl;
106       int j = p->iColumn;
107       if( j>=0 ){
108         sqlite3 *db = pParse->db;
109         zColl = p->pTab->aCol[j].zColl;
110         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
111         pExpr->pColl = pColl;
112       }
113       break;
114     }
115     if( op!=TK_CAST && op!=TK_UPLUS ){
116       break;
117     }
118     p = p->pLeft;
119   }
120   if( sqlite3CheckCollSeq(pParse, pColl) ){
121     pColl = 0;
122   }
123   return pColl;
124 }
125 
126 /*
127 ** pExpr is an operand of a comparison operator.  aff2 is the
128 ** type affinity of the other operand.  This routine returns the
129 ** type affinity that should be used for the comparison operator.
130 */
131 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
132   char aff1 = sqlite3ExprAffinity(pExpr);
133   if( aff1 && aff2 ){
134     /* Both sides of the comparison are columns. If one has numeric
135     ** affinity, use that. Otherwise use no affinity.
136     */
137     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
138       return SQLITE_AFF_NUMERIC;
139     }else{
140       return SQLITE_AFF_NONE;
141     }
142   }else if( !aff1 && !aff2 ){
143     /* Neither side of the comparison is a column.  Compare the
144     ** results directly.
145     */
146     return SQLITE_AFF_NONE;
147   }else{
148     /* One side is a column, the other is not. Use the columns affinity. */
149     assert( aff1==0 || aff2==0 );
150     return (aff1 + aff2);
151   }
152 }
153 
154 /*
155 ** pExpr is a comparison operator.  Return the type affinity that should
156 ** be applied to both operands prior to doing the comparison.
157 */
158 static char comparisonAffinity(Expr *pExpr){
159   char aff;
160   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
161           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
162           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
163   assert( pExpr->pLeft );
164   aff = sqlite3ExprAffinity(pExpr->pLeft);
165   if( pExpr->pRight ){
166     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
167   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
168     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
169   }else if( !aff ){
170     aff = SQLITE_AFF_NONE;
171   }
172   return aff;
173 }
174 
175 /*
176 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
177 ** idx_affinity is the affinity of an indexed column. Return true
178 ** if the index with affinity idx_affinity may be used to implement
179 ** the comparison in pExpr.
180 */
181 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
182   char aff = comparisonAffinity(pExpr);
183   switch( aff ){
184     case SQLITE_AFF_NONE:
185       return 1;
186     case SQLITE_AFF_TEXT:
187       return idx_affinity==SQLITE_AFF_TEXT;
188     default:
189       return sqlite3IsNumericAffinity(idx_affinity);
190   }
191 }
192 
193 /*
194 ** Return the P5 value that should be used for a binary comparison
195 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
196 */
197 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
198   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
199   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
200   return aff;
201 }
202 
203 /*
204 ** Return a pointer to the collation sequence that should be used by
205 ** a binary comparison operator comparing pLeft and pRight.
206 **
207 ** If the left hand expression has a collating sequence type, then it is
208 ** used. Otherwise the collation sequence for the right hand expression
209 ** is used, or the default (BINARY) if neither expression has a collating
210 ** type.
211 **
212 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
213 ** it is not considered.
214 */
215 CollSeq *sqlite3BinaryCompareCollSeq(
216   Parse *pParse,
217   Expr *pLeft,
218   Expr *pRight
219 ){
220   CollSeq *pColl;
221   assert( pLeft );
222   if( pLeft->flags & EP_ExpCollate ){
223     assert( pLeft->pColl );
224     pColl = pLeft->pColl;
225   }else if( pRight && pRight->flags & EP_ExpCollate ){
226     assert( pRight->pColl );
227     pColl = pRight->pColl;
228   }else{
229     pColl = sqlite3ExprCollSeq(pParse, pLeft);
230     if( !pColl ){
231       pColl = sqlite3ExprCollSeq(pParse, pRight);
232     }
233   }
234   return pColl;
235 }
236 
237 /*
238 ** Generate code for a comparison operator.
239 */
240 static int codeCompare(
241   Parse *pParse,    /* The parsing (and code generating) context */
242   Expr *pLeft,      /* The left operand */
243   Expr *pRight,     /* The right operand */
244   int opcode,       /* The comparison opcode */
245   int in1, int in2, /* Register holding operands */
246   int dest,         /* Jump here if true.  */
247   int jumpIfNull    /* If true, jump if either operand is NULL */
248 ){
249   int p5;
250   int addr;
251   CollSeq *p4;
252 
253   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
254   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
255   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
256                            (void*)p4, P4_COLLSEQ);
257   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
258   return addr;
259 }
260 
261 #if SQLITE_MAX_EXPR_DEPTH>0
262 /*
263 ** Check that argument nHeight is less than or equal to the maximum
264 ** expression depth allowed. If it is not, leave an error message in
265 ** pParse.
266 */
267 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
268   int rc = SQLITE_OK;
269   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
270   if( nHeight>mxHeight ){
271     sqlite3ErrorMsg(pParse,
272        "Expression tree is too large (maximum depth %d)", mxHeight
273     );
274     rc = SQLITE_ERROR;
275   }
276   return rc;
277 }
278 
279 /* The following three functions, heightOfExpr(), heightOfExprList()
280 ** and heightOfSelect(), are used to determine the maximum height
281 ** of any expression tree referenced by the structure passed as the
282 ** first argument.
283 **
284 ** If this maximum height is greater than the current value pointed
285 ** to by pnHeight, the second parameter, then set *pnHeight to that
286 ** value.
287 */
288 static void heightOfExpr(Expr *p, int *pnHeight){
289   if( p ){
290     if( p->nHeight>*pnHeight ){
291       *pnHeight = p->nHeight;
292     }
293   }
294 }
295 static void heightOfExprList(ExprList *p, int *pnHeight){
296   if( p ){
297     int i;
298     for(i=0; i<p->nExpr; i++){
299       heightOfExpr(p->a[i].pExpr, pnHeight);
300     }
301   }
302 }
303 static void heightOfSelect(Select *p, int *pnHeight){
304   if( p ){
305     heightOfExpr(p->pWhere, pnHeight);
306     heightOfExpr(p->pHaving, pnHeight);
307     heightOfExpr(p->pLimit, pnHeight);
308     heightOfExpr(p->pOffset, pnHeight);
309     heightOfExprList(p->pEList, pnHeight);
310     heightOfExprList(p->pGroupBy, pnHeight);
311     heightOfExprList(p->pOrderBy, pnHeight);
312     heightOfSelect(p->pPrior, pnHeight);
313   }
314 }
315 
316 /*
317 ** Set the Expr.nHeight variable in the structure passed as an
318 ** argument. An expression with no children, Expr.pList or
319 ** Expr.pSelect member has a height of 1. Any other expression
320 ** has a height equal to the maximum height of any other
321 ** referenced Expr plus one.
322 */
323 static void exprSetHeight(Expr *p){
324   int nHeight = 0;
325   heightOfExpr(p->pLeft, &nHeight);
326   heightOfExpr(p->pRight, &nHeight);
327   if( ExprHasProperty(p, EP_xIsSelect) ){
328     heightOfSelect(p->x.pSelect, &nHeight);
329   }else{
330     heightOfExprList(p->x.pList, &nHeight);
331   }
332   p->nHeight = nHeight + 1;
333 }
334 
335 /*
336 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
337 ** the height is greater than the maximum allowed expression depth,
338 ** leave an error in pParse.
339 */
340 void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
341   exprSetHeight(p);
342   sqlite3ExprCheckHeight(pParse, p->nHeight);
343 }
344 
345 /*
346 ** Return the maximum height of any expression tree referenced
347 ** by the select statement passed as an argument.
348 */
349 int sqlite3SelectExprHeight(Select *p){
350   int nHeight = 0;
351   heightOfSelect(p, &nHeight);
352   return nHeight;
353 }
354 #else
355   #define exprSetHeight(y)
356 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
357 
358 /*
359 ** This routine is the core allocator for Expr nodes.
360 **
361 ** Construct a new expression node and return a pointer to it.  Memory
362 ** for this node and for the pToken argument is a single allocation
363 ** obtained from sqlite3DbMalloc().  The calling function
364 ** is responsible for making sure the node eventually gets freed.
365 **
366 ** If dequote is true, then the token (if it exists) is dequoted.
367 ** If dequote is false, no dequoting is performance.  The deQuote
368 ** parameter is ignored if pToken is NULL or if the token does not
369 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
370 ** then the EP_DblQuoted flag is set on the expression node.
371 **
372 ** Special case:  If op==TK_INTEGER and pToken points to a string that
373 ** can be translated into a 32-bit integer, then the token is not
374 ** stored in u.zToken.  Instead, the integer values is written
375 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
376 ** is allocated to hold the integer text and the dequote flag is ignored.
377 */
378 Expr *sqlite3ExprAlloc(
379   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
380   int op,                 /* Expression opcode */
381   const Token *pToken,    /* Token argument.  Might be NULL */
382   int dequote             /* True to dequote */
383 ){
384   Expr *pNew;
385   int nExtra = 0;
386   int iValue = 0;
387 
388   if( pToken ){
389     if( op!=TK_INTEGER || pToken->z==0
390           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
391       nExtra = pToken->n+1;
392     }
393   }
394   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
395   if( pNew ){
396     pNew->op = (u8)op;
397     pNew->iAgg = -1;
398     if( pToken ){
399       if( nExtra==0 ){
400         pNew->flags |= EP_IntValue;
401         pNew->u.iValue = iValue;
402       }else{
403         int c;
404         pNew->u.zToken = (char*)&pNew[1];
405         memcpy(pNew->u.zToken, pToken->z, pToken->n);
406         pNew->u.zToken[pToken->n] = 0;
407         if( dequote && nExtra>=3
408              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
409           sqlite3Dequote(pNew->u.zToken);
410           if( c=='"' ) pNew->flags |= EP_DblQuoted;
411         }
412       }
413     }
414 #if SQLITE_MAX_EXPR_DEPTH>0
415     pNew->nHeight = 1;
416 #endif
417   }
418   return pNew;
419 }
420 
421 /*
422 ** Allocate a new expression node from a zero-terminated token that has
423 ** already been dequoted.
424 */
425 Expr *sqlite3Expr(
426   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
427   int op,                 /* Expression opcode */
428   const char *zToken      /* Token argument.  Might be NULL */
429 ){
430   Token x;
431   x.z = zToken;
432   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
433   return sqlite3ExprAlloc(db, op, &x, 0);
434 }
435 
436 /*
437 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
438 **
439 ** If pRoot==NULL that means that a memory allocation error has occurred.
440 ** In that case, delete the subtrees pLeft and pRight.
441 */
442 void sqlite3ExprAttachSubtrees(
443   sqlite3 *db,
444   Expr *pRoot,
445   Expr *pLeft,
446   Expr *pRight
447 ){
448   if( pRoot==0 ){
449     assert( db->mallocFailed );
450     sqlite3ExprDelete(db, pLeft);
451     sqlite3ExprDelete(db, pRight);
452   }else{
453     if( pRight ){
454       pRoot->pRight = pRight;
455       if( pRight->flags & EP_ExpCollate ){
456         pRoot->flags |= EP_ExpCollate;
457         pRoot->pColl = pRight->pColl;
458       }
459     }
460     if( pLeft ){
461       pRoot->pLeft = pLeft;
462       if( pLeft->flags & EP_ExpCollate ){
463         pRoot->flags |= EP_ExpCollate;
464         pRoot->pColl = pLeft->pColl;
465       }
466     }
467     exprSetHeight(pRoot);
468   }
469 }
470 
471 /*
472 ** Allocate a Expr node which joins as many as two subtrees.
473 **
474 ** One or both of the subtrees can be NULL.  Return a pointer to the new
475 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
476 ** free the subtrees and return NULL.
477 */
478 Expr *sqlite3PExpr(
479   Parse *pParse,          /* Parsing context */
480   int op,                 /* Expression opcode */
481   Expr *pLeft,            /* Left operand */
482   Expr *pRight,           /* Right operand */
483   const Token *pToken     /* Argument token */
484 ){
485   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
486   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
487   return p;
488 }
489 
490 /*
491 ** Join two expressions using an AND operator.  If either expression is
492 ** NULL, then just return the other expression.
493 */
494 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
495   if( pLeft==0 ){
496     return pRight;
497   }else if( pRight==0 ){
498     return pLeft;
499   }else{
500     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
501     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
502     return pNew;
503   }
504 }
505 
506 /*
507 ** Construct a new expression node for a function with multiple
508 ** arguments.
509 */
510 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
511   Expr *pNew;
512   sqlite3 *db = pParse->db;
513   assert( pToken );
514   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
515   if( pNew==0 ){
516     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
517     return 0;
518   }
519   pNew->x.pList = pList;
520   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
521   sqlite3ExprSetHeight(pParse, pNew);
522   return pNew;
523 }
524 
525 /*
526 ** Assign a variable number to an expression that encodes a wildcard
527 ** in the original SQL statement.
528 **
529 ** Wildcards consisting of a single "?" are assigned the next sequential
530 ** variable number.
531 **
532 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
533 ** sure "nnn" is not too be to avoid a denial of service attack when
534 ** the SQL statement comes from an external source.
535 **
536 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
537 ** as the previous instance of the same wildcard.  Or if this is the first
538 ** instance of the wildcard, the next sequenial variable number is
539 ** assigned.
540 */
541 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
542   sqlite3 *db = pParse->db;
543   const char *z;
544 
545   if( pExpr==0 ) return;
546   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
547   z = pExpr->u.zToken;
548   assert( z!=0 );
549   assert( z[0]!=0 );
550   if( z[1]==0 ){
551     /* Wildcard of the form "?".  Assign the next variable number */
552     assert( z[0]=='?' );
553     pExpr->iColumn = (ynVar)(++pParse->nVar);
554   }else if( z[0]=='?' ){
555     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
556     ** use it as the variable number */
557     i64 i;
558     int bOk = sqlite3Atoi64(&z[1], &i);
559     pExpr->iColumn = (ynVar)i;
560     testcase( i==0 );
561     testcase( i==1 );
562     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
563     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
564     if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
565       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
566           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
567     }
568     if( i>pParse->nVar ){
569       pParse->nVar = (int)i;
570     }
571   }else{
572     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
573     ** number as the prior appearance of the same name, or if the name
574     ** has never appeared before, reuse the same variable number
575     */
576     int i;
577     u32 n;
578     n = sqlite3Strlen30(z);
579     for(i=0; i<pParse->nVarExpr; i++){
580       Expr *pE = pParse->apVarExpr[i];
581       assert( pE!=0 );
582       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
583         pExpr->iColumn = pE->iColumn;
584         break;
585       }
586     }
587     if( i>=pParse->nVarExpr ){
588       pExpr->iColumn = (ynVar)(++pParse->nVar);
589       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
590         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
591         pParse->apVarExpr =
592             sqlite3DbReallocOrFree(
593               db,
594               pParse->apVarExpr,
595               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
596             );
597       }
598       if( !db->mallocFailed ){
599         assert( pParse->apVarExpr!=0 );
600         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
601       }
602     }
603   }
604   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
605     sqlite3ErrorMsg(pParse, "too many SQL variables");
606   }
607 }
608 
609 /*
610 ** Recursively delete an expression tree.
611 */
612 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
613   if( p==0 ) return;
614   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
615     sqlite3ExprDelete(db, p->pLeft);
616     sqlite3ExprDelete(db, p->pRight);
617     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
618       sqlite3DbFree(db, p->u.zToken);
619     }
620     if( ExprHasProperty(p, EP_xIsSelect) ){
621       sqlite3SelectDelete(db, p->x.pSelect);
622     }else{
623       sqlite3ExprListDelete(db, p->x.pList);
624     }
625   }
626   if( !ExprHasProperty(p, EP_Static) ){
627     sqlite3DbFree(db, p);
628   }
629 }
630 
631 /*
632 ** Return the number of bytes allocated for the expression structure
633 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
634 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
635 */
636 static int exprStructSize(Expr *p){
637   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
638   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
639   return EXPR_FULLSIZE;
640 }
641 
642 /*
643 ** The dupedExpr*Size() routines each return the number of bytes required
644 ** to store a copy of an expression or expression tree.  They differ in
645 ** how much of the tree is measured.
646 **
647 **     dupedExprStructSize()     Size of only the Expr structure
648 **     dupedExprNodeSize()       Size of Expr + space for token
649 **     dupedExprSize()           Expr + token + subtree components
650 **
651 ***************************************************************************
652 **
653 ** The dupedExprStructSize() function returns two values OR-ed together:
654 ** (1) the space required for a copy of the Expr structure only and
655 ** (2) the EP_xxx flags that indicate what the structure size should be.
656 ** The return values is always one of:
657 **
658 **      EXPR_FULLSIZE
659 **      EXPR_REDUCEDSIZE   | EP_Reduced
660 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
661 **
662 ** The size of the structure can be found by masking the return value
663 ** of this routine with 0xfff.  The flags can be found by masking the
664 ** return value with EP_Reduced|EP_TokenOnly.
665 **
666 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
667 ** (unreduced) Expr objects as they or originally constructed by the parser.
668 ** During expression analysis, extra information is computed and moved into
669 ** later parts of teh Expr object and that extra information might get chopped
670 ** off if the expression is reduced.  Note also that it does not work to
671 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
672 ** to reduce a pristine expression tree from the parser.  The implementation
673 ** of dupedExprStructSize() contain multiple assert() statements that attempt
674 ** to enforce this constraint.
675 */
676 static int dupedExprStructSize(Expr *p, int flags){
677   int nSize;
678   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
679   if( 0==(flags&EXPRDUP_REDUCE) ){
680     nSize = EXPR_FULLSIZE;
681   }else{
682     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
683     assert( !ExprHasProperty(p, EP_FromJoin) );
684     assert( (p->flags2 & EP2_MallocedToken)==0 );
685     assert( (p->flags2 & EP2_Irreducible)==0 );
686     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
687       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
688     }else{
689       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
690     }
691   }
692   return nSize;
693 }
694 
695 /*
696 ** This function returns the space in bytes required to store the copy
697 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
698 ** string is defined.)
699 */
700 static int dupedExprNodeSize(Expr *p, int flags){
701   int nByte = dupedExprStructSize(p, flags) & 0xfff;
702   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
703     nByte += sqlite3Strlen30(p->u.zToken)+1;
704   }
705   return ROUND8(nByte);
706 }
707 
708 /*
709 ** Return the number of bytes required to create a duplicate of the
710 ** expression passed as the first argument. The second argument is a
711 ** mask containing EXPRDUP_XXX flags.
712 **
713 ** The value returned includes space to create a copy of the Expr struct
714 ** itself and the buffer referred to by Expr.u.zToken, if any.
715 **
716 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
717 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
718 ** and Expr.pRight variables (but not for any structures pointed to or
719 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
720 */
721 static int dupedExprSize(Expr *p, int flags){
722   int nByte = 0;
723   if( p ){
724     nByte = dupedExprNodeSize(p, flags);
725     if( flags&EXPRDUP_REDUCE ){
726       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
727     }
728   }
729   return nByte;
730 }
731 
732 /*
733 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
734 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
735 ** to store the copy of expression p, the copies of p->u.zToken
736 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
737 ** if any. Before returning, *pzBuffer is set to the first byte passed the
738 ** portion of the buffer copied into by this function.
739 */
740 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
741   Expr *pNew = 0;                      /* Value to return */
742   if( p ){
743     const int isReduced = (flags&EXPRDUP_REDUCE);
744     u8 *zAlloc;
745     u32 staticFlag = 0;
746 
747     assert( pzBuffer==0 || isReduced );
748 
749     /* Figure out where to write the new Expr structure. */
750     if( pzBuffer ){
751       zAlloc = *pzBuffer;
752       staticFlag = EP_Static;
753     }else{
754       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
755     }
756     pNew = (Expr *)zAlloc;
757 
758     if( pNew ){
759       /* Set nNewSize to the size allocated for the structure pointed to
760       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
761       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
762       ** by the copy of the p->u.zToken string (if any).
763       */
764       const unsigned nStructSize = dupedExprStructSize(p, flags);
765       const int nNewSize = nStructSize & 0xfff;
766       int nToken;
767       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
768         nToken = sqlite3Strlen30(p->u.zToken) + 1;
769       }else{
770         nToken = 0;
771       }
772       if( isReduced ){
773         assert( ExprHasProperty(p, EP_Reduced)==0 );
774         memcpy(zAlloc, p, nNewSize);
775       }else{
776         int nSize = exprStructSize(p);
777         memcpy(zAlloc, p, nSize);
778         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
779       }
780 
781       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
782       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
783       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
784       pNew->flags |= staticFlag;
785 
786       /* Copy the p->u.zToken string, if any. */
787       if( nToken ){
788         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
789         memcpy(zToken, p->u.zToken, nToken);
790       }
791 
792       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
793         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
794         if( ExprHasProperty(p, EP_xIsSelect) ){
795           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
796         }else{
797           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
798         }
799       }
800 
801       /* Fill in pNew->pLeft and pNew->pRight. */
802       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
803         zAlloc += dupedExprNodeSize(p, flags);
804         if( ExprHasProperty(pNew, EP_Reduced) ){
805           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
806           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
807         }
808         if( pzBuffer ){
809           *pzBuffer = zAlloc;
810         }
811       }else{
812         pNew->flags2 = 0;
813         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
814           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
815           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
816         }
817       }
818 
819     }
820   }
821   return pNew;
822 }
823 
824 /*
825 ** The following group of routines make deep copies of expressions,
826 ** expression lists, ID lists, and select statements.  The copies can
827 ** be deleted (by being passed to their respective ...Delete() routines)
828 ** without effecting the originals.
829 **
830 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
831 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
832 ** by subsequent calls to sqlite*ListAppend() routines.
833 **
834 ** Any tables that the SrcList might point to are not duplicated.
835 **
836 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
837 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
838 ** truncated version of the usual Expr structure that will be stored as
839 ** part of the in-memory representation of the database schema.
840 */
841 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
842   return exprDup(db, p, flags, 0);
843 }
844 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
845   ExprList *pNew;
846   struct ExprList_item *pItem, *pOldItem;
847   int i;
848   if( p==0 ) return 0;
849   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
850   if( pNew==0 ) return 0;
851   pNew->iECursor = 0;
852   pNew->nExpr = pNew->nAlloc = p->nExpr;
853   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
854   if( pItem==0 ){
855     sqlite3DbFree(db, pNew);
856     return 0;
857   }
858   pOldItem = p->a;
859   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
860     Expr *pOldExpr = pOldItem->pExpr;
861     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
862     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
863     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
864     pItem->sortOrder = pOldItem->sortOrder;
865     pItem->done = 0;
866     pItem->iCol = pOldItem->iCol;
867     pItem->iAlias = pOldItem->iAlias;
868   }
869   return pNew;
870 }
871 
872 /*
873 ** If cursors, triggers, views and subqueries are all omitted from
874 ** the build, then none of the following routines, except for
875 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
876 ** called with a NULL argument.
877 */
878 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
879  || !defined(SQLITE_OMIT_SUBQUERY)
880 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
881   SrcList *pNew;
882   int i;
883   int nByte;
884   if( p==0 ) return 0;
885   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
886   pNew = sqlite3DbMallocRaw(db, nByte );
887   if( pNew==0 ) return 0;
888   pNew->nSrc = pNew->nAlloc = p->nSrc;
889   for(i=0; i<p->nSrc; i++){
890     struct SrcList_item *pNewItem = &pNew->a[i];
891     struct SrcList_item *pOldItem = &p->a[i];
892     Table *pTab;
893     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
894     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
895     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
896     pNewItem->jointype = pOldItem->jointype;
897     pNewItem->iCursor = pOldItem->iCursor;
898     pNewItem->isPopulated = pOldItem->isPopulated;
899     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
900     pNewItem->notIndexed = pOldItem->notIndexed;
901     pNewItem->pIndex = pOldItem->pIndex;
902     pTab = pNewItem->pTab = pOldItem->pTab;
903     if( pTab ){
904       pTab->nRef++;
905     }
906     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
907     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
908     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
909     pNewItem->colUsed = pOldItem->colUsed;
910   }
911   return pNew;
912 }
913 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
914   IdList *pNew;
915   int i;
916   if( p==0 ) return 0;
917   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
918   if( pNew==0 ) return 0;
919   pNew->nId = pNew->nAlloc = p->nId;
920   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
921   if( pNew->a==0 ){
922     sqlite3DbFree(db, pNew);
923     return 0;
924   }
925   for(i=0; i<p->nId; i++){
926     struct IdList_item *pNewItem = &pNew->a[i];
927     struct IdList_item *pOldItem = &p->a[i];
928     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
929     pNewItem->idx = pOldItem->idx;
930   }
931   return pNew;
932 }
933 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
934   Select *pNew;
935   if( p==0 ) return 0;
936   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
937   if( pNew==0 ) return 0;
938   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
939   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
940   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
941   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
942   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
943   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
944   pNew->op = p->op;
945   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
946   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
947   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
948   pNew->iLimit = 0;
949   pNew->iOffset = 0;
950   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
951   pNew->pRightmost = 0;
952   pNew->addrOpenEphm[0] = -1;
953   pNew->addrOpenEphm[1] = -1;
954   pNew->addrOpenEphm[2] = -1;
955   return pNew;
956 }
957 #else
958 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
959   assert( p==0 );
960   return 0;
961 }
962 #endif
963 
964 
965 /*
966 ** Add a new element to the end of an expression list.  If pList is
967 ** initially NULL, then create a new expression list.
968 **
969 ** If a memory allocation error occurs, the entire list is freed and
970 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
971 ** that the new entry was successfully appended.
972 */
973 ExprList *sqlite3ExprListAppend(
974   Parse *pParse,          /* Parsing context */
975   ExprList *pList,        /* List to which to append. Might be NULL */
976   Expr *pExpr             /* Expression to be appended. Might be NULL */
977 ){
978   sqlite3 *db = pParse->db;
979   if( pList==0 ){
980     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
981     if( pList==0 ){
982       goto no_mem;
983     }
984     assert( pList->nAlloc==0 );
985   }
986   if( pList->nAlloc<=pList->nExpr ){
987     struct ExprList_item *a;
988     int n = pList->nAlloc*2 + 4;
989     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
990     if( a==0 ){
991       goto no_mem;
992     }
993     pList->a = a;
994     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
995   }
996   assert( pList->a!=0 );
997   if( 1 ){
998     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
999     memset(pItem, 0, sizeof(*pItem));
1000     pItem->pExpr = pExpr;
1001   }
1002   return pList;
1003 
1004 no_mem:
1005   /* Avoid leaking memory if malloc has failed. */
1006   sqlite3ExprDelete(db, pExpr);
1007   sqlite3ExprListDelete(db, pList);
1008   return 0;
1009 }
1010 
1011 /*
1012 ** Set the ExprList.a[].zName element of the most recently added item
1013 ** on the expression list.
1014 **
1015 ** pList might be NULL following an OOM error.  But pName should never be
1016 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1017 ** is set.
1018 */
1019 void sqlite3ExprListSetName(
1020   Parse *pParse,          /* Parsing context */
1021   ExprList *pList,        /* List to which to add the span. */
1022   Token *pName,           /* Name to be added */
1023   int dequote             /* True to cause the name to be dequoted */
1024 ){
1025   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1026   if( pList ){
1027     struct ExprList_item *pItem;
1028     assert( pList->nExpr>0 );
1029     pItem = &pList->a[pList->nExpr-1];
1030     assert( pItem->zName==0 );
1031     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1032     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
1033   }
1034 }
1035 
1036 /*
1037 ** Set the ExprList.a[].zSpan element of the most recently added item
1038 ** on the expression list.
1039 **
1040 ** pList might be NULL following an OOM error.  But pSpan should never be
1041 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1042 ** is set.
1043 */
1044 void sqlite3ExprListSetSpan(
1045   Parse *pParse,          /* Parsing context */
1046   ExprList *pList,        /* List to which to add the span. */
1047   ExprSpan *pSpan         /* The span to be added */
1048 ){
1049   sqlite3 *db = pParse->db;
1050   assert( pList!=0 || db->mallocFailed!=0 );
1051   if( pList ){
1052     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1053     assert( pList->nExpr>0 );
1054     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1055     sqlite3DbFree(db, pItem->zSpan);
1056     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1057                                     (int)(pSpan->zEnd - pSpan->zStart));
1058   }
1059 }
1060 
1061 /*
1062 ** If the expression list pEList contains more than iLimit elements,
1063 ** leave an error message in pParse.
1064 */
1065 void sqlite3ExprListCheckLength(
1066   Parse *pParse,
1067   ExprList *pEList,
1068   const char *zObject
1069 ){
1070   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1071   testcase( pEList && pEList->nExpr==mx );
1072   testcase( pEList && pEList->nExpr==mx+1 );
1073   if( pEList && pEList->nExpr>mx ){
1074     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1075   }
1076 }
1077 
1078 /*
1079 ** Delete an entire expression list.
1080 */
1081 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1082   int i;
1083   struct ExprList_item *pItem;
1084   if( pList==0 ) return;
1085   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
1086   assert( pList->nExpr<=pList->nAlloc );
1087   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1088     sqlite3ExprDelete(db, pItem->pExpr);
1089     sqlite3DbFree(db, pItem->zName);
1090     sqlite3DbFree(db, pItem->zSpan);
1091   }
1092   sqlite3DbFree(db, pList->a);
1093   sqlite3DbFree(db, pList);
1094 }
1095 
1096 /*
1097 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
1098 ** to an integer.  These routines are checking an expression to see
1099 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
1100 ** not constant.
1101 **
1102 ** These callback routines are used to implement the following:
1103 **
1104 **     sqlite3ExprIsConstant()
1105 **     sqlite3ExprIsConstantNotJoin()
1106 **     sqlite3ExprIsConstantOrFunction()
1107 **
1108 */
1109 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1110 
1111   /* If pWalker->u.i is 3 then any term of the expression that comes from
1112   ** the ON or USING clauses of a join disqualifies the expression
1113   ** from being considered constant. */
1114   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
1115     pWalker->u.i = 0;
1116     return WRC_Abort;
1117   }
1118 
1119   switch( pExpr->op ){
1120     /* Consider functions to be constant if all their arguments are constant
1121     ** and pWalker->u.i==2 */
1122     case TK_FUNCTION:
1123       if( pWalker->u.i==2 ) return 0;
1124       /* Fall through */
1125     case TK_ID:
1126     case TK_COLUMN:
1127     case TK_AGG_FUNCTION:
1128     case TK_AGG_COLUMN:
1129       testcase( pExpr->op==TK_ID );
1130       testcase( pExpr->op==TK_COLUMN );
1131       testcase( pExpr->op==TK_AGG_FUNCTION );
1132       testcase( pExpr->op==TK_AGG_COLUMN );
1133       pWalker->u.i = 0;
1134       return WRC_Abort;
1135     default:
1136       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1137       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
1138       return WRC_Continue;
1139   }
1140 }
1141 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1142   UNUSED_PARAMETER(NotUsed);
1143   pWalker->u.i = 0;
1144   return WRC_Abort;
1145 }
1146 static int exprIsConst(Expr *p, int initFlag){
1147   Walker w;
1148   w.u.i = initFlag;
1149   w.xExprCallback = exprNodeIsConstant;
1150   w.xSelectCallback = selectNodeIsConstant;
1151   sqlite3WalkExpr(&w, p);
1152   return w.u.i;
1153 }
1154 
1155 /*
1156 ** Walk an expression tree.  Return 1 if the expression is constant
1157 ** and 0 if it involves variables or function calls.
1158 **
1159 ** For the purposes of this function, a double-quoted string (ex: "abc")
1160 ** is considered a variable but a single-quoted string (ex: 'abc') is
1161 ** a constant.
1162 */
1163 int sqlite3ExprIsConstant(Expr *p){
1164   return exprIsConst(p, 1);
1165 }
1166 
1167 /*
1168 ** Walk an expression tree.  Return 1 if the expression is constant
1169 ** that does no originate from the ON or USING clauses of a join.
1170 ** Return 0 if it involves variables or function calls or terms from
1171 ** an ON or USING clause.
1172 */
1173 int sqlite3ExprIsConstantNotJoin(Expr *p){
1174   return exprIsConst(p, 3);
1175 }
1176 
1177 /*
1178 ** Walk an expression tree.  Return 1 if the expression is constant
1179 ** or a function call with constant arguments.  Return and 0 if there
1180 ** are any variables.
1181 **
1182 ** For the purposes of this function, a double-quoted string (ex: "abc")
1183 ** is considered a variable but a single-quoted string (ex: 'abc') is
1184 ** a constant.
1185 */
1186 int sqlite3ExprIsConstantOrFunction(Expr *p){
1187   return exprIsConst(p, 2);
1188 }
1189 
1190 /*
1191 ** If the expression p codes a constant integer that is small enough
1192 ** to fit in a 32-bit integer, return 1 and put the value of the integer
1193 ** in *pValue.  If the expression is not an integer or if it is too big
1194 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1195 */
1196 int sqlite3ExprIsInteger(Expr *p, int *pValue){
1197   int rc = 0;
1198   if( p->flags & EP_IntValue ){
1199     *pValue = p->u.iValue;
1200     return 1;
1201   }
1202   switch( p->op ){
1203     case TK_INTEGER: {
1204       rc = sqlite3GetInt32(p->u.zToken, pValue);
1205       assert( rc==0 );
1206       break;
1207     }
1208     case TK_UPLUS: {
1209       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1210       break;
1211     }
1212     case TK_UMINUS: {
1213       int v;
1214       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1215         *pValue = -v;
1216         rc = 1;
1217       }
1218       break;
1219     }
1220     default: break;
1221   }
1222   if( rc ){
1223     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
1224                || (p->flags2 & EP2_MallocedToken)==0 );
1225     p->op = TK_INTEGER;
1226     p->flags |= EP_IntValue;
1227     p->u.iValue = *pValue;
1228   }
1229   return rc;
1230 }
1231 
1232 /*
1233 ** Return FALSE if there is no chance that the expression can be NULL.
1234 **
1235 ** If the expression might be NULL or if the expression is too complex
1236 ** to tell return TRUE.
1237 **
1238 ** This routine is used as an optimization, to skip OP_IsNull opcodes
1239 ** when we know that a value cannot be NULL.  Hence, a false positive
1240 ** (returning TRUE when in fact the expression can never be NULL) might
1241 ** be a small performance hit but is otherwise harmless.  On the other
1242 ** hand, a false negative (returning FALSE when the result could be NULL)
1243 ** will likely result in an incorrect answer.  So when in doubt, return
1244 ** TRUE.
1245 */
1246 int sqlite3ExprCanBeNull(const Expr *p){
1247   u8 op;
1248   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1249   op = p->op;
1250   if( op==TK_REGISTER ) op = p->op2;
1251   switch( op ){
1252     case TK_INTEGER:
1253     case TK_STRING:
1254     case TK_FLOAT:
1255     case TK_BLOB:
1256       return 0;
1257     default:
1258       return 1;
1259   }
1260 }
1261 
1262 /*
1263 ** Generate an OP_IsNull instruction that tests register iReg and jumps
1264 ** to location iDest if the value in iReg is NULL.  The value in iReg
1265 ** was computed by pExpr.  If we can look at pExpr at compile-time and
1266 ** determine that it can never generate a NULL, then the OP_IsNull operation
1267 ** can be omitted.
1268 */
1269 void sqlite3ExprCodeIsNullJump(
1270   Vdbe *v,            /* The VDBE under construction */
1271   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
1272   int iReg,           /* Test the value in this register for NULL */
1273   int iDest           /* Jump here if the value is null */
1274 ){
1275   if( sqlite3ExprCanBeNull(pExpr) ){
1276     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
1277   }
1278 }
1279 
1280 /*
1281 ** Return TRUE if the given expression is a constant which would be
1282 ** unchanged by OP_Affinity with the affinity given in the second
1283 ** argument.
1284 **
1285 ** This routine is used to determine if the OP_Affinity operation
1286 ** can be omitted.  When in doubt return FALSE.  A false negative
1287 ** is harmless.  A false positive, however, can result in the wrong
1288 ** answer.
1289 */
1290 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1291   u8 op;
1292   if( aff==SQLITE_AFF_NONE ) return 1;
1293   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1294   op = p->op;
1295   if( op==TK_REGISTER ) op = p->op2;
1296   switch( op ){
1297     case TK_INTEGER: {
1298       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1299     }
1300     case TK_FLOAT: {
1301       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1302     }
1303     case TK_STRING: {
1304       return aff==SQLITE_AFF_TEXT;
1305     }
1306     case TK_BLOB: {
1307       return 1;
1308     }
1309     case TK_COLUMN: {
1310       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
1311       return p->iColumn<0
1312           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
1313     }
1314     default: {
1315       return 0;
1316     }
1317   }
1318 }
1319 
1320 /*
1321 ** Return TRUE if the given string is a row-id column name.
1322 */
1323 int sqlite3IsRowid(const char *z){
1324   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1325   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1326   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1327   return 0;
1328 }
1329 
1330 /*
1331 ** Return true if we are able to the IN operator optimization on a
1332 ** query of the form
1333 **
1334 **       x IN (SELECT ...)
1335 **
1336 ** Where the SELECT... clause is as specified by the parameter to this
1337 ** routine.
1338 **
1339 ** The Select object passed in has already been preprocessed and no
1340 ** errors have been found.
1341 */
1342 #ifndef SQLITE_OMIT_SUBQUERY
1343 static int isCandidateForInOpt(Select *p){
1344   SrcList *pSrc;
1345   ExprList *pEList;
1346   Table *pTab;
1347   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
1348   if( p->pPrior ) return 0;              /* Not a compound SELECT */
1349   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1350     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1351     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1352     return 0; /* No DISTINCT keyword and no aggregate functions */
1353   }
1354   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
1355   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
1356   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
1357   if( p->pWhere ) return 0;              /* Has no WHERE clause */
1358   pSrc = p->pSrc;
1359   assert( pSrc!=0 );
1360   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
1361   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
1362   pTab = pSrc->a[0].pTab;
1363   if( NEVER(pTab==0) ) return 0;
1364   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
1365   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
1366   pEList = p->pEList;
1367   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
1368   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1369   return 1;
1370 }
1371 #endif /* SQLITE_OMIT_SUBQUERY */
1372 
1373 /*
1374 ** This function is used by the implementation of the IN (...) operator.
1375 ** It's job is to find or create a b-tree structure that may be used
1376 ** either to test for membership of the (...) set or to iterate through
1377 ** its members, skipping duplicates.
1378 **
1379 ** The index of the cursor opened on the b-tree (database table, database index
1380 ** or ephermal table) is stored in pX->iTable before this function returns.
1381 ** The returned value of this function indicates the b-tree type, as follows:
1382 **
1383 **   IN_INDEX_ROWID - The cursor was opened on a database table.
1384 **   IN_INDEX_INDEX - The cursor was opened on a database index.
1385 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
1386 **                    populated epheremal table.
1387 **
1388 ** An existing b-tree may only be used if the SELECT is of the simple
1389 ** form:
1390 **
1391 **     SELECT <column> FROM <table>
1392 **
1393 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
1394 ** through the set members, skipping any duplicates. In this case an
1395 ** epheremal table must be used unless the selected <column> is guaranteed
1396 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
1397 ** has a UNIQUE constraint or UNIQUE index.
1398 **
1399 ** If the prNotFound parameter is not 0, then the b-tree will be used
1400 ** for fast set membership tests. In this case an epheremal table must
1401 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
1402 ** be found with <column> as its left-most column.
1403 **
1404 ** When the b-tree is being used for membership tests, the calling function
1405 ** needs to know whether or not the structure contains an SQL NULL
1406 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
1407 ** If there is any chance that the (...) might contain a NULL value at
1408 ** runtime, then a register is allocated and the register number written
1409 ** to *prNotFound. If there is no chance that the (...) contains a
1410 ** NULL value, then *prNotFound is left unchanged.
1411 **
1412 ** If a register is allocated and its location stored in *prNotFound, then
1413 ** its initial value is NULL.  If the (...) does not remain constant
1414 ** for the duration of the query (i.e. the SELECT within the (...)
1415 ** is a correlated subquery) then the value of the allocated register is
1416 ** reset to NULL each time the subquery is rerun. This allows the
1417 ** caller to use vdbe code equivalent to the following:
1418 **
1419 **   if( register==NULL ){
1420 **     has_null = <test if data structure contains null>
1421 **     register = 1
1422 **   }
1423 **
1424 ** in order to avoid running the <test if data structure contains null>
1425 ** test more often than is necessary.
1426 */
1427 #ifndef SQLITE_OMIT_SUBQUERY
1428 int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
1429   Select *p;                            /* SELECT to the right of IN operator */
1430   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
1431   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
1432   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
1433 
1434   assert( pX->op==TK_IN );
1435 
1436   /* Check to see if an existing table or index can be used to
1437   ** satisfy the query.  This is preferable to generating a new
1438   ** ephemeral table.
1439   */
1440   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
1441   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
1442     sqlite3 *db = pParse->db;              /* Database connection */
1443     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
1444     int iCol = pExpr->iColumn;             /* Index of column <column> */
1445     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
1446     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
1447     int iDb;                               /* Database idx for pTab */
1448 
1449     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
1450     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1451     sqlite3CodeVerifySchema(pParse, iDb);
1452     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1453 
1454     /* This function is only called from two places. In both cases the vdbe
1455     ** has already been allocated. So assume sqlite3GetVdbe() is always
1456     ** successful here.
1457     */
1458     assert(v);
1459     if( iCol<0 ){
1460       int iMem = ++pParse->nMem;
1461       int iAddr;
1462 
1463       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
1464       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
1465 
1466       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1467       eType = IN_INDEX_ROWID;
1468 
1469       sqlite3VdbeJumpHere(v, iAddr);
1470     }else{
1471       Index *pIdx;                         /* Iterator variable */
1472 
1473       /* The collation sequence used by the comparison. If an index is to
1474       ** be used in place of a temp-table, it must be ordered according
1475       ** to this collation sequence.  */
1476       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
1477 
1478       /* Check that the affinity that will be used to perform the
1479       ** comparison is the same as the affinity of the column. If
1480       ** it is not, it is not possible to use any index.
1481       */
1482       char aff = comparisonAffinity(pX);
1483       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
1484 
1485       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
1486         if( (pIdx->aiColumn[0]==iCol)
1487          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
1488          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
1489         ){
1490           int iMem = ++pParse->nMem;
1491           int iAddr;
1492           char *pKey;
1493 
1494           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
1495           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
1496           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
1497 
1498           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
1499                                pKey,P4_KEYINFO_HANDOFF);
1500           VdbeComment((v, "%s", pIdx->zName));
1501           eType = IN_INDEX_INDEX;
1502 
1503           sqlite3VdbeJumpHere(v, iAddr);
1504           if( prNotFound && !pTab->aCol[iCol].notNull ){
1505             *prNotFound = ++pParse->nMem;
1506           }
1507         }
1508       }
1509     }
1510   }
1511 
1512   if( eType==0 ){
1513     /* Could not found an existing table or index to use as the RHS b-tree.
1514     ** We will have to generate an ephemeral table to do the job.
1515     */
1516     double savedNQueryLoop = pParse->nQueryLoop;
1517     int rMayHaveNull = 0;
1518     eType = IN_INDEX_EPH;
1519     if( prNotFound ){
1520       *prNotFound = rMayHaveNull = ++pParse->nMem;
1521     }else{
1522       testcase( pParse->nQueryLoop>(double)1 );
1523       pParse->nQueryLoop = (double)1;
1524       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
1525         eType = IN_INDEX_ROWID;
1526       }
1527     }
1528     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
1529     pParse->nQueryLoop = savedNQueryLoop;
1530   }else{
1531     pX->iTable = iTab;
1532   }
1533   return eType;
1534 }
1535 #endif
1536 
1537 /*
1538 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
1539 ** or IN operators.  Examples:
1540 **
1541 **     (SELECT a FROM b)          -- subquery
1542 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
1543 **     x IN (4,5,11)              -- IN operator with list on right-hand side
1544 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1545 **
1546 ** The pExpr parameter describes the expression that contains the IN
1547 ** operator or subquery.
1548 **
1549 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
1550 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
1551 ** to some integer key column of a table B-Tree. In this case, use an
1552 ** intkey B-Tree to store the set of IN(...) values instead of the usual
1553 ** (slower) variable length keys B-Tree.
1554 **
1555 ** If rMayHaveNull is non-zero, that means that the operation is an IN
1556 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
1557 ** Furthermore, the IN is in a WHERE clause and that we really want
1558 ** to iterate over the RHS of the IN operator in order to quickly locate
1559 ** all corresponding LHS elements.  All this routine does is initialize
1560 ** the register given by rMayHaveNull to NULL.  Calling routines will take
1561 ** care of changing this register value to non-NULL if the RHS is NULL-free.
1562 **
1563 ** If rMayHaveNull is zero, that means that the subquery is being used
1564 ** for membership testing only.  There is no need to initialize any
1565 ** registers to indicate the presense or absence of NULLs on the RHS.
1566 **
1567 ** For a SELECT or EXISTS operator, return the register that holds the
1568 ** result.  For IN operators or if an error occurs, the return value is 0.
1569 */
1570 #ifndef SQLITE_OMIT_SUBQUERY
1571 int sqlite3CodeSubselect(
1572   Parse *pParse,          /* Parsing context */
1573   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
1574   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
1575   int isRowid             /* If true, LHS of IN operator is a rowid */
1576 ){
1577   int testAddr = 0;                       /* One-time test address */
1578   int rReg = 0;                           /* Register storing resulting */
1579   Vdbe *v = sqlite3GetVdbe(pParse);
1580   if( NEVER(v==0) ) return 0;
1581   sqlite3ExprCachePush(pParse);
1582 
1583   /* This code must be run in its entirety every time it is encountered
1584   ** if any of the following is true:
1585   **
1586   **    *  The right-hand side is a correlated subquery
1587   **    *  The right-hand side is an expression list containing variables
1588   **    *  We are inside a trigger
1589   **
1590   ** If all of the above are false, then we can run this code just once
1591   ** save the results, and reuse the same result on subsequent invocations.
1592   */
1593   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
1594     int mem = ++pParse->nMem;
1595     sqlite3VdbeAddOp1(v, OP_If, mem);
1596     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
1597     assert( testAddr>0 || pParse->db->mallocFailed );
1598   }
1599 
1600   switch( pExpr->op ){
1601     case TK_IN: {
1602       char affinity;              /* Affinity of the LHS of the IN */
1603       KeyInfo keyInfo;            /* Keyinfo for the generated table */
1604       int addr;                   /* Address of OP_OpenEphemeral instruction */
1605       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
1606 
1607       if( rMayHaveNull ){
1608         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
1609       }
1610 
1611       affinity = sqlite3ExprAffinity(pLeft);
1612 
1613       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1614       ** expression it is handled the same way.  An ephemeral table is
1615       ** filled with single-field index keys representing the results
1616       ** from the SELECT or the <exprlist>.
1617       **
1618       ** If the 'x' expression is a column value, or the SELECT...
1619       ** statement returns a column value, then the affinity of that
1620       ** column is used to build the index keys. If both 'x' and the
1621       ** SELECT... statement are columns, then numeric affinity is used
1622       ** if either column has NUMERIC or INTEGER affinity. If neither
1623       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1624       ** is used.
1625       */
1626       pExpr->iTable = pParse->nTab++;
1627       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
1628       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
1629       memset(&keyInfo, 0, sizeof(keyInfo));
1630       keyInfo.nField = 1;
1631 
1632       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1633         /* Case 1:     expr IN (SELECT ...)
1634         **
1635         ** Generate code to write the results of the select into the temporary
1636         ** table allocated and opened above.
1637         */
1638         SelectDest dest;
1639         ExprList *pEList;
1640 
1641         assert( !isRowid );
1642         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
1643         dest.affinity = (u8)affinity;
1644         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1645         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
1646           return 0;
1647         }
1648         pEList = pExpr->x.pSelect->pEList;
1649         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
1650           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1651               pEList->a[0].pExpr);
1652         }
1653       }else if( ALWAYS(pExpr->x.pList!=0) ){
1654         /* Case 2:     expr IN (exprlist)
1655         **
1656         ** For each expression, build an index key from the evaluation and
1657         ** store it in the temporary table. If <expr> is a column, then use
1658         ** that columns affinity when building index keys. If <expr> is not
1659         ** a column, use numeric affinity.
1660         */
1661         int i;
1662         ExprList *pList = pExpr->x.pList;
1663         struct ExprList_item *pItem;
1664         int r1, r2, r3;
1665 
1666         if( !affinity ){
1667           affinity = SQLITE_AFF_NONE;
1668         }
1669         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
1670 
1671         /* Loop through each expression in <exprlist>. */
1672         r1 = sqlite3GetTempReg(pParse);
1673         r2 = sqlite3GetTempReg(pParse);
1674         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
1675         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1676           Expr *pE2 = pItem->pExpr;
1677           int iValToIns;
1678 
1679           /* If the expression is not constant then we will need to
1680           ** disable the test that was generated above that makes sure
1681           ** this code only executes once.  Because for a non-constant
1682           ** expression we need to rerun this code each time.
1683           */
1684           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
1685             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
1686             testAddr = 0;
1687           }
1688 
1689           /* Evaluate the expression and insert it into the temp table */
1690           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
1691             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
1692           }else{
1693             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
1694             if( isRowid ){
1695               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
1696                                 sqlite3VdbeCurrentAddr(v)+2);
1697               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
1698             }else{
1699               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
1700               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
1701               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
1702             }
1703           }
1704         }
1705         sqlite3ReleaseTempReg(pParse, r1);
1706         sqlite3ReleaseTempReg(pParse, r2);
1707       }
1708       if( !isRowid ){
1709         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
1710       }
1711       break;
1712     }
1713 
1714     case TK_EXISTS:
1715     case TK_SELECT:
1716     default: {
1717       /* If this has to be a scalar SELECT.  Generate code to put the
1718       ** value of this select in a memory cell and record the number
1719       ** of the memory cell in iColumn.  If this is an EXISTS, write
1720       ** an integer 0 (not exists) or 1 (exists) into a memory cell
1721       ** and record that memory cell in iColumn.
1722       */
1723       Select *pSel;                         /* SELECT statement to encode */
1724       SelectDest dest;                      /* How to deal with SELECt result */
1725 
1726       testcase( pExpr->op==TK_EXISTS );
1727       testcase( pExpr->op==TK_SELECT );
1728       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
1729 
1730       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1731       pSel = pExpr->x.pSelect;
1732       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
1733       if( pExpr->op==TK_SELECT ){
1734         dest.eDest = SRT_Mem;
1735         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
1736         VdbeComment((v, "Init subquery result"));
1737       }else{
1738         dest.eDest = SRT_Exists;
1739         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
1740         VdbeComment((v, "Init EXISTS result"));
1741       }
1742       sqlite3ExprDelete(pParse->db, pSel->pLimit);
1743       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
1744                                   &sqlite3IntTokens[1]);
1745       if( sqlite3Select(pParse, pSel, &dest) ){
1746         return 0;
1747       }
1748       rReg = dest.iParm;
1749       ExprSetIrreducible(pExpr);
1750       break;
1751     }
1752   }
1753 
1754   if( testAddr ){
1755     sqlite3VdbeJumpHere(v, testAddr-1);
1756   }
1757   sqlite3ExprCachePop(pParse, 1);
1758 
1759   return rReg;
1760 }
1761 #endif /* SQLITE_OMIT_SUBQUERY */
1762 
1763 #ifndef SQLITE_OMIT_SUBQUERY
1764 /*
1765 ** Generate code for an IN expression.
1766 **
1767 **      x IN (SELECT ...)
1768 **      x IN (value, value, ...)
1769 **
1770 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
1771 ** is an array of zero or more values.  The expression is true if the LHS is
1772 ** contained within the RHS.  The value of the expression is unknown (NULL)
1773 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
1774 ** RHS contains one or more NULL values.
1775 **
1776 ** This routine generates code will jump to destIfFalse if the LHS is not
1777 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
1778 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
1779 ** within the RHS then fall through.
1780 */
1781 static void sqlite3ExprCodeIN(
1782   Parse *pParse,        /* Parsing and code generating context */
1783   Expr *pExpr,          /* The IN expression */
1784   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
1785   int destIfNull        /* Jump here if the results are unknown due to NULLs */
1786 ){
1787   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
1788   char affinity;        /* Comparison affinity to use */
1789   int eType;            /* Type of the RHS */
1790   int r1;               /* Temporary use register */
1791   Vdbe *v;              /* Statement under construction */
1792 
1793   /* Compute the RHS.   After this step, the table with cursor
1794   ** pExpr->iTable will contains the values that make up the RHS.
1795   */
1796   v = pParse->pVdbe;
1797   assert( v!=0 );       /* OOM detected prior to this routine */
1798   VdbeNoopComment((v, "begin IN expr"));
1799   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
1800 
1801   /* Figure out the affinity to use to create a key from the results
1802   ** of the expression. affinityStr stores a static string suitable for
1803   ** P4 of OP_MakeRecord.
1804   */
1805   affinity = comparisonAffinity(pExpr);
1806 
1807   /* Code the LHS, the <expr> from "<expr> IN (...)".
1808   */
1809   sqlite3ExprCachePush(pParse);
1810   r1 = sqlite3GetTempReg(pParse);
1811   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
1812 
1813   /* If the LHS is NULL, then the result is either false or NULL depending
1814   ** on whether the RHS is empty or not, respectively.
1815   */
1816   if( destIfNull==destIfFalse ){
1817     /* Shortcut for the common case where the false and NULL outcomes are
1818     ** the same. */
1819     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
1820   }else{
1821     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
1822     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
1823     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
1824     sqlite3VdbeJumpHere(v, addr1);
1825   }
1826 
1827   if( eType==IN_INDEX_ROWID ){
1828     /* In this case, the RHS is the ROWID of table b-tree
1829     */
1830     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
1831     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
1832   }else{
1833     /* In this case, the RHS is an index b-tree.
1834     */
1835     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
1836 
1837     /* If the set membership test fails, then the result of the
1838     ** "x IN (...)" expression must be either 0 or NULL. If the set
1839     ** contains no NULL values, then the result is 0. If the set
1840     ** contains one or more NULL values, then the result of the
1841     ** expression is also NULL.
1842     */
1843     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
1844       /* This branch runs if it is known at compile time that the RHS
1845       ** cannot contain NULL values. This happens as the result
1846       ** of a "NOT NULL" constraint in the database schema.
1847       **
1848       ** Also run this branch if NULL is equivalent to FALSE
1849       ** for this particular IN operator.
1850       */
1851       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
1852 
1853     }else{
1854       /* In this branch, the RHS of the IN might contain a NULL and
1855       ** the presence of a NULL on the RHS makes a difference in the
1856       ** outcome.
1857       */
1858       int j1, j2, j3;
1859 
1860       /* First check to see if the LHS is contained in the RHS.  If so,
1861       ** then the presence of NULLs in the RHS does not matter, so jump
1862       ** over all of the code that follows.
1863       */
1864       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
1865 
1866       /* Here we begin generating code that runs if the LHS is not
1867       ** contained within the RHS.  Generate additional code that
1868       ** tests the RHS for NULLs.  If the RHS contains a NULL then
1869       ** jump to destIfNull.  If there are no NULLs in the RHS then
1870       ** jump to destIfFalse.
1871       */
1872       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
1873       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
1874       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
1875       sqlite3VdbeJumpHere(v, j3);
1876       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
1877       sqlite3VdbeJumpHere(v, j2);
1878 
1879       /* Jump to the appropriate target depending on whether or not
1880       ** the RHS contains a NULL
1881       */
1882       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
1883       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
1884 
1885       /* The OP_Found at the top of this branch jumps here when true,
1886       ** causing the overall IN expression evaluation to fall through.
1887       */
1888       sqlite3VdbeJumpHere(v, j1);
1889     }
1890   }
1891   sqlite3ReleaseTempReg(pParse, r1);
1892   sqlite3ExprCachePop(pParse, 1);
1893   VdbeComment((v, "end IN expr"));
1894 }
1895 #endif /* SQLITE_OMIT_SUBQUERY */
1896 
1897 /*
1898 ** Duplicate an 8-byte value
1899 */
1900 static char *dup8bytes(Vdbe *v, const char *in){
1901   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
1902   if( out ){
1903     memcpy(out, in, 8);
1904   }
1905   return out;
1906 }
1907 
1908 #ifndef SQLITE_OMIT_FLOATING_POINT
1909 /*
1910 ** Generate an instruction that will put the floating point
1911 ** value described by z[0..n-1] into register iMem.
1912 **
1913 ** The z[] string will probably not be zero-terminated.  But the
1914 ** z[n] character is guaranteed to be something that does not look
1915 ** like the continuation of the number.
1916 */
1917 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
1918   if( ALWAYS(z!=0) ){
1919     double value;
1920     char *zV;
1921     sqlite3AtoF(z, &value);
1922     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
1923     if( negateFlag ) value = -value;
1924     zV = dup8bytes(v, (char*)&value);
1925     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
1926   }
1927 }
1928 #endif
1929 
1930 
1931 /*
1932 ** Generate an instruction that will put the integer describe by
1933 ** text z[0..n-1] into register iMem.
1934 **
1935 ** The z[] string will probably not be zero-terminated.  But the
1936 ** z[n] character is guaranteed to be something that does not look
1937 ** like the continuation of the number.
1938 */
1939 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
1940   Vdbe *v = pParse->pVdbe;
1941   if( pExpr->flags & EP_IntValue ){
1942     int i = pExpr->u.iValue;
1943     if( negFlag ) i = -i;
1944     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
1945   }else{
1946     const char *z = pExpr->u.zToken;
1947     assert( z!=0 );
1948     if( sqlite3FitsIn64Bits(z, negFlag) ){
1949       i64 value;
1950       char *zV;
1951       sqlite3Atoi64(z, &value);
1952       if( negFlag ) value = -value;
1953       zV = dup8bytes(v, (char*)&value);
1954       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
1955     }else{
1956 #ifdef SQLITE_OMIT_FLOATING_POINT
1957       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
1958 #else
1959       codeReal(v, z, negFlag, iMem);
1960 #endif
1961     }
1962   }
1963 }
1964 
1965 /*
1966 ** Clear a cache entry.
1967 */
1968 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
1969   if( p->tempReg ){
1970     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
1971       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
1972     }
1973     p->tempReg = 0;
1974   }
1975 }
1976 
1977 
1978 /*
1979 ** Record in the column cache that a particular column from a
1980 ** particular table is stored in a particular register.
1981 */
1982 void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
1983   int i;
1984   int minLru;
1985   int idxLru;
1986   struct yColCache *p;
1987 
1988   assert( iReg>0 );  /* Register numbers are always positive */
1989   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
1990 
1991   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
1992   ** for testing only - to verify that SQLite always gets the same answer
1993   ** with and without the column cache.
1994   */
1995   if( pParse->db->flags & SQLITE_ColumnCache ) return;
1996 
1997   /* First replace any existing entry.
1998   **
1999   ** Actually, the way the column cache is currently used, we are guaranteed
2000   ** that the object will never already be in cache.  Verify this guarantee.
2001   */
2002 #ifndef NDEBUG
2003   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2004 #if 0 /* This code wold remove the entry from the cache if it existed */
2005     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
2006       cacheEntryClear(pParse, p);
2007       p->iLevel = pParse->iCacheLevel;
2008       p->iReg = iReg;
2009       p->lru = pParse->iCacheCnt++;
2010       return;
2011     }
2012 #endif
2013     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
2014   }
2015 #endif
2016 
2017   /* Find an empty slot and replace it */
2018   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2019     if( p->iReg==0 ){
2020       p->iLevel = pParse->iCacheLevel;
2021       p->iTable = iTab;
2022       p->iColumn = iCol;
2023       p->iReg = iReg;
2024       p->tempReg = 0;
2025       p->lru = pParse->iCacheCnt++;
2026       return;
2027     }
2028   }
2029 
2030   /* Replace the last recently used */
2031   minLru = 0x7fffffff;
2032   idxLru = -1;
2033   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2034     if( p->lru<minLru ){
2035       idxLru = i;
2036       minLru = p->lru;
2037     }
2038   }
2039   if( ALWAYS(idxLru>=0) ){
2040     p = &pParse->aColCache[idxLru];
2041     p->iLevel = pParse->iCacheLevel;
2042     p->iTable = iTab;
2043     p->iColumn = iCol;
2044     p->iReg = iReg;
2045     p->tempReg = 0;
2046     p->lru = pParse->iCacheCnt++;
2047     return;
2048   }
2049 }
2050 
2051 /*
2052 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2053 ** Purge the range of registers from the column cache.
2054 */
2055 void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
2056   int i;
2057   int iLast = iReg + nReg - 1;
2058   struct yColCache *p;
2059   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2060     int r = p->iReg;
2061     if( r>=iReg && r<=iLast ){
2062       cacheEntryClear(pParse, p);
2063       p->iReg = 0;
2064     }
2065   }
2066 }
2067 
2068 /*
2069 ** Remember the current column cache context.  Any new entries added
2070 ** added to the column cache after this call are removed when the
2071 ** corresponding pop occurs.
2072 */
2073 void sqlite3ExprCachePush(Parse *pParse){
2074   pParse->iCacheLevel++;
2075 }
2076 
2077 /*
2078 ** Remove from the column cache any entries that were added since the
2079 ** the previous N Push operations.  In other words, restore the cache
2080 ** to the state it was in N Pushes ago.
2081 */
2082 void sqlite3ExprCachePop(Parse *pParse, int N){
2083   int i;
2084   struct yColCache *p;
2085   assert( N>0 );
2086   assert( pParse->iCacheLevel>=N );
2087   pParse->iCacheLevel -= N;
2088   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2089     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2090       cacheEntryClear(pParse, p);
2091       p->iReg = 0;
2092     }
2093   }
2094 }
2095 
2096 /*
2097 ** When a cached column is reused, make sure that its register is
2098 ** no longer available as a temp register.  ticket #3879:  that same
2099 ** register might be in the cache in multiple places, so be sure to
2100 ** get them all.
2101 */
2102 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
2103   int i;
2104   struct yColCache *p;
2105   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2106     if( p->iReg==iReg ){
2107       p->tempReg = 0;
2108     }
2109   }
2110 }
2111 
2112 /*
2113 ** Generate code to extract the value of the iCol-th column of a table.
2114 */
2115 void sqlite3ExprCodeGetColumnOfTable(
2116   Vdbe *v,        /* The VDBE under construction */
2117   Table *pTab,    /* The table containing the value */
2118   int iTabCur,    /* The cursor for this table */
2119   int iCol,       /* Index of the column to extract */
2120   int regOut      /* Extract the valud into this register */
2121 ){
2122   if( iCol<0 || iCol==pTab->iPKey ){
2123     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
2124   }else{
2125     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
2126     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
2127   }
2128   if( iCol>=0 ){
2129     sqlite3ColumnDefault(v, pTab, iCol, regOut);
2130   }
2131 }
2132 
2133 /*
2134 ** Generate code that will extract the iColumn-th column from
2135 ** table pTab and store the column value in a register.  An effort
2136 ** is made to store the column value in register iReg, but this is
2137 ** not guaranteed.  The location of the column value is returned.
2138 **
2139 ** There must be an open cursor to pTab in iTable when this routine
2140 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
2141 */
2142 int sqlite3ExprCodeGetColumn(
2143   Parse *pParse,   /* Parsing and code generating context */
2144   Table *pTab,     /* Description of the table we are reading from */
2145   int iColumn,     /* Index of the table column */
2146   int iTable,      /* The cursor pointing to the table */
2147   int iReg         /* Store results here */
2148 ){
2149   Vdbe *v = pParse->pVdbe;
2150   int i;
2151   struct yColCache *p;
2152 
2153   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2154     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
2155       p->lru = pParse->iCacheCnt++;
2156       sqlite3ExprCachePinRegister(pParse, p->iReg);
2157       return p->iReg;
2158     }
2159   }
2160   assert( v!=0 );
2161   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
2162   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2163   return iReg;
2164 }
2165 
2166 /*
2167 ** Clear all column cache entries.
2168 */
2169 void sqlite3ExprCacheClear(Parse *pParse){
2170   int i;
2171   struct yColCache *p;
2172 
2173   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2174     if( p->iReg ){
2175       cacheEntryClear(pParse, p);
2176       p->iReg = 0;
2177     }
2178   }
2179 }
2180 
2181 /*
2182 ** Record the fact that an affinity change has occurred on iCount
2183 ** registers starting with iStart.
2184 */
2185 void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2186   sqlite3ExprCacheRemove(pParse, iStart, iCount);
2187 }
2188 
2189 /*
2190 ** Generate code to move content from registers iFrom...iFrom+nReg-1
2191 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
2192 */
2193 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
2194   int i;
2195   struct yColCache *p;
2196   if( NEVER(iFrom==iTo) ) return;
2197   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
2198   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2199     int x = p->iReg;
2200     if( x>=iFrom && x<iFrom+nReg ){
2201       p->iReg += iTo-iFrom;
2202     }
2203   }
2204 }
2205 
2206 /*
2207 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
2208 ** over to iTo..iTo+nReg-1.
2209 */
2210 void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
2211   int i;
2212   if( NEVER(iFrom==iTo) ) return;
2213   for(i=0; i<nReg; i++){
2214     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
2215   }
2216 }
2217 
2218 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
2219 /*
2220 ** Return true if any register in the range iFrom..iTo (inclusive)
2221 ** is used as part of the column cache.
2222 **
2223 ** This routine is used within assert() and testcase() macros only
2224 ** and does not appear in a normal build.
2225 */
2226 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2227   int i;
2228   struct yColCache *p;
2229   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2230     int r = p->iReg;
2231     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
2232   }
2233   return 0;
2234 }
2235 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
2236 
2237 /*
2238 ** If the last instruction coded is an ephemeral copy of any of
2239 ** the registers in the nReg registers beginning with iReg, then
2240 ** convert the last instruction from OP_SCopy to OP_Copy.
2241 */
2242 void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
2243   VdbeOp *pOp;
2244   Vdbe *v;
2245 
2246   assert( pParse->db->mallocFailed==0 );
2247   v = pParse->pVdbe;
2248   assert( v!=0 );
2249   pOp = sqlite3VdbeGetOp(v, -1);
2250   assert( pOp!=0 );
2251   if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
2252     pOp->opcode = OP_Copy;
2253   }
2254 }
2255 
2256 /*
2257 ** Generate code to store the value of the iAlias-th alias in register
2258 ** target.  The first time this is called, pExpr is evaluated to compute
2259 ** the value of the alias.  The value is stored in an auxiliary register
2260 ** and the number of that register is returned.  On subsequent calls,
2261 ** the register number is returned without generating any code.
2262 **
2263 ** Note that in order for this to work, code must be generated in the
2264 ** same order that it is executed.
2265 **
2266 ** Aliases are numbered starting with 1.  So iAlias is in the range
2267 ** of 1 to pParse->nAlias inclusive.
2268 **
2269 ** pParse->aAlias[iAlias-1] records the register number where the value
2270 ** of the iAlias-th alias is stored.  If zero, that means that the
2271 ** alias has not yet been computed.
2272 */
2273 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
2274 #if 0
2275   sqlite3 *db = pParse->db;
2276   int iReg;
2277   if( pParse->nAliasAlloc<pParse->nAlias ){
2278     pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
2279                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
2280     testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
2281     if( db->mallocFailed ) return 0;
2282     memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
2283            (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
2284     pParse->nAliasAlloc = pParse->nAlias;
2285   }
2286   assert( iAlias>0 && iAlias<=pParse->nAlias );
2287   iReg = pParse->aAlias[iAlias-1];
2288   if( iReg==0 ){
2289     if( pParse->iCacheLevel>0 ){
2290       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
2291     }else{
2292       iReg = ++pParse->nMem;
2293       sqlite3ExprCode(pParse, pExpr, iReg);
2294       pParse->aAlias[iAlias-1] = iReg;
2295     }
2296   }
2297   return iReg;
2298 #else
2299   UNUSED_PARAMETER(iAlias);
2300   return sqlite3ExprCodeTarget(pParse, pExpr, target);
2301 #endif
2302 }
2303 
2304 /*
2305 ** Generate code into the current Vdbe to evaluate the given
2306 ** expression.  Attempt to store the results in register "target".
2307 ** Return the register where results are stored.
2308 **
2309 ** With this routine, there is no guarantee that results will
2310 ** be stored in target.  The result might be stored in some other
2311 ** register if it is convenient to do so.  The calling function
2312 ** must check the return code and move the results to the desired
2313 ** register.
2314 */
2315 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
2316   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
2317   int op;                   /* The opcode being coded */
2318   int inReg = target;       /* Results stored in register inReg */
2319   int regFree1 = 0;         /* If non-zero free this temporary register */
2320   int regFree2 = 0;         /* If non-zero free this temporary register */
2321   int r1, r2, r3, r4;       /* Various register numbers */
2322   sqlite3 *db = pParse->db; /* The database connection */
2323 
2324   assert( target>0 && target<=pParse->nMem );
2325   if( v==0 ){
2326     assert( pParse->db->mallocFailed );
2327     return 0;
2328   }
2329 
2330   if( pExpr==0 ){
2331     op = TK_NULL;
2332   }else{
2333     op = pExpr->op;
2334   }
2335   switch( op ){
2336     case TK_AGG_COLUMN: {
2337       AggInfo *pAggInfo = pExpr->pAggInfo;
2338       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
2339       if( !pAggInfo->directMode ){
2340         assert( pCol->iMem>0 );
2341         inReg = pCol->iMem;
2342         break;
2343       }else if( pAggInfo->useSortingIdx ){
2344         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
2345                               pCol->iSorterColumn, target);
2346         break;
2347       }
2348       /* Otherwise, fall thru into the TK_COLUMN case */
2349     }
2350     case TK_COLUMN: {
2351       if( pExpr->iTable<0 ){
2352         /* This only happens when coding check constraints */
2353         assert( pParse->ckBase>0 );
2354         inReg = pExpr->iColumn + pParse->ckBase;
2355       }else{
2356         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2357                                  pExpr->iColumn, pExpr->iTable, target);
2358       }
2359       break;
2360     }
2361     case TK_INTEGER: {
2362       codeInteger(pParse, pExpr, 0, target);
2363       break;
2364     }
2365 #ifndef SQLITE_OMIT_FLOATING_POINT
2366     case TK_FLOAT: {
2367       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2368       codeReal(v, pExpr->u.zToken, 0, target);
2369       break;
2370     }
2371 #endif
2372     case TK_STRING: {
2373       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2374       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
2375       break;
2376     }
2377     case TK_NULL: {
2378       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2379       break;
2380     }
2381 #ifndef SQLITE_OMIT_BLOB_LITERAL
2382     case TK_BLOB: {
2383       int n;
2384       const char *z;
2385       char *zBlob;
2386       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2387       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
2388       assert( pExpr->u.zToken[1]=='\'' );
2389       z = &pExpr->u.zToken[2];
2390       n = sqlite3Strlen30(z) - 1;
2391       assert( z[n]=='\'' );
2392       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2393       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2394       break;
2395     }
2396 #endif
2397     case TK_VARIABLE: {
2398       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2399       assert( pExpr->u.zToken!=0 );
2400       assert( pExpr->u.zToken[0]!=0 );
2401       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
2402       if( pExpr->u.zToken[1]!=0 ){
2403         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
2404       }
2405       break;
2406     }
2407     case TK_REGISTER: {
2408       inReg = pExpr->iTable;
2409       break;
2410     }
2411     case TK_AS: {
2412       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
2413       break;
2414     }
2415 #ifndef SQLITE_OMIT_CAST
2416     case TK_CAST: {
2417       /* Expressions of the form:   CAST(pLeft AS token) */
2418       int aff, to_op;
2419       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2420       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2421       aff = sqlite3AffinityType(pExpr->u.zToken);
2422       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
2423       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
2424       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
2425       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
2426       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
2427       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
2428       testcase( to_op==OP_ToText );
2429       testcase( to_op==OP_ToBlob );
2430       testcase( to_op==OP_ToNumeric );
2431       testcase( to_op==OP_ToInt );
2432       testcase( to_op==OP_ToReal );
2433       if( inReg!=target ){
2434         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
2435         inReg = target;
2436       }
2437       sqlite3VdbeAddOp1(v, to_op, inReg);
2438       testcase( usedAsColumnCache(pParse, inReg, inReg) );
2439       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
2440       break;
2441     }
2442 #endif /* SQLITE_OMIT_CAST */
2443     case TK_LT:
2444     case TK_LE:
2445     case TK_GT:
2446     case TK_GE:
2447     case TK_NE:
2448     case TK_EQ: {
2449       assert( TK_LT==OP_Lt );
2450       assert( TK_LE==OP_Le );
2451       assert( TK_GT==OP_Gt );
2452       assert( TK_GE==OP_Ge );
2453       assert( TK_EQ==OP_Eq );
2454       assert( TK_NE==OP_Ne );
2455       testcase( op==TK_LT );
2456       testcase( op==TK_LE );
2457       testcase( op==TK_GT );
2458       testcase( op==TK_GE );
2459       testcase( op==TK_EQ );
2460       testcase( op==TK_NE );
2461       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2462       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
2463       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2464                   r1, r2, inReg, SQLITE_STOREP2);
2465       testcase( regFree1==0 );
2466       testcase( regFree2==0 );
2467       break;
2468     }
2469     case TK_IS:
2470     case TK_ISNOT: {
2471       testcase( op==TK_IS );
2472       testcase( op==TK_ISNOT );
2473       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2474       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
2475       op = (op==TK_IS) ? TK_EQ : TK_NE;
2476       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2477                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
2478       testcase( regFree1==0 );
2479       testcase( regFree2==0 );
2480       break;
2481     }
2482     case TK_AND:
2483     case TK_OR:
2484     case TK_PLUS:
2485     case TK_STAR:
2486     case TK_MINUS:
2487     case TK_REM:
2488     case TK_BITAND:
2489     case TK_BITOR:
2490     case TK_SLASH:
2491     case TK_LSHIFT:
2492     case TK_RSHIFT:
2493     case TK_CONCAT: {
2494       assert( TK_AND==OP_And );
2495       assert( TK_OR==OP_Or );
2496       assert( TK_PLUS==OP_Add );
2497       assert( TK_MINUS==OP_Subtract );
2498       assert( TK_REM==OP_Remainder );
2499       assert( TK_BITAND==OP_BitAnd );
2500       assert( TK_BITOR==OP_BitOr );
2501       assert( TK_SLASH==OP_Divide );
2502       assert( TK_LSHIFT==OP_ShiftLeft );
2503       assert( TK_RSHIFT==OP_ShiftRight );
2504       assert( TK_CONCAT==OP_Concat );
2505       testcase( op==TK_AND );
2506       testcase( op==TK_OR );
2507       testcase( op==TK_PLUS );
2508       testcase( op==TK_MINUS );
2509       testcase( op==TK_REM );
2510       testcase( op==TK_BITAND );
2511       testcase( op==TK_BITOR );
2512       testcase( op==TK_SLASH );
2513       testcase( op==TK_LSHIFT );
2514       testcase( op==TK_RSHIFT );
2515       testcase( op==TK_CONCAT );
2516       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2517       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
2518       sqlite3VdbeAddOp3(v, op, r2, r1, target);
2519       testcase( regFree1==0 );
2520       testcase( regFree2==0 );
2521       break;
2522     }
2523     case TK_UMINUS: {
2524       Expr *pLeft = pExpr->pLeft;
2525       assert( pLeft );
2526       if( pLeft->op==TK_INTEGER ){
2527         codeInteger(pParse, pLeft, 1, target);
2528 #ifndef SQLITE_OMIT_FLOATING_POINT
2529       }else if( pLeft->op==TK_FLOAT ){
2530         assert( !ExprHasProperty(pExpr, EP_IntValue) );
2531         codeReal(v, pLeft->u.zToken, 1, target);
2532 #endif
2533       }else{
2534         regFree1 = r1 = sqlite3GetTempReg(pParse);
2535         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
2536         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
2537         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
2538         testcase( regFree2==0 );
2539       }
2540       inReg = target;
2541       break;
2542     }
2543     case TK_BITNOT:
2544     case TK_NOT: {
2545       assert( TK_BITNOT==OP_BitNot );
2546       assert( TK_NOT==OP_Not );
2547       testcase( op==TK_BITNOT );
2548       testcase( op==TK_NOT );
2549       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2550       testcase( regFree1==0 );
2551       inReg = target;
2552       sqlite3VdbeAddOp2(v, op, r1, inReg);
2553       break;
2554     }
2555     case TK_ISNULL:
2556     case TK_NOTNULL: {
2557       int addr;
2558       assert( TK_ISNULL==OP_IsNull );
2559       assert( TK_NOTNULL==OP_NotNull );
2560       testcase( op==TK_ISNULL );
2561       testcase( op==TK_NOTNULL );
2562       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2563       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2564       testcase( regFree1==0 );
2565       addr = sqlite3VdbeAddOp1(v, op, r1);
2566       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
2567       sqlite3VdbeJumpHere(v, addr);
2568       break;
2569     }
2570     case TK_AGG_FUNCTION: {
2571       AggInfo *pInfo = pExpr->pAggInfo;
2572       if( pInfo==0 ){
2573         assert( !ExprHasProperty(pExpr, EP_IntValue) );
2574         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
2575       }else{
2576         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
2577       }
2578       break;
2579     }
2580     case TK_CONST_FUNC:
2581     case TK_FUNCTION: {
2582       ExprList *pFarg;       /* List of function arguments */
2583       int nFarg;             /* Number of function arguments */
2584       FuncDef *pDef;         /* The function definition object */
2585       int nId;               /* Length of the function name in bytes */
2586       const char *zId;       /* The function name */
2587       int constMask = 0;     /* Mask of function arguments that are constant */
2588       int i;                 /* Loop counter */
2589       u8 enc = ENC(db);      /* The text encoding used by this database */
2590       CollSeq *pColl = 0;    /* A collating sequence */
2591 
2592       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2593       testcase( op==TK_CONST_FUNC );
2594       testcase( op==TK_FUNCTION );
2595       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
2596         pFarg = 0;
2597       }else{
2598         pFarg = pExpr->x.pList;
2599       }
2600       nFarg = pFarg ? pFarg->nExpr : 0;
2601       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2602       zId = pExpr->u.zToken;
2603       nId = sqlite3Strlen30(zId);
2604       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
2605       if( pDef==0 ){
2606         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
2607         break;
2608       }
2609 
2610       /* Attempt a direct implementation of the built-in COALESCE() and
2611       ** IFNULL() functions.  This avoids unnecessary evalation of
2612       ** arguments past the first non-NULL argument.
2613       */
2614       if( pDef->flags & SQLITE_FUNC_COALESCE ){
2615         int endCoalesce = sqlite3VdbeMakeLabel(v);
2616         assert( nFarg>=2 );
2617         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
2618         for(i=1; i<nFarg; i++){
2619           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
2620           sqlite3ExprCacheRemove(pParse, target, 1);
2621           sqlite3ExprCachePush(pParse);
2622           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
2623           sqlite3ExprCachePop(pParse, 1);
2624         }
2625         sqlite3VdbeResolveLabel(v, endCoalesce);
2626         break;
2627       }
2628 
2629 
2630       if( pFarg ){
2631         r1 = sqlite3GetTempRange(pParse, nFarg);
2632         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
2633         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
2634         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
2635       }else{
2636         r1 = 0;
2637       }
2638 #ifndef SQLITE_OMIT_VIRTUALTABLE
2639       /* Possibly overload the function if the first argument is
2640       ** a virtual table column.
2641       **
2642       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2643       ** second argument, not the first, as the argument to test to
2644       ** see if it is a column in a virtual table.  This is done because
2645       ** the left operand of infix functions (the operand we want to
2646       ** control overloading) ends up as the second argument to the
2647       ** function.  The expression "A glob B" is equivalent to
2648       ** "glob(B,A).  We want to use the A in "A glob B" to test
2649       ** for function overloading.  But we use the B term in "glob(B,A)".
2650       */
2651       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
2652         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
2653       }else if( nFarg>0 ){
2654         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
2655       }
2656 #endif
2657       for(i=0; i<nFarg; i++){
2658         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
2659           constMask |= (1<<i);
2660         }
2661         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
2662           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
2663         }
2664       }
2665       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
2666         if( !pColl ) pColl = db->pDfltColl;
2667         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
2668       }
2669       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
2670                         (char*)pDef, P4_FUNCDEF);
2671       sqlite3VdbeChangeP5(v, (u8)nFarg);
2672       if( nFarg ){
2673         sqlite3ReleaseTempRange(pParse, r1, nFarg);
2674       }
2675       break;
2676     }
2677 #ifndef SQLITE_OMIT_SUBQUERY
2678     case TK_EXISTS:
2679     case TK_SELECT: {
2680       testcase( op==TK_EXISTS );
2681       testcase( op==TK_SELECT );
2682       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
2683       break;
2684     }
2685     case TK_IN: {
2686       int destIfFalse = sqlite3VdbeMakeLabel(v);
2687       int destIfNull = sqlite3VdbeMakeLabel(v);
2688       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2689       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
2690       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2691       sqlite3VdbeResolveLabel(v, destIfFalse);
2692       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
2693       sqlite3VdbeResolveLabel(v, destIfNull);
2694       break;
2695     }
2696 #endif /* SQLITE_OMIT_SUBQUERY */
2697 
2698 
2699     /*
2700     **    x BETWEEN y AND z
2701     **
2702     ** This is equivalent to
2703     **
2704     **    x>=y AND x<=z
2705     **
2706     ** X is stored in pExpr->pLeft.
2707     ** Y is stored in pExpr->pList->a[0].pExpr.
2708     ** Z is stored in pExpr->pList->a[1].pExpr.
2709     */
2710     case TK_BETWEEN: {
2711       Expr *pLeft = pExpr->pLeft;
2712       struct ExprList_item *pLItem = pExpr->x.pList->a;
2713       Expr *pRight = pLItem->pExpr;
2714 
2715       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
2716       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
2717       testcase( regFree1==0 );
2718       testcase( regFree2==0 );
2719       r3 = sqlite3GetTempReg(pParse);
2720       r4 = sqlite3GetTempReg(pParse);
2721       codeCompare(pParse, pLeft, pRight, OP_Ge,
2722                   r1, r2, r3, SQLITE_STOREP2);
2723       pLItem++;
2724       pRight = pLItem->pExpr;
2725       sqlite3ReleaseTempReg(pParse, regFree2);
2726       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
2727       testcase( regFree2==0 );
2728       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
2729       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
2730       sqlite3ReleaseTempReg(pParse, r3);
2731       sqlite3ReleaseTempReg(pParse, r4);
2732       break;
2733     }
2734     case TK_UPLUS: {
2735       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2736       break;
2737     }
2738 
2739     case TK_TRIGGER: {
2740       /* If the opcode is TK_TRIGGER, then the expression is a reference
2741       ** to a column in the new.* or old.* pseudo-tables available to
2742       ** trigger programs. In this case Expr.iTable is set to 1 for the
2743       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
2744       ** is set to the column of the pseudo-table to read, or to -1 to
2745       ** read the rowid field.
2746       **
2747       ** The expression is implemented using an OP_Param opcode. The p1
2748       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
2749       ** to reference another column of the old.* pseudo-table, where
2750       ** i is the index of the column. For a new.rowid reference, p1 is
2751       ** set to (n+1), where n is the number of columns in each pseudo-table.
2752       ** For a reference to any other column in the new.* pseudo-table, p1
2753       ** is set to (n+2+i), where n and i are as defined previously. For
2754       ** example, if the table on which triggers are being fired is
2755       ** declared as:
2756       **
2757       **   CREATE TABLE t1(a, b);
2758       **
2759       ** Then p1 is interpreted as follows:
2760       **
2761       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
2762       **   p1==1   ->    old.a         p1==4   ->    new.a
2763       **   p1==2   ->    old.b         p1==5   ->    new.b
2764       */
2765       Table *pTab = pExpr->pTab;
2766       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
2767 
2768       assert( pExpr->iTable==0 || pExpr->iTable==1 );
2769       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
2770       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
2771       assert( p1>=0 && p1<(pTab->nCol*2+2) );
2772 
2773       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
2774       VdbeComment((v, "%s.%s -> $%d",
2775         (pExpr->iTable ? "new" : "old"),
2776         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
2777         target
2778       ));
2779 
2780 #ifndef SQLITE_OMIT_FLOATING_POINT
2781       /* If the column has REAL affinity, it may currently be stored as an
2782       ** integer. Use OP_RealAffinity to make sure it is really real.  */
2783       if( pExpr->iColumn>=0
2784        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
2785       ){
2786         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
2787       }
2788 #endif
2789       break;
2790     }
2791 
2792 
2793     /*
2794     ** Form A:
2795     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2796     **
2797     ** Form B:
2798     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2799     **
2800     ** Form A is can be transformed into the equivalent form B as follows:
2801     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
2802     **        WHEN x=eN THEN rN ELSE y END
2803     **
2804     ** X (if it exists) is in pExpr->pLeft.
2805     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
2806     ** ELSE clause and no other term matches, then the result of the
2807     ** exprssion is NULL.
2808     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
2809     **
2810     ** The result of the expression is the Ri for the first matching Ei,
2811     ** or if there is no matching Ei, the ELSE term Y, or if there is
2812     ** no ELSE term, NULL.
2813     */
2814     default: assert( op==TK_CASE ); {
2815       int endLabel;                     /* GOTO label for end of CASE stmt */
2816       int nextCase;                     /* GOTO label for next WHEN clause */
2817       int nExpr;                        /* 2x number of WHEN terms */
2818       int i;                            /* Loop counter */
2819       ExprList *pEList;                 /* List of WHEN terms */
2820       struct ExprList_item *aListelem;  /* Array of WHEN terms */
2821       Expr opCompare;                   /* The X==Ei expression */
2822       Expr cacheX;                      /* Cached expression X */
2823       Expr *pX;                         /* The X expression */
2824       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
2825       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
2826 
2827       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
2828       assert((pExpr->x.pList->nExpr % 2) == 0);
2829       assert(pExpr->x.pList->nExpr > 0);
2830       pEList = pExpr->x.pList;
2831       aListelem = pEList->a;
2832       nExpr = pEList->nExpr;
2833       endLabel = sqlite3VdbeMakeLabel(v);
2834       if( (pX = pExpr->pLeft)!=0 ){
2835         cacheX = *pX;
2836         testcase( pX->op==TK_COLUMN );
2837         testcase( pX->op==TK_REGISTER );
2838         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
2839         testcase( regFree1==0 );
2840         cacheX.op = TK_REGISTER;
2841         opCompare.op = TK_EQ;
2842         opCompare.pLeft = &cacheX;
2843         pTest = &opCompare;
2844       }
2845       for(i=0; i<nExpr; i=i+2){
2846         sqlite3ExprCachePush(pParse);
2847         if( pX ){
2848           assert( pTest!=0 );
2849           opCompare.pRight = aListelem[i].pExpr;
2850         }else{
2851           pTest = aListelem[i].pExpr;
2852         }
2853         nextCase = sqlite3VdbeMakeLabel(v);
2854         testcase( pTest->op==TK_COLUMN );
2855         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
2856         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
2857         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
2858         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
2859         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
2860         sqlite3ExprCachePop(pParse, 1);
2861         sqlite3VdbeResolveLabel(v, nextCase);
2862       }
2863       if( pExpr->pRight ){
2864         sqlite3ExprCachePush(pParse);
2865         sqlite3ExprCode(pParse, pExpr->pRight, target);
2866         sqlite3ExprCachePop(pParse, 1);
2867       }else{
2868         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2869       }
2870       assert( db->mallocFailed || pParse->nErr>0
2871            || pParse->iCacheLevel==iCacheLevel );
2872       sqlite3VdbeResolveLabel(v, endLabel);
2873       break;
2874     }
2875 #ifndef SQLITE_OMIT_TRIGGER
2876     case TK_RAISE: {
2877       assert( pExpr->affinity==OE_Rollback
2878            || pExpr->affinity==OE_Abort
2879            || pExpr->affinity==OE_Fail
2880            || pExpr->affinity==OE_Ignore
2881       );
2882       if( !pParse->pTriggerTab ){
2883         sqlite3ErrorMsg(pParse,
2884                        "RAISE() may only be used within a trigger-program");
2885         return 0;
2886       }
2887       if( pExpr->affinity==OE_Abort ){
2888         sqlite3MayAbort(pParse);
2889       }
2890       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2891       if( pExpr->affinity==OE_Ignore ){
2892         sqlite3VdbeAddOp4(
2893             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
2894       }else{
2895         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
2896       }
2897 
2898       break;
2899     }
2900 #endif
2901   }
2902   sqlite3ReleaseTempReg(pParse, regFree1);
2903   sqlite3ReleaseTempReg(pParse, regFree2);
2904   return inReg;
2905 }
2906 
2907 /*
2908 ** Generate code to evaluate an expression and store the results
2909 ** into a register.  Return the register number where the results
2910 ** are stored.
2911 **
2912 ** If the register is a temporary register that can be deallocated,
2913 ** then write its number into *pReg.  If the result register is not
2914 ** a temporary, then set *pReg to zero.
2915 */
2916 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
2917   int r1 = sqlite3GetTempReg(pParse);
2918   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
2919   if( r2==r1 ){
2920     *pReg = r1;
2921   }else{
2922     sqlite3ReleaseTempReg(pParse, r1);
2923     *pReg = 0;
2924   }
2925   return r2;
2926 }
2927 
2928 /*
2929 ** Generate code that will evaluate expression pExpr and store the
2930 ** results in register target.  The results are guaranteed to appear
2931 ** in register target.
2932 */
2933 int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
2934   int inReg;
2935 
2936   assert( target>0 && target<=pParse->nMem );
2937   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
2938   assert( pParse->pVdbe || pParse->db->mallocFailed );
2939   if( inReg!=target && pParse->pVdbe ){
2940     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
2941   }
2942   return target;
2943 }
2944 
2945 /*
2946 ** Generate code that evalutes the given expression and puts the result
2947 ** in register target.
2948 **
2949 ** Also make a copy of the expression results into another "cache" register
2950 ** and modify the expression so that the next time it is evaluated,
2951 ** the result is a copy of the cache register.
2952 **
2953 ** This routine is used for expressions that are used multiple
2954 ** times.  They are evaluated once and the results of the expression
2955 ** are reused.
2956 */
2957 int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
2958   Vdbe *v = pParse->pVdbe;
2959   int inReg;
2960   inReg = sqlite3ExprCode(pParse, pExpr, target);
2961   assert( target>0 );
2962   /* This routine is called for terms to INSERT or UPDATE.  And the only
2963   ** other place where expressions can be converted into TK_REGISTER is
2964   ** in WHERE clause processing.  So as currently implemented, there is
2965   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
2966   ** keep the ALWAYS() in case the conditions above change with future
2967   ** modifications or enhancements. */
2968   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
2969     int iMem;
2970     iMem = ++pParse->nMem;
2971     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
2972     pExpr->iTable = iMem;
2973     pExpr->op2 = pExpr->op;
2974     pExpr->op = TK_REGISTER;
2975   }
2976   return inReg;
2977 }
2978 
2979 /*
2980 ** Return TRUE if pExpr is an constant expression that is appropriate
2981 ** for factoring out of a loop.  Appropriate expressions are:
2982 **
2983 **    *  Any expression that evaluates to two or more opcodes.
2984 **
2985 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
2986 **       or OP_Variable that does not need to be placed in a
2987 **       specific register.
2988 **
2989 ** There is no point in factoring out single-instruction constant
2990 ** expressions that need to be placed in a particular register.
2991 ** We could factor them out, but then we would end up adding an
2992 ** OP_SCopy instruction to move the value into the correct register
2993 ** later.  We might as well just use the original instruction and
2994 ** avoid the OP_SCopy.
2995 */
2996 static int isAppropriateForFactoring(Expr *p){
2997   if( !sqlite3ExprIsConstantNotJoin(p) ){
2998     return 0;  /* Only constant expressions are appropriate for factoring */
2999   }
3000   if( (p->flags & EP_FixedDest)==0 ){
3001     return 1;  /* Any constant without a fixed destination is appropriate */
3002   }
3003   while( p->op==TK_UPLUS ) p = p->pLeft;
3004   switch( p->op ){
3005 #ifndef SQLITE_OMIT_BLOB_LITERAL
3006     case TK_BLOB:
3007 #endif
3008     case TK_VARIABLE:
3009     case TK_INTEGER:
3010     case TK_FLOAT:
3011     case TK_NULL:
3012     case TK_STRING: {
3013       testcase( p->op==TK_BLOB );
3014       testcase( p->op==TK_VARIABLE );
3015       testcase( p->op==TK_INTEGER );
3016       testcase( p->op==TK_FLOAT );
3017       testcase( p->op==TK_NULL );
3018       testcase( p->op==TK_STRING );
3019       /* Single-instruction constants with a fixed destination are
3020       ** better done in-line.  If we factor them, they will just end
3021       ** up generating an OP_SCopy to move the value to the destination
3022       ** register. */
3023       return 0;
3024     }
3025     case TK_UMINUS: {
3026       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
3027         return 0;
3028       }
3029       break;
3030     }
3031     default: {
3032       break;
3033     }
3034   }
3035   return 1;
3036 }
3037 
3038 /*
3039 ** If pExpr is a constant expression that is appropriate for
3040 ** factoring out of a loop, then evaluate the expression
3041 ** into a register and convert the expression into a TK_REGISTER
3042 ** expression.
3043 */
3044 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
3045   Parse *pParse = pWalker->pParse;
3046   switch( pExpr->op ){
3047     case TK_IN:
3048     case TK_REGISTER: {
3049       return WRC_Prune;
3050     }
3051     case TK_FUNCTION:
3052     case TK_AGG_FUNCTION:
3053     case TK_CONST_FUNC: {
3054       /* The arguments to a function have a fixed destination.
3055       ** Mark them this way to avoid generated unneeded OP_SCopy
3056       ** instructions.
3057       */
3058       ExprList *pList = pExpr->x.pList;
3059       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3060       if( pList ){
3061         int i = pList->nExpr;
3062         struct ExprList_item *pItem = pList->a;
3063         for(; i>0; i--, pItem++){
3064           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
3065         }
3066       }
3067       break;
3068     }
3069   }
3070   if( isAppropriateForFactoring(pExpr) ){
3071     int r1 = ++pParse->nMem;
3072     int r2;
3073     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3074     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
3075     pExpr->op2 = pExpr->op;
3076     pExpr->op = TK_REGISTER;
3077     pExpr->iTable = r2;
3078     return WRC_Prune;
3079   }
3080   return WRC_Continue;
3081 }
3082 
3083 /*
3084 ** Preevaluate constant subexpressions within pExpr and store the
3085 ** results in registers.  Modify pExpr so that the constant subexpresions
3086 ** are TK_REGISTER opcodes that refer to the precomputed values.
3087 */
3088 void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
3089   Walker w;
3090   w.xExprCallback = evalConstExpr;
3091   w.xSelectCallback = 0;
3092   w.pParse = pParse;
3093   sqlite3WalkExpr(&w, pExpr);
3094 }
3095 
3096 
3097 /*
3098 ** Generate code that pushes the value of every element of the given
3099 ** expression list into a sequence of registers beginning at target.
3100 **
3101 ** Return the number of elements evaluated.
3102 */
3103 int sqlite3ExprCodeExprList(
3104   Parse *pParse,     /* Parsing context */
3105   ExprList *pList,   /* The expression list to be coded */
3106   int target,        /* Where to write results */
3107   int doHardCopy     /* Make a hard copy of every element */
3108 ){
3109   struct ExprList_item *pItem;
3110   int i, n;
3111   assert( pList!=0 );
3112   assert( target>0 );
3113   n = pList->nExpr;
3114   for(pItem=pList->a, i=0; i<n; i++, pItem++){
3115     if( pItem->iAlias ){
3116       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
3117       Vdbe *v = sqlite3GetVdbe(pParse);
3118       if( iReg!=target+i ){
3119         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
3120       }
3121     }else{
3122       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
3123     }
3124     if( doHardCopy && !pParse->db->mallocFailed ){
3125       sqlite3ExprHardCopy(pParse, target, n);
3126     }
3127   }
3128   return n;
3129 }
3130 
3131 /*
3132 ** Generate code for a BETWEEN operator.
3133 **
3134 **    x BETWEEN y AND z
3135 **
3136 ** The above is equivalent to
3137 **
3138 **    x>=y AND x<=z
3139 **
3140 ** Code it as such, taking care to do the common subexpression
3141 ** elementation of x.
3142 */
3143 static void exprCodeBetween(
3144   Parse *pParse,    /* Parsing and code generating context */
3145   Expr *pExpr,      /* The BETWEEN expression */
3146   int dest,         /* Jump here if the jump is taken */
3147   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
3148   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
3149 ){
3150   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
3151   Expr compLeft;    /* The  x>=y  term */
3152   Expr compRight;   /* The  x<=z  term */
3153   Expr exprX;       /* The  x  subexpression */
3154   int regFree1 = 0; /* Temporary use register */
3155 
3156   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3157   exprX = *pExpr->pLeft;
3158   exprAnd.op = TK_AND;
3159   exprAnd.pLeft = &compLeft;
3160   exprAnd.pRight = &compRight;
3161   compLeft.op = TK_GE;
3162   compLeft.pLeft = &exprX;
3163   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
3164   compRight.op = TK_LE;
3165   compRight.pLeft = &exprX;
3166   compRight.pRight = pExpr->x.pList->a[1].pExpr;
3167   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
3168   exprX.op = TK_REGISTER;
3169   if( jumpIfTrue ){
3170     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
3171   }else{
3172     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
3173   }
3174   sqlite3ReleaseTempReg(pParse, regFree1);
3175 
3176   /* Ensure adequate test coverage */
3177   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
3178   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
3179   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
3180   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
3181   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
3182   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
3183   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
3184   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
3185 }
3186 
3187 /*
3188 ** Generate code for a boolean expression such that a jump is made
3189 ** to the label "dest" if the expression is true but execution
3190 ** continues straight thru if the expression is false.
3191 **
3192 ** If the expression evaluates to NULL (neither true nor false), then
3193 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
3194 **
3195 ** This code depends on the fact that certain token values (ex: TK_EQ)
3196 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3197 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
3198 ** the make process cause these values to align.  Assert()s in the code
3199 ** below verify that the numbers are aligned correctly.
3200 */
3201 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3202   Vdbe *v = pParse->pVdbe;
3203   int op = 0;
3204   int regFree1 = 0;
3205   int regFree2 = 0;
3206   int r1, r2;
3207 
3208   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
3209   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
3210   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
3211   op = pExpr->op;
3212   switch( op ){
3213     case TK_AND: {
3214       int d2 = sqlite3VdbeMakeLabel(v);
3215       testcase( jumpIfNull==0 );
3216       sqlite3ExprCachePush(pParse);
3217       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
3218       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3219       sqlite3VdbeResolveLabel(v, d2);
3220       sqlite3ExprCachePop(pParse, 1);
3221       break;
3222     }
3223     case TK_OR: {
3224       testcase( jumpIfNull==0 );
3225       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3226       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3227       break;
3228     }
3229     case TK_NOT: {
3230       testcase( jumpIfNull==0 );
3231       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3232       break;
3233     }
3234     case TK_LT:
3235     case TK_LE:
3236     case TK_GT:
3237     case TK_GE:
3238     case TK_NE:
3239     case TK_EQ: {
3240       assert( TK_LT==OP_Lt );
3241       assert( TK_LE==OP_Le );
3242       assert( TK_GT==OP_Gt );
3243       assert( TK_GE==OP_Ge );
3244       assert( TK_EQ==OP_Eq );
3245       assert( TK_NE==OP_Ne );
3246       testcase( op==TK_LT );
3247       testcase( op==TK_LE );
3248       testcase( op==TK_GT );
3249       testcase( op==TK_GE );
3250       testcase( op==TK_EQ );
3251       testcase( op==TK_NE );
3252       testcase( jumpIfNull==0 );
3253       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3254       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3255       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3256                   r1, r2, dest, jumpIfNull);
3257       testcase( regFree1==0 );
3258       testcase( regFree2==0 );
3259       break;
3260     }
3261     case TK_IS:
3262     case TK_ISNOT: {
3263       testcase( op==TK_IS );
3264       testcase( op==TK_ISNOT );
3265       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3266       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3267       op = (op==TK_IS) ? TK_EQ : TK_NE;
3268       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3269                   r1, r2, dest, SQLITE_NULLEQ);
3270       testcase( regFree1==0 );
3271       testcase( regFree2==0 );
3272       break;
3273     }
3274     case TK_ISNULL:
3275     case TK_NOTNULL: {
3276       assert( TK_ISNULL==OP_IsNull );
3277       assert( TK_NOTNULL==OP_NotNull );
3278       testcase( op==TK_ISNULL );
3279       testcase( op==TK_NOTNULL );
3280       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3281       sqlite3VdbeAddOp2(v, op, r1, dest);
3282       testcase( regFree1==0 );
3283       break;
3284     }
3285     case TK_BETWEEN: {
3286       testcase( jumpIfNull==0 );
3287       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
3288       break;
3289     }
3290     case TK_IN: {
3291       int destIfFalse = sqlite3VdbeMakeLabel(v);
3292       int destIfNull = jumpIfNull ? dest : destIfFalse;
3293       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3294       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
3295       sqlite3VdbeResolveLabel(v, destIfFalse);
3296       break;
3297     }
3298     default: {
3299       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3300       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
3301       testcase( regFree1==0 );
3302       testcase( jumpIfNull==0 );
3303       break;
3304     }
3305   }
3306   sqlite3ReleaseTempReg(pParse, regFree1);
3307   sqlite3ReleaseTempReg(pParse, regFree2);
3308 }
3309 
3310 /*
3311 ** Generate code for a boolean expression such that a jump is made
3312 ** to the label "dest" if the expression is false but execution
3313 ** continues straight thru if the expression is true.
3314 **
3315 ** If the expression evaluates to NULL (neither true nor false) then
3316 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
3317 ** is 0.
3318 */
3319 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3320   Vdbe *v = pParse->pVdbe;
3321   int op = 0;
3322   int regFree1 = 0;
3323   int regFree2 = 0;
3324   int r1, r2;
3325 
3326   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
3327   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
3328   if( pExpr==0 )    return;
3329 
3330   /* The value of pExpr->op and op are related as follows:
3331   **
3332   **       pExpr->op            op
3333   **       ---------          ----------
3334   **       TK_ISNULL          OP_NotNull
3335   **       TK_NOTNULL         OP_IsNull
3336   **       TK_NE              OP_Eq
3337   **       TK_EQ              OP_Ne
3338   **       TK_GT              OP_Le
3339   **       TK_LE              OP_Gt
3340   **       TK_GE              OP_Lt
3341   **       TK_LT              OP_Ge
3342   **
3343   ** For other values of pExpr->op, op is undefined and unused.
3344   ** The value of TK_ and OP_ constants are arranged such that we
3345   ** can compute the mapping above using the following expression.
3346   ** Assert()s verify that the computation is correct.
3347   */
3348   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3349 
3350   /* Verify correct alignment of TK_ and OP_ constants
3351   */
3352   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3353   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3354   assert( pExpr->op!=TK_NE || op==OP_Eq );
3355   assert( pExpr->op!=TK_EQ || op==OP_Ne );
3356   assert( pExpr->op!=TK_LT || op==OP_Ge );
3357   assert( pExpr->op!=TK_LE || op==OP_Gt );
3358   assert( pExpr->op!=TK_GT || op==OP_Le );
3359   assert( pExpr->op!=TK_GE || op==OP_Lt );
3360 
3361   switch( pExpr->op ){
3362     case TK_AND: {
3363       testcase( jumpIfNull==0 );
3364       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3365       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3366       break;
3367     }
3368     case TK_OR: {
3369       int d2 = sqlite3VdbeMakeLabel(v);
3370       testcase( jumpIfNull==0 );
3371       sqlite3ExprCachePush(pParse);
3372       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
3373       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3374       sqlite3VdbeResolveLabel(v, d2);
3375       sqlite3ExprCachePop(pParse, 1);
3376       break;
3377     }
3378     case TK_NOT: {
3379       testcase( jumpIfNull==0 );
3380       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3381       break;
3382     }
3383     case TK_LT:
3384     case TK_LE:
3385     case TK_GT:
3386     case TK_GE:
3387     case TK_NE:
3388     case TK_EQ: {
3389       testcase( op==TK_LT );
3390       testcase( op==TK_LE );
3391       testcase( op==TK_GT );
3392       testcase( op==TK_GE );
3393       testcase( op==TK_EQ );
3394       testcase( op==TK_NE );
3395       testcase( jumpIfNull==0 );
3396       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3397       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3398       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3399                   r1, r2, dest, jumpIfNull);
3400       testcase( regFree1==0 );
3401       testcase( regFree2==0 );
3402       break;
3403     }
3404     case TK_IS:
3405     case TK_ISNOT: {
3406       testcase( pExpr->op==TK_IS );
3407       testcase( pExpr->op==TK_ISNOT );
3408       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3409       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3410       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
3411       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3412                   r1, r2, dest, SQLITE_NULLEQ);
3413       testcase( regFree1==0 );
3414       testcase( regFree2==0 );
3415       break;
3416     }
3417     case TK_ISNULL:
3418     case TK_NOTNULL: {
3419       testcase( op==TK_ISNULL );
3420       testcase( op==TK_NOTNULL );
3421       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3422       sqlite3VdbeAddOp2(v, op, r1, dest);
3423       testcase( regFree1==0 );
3424       break;
3425     }
3426     case TK_BETWEEN: {
3427       testcase( jumpIfNull==0 );
3428       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
3429       break;
3430     }
3431     case TK_IN: {
3432       if( jumpIfNull ){
3433         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
3434       }else{
3435         int destIfNull = sqlite3VdbeMakeLabel(v);
3436         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
3437         sqlite3VdbeResolveLabel(v, destIfNull);
3438       }
3439       break;
3440     }
3441     default: {
3442       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3443       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
3444       testcase( regFree1==0 );
3445       testcase( jumpIfNull==0 );
3446       break;
3447     }
3448   }
3449   sqlite3ReleaseTempReg(pParse, regFree1);
3450   sqlite3ReleaseTempReg(pParse, regFree2);
3451 }
3452 
3453 /*
3454 ** Do a deep comparison of two expression trees.  Return 0 if the two
3455 ** expressions are completely identical.  Return 1 if they differ only
3456 ** by a COLLATE operator at the top level.  Return 2 if there are differences
3457 ** other than the top-level COLLATE operator.
3458 **
3459 ** Sometimes this routine will return 2 even if the two expressions
3460 ** really are equivalent.  If we cannot prove that the expressions are
3461 ** identical, we return 2 just to be safe.  So if this routine
3462 ** returns 2, then you do not really know for certain if the two
3463 ** expressions are the same.  But if you get a 0 or 1 return, then you
3464 ** can be sure the expressions are the same.  In the places where
3465 ** this routine is used, it does not hurt to get an extra 2 - that
3466 ** just might result in some slightly slower code.  But returning
3467 ** an incorrect 0 or 1 could lead to a malfunction.
3468 */
3469 int sqlite3ExprCompare(Expr *pA, Expr *pB){
3470   if( pA==0||pB==0 ){
3471     return pB==pA ? 0 : 2;
3472   }
3473   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
3474   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
3475   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
3476     return 2;
3477   }
3478   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
3479   if( pA->op!=pB->op ) return 2;
3480   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
3481   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
3482   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
3483   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
3484   if( ExprHasProperty(pA, EP_IntValue) ){
3485     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
3486       return 2;
3487     }
3488   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
3489     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
3490     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
3491       return 2;
3492     }
3493   }
3494   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
3495   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
3496   return 0;
3497 }
3498 
3499 /*
3500 ** Compare two ExprList objects.  Return 0 if they are identical and
3501 ** non-zero if they differ in any way.
3502 **
3503 ** This routine might return non-zero for equivalent ExprLists.  The
3504 ** only consequence will be disabled optimizations.  But this routine
3505 ** must never return 0 if the two ExprList objects are different, or
3506 ** a malfunction will result.
3507 **
3508 ** Two NULL pointers are considered to be the same.  But a NULL pointer
3509 ** always differs from a non-NULL pointer.
3510 */
3511 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
3512   int i;
3513   if( pA==0 && pB==0 ) return 0;
3514   if( pA==0 || pB==0 ) return 1;
3515   if( pA->nExpr!=pB->nExpr ) return 1;
3516   for(i=0; i<pA->nExpr; i++){
3517     Expr *pExprA = pA->a[i].pExpr;
3518     Expr *pExprB = pB->a[i].pExpr;
3519     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
3520     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
3521   }
3522   return 0;
3523 }
3524 
3525 /*
3526 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
3527 ** the new element.  Return a negative number if malloc fails.
3528 */
3529 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
3530   int i;
3531   pInfo->aCol = sqlite3ArrayAllocate(
3532        db,
3533        pInfo->aCol,
3534        sizeof(pInfo->aCol[0]),
3535        3,
3536        &pInfo->nColumn,
3537        &pInfo->nColumnAlloc,
3538        &i
3539   );
3540   return i;
3541 }
3542 
3543 /*
3544 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
3545 ** the new element.  Return a negative number if malloc fails.
3546 */
3547 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
3548   int i;
3549   pInfo->aFunc = sqlite3ArrayAllocate(
3550        db,
3551        pInfo->aFunc,
3552        sizeof(pInfo->aFunc[0]),
3553        3,
3554        &pInfo->nFunc,
3555        &pInfo->nFuncAlloc,
3556        &i
3557   );
3558   return i;
3559 }
3560 
3561 /*
3562 ** This is the xExprCallback for a tree walker.  It is used to
3563 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
3564 ** for additional information.
3565 */
3566 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
3567   int i;
3568   NameContext *pNC = pWalker->u.pNC;
3569   Parse *pParse = pNC->pParse;
3570   SrcList *pSrcList = pNC->pSrcList;
3571   AggInfo *pAggInfo = pNC->pAggInfo;
3572 
3573   switch( pExpr->op ){
3574     case TK_AGG_COLUMN:
3575     case TK_COLUMN: {
3576       testcase( pExpr->op==TK_AGG_COLUMN );
3577       testcase( pExpr->op==TK_COLUMN );
3578       /* Check to see if the column is in one of the tables in the FROM
3579       ** clause of the aggregate query */
3580       if( ALWAYS(pSrcList!=0) ){
3581         struct SrcList_item *pItem = pSrcList->a;
3582         for(i=0; i<pSrcList->nSrc; i++, pItem++){
3583           struct AggInfo_col *pCol;
3584           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3585           if( pExpr->iTable==pItem->iCursor ){
3586             /* If we reach this point, it means that pExpr refers to a table
3587             ** that is in the FROM clause of the aggregate query.
3588             **
3589             ** Make an entry for the column in pAggInfo->aCol[] if there
3590             ** is not an entry there already.
3591             */
3592             int k;
3593             pCol = pAggInfo->aCol;
3594             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
3595               if( pCol->iTable==pExpr->iTable &&
3596                   pCol->iColumn==pExpr->iColumn ){
3597                 break;
3598               }
3599             }
3600             if( (k>=pAggInfo->nColumn)
3601              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
3602             ){
3603               pCol = &pAggInfo->aCol[k];
3604               pCol->pTab = pExpr->pTab;
3605               pCol->iTable = pExpr->iTable;
3606               pCol->iColumn = pExpr->iColumn;
3607               pCol->iMem = ++pParse->nMem;
3608               pCol->iSorterColumn = -1;
3609               pCol->pExpr = pExpr;
3610               if( pAggInfo->pGroupBy ){
3611                 int j, n;
3612                 ExprList *pGB = pAggInfo->pGroupBy;
3613                 struct ExprList_item *pTerm = pGB->a;
3614                 n = pGB->nExpr;
3615                 for(j=0; j<n; j++, pTerm++){
3616                   Expr *pE = pTerm->pExpr;
3617                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
3618                       pE->iColumn==pExpr->iColumn ){
3619                     pCol->iSorterColumn = j;
3620                     break;
3621                   }
3622                 }
3623               }
3624               if( pCol->iSorterColumn<0 ){
3625                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
3626               }
3627             }
3628             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
3629             ** because it was there before or because we just created it).
3630             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
3631             ** pAggInfo->aCol[] entry.
3632             */
3633             ExprSetIrreducible(pExpr);
3634             pExpr->pAggInfo = pAggInfo;
3635             pExpr->op = TK_AGG_COLUMN;
3636             pExpr->iAgg = (i16)k;
3637             break;
3638           } /* endif pExpr->iTable==pItem->iCursor */
3639         } /* end loop over pSrcList */
3640       }
3641       return WRC_Prune;
3642     }
3643     case TK_AGG_FUNCTION: {
3644       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
3645       ** to be ignored */
3646       if( pNC->nDepth==0 ){
3647         /* Check to see if pExpr is a duplicate of another aggregate
3648         ** function that is already in the pAggInfo structure
3649         */
3650         struct AggInfo_func *pItem = pAggInfo->aFunc;
3651         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
3652           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
3653             break;
3654           }
3655         }
3656         if( i>=pAggInfo->nFunc ){
3657           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
3658           */
3659           u8 enc = ENC(pParse->db);
3660           i = addAggInfoFunc(pParse->db, pAggInfo);
3661           if( i>=0 ){
3662             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3663             pItem = &pAggInfo->aFunc[i];
3664             pItem->pExpr = pExpr;
3665             pItem->iMem = ++pParse->nMem;
3666             assert( !ExprHasProperty(pExpr, EP_IntValue) );
3667             pItem->pFunc = sqlite3FindFunction(pParse->db,
3668                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
3669                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
3670             if( pExpr->flags & EP_Distinct ){
3671               pItem->iDistinct = pParse->nTab++;
3672             }else{
3673               pItem->iDistinct = -1;
3674             }
3675           }
3676         }
3677         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
3678         */
3679         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3680         ExprSetIrreducible(pExpr);
3681         pExpr->iAgg = (i16)i;
3682         pExpr->pAggInfo = pAggInfo;
3683         return WRC_Prune;
3684       }
3685     }
3686   }
3687   return WRC_Continue;
3688 }
3689 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
3690   NameContext *pNC = pWalker->u.pNC;
3691   if( pNC->nDepth==0 ){
3692     pNC->nDepth++;
3693     sqlite3WalkSelect(pWalker, pSelect);
3694     pNC->nDepth--;
3695     return WRC_Prune;
3696   }else{
3697     return WRC_Continue;
3698   }
3699 }
3700 
3701 /*
3702 ** Analyze the given expression looking for aggregate functions and
3703 ** for variables that need to be added to the pParse->aAgg[] array.
3704 ** Make additional entries to the pParse->aAgg[] array as necessary.
3705 **
3706 ** This routine should only be called after the expression has been
3707 ** analyzed by sqlite3ResolveExprNames().
3708 */
3709 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
3710   Walker w;
3711   w.xExprCallback = analyzeAggregate;
3712   w.xSelectCallback = analyzeAggregatesInSelect;
3713   w.u.pNC = pNC;
3714   assert( pNC->pSrcList!=0 );
3715   sqlite3WalkExpr(&w, pExpr);
3716 }
3717 
3718 /*
3719 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
3720 ** expression list.  Return the number of errors.
3721 **
3722 ** If an error is found, the analysis is cut short.
3723 */
3724 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
3725   struct ExprList_item *pItem;
3726   int i;
3727   if( pList ){
3728     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
3729       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
3730     }
3731   }
3732 }
3733 
3734 /*
3735 ** Allocate a single new register for use to hold some intermediate result.
3736 */
3737 int sqlite3GetTempReg(Parse *pParse){
3738   if( pParse->nTempReg==0 ){
3739     return ++pParse->nMem;
3740   }
3741   return pParse->aTempReg[--pParse->nTempReg];
3742 }
3743 
3744 /*
3745 ** Deallocate a register, making available for reuse for some other
3746 ** purpose.
3747 **
3748 ** If a register is currently being used by the column cache, then
3749 ** the dallocation is deferred until the column cache line that uses
3750 ** the register becomes stale.
3751 */
3752 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
3753   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
3754     int i;
3755     struct yColCache *p;
3756     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3757       if( p->iReg==iReg ){
3758         p->tempReg = 1;
3759         return;
3760       }
3761     }
3762     pParse->aTempReg[pParse->nTempReg++] = iReg;
3763   }
3764 }
3765 
3766 /*
3767 ** Allocate or deallocate a block of nReg consecutive registers
3768 */
3769 int sqlite3GetTempRange(Parse *pParse, int nReg){
3770   int i, n;
3771   i = pParse->iRangeReg;
3772   n = pParse->nRangeReg;
3773   if( nReg<=n ){
3774     assert( !usedAsColumnCache(pParse, i, i+n-1) );
3775     pParse->iRangeReg += nReg;
3776     pParse->nRangeReg -= nReg;
3777   }else{
3778     i = pParse->nMem+1;
3779     pParse->nMem += nReg;
3780   }
3781   return i;
3782 }
3783 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
3784   sqlite3ExprCacheRemove(pParse, iReg, nReg);
3785   if( nReg>pParse->nRangeReg ){
3786     pParse->nRangeReg = nReg;
3787     pParse->iRangeReg = iReg;
3788   }
3789 }
3790