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