xref: /sqlite-3.40.0/src/expr.c (revision 961303c1)
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.312 2007/09/01 18:24:55 danielk1977 Exp $
16 */
17 #include "sqliteInt.h"
18 #include <ctype.h>
19 
20 /*
21 ** Return the 'affinity' of the expression pExpr if any.
22 **
23 ** If pExpr is a column, a reference to a column via an 'AS' alias,
24 ** or a sub-select with a column as the return value, then the
25 ** affinity of that column is returned. Otherwise, 0x00 is returned,
26 ** indicating no affinity for the expression.
27 **
28 ** i.e. the WHERE clause expresssions in the following statements all
29 ** have an affinity:
30 **
31 ** CREATE TABLE t1(a);
32 ** SELECT * FROM t1 WHERE a;
33 ** SELECT a AS b FROM t1 WHERE b;
34 ** SELECT * FROM t1 WHERE (select a from t1);
35 */
36 char sqlite3ExprAffinity(Expr *pExpr){
37   int op = pExpr->op;
38   if( op==TK_SELECT ){
39     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
40   }
41 #ifndef SQLITE_OMIT_CAST
42   if( op==TK_CAST ){
43     return sqlite3AffinityType(&pExpr->token);
44   }
45 #endif
46   return pExpr->affinity;
47 }
48 
49 /*
50 ** Set the collating sequence for expression pExpr to be the collating
51 ** sequence named by pToken.   Return a pointer to the revised expression.
52 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
53 ** flag.  An explicit collating sequence will override implicit
54 ** collating sequences.
55 */
56 Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
57   CollSeq *pColl;
58   if( pExpr==0 ) return 0;
59   pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
60   if( pColl ){
61     pExpr->pColl = pColl;
62     pExpr->flags |= EP_ExpCollate;
63   }
64   return pExpr;
65 }
66 
67 /*
68 ** Return the default collation sequence for the expression pExpr. If
69 ** there is no default collation type, return 0.
70 */
71 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
72   CollSeq *pColl = 0;
73   if( pExpr ){
74     int op;
75     pColl = pExpr->pColl;
76     op = pExpr->op;
77     if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
78       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
79     }
80   }
81   if( sqlite3CheckCollSeq(pParse, pColl) ){
82     pColl = 0;
83   }
84   return pColl;
85 }
86 
87 /*
88 ** pExpr is an operand of a comparison operator.  aff2 is the
89 ** type affinity of the other operand.  This routine returns the
90 ** type affinity that should be used for the comparison operator.
91 */
92 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
93   char aff1 = sqlite3ExprAffinity(pExpr);
94   if( aff1 && aff2 ){
95     /* Both sides of the comparison are columns. If one has numeric
96     ** affinity, use that. Otherwise use no affinity.
97     */
98     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
99       return SQLITE_AFF_NUMERIC;
100     }else{
101       return SQLITE_AFF_NONE;
102     }
103   }else if( !aff1 && !aff2 ){
104     /* Neither side of the comparison is a column.  Compare the
105     ** results directly.
106     */
107     return SQLITE_AFF_NONE;
108   }else{
109     /* One side is a column, the other is not. Use the columns affinity. */
110     assert( aff1==0 || aff2==0 );
111     return (aff1 + aff2);
112   }
113 }
114 
115 /*
116 ** pExpr is a comparison operator.  Return the type affinity that should
117 ** be applied to both operands prior to doing the comparison.
118 */
119 static char comparisonAffinity(Expr *pExpr){
120   char aff;
121   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
122           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
123           pExpr->op==TK_NE );
124   assert( pExpr->pLeft );
125   aff = sqlite3ExprAffinity(pExpr->pLeft);
126   if( pExpr->pRight ){
127     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
128   }
129   else if( pExpr->pSelect ){
130     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
131   }
132   else if( !aff ){
133     aff = SQLITE_AFF_NONE;
134   }
135   return aff;
136 }
137 
138 /*
139 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
140 ** idx_affinity is the affinity of an indexed column. Return true
141 ** if the index with affinity idx_affinity may be used to implement
142 ** the comparison in pExpr.
143 */
144 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
145   char aff = comparisonAffinity(pExpr);
146   switch( aff ){
147     case SQLITE_AFF_NONE:
148       return 1;
149     case SQLITE_AFF_TEXT:
150       return idx_affinity==SQLITE_AFF_TEXT;
151     default:
152       return sqlite3IsNumericAffinity(idx_affinity);
153   }
154 }
155 
156 /*
157 ** Return the P1 value that should be used for a binary comparison
158 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
159 ** If jumpIfNull is true, then set the low byte of the returned
160 ** P1 value to tell the opcode to jump if either expression
161 ** evaluates to NULL.
162 */
163 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
164   char aff = sqlite3ExprAffinity(pExpr2);
165   return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
166 }
167 
168 /*
169 ** Return a pointer to the collation sequence that should be used by
170 ** a binary comparison operator comparing pLeft and pRight.
171 **
172 ** If the left hand expression has a collating sequence type, then it is
173 ** used. Otherwise the collation sequence for the right hand expression
174 ** is used, or the default (BINARY) if neither expression has a collating
175 ** type.
176 **
177 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
178 ** it is not considered.
179 */
180 CollSeq *sqlite3BinaryCompareCollSeq(
181   Parse *pParse,
182   Expr *pLeft,
183   Expr *pRight
184 ){
185   CollSeq *pColl;
186   assert( pLeft );
187   if( pLeft->flags & EP_ExpCollate ){
188     assert( pLeft->pColl );
189     pColl = pLeft->pColl;
190   }else if( pRight && pRight->flags & EP_ExpCollate ){
191     assert( pRight->pColl );
192     pColl = pRight->pColl;
193   }else{
194     pColl = sqlite3ExprCollSeq(pParse, pLeft);
195     if( !pColl ){
196       pColl = sqlite3ExprCollSeq(pParse, pRight);
197     }
198   }
199   return pColl;
200 }
201 
202 /*
203 ** Generate code for a comparison operator.
204 */
205 static int codeCompare(
206   Parse *pParse,    /* The parsing (and code generating) context */
207   Expr *pLeft,      /* The left operand */
208   Expr *pRight,     /* The right operand */
209   int opcode,       /* The comparison opcode */
210   int dest,         /* Jump here if true.  */
211   int jumpIfNull    /* If true, jump if either operand is NULL */
212 ){
213   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
214   CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
215   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
216 }
217 
218 /*
219 ** Construct a new expression node and return a pointer to it.  Memory
220 ** for this node is obtained from sqlite3_malloc().  The calling function
221 ** is responsible for making sure the node eventually gets freed.
222 */
223 Expr *sqlite3Expr(
224   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
225   int op,                 /* Expression opcode */
226   Expr *pLeft,            /* Left operand */
227   Expr *pRight,           /* Right operand */
228   const Token *pToken     /* Argument token */
229 ){
230   Expr *pNew;
231   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
232   if( pNew==0 ){
233     /* When malloc fails, delete pLeft and pRight. Expressions passed to
234     ** this function must always be allocated with sqlite3Expr() for this
235     ** reason.
236     */
237     sqlite3ExprDelete(pLeft);
238     sqlite3ExprDelete(pRight);
239     return 0;
240   }
241   pNew->op = op;
242   pNew->pLeft = pLeft;
243   pNew->pRight = pRight;
244   pNew->iAgg = -1;
245   if( pToken ){
246     assert( pToken->dyn==0 );
247     pNew->span = pNew->token = *pToken;
248   }else if( pLeft ){
249     if( pRight ){
250       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
251       if( pRight->flags & EP_ExpCollate ){
252         pNew->flags |= EP_ExpCollate;
253         pNew->pColl = pRight->pColl;
254       }
255     }
256     if( pLeft->flags & EP_ExpCollate ){
257       pNew->flags |= EP_ExpCollate;
258       pNew->pColl = pLeft->pColl;
259     }
260   }
261 
262   sqlite3ExprSetHeight(pNew);
263   return pNew;
264 }
265 
266 /*
267 ** Works like sqlite3Expr() except that it takes an extra Parse*
268 ** argument and notifies the associated connection object if malloc fails.
269 */
270 Expr *sqlite3PExpr(
271   Parse *pParse,          /* Parsing context */
272   int op,                 /* Expression opcode */
273   Expr *pLeft,            /* Left operand */
274   Expr *pRight,           /* Right operand */
275   const Token *pToken     /* Argument token */
276 ){
277   return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
278 }
279 
280 /*
281 ** When doing a nested parse, you can include terms in an expression
282 ** that look like this:   #0 #1 #2 ...  These terms refer to elements
283 ** on the stack.  "#0" means the top of the stack.
284 ** "#1" means the next down on the stack.  And so forth.
285 **
286 ** This routine is called by the parser to deal with on of those terms.
287 ** It immediately generates code to store the value in a memory location.
288 ** The returns an expression that will code to extract the value from
289 ** that memory location as needed.
290 */
291 Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
292   Vdbe *v = pParse->pVdbe;
293   Expr *p;
294   int depth;
295   if( pParse->nested==0 ){
296     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
297     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
298   }
299   if( v==0 ) return 0;
300   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
301   if( p==0 ){
302     return 0;  /* Malloc failed */
303   }
304   depth = atoi((char*)&pToken->z[1]);
305   p->iTable = pParse->nMem++;
306   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
307   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
308   return p;
309 }
310 
311 /*
312 ** Join two expressions using an AND operator.  If either expression is
313 ** NULL, then just return the other expression.
314 */
315 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
316   if( pLeft==0 ){
317     return pRight;
318   }else if( pRight==0 ){
319     return pLeft;
320   }else{
321     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
322   }
323 }
324 
325 /*
326 ** Set the Expr.span field of the given expression to span all
327 ** text between the two given tokens.
328 */
329 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
330   assert( pRight!=0 );
331   assert( pLeft!=0 );
332   if( pExpr && pRight->z && pLeft->z ){
333     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
334     if( pLeft->dyn==0 && pRight->dyn==0 ){
335       pExpr->span.z = pLeft->z;
336       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
337     }else{
338       pExpr->span.z = 0;
339     }
340   }
341 }
342 
343 /*
344 ** Construct a new expression node for a function with multiple
345 ** arguments.
346 */
347 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
348   Expr *pNew;
349   assert( pToken );
350   pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) );
351   if( pNew==0 ){
352     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
353     return 0;
354   }
355   pNew->op = TK_FUNCTION;
356   pNew->pList = pList;
357   assert( pToken->dyn==0 );
358   pNew->token = *pToken;
359   pNew->span = pNew->token;
360 
361   sqlite3ExprSetHeight(pNew);
362   return pNew;
363 }
364 
365 /*
366 ** Assign a variable number to an expression that encodes a wildcard
367 ** in the original SQL statement.
368 **
369 ** Wildcards consisting of a single "?" are assigned the next sequential
370 ** variable number.
371 **
372 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
373 ** sure "nnn" is not too be to avoid a denial of service attack when
374 ** the SQL statement comes from an external source.
375 **
376 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
377 ** as the previous instance of the same wildcard.  Or if this is the first
378 ** instance of the wildcard, the next sequenial variable number is
379 ** assigned.
380 */
381 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
382   Token *pToken;
383   sqlite3 *db = pParse->db;
384 
385   if( pExpr==0 ) return;
386   pToken = &pExpr->token;
387   assert( pToken->n>=1 );
388   assert( pToken->z!=0 );
389   assert( pToken->z[0]!=0 );
390   if( pToken->n==1 ){
391     /* Wildcard of the form "?".  Assign the next variable number */
392     pExpr->iTable = ++pParse->nVar;
393   }else if( pToken->z[0]=='?' ){
394     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
395     ** use it as the variable number */
396     int i;
397     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
398     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
399       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
400           SQLITE_MAX_VARIABLE_NUMBER);
401     }
402     if( i>pParse->nVar ){
403       pParse->nVar = i;
404     }
405   }else{
406     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
407     ** number as the prior appearance of the same name, or if the name
408     ** has never appeared before, reuse the same variable number
409     */
410     int i, n;
411     n = pToken->n;
412     for(i=0; i<pParse->nVarExpr; i++){
413       Expr *pE;
414       if( (pE = pParse->apVarExpr[i])!=0
415           && pE->token.n==n
416           && memcmp(pE->token.z, pToken->z, n)==0 ){
417         pExpr->iTable = pE->iTable;
418         break;
419       }
420     }
421     if( i>=pParse->nVarExpr ){
422       pExpr->iTable = ++pParse->nVar;
423       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
424         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
425         pParse->apVarExpr =
426             sqlite3DbReallocOrFree(
427               db,
428               pParse->apVarExpr,
429               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
430             );
431       }
432       if( !db->mallocFailed ){
433         assert( pParse->apVarExpr!=0 );
434         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
435       }
436     }
437   }
438   if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
439     sqlite3ErrorMsg(pParse, "too many SQL variables");
440   }
441 }
442 
443 /*
444 ** Recursively delete an expression tree.
445 */
446 void sqlite3ExprDelete(Expr *p){
447   if( p==0 ) return;
448   if( p->span.dyn ) sqlite3_free((char*)p->span.z);
449   if( p->token.dyn ) sqlite3_free((char*)p->token.z);
450   sqlite3ExprDelete(p->pLeft);
451   sqlite3ExprDelete(p->pRight);
452   sqlite3ExprListDelete(p->pList);
453   sqlite3SelectDelete(p->pSelect);
454   sqlite3_free(p);
455 }
456 
457 /*
458 ** The Expr.token field might be a string literal that is quoted.
459 ** If so, remove the quotation marks.
460 */
461 void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
462   if( ExprHasAnyProperty(p, EP_Dequoted) ){
463     return;
464   }
465   ExprSetProperty(p, EP_Dequoted);
466   if( p->token.dyn==0 ){
467     sqlite3TokenCopy(db, &p->token, &p->token);
468   }
469   sqlite3Dequote((char*)p->token.z);
470 }
471 
472 
473 /*
474 ** The following group of routines make deep copies of expressions,
475 ** expression lists, ID lists, and select statements.  The copies can
476 ** be deleted (by being passed to their respective ...Delete() routines)
477 ** without effecting the originals.
478 **
479 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
480 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
481 ** by subsequent calls to sqlite*ListAppend() routines.
482 **
483 ** Any tables that the SrcList might point to are not duplicated.
484 */
485 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
486   Expr *pNew;
487   if( p==0 ) return 0;
488   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
489   if( pNew==0 ) return 0;
490   memcpy(pNew, p, sizeof(*pNew));
491   if( p->token.z!=0 ){
492     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
493     pNew->token.dyn = 1;
494   }else{
495     assert( pNew->token.z==0 );
496   }
497   pNew->span.z = 0;
498   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
499   pNew->pRight = sqlite3ExprDup(db, p->pRight);
500   pNew->pList = sqlite3ExprListDup(db, p->pList);
501   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
502   return pNew;
503 }
504 void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
505   if( pTo->dyn ) sqlite3_free((char*)pTo->z);
506   if( pFrom->z ){
507     pTo->n = pFrom->n;
508     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
509     pTo->dyn = 1;
510   }else{
511     pTo->z = 0;
512   }
513 }
514 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
515   ExprList *pNew;
516   struct ExprList_item *pItem, *pOldItem;
517   int i;
518   if( p==0 ) return 0;
519   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
520   if( pNew==0 ) return 0;
521   pNew->iECursor = 0;
522   pNew->nExpr = pNew->nAlloc = p->nExpr;
523   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
524   if( pItem==0 ){
525     sqlite3_free(pNew);
526     return 0;
527   }
528   pOldItem = p->a;
529   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
530     Expr *pNewExpr, *pOldExpr;
531     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
532     if( pOldExpr->span.z!=0 && pNewExpr ){
533       /* Always make a copy of the span for top-level expressions in the
534       ** expression list.  The logic in SELECT processing that determines
535       ** the names of columns in the result set needs this information */
536       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
537     }
538     assert( pNewExpr==0 || pNewExpr->span.z!=0
539             || pOldExpr->span.z==0
540             || db->mallocFailed );
541     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
542     pItem->sortOrder = pOldItem->sortOrder;
543     pItem->isAgg = pOldItem->isAgg;
544     pItem->done = 0;
545   }
546   return pNew;
547 }
548 
549 /*
550 ** If cursors, triggers, views and subqueries are all omitted from
551 ** the build, then none of the following routines, except for
552 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
553 ** called with a NULL argument.
554 */
555 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
556  || !defined(SQLITE_OMIT_SUBQUERY)
557 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
558   SrcList *pNew;
559   int i;
560   int nByte;
561   if( p==0 ) return 0;
562   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
563   pNew = sqlite3DbMallocRaw(db, nByte );
564   if( pNew==0 ) return 0;
565   pNew->nSrc = pNew->nAlloc = p->nSrc;
566   for(i=0; i<p->nSrc; i++){
567     struct SrcList_item *pNewItem = &pNew->a[i];
568     struct SrcList_item *pOldItem = &p->a[i];
569     Table *pTab;
570     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
571     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
572     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
573     pNewItem->jointype = pOldItem->jointype;
574     pNewItem->iCursor = pOldItem->iCursor;
575     pNewItem->isPopulated = pOldItem->isPopulated;
576     pTab = pNewItem->pTab = pOldItem->pTab;
577     if( pTab ){
578       pTab->nRef++;
579     }
580     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
581     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
582     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
583     pNewItem->colUsed = pOldItem->colUsed;
584   }
585   return pNew;
586 }
587 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
588   IdList *pNew;
589   int i;
590   if( p==0 ) return 0;
591   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
592   if( pNew==0 ) return 0;
593   pNew->nId = pNew->nAlloc = p->nId;
594   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
595   if( pNew->a==0 ){
596     sqlite3_free(pNew);
597     return 0;
598   }
599   for(i=0; i<p->nId; i++){
600     struct IdList_item *pNewItem = &pNew->a[i];
601     struct IdList_item *pOldItem = &p->a[i];
602     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
603     pNewItem->idx = pOldItem->idx;
604   }
605   return pNew;
606 }
607 Select *sqlite3SelectDup(sqlite3 *db, Select *p){
608   Select *pNew;
609   if( p==0 ) return 0;
610   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
611   if( pNew==0 ) return 0;
612   pNew->isDistinct = p->isDistinct;
613   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
614   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
615   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
616   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
617   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
618   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
619   pNew->op = p->op;
620   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
621   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
622   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
623   pNew->iLimit = -1;
624   pNew->iOffset = -1;
625   pNew->isResolved = p->isResolved;
626   pNew->isAgg = p->isAgg;
627   pNew->usesEphm = 0;
628   pNew->disallowOrderBy = 0;
629   pNew->pRightmost = 0;
630   pNew->addrOpenEphm[0] = -1;
631   pNew->addrOpenEphm[1] = -1;
632   pNew->addrOpenEphm[2] = -1;
633   return pNew;
634 }
635 #else
636 Select *sqlite3SelectDup(sqlite3 *db, Select *p){
637   assert( p==0 );
638   return 0;
639 }
640 #endif
641 
642 
643 /*
644 ** Add a new element to the end of an expression list.  If pList is
645 ** initially NULL, then create a new expression list.
646 */
647 ExprList *sqlite3ExprListAppend(
648   Parse *pParse,          /* Parsing context */
649   ExprList *pList,        /* List to which to append. Might be NULL */
650   Expr *pExpr,            /* Expression to be appended */
651   Token *pName            /* AS keyword for the expression */
652 ){
653   sqlite3 *db = pParse->db;
654   if( pList==0 ){
655     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
656     if( pList==0 ){
657       goto no_mem;
658     }
659     assert( pList->nAlloc==0 );
660   }
661   if( pList->nAlloc<=pList->nExpr ){
662     struct ExprList_item *a;
663     int n = pList->nAlloc*2 + 4;
664     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
665     if( a==0 ){
666       goto no_mem;
667     }
668     pList->a = a;
669     pList->nAlloc = n;
670   }
671   assert( pList->a!=0 );
672   if( pExpr || pName ){
673     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
674     memset(pItem, 0, sizeof(*pItem));
675     pItem->zName = sqlite3NameFromToken(db, pName);
676     pItem->pExpr = pExpr;
677   }
678   return pList;
679 
680 no_mem:
681   /* Avoid leaking memory if malloc has failed. */
682   sqlite3ExprDelete(pExpr);
683   sqlite3ExprListDelete(pList);
684   return 0;
685 }
686 
687 /*
688 ** If the expression list pEList contains more than iLimit elements,
689 ** leave an error message in pParse.
690 */
691 void sqlite3ExprListCheckLength(
692   Parse *pParse,
693   ExprList *pEList,
694   int iLimit,
695   const char *zObject
696 ){
697   if( pEList && pEList->nExpr>iLimit ){
698     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
699   }
700 }
701 
702 
703 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
704 /* The following three functions, heightOfExpr(), heightOfExprList()
705 ** and heightOfSelect(), are used to determine the maximum height
706 ** of any expression tree referenced by the structure passed as the
707 ** first argument.
708 **
709 ** If this maximum height is greater than the current value pointed
710 ** to by pnHeight, the second parameter, then set *pnHeight to that
711 ** value.
712 */
713 static void heightOfExpr(Expr *p, int *pnHeight){
714   if( p ){
715     if( p->nHeight>*pnHeight ){
716       *pnHeight = p->nHeight;
717     }
718   }
719 }
720 static void heightOfExprList(ExprList *p, int *pnHeight){
721   if( p ){
722     int i;
723     for(i=0; i<p->nExpr; i++){
724       heightOfExpr(p->a[i].pExpr, pnHeight);
725     }
726   }
727 }
728 static void heightOfSelect(Select *p, int *pnHeight){
729   if( p ){
730     heightOfExpr(p->pWhere, pnHeight);
731     heightOfExpr(p->pHaving, pnHeight);
732     heightOfExpr(p->pLimit, pnHeight);
733     heightOfExpr(p->pOffset, pnHeight);
734     heightOfExprList(p->pEList, pnHeight);
735     heightOfExprList(p->pGroupBy, pnHeight);
736     heightOfExprList(p->pOrderBy, pnHeight);
737     heightOfSelect(p->pPrior, pnHeight);
738   }
739 }
740 
741 /*
742 ** Set the Expr.nHeight variable in the structure passed as an
743 ** argument. An expression with no children, Expr.pList or
744 ** Expr.pSelect member has a height of 1. Any other expression
745 ** has a height equal to the maximum height of any other
746 ** referenced Expr plus one.
747 */
748 void sqlite3ExprSetHeight(Expr *p){
749   int nHeight = 0;
750   heightOfExpr(p->pLeft, &nHeight);
751   heightOfExpr(p->pRight, &nHeight);
752   heightOfExprList(p->pList, &nHeight);
753   heightOfSelect(p->pSelect, &nHeight);
754   p->nHeight = nHeight + 1;
755 }
756 
757 /*
758 ** Return the maximum height of any expression tree referenced
759 ** by the select statement passed as an argument.
760 */
761 int sqlite3SelectExprHeight(Select *p){
762   int nHeight = 0;
763   heightOfSelect(p, &nHeight);
764   return nHeight;
765 }
766 #endif
767 
768 /*
769 ** Delete an entire expression list.
770 */
771 void sqlite3ExprListDelete(ExprList *pList){
772   int i;
773   struct ExprList_item *pItem;
774   if( pList==0 ) return;
775   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
776   assert( pList->nExpr<=pList->nAlloc );
777   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
778     sqlite3ExprDelete(pItem->pExpr);
779     sqlite3_free(pItem->zName);
780   }
781   sqlite3_free(pList->a);
782   sqlite3_free(pList);
783 }
784 
785 /*
786 ** Walk an expression tree.  Call xFunc for each node visited.
787 **
788 ** The return value from xFunc determines whether the tree walk continues.
789 ** 0 means continue walking the tree.  1 means do not walk children
790 ** of the current node but continue with siblings.  2 means abandon
791 ** the tree walk completely.
792 **
793 ** The return value from this routine is 1 to abandon the tree walk
794 ** and 0 to continue.
795 **
796 ** NOTICE:  This routine does *not* descend into subqueries.
797 */
798 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
799 static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
800   int rc;
801   if( pExpr==0 ) return 0;
802   rc = (*xFunc)(pArg, pExpr);
803   if( rc==0 ){
804     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
805     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
806     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
807   }
808   return rc>1;
809 }
810 
811 /*
812 ** Call walkExprTree() for every expression in list p.
813 */
814 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
815   int i;
816   struct ExprList_item *pItem;
817   if( !p ) return 0;
818   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
819     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
820   }
821   return 0;
822 }
823 
824 /*
825 ** Call walkExprTree() for every expression in Select p, not including
826 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
827 ** or OFFSET expressions..
828 */
829 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
830   walkExprList(p->pEList, xFunc, pArg);
831   walkExprTree(p->pWhere, xFunc, pArg);
832   walkExprList(p->pGroupBy, xFunc, pArg);
833   walkExprTree(p->pHaving, xFunc, pArg);
834   walkExprList(p->pOrderBy, xFunc, pArg);
835   if( p->pPrior ){
836     walkSelectExpr(p->pPrior, xFunc, pArg);
837   }
838   return 0;
839 }
840 
841 
842 /*
843 ** This routine is designed as an xFunc for walkExprTree().
844 **
845 ** pArg is really a pointer to an integer.  If we can tell by looking
846 ** at pExpr that the expression that contains pExpr is not a constant
847 ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
848 ** If pExpr does does not disqualify the expression from being a constant
849 ** then do nothing.
850 **
851 ** After walking the whole tree, if no nodes are found that disqualify
852 ** the expression as constant, then we assume the whole expression
853 ** is constant.  See sqlite3ExprIsConstant() for additional information.
854 */
855 static int exprNodeIsConstant(void *pArg, Expr *pExpr){
856   int *pN = (int*)pArg;
857 
858   /* If *pArg is 3 then any term of the expression that comes from
859   ** the ON or USING clauses of a join disqualifies the expression
860   ** from being considered constant. */
861   if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
862     *pN = 0;
863     return 2;
864   }
865 
866   switch( pExpr->op ){
867     /* Consider functions to be constant if all their arguments are constant
868     ** and *pArg==2 */
869     case TK_FUNCTION:
870       if( (*pN)==2 ) return 0;
871       /* Fall through */
872     case TK_ID:
873     case TK_COLUMN:
874     case TK_DOT:
875     case TK_AGG_FUNCTION:
876     case TK_AGG_COLUMN:
877 #ifndef SQLITE_OMIT_SUBQUERY
878     case TK_SELECT:
879     case TK_EXISTS:
880 #endif
881       *pN = 0;
882       return 2;
883     case TK_IN:
884       if( pExpr->pSelect ){
885         *pN = 0;
886         return 2;
887       }
888     default:
889       return 0;
890   }
891 }
892 
893 /*
894 ** Walk an expression tree.  Return 1 if the expression is constant
895 ** and 0 if it involves variables or function calls.
896 **
897 ** For the purposes of this function, a double-quoted string (ex: "abc")
898 ** is considered a variable but a single-quoted string (ex: 'abc') is
899 ** a constant.
900 */
901 int sqlite3ExprIsConstant(Expr *p){
902   int isConst = 1;
903   walkExprTree(p, exprNodeIsConstant, &isConst);
904   return isConst;
905 }
906 
907 /*
908 ** Walk an expression tree.  Return 1 if the expression is constant
909 ** that does no originate from the ON or USING clauses of a join.
910 ** Return 0 if it involves variables or function calls or terms from
911 ** an ON or USING clause.
912 */
913 int sqlite3ExprIsConstantNotJoin(Expr *p){
914   int isConst = 3;
915   walkExprTree(p, exprNodeIsConstant, &isConst);
916   return isConst!=0;
917 }
918 
919 /*
920 ** Walk an expression tree.  Return 1 if the expression is constant
921 ** or a function call with constant arguments.  Return and 0 if there
922 ** are any variables.
923 **
924 ** For the purposes of this function, a double-quoted string (ex: "abc")
925 ** is considered a variable but a single-quoted string (ex: 'abc') is
926 ** a constant.
927 */
928 int sqlite3ExprIsConstantOrFunction(Expr *p){
929   int isConst = 2;
930   walkExprTree(p, exprNodeIsConstant, &isConst);
931   return isConst!=0;
932 }
933 
934 /*
935 ** If the expression p codes a constant integer that is small enough
936 ** to fit in a 32-bit integer, return 1 and put the value of the integer
937 ** in *pValue.  If the expression is not an integer or if it is too big
938 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
939 */
940 int sqlite3ExprIsInteger(Expr *p, int *pValue){
941   switch( p->op ){
942     case TK_INTEGER: {
943       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
944         return 1;
945       }
946       break;
947     }
948     case TK_UPLUS: {
949       return sqlite3ExprIsInteger(p->pLeft, pValue);
950     }
951     case TK_UMINUS: {
952       int v;
953       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
954         *pValue = -v;
955         return 1;
956       }
957       break;
958     }
959     default: break;
960   }
961   return 0;
962 }
963 
964 /*
965 ** Return TRUE if the given string is a row-id column name.
966 */
967 int sqlite3IsRowid(const char *z){
968   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
969   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
970   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
971   return 0;
972 }
973 
974 /*
975 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
976 ** that name in the set of source tables in pSrcList and make the pExpr
977 ** expression node refer back to that source column.  The following changes
978 ** are made to pExpr:
979 **
980 **    pExpr->iDb           Set the index in db->aDb[] of the database holding
981 **                         the table.
982 **    pExpr->iTable        Set to the cursor number for the table obtained
983 **                         from pSrcList.
984 **    pExpr->iColumn       Set to the column number within the table.
985 **    pExpr->op            Set to TK_COLUMN.
986 **    pExpr->pLeft         Any expression this points to is deleted
987 **    pExpr->pRight        Any expression this points to is deleted.
988 **
989 ** The pDbToken is the name of the database (the "X").  This value may be
990 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
991 ** can be used.  The pTableToken is the name of the table (the "Y").  This
992 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
993 ** means that the form of the name is Z and that columns from any table
994 ** can be used.
995 **
996 ** If the name cannot be resolved unambiguously, leave an error message
997 ** in pParse and return non-zero.  Return zero on success.
998 */
999 static int lookupName(
1000   Parse *pParse,       /* The parsing context */
1001   Token *pDbToken,     /* Name of the database containing table, or NULL */
1002   Token *pTableToken,  /* Name of table containing column, or NULL */
1003   Token *pColumnToken, /* Name of the column. */
1004   NameContext *pNC,    /* The name context used to resolve the name */
1005   Expr *pExpr          /* Make this EXPR node point to the selected column */
1006 ){
1007   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
1008   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
1009   char *zCol = 0;      /* Name of the column.  The "Z" */
1010   int i, j;            /* Loop counters */
1011   int cnt = 0;         /* Number of matching column names */
1012   int cntTab = 0;      /* Number of matching table names */
1013   sqlite3 *db = pParse->db;  /* The database */
1014   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
1015   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
1016   NameContext *pTopNC = pNC;        /* First namecontext in the list */
1017 
1018   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
1019   zDb = sqlite3NameFromToken(db, pDbToken);
1020   zTab = sqlite3NameFromToken(db, pTableToken);
1021   zCol = sqlite3NameFromToken(db, pColumnToken);
1022   if( db->mallocFailed ){
1023     goto lookupname_end;
1024   }
1025 
1026   pExpr->iTable = -1;
1027   while( pNC && cnt==0 ){
1028     ExprList *pEList;
1029     SrcList *pSrcList = pNC->pSrcList;
1030 
1031     if( pSrcList ){
1032       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
1033         Table *pTab;
1034         int iDb;
1035         Column *pCol;
1036 
1037         pTab = pItem->pTab;
1038         assert( pTab!=0 );
1039         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1040         assert( pTab->nCol>0 );
1041         if( zTab ){
1042           if( pItem->zAlias ){
1043             char *zTabName = pItem->zAlias;
1044             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1045           }else{
1046             char *zTabName = pTab->zName;
1047             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1048             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
1049               continue;
1050             }
1051           }
1052         }
1053         if( 0==(cntTab++) ){
1054           pExpr->iTable = pItem->iCursor;
1055           pExpr->pSchema = pTab->pSchema;
1056           pMatch = pItem;
1057         }
1058         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
1059           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1060             const char *zColl = pTab->aCol[j].zColl;
1061             IdList *pUsing;
1062             cnt++;
1063             pExpr->iTable = pItem->iCursor;
1064             pMatch = pItem;
1065             pExpr->pSchema = pTab->pSchema;
1066             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
1067             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
1068             pExpr->affinity = pTab->aCol[j].affinity;
1069             if( (pExpr->flags & EP_ExpCollate)==0 ){
1070               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
1071             }
1072             if( i<pSrcList->nSrc-1 ){
1073               if( pItem[1].jointype & JT_NATURAL ){
1074                 /* If this match occurred in the left table of a natural join,
1075                 ** then skip the right table to avoid a duplicate match */
1076                 pItem++;
1077                 i++;
1078               }else if( (pUsing = pItem[1].pUsing)!=0 ){
1079                 /* If this match occurs on a column that is in the USING clause
1080                 ** of a join, skip the search of the right table of the join
1081                 ** to avoid a duplicate match there. */
1082                 int k;
1083                 for(k=0; k<pUsing->nId; k++){
1084                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
1085                     pItem++;
1086                     i++;
1087                     break;
1088                   }
1089                 }
1090               }
1091             }
1092             break;
1093           }
1094         }
1095       }
1096     }
1097 
1098 #ifndef SQLITE_OMIT_TRIGGER
1099     /* If we have not already resolved the name, then maybe
1100     ** it is a new.* or old.* trigger argument reference
1101     */
1102     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
1103       TriggerStack *pTriggerStack = pParse->trigStack;
1104       Table *pTab = 0;
1105       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
1106         pExpr->iTable = pTriggerStack->newIdx;
1107         assert( pTriggerStack->pTab );
1108         pTab = pTriggerStack->pTab;
1109       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
1110         pExpr->iTable = pTriggerStack->oldIdx;
1111         assert( pTriggerStack->pTab );
1112         pTab = pTriggerStack->pTab;
1113       }
1114 
1115       if( pTab ){
1116         int iCol;
1117         Column *pCol = pTab->aCol;
1118 
1119         pExpr->pSchema = pTab->pSchema;
1120         cntTab++;
1121         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
1122           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1123             const char *zColl = pTab->aCol[iCol].zColl;
1124             cnt++;
1125             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1126             pExpr->affinity = pTab->aCol[iCol].affinity;
1127             if( (pExpr->flags & EP_ExpCollate)==0 ){
1128               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
1129             }
1130             pExpr->pTab = pTab;
1131             break;
1132           }
1133         }
1134       }
1135     }
1136 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1137 
1138     /*
1139     ** Perhaps the name is a reference to the ROWID
1140     */
1141     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
1142       cnt = 1;
1143       pExpr->iColumn = -1;
1144       pExpr->affinity = SQLITE_AFF_INTEGER;
1145     }
1146 
1147     /*
1148     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
1149     ** might refer to an result-set alias.  This happens, for example, when
1150     ** we are resolving names in the WHERE clause of the following command:
1151     **
1152     **     SELECT a+b AS x FROM table WHERE x<10;
1153     **
1154     ** In cases like this, replace pExpr with a copy of the expression that
1155     ** forms the result set entry ("a+b" in the example) and return immediately.
1156     ** Note that the expression in the result set should have already been
1157     ** resolved by the time the WHERE clause is resolved.
1158     */
1159     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
1160       for(j=0; j<pEList->nExpr; j++){
1161         char *zAs = pEList->a[j].zName;
1162         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
1163           Expr *pDup, *pOrig;
1164           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
1165           assert( pExpr->pList==0 );
1166           assert( pExpr->pSelect==0 );
1167           pOrig = pEList->a[j].pExpr;
1168           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
1169             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
1170             sqlite3_free(zCol);
1171             return 2;
1172           }
1173           pDup = sqlite3ExprDup(db, pOrig);
1174           if( pExpr->flags & EP_ExpCollate ){
1175             pDup->pColl = pExpr->pColl;
1176             pDup->flags |= EP_ExpCollate;
1177           }
1178           if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z);
1179           if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z);
1180           memcpy(pExpr, pDup, sizeof(*pExpr));
1181           sqlite3_free(pDup);
1182           cnt = 1;
1183           pMatch = 0;
1184           assert( zTab==0 && zDb==0 );
1185           goto lookupname_end_2;
1186         }
1187       }
1188     }
1189 
1190     /* Advance to the next name context.  The loop will exit when either
1191     ** we have a match (cnt>0) or when we run out of name contexts.
1192     */
1193     if( cnt==0 ){
1194       pNC = pNC->pNext;
1195     }
1196   }
1197 
1198   /*
1199   ** If X and Y are NULL (in other words if only the column name Z is
1200   ** supplied) and the value of Z is enclosed in double-quotes, then
1201   ** Z is a string literal if it doesn't match any column names.  In that
1202   ** case, we need to return right away and not make any changes to
1203   ** pExpr.
1204   **
1205   ** Because no reference was made to outer contexts, the pNC->nRef
1206   ** fields are not changed in any context.
1207   */
1208   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
1209     sqlite3_free(zCol);
1210     return 0;
1211   }
1212 
1213   /*
1214   ** cnt==0 means there was not match.  cnt>1 means there were two or
1215   ** more matches.  Either way, we have an error.
1216   */
1217   if( cnt!=1 ){
1218     char *z = 0;
1219     char *zErr;
1220     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
1221     if( zDb ){
1222       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
1223     }else if( zTab ){
1224       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
1225     }else{
1226       z = sqlite3StrDup(zCol);
1227     }
1228     if( z ){
1229       sqlite3ErrorMsg(pParse, zErr, z);
1230       sqlite3_free(z);
1231       pTopNC->nErr++;
1232     }else{
1233       db->mallocFailed = 1;
1234     }
1235   }
1236 
1237   /* If a column from a table in pSrcList is referenced, then record
1238   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
1239   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
1240   ** column number is greater than the number of bits in the bitmask
1241   ** then set the high-order bit of the bitmask.
1242   */
1243   if( pExpr->iColumn>=0 && pMatch!=0 ){
1244     int n = pExpr->iColumn;
1245     if( n>=sizeof(Bitmask)*8 ){
1246       n = sizeof(Bitmask)*8-1;
1247     }
1248     assert( pMatch->iCursor==pExpr->iTable );
1249     pMatch->colUsed |= ((Bitmask)1)<<n;
1250   }
1251 
1252 lookupname_end:
1253   /* Clean up and return
1254   */
1255   sqlite3_free(zDb);
1256   sqlite3_free(zTab);
1257   sqlite3ExprDelete(pExpr->pLeft);
1258   pExpr->pLeft = 0;
1259   sqlite3ExprDelete(pExpr->pRight);
1260   pExpr->pRight = 0;
1261   pExpr->op = TK_COLUMN;
1262 lookupname_end_2:
1263   sqlite3_free(zCol);
1264   if( cnt==1 ){
1265     assert( pNC!=0 );
1266     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1267     if( pMatch && !pMatch->pSelect ){
1268       pExpr->pTab = pMatch->pTab;
1269     }
1270     /* Increment the nRef value on all name contexts from TopNC up to
1271     ** the point where the name matched. */
1272     for(;;){
1273       assert( pTopNC!=0 );
1274       pTopNC->nRef++;
1275       if( pTopNC==pNC ) break;
1276       pTopNC = pTopNC->pNext;
1277     }
1278     return 0;
1279   } else {
1280     return 1;
1281   }
1282 }
1283 
1284 /*
1285 ** This routine is designed as an xFunc for walkExprTree().
1286 **
1287 ** Resolve symbolic names into TK_COLUMN operators for the current
1288 ** node in the expression tree.  Return 0 to continue the search down
1289 ** the tree or 2 to abort the tree walk.
1290 **
1291 ** This routine also does error checking and name resolution for
1292 ** function names.  The operator for aggregate functions is changed
1293 ** to TK_AGG_FUNCTION.
1294 */
1295 static int nameResolverStep(void *pArg, Expr *pExpr){
1296   NameContext *pNC = (NameContext*)pArg;
1297   Parse *pParse;
1298 
1299   if( pExpr==0 ) return 1;
1300   assert( pNC!=0 );
1301   pParse = pNC->pParse;
1302 
1303   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1304   ExprSetProperty(pExpr, EP_Resolved);
1305 #ifndef NDEBUG
1306   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1307     SrcList *pSrcList = pNC->pSrcList;
1308     int i;
1309     for(i=0; i<pNC->pSrcList->nSrc; i++){
1310       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1311     }
1312   }
1313 #endif
1314   switch( pExpr->op ){
1315     /* Double-quoted strings (ex: "abc") are used as identifiers if
1316     ** possible.  Otherwise they remain as strings.  Single-quoted
1317     ** strings (ex: 'abc') are always string literals.
1318     */
1319     case TK_STRING: {
1320       if( pExpr->token.z[0]=='\'' ) break;
1321       /* Fall thru into the TK_ID case if this is a double-quoted string */
1322     }
1323     /* A lone identifier is the name of a column.
1324     */
1325     case TK_ID: {
1326       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1327       return 1;
1328     }
1329 
1330     /* A table name and column name:     ID.ID
1331     ** Or a database, table and column:  ID.ID.ID
1332     */
1333     case TK_DOT: {
1334       Token *pColumn;
1335       Token *pTable;
1336       Token *pDb;
1337       Expr *pRight;
1338 
1339       /* if( pSrcList==0 ) break; */
1340       pRight = pExpr->pRight;
1341       if( pRight->op==TK_ID ){
1342         pDb = 0;
1343         pTable = &pExpr->pLeft->token;
1344         pColumn = &pRight->token;
1345       }else{
1346         assert( pRight->op==TK_DOT );
1347         pDb = &pExpr->pLeft->token;
1348         pTable = &pRight->pLeft->token;
1349         pColumn = &pRight->pRight->token;
1350       }
1351       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1352       return 1;
1353     }
1354 
1355     /* Resolve function names
1356     */
1357     case TK_CONST_FUNC:
1358     case TK_FUNCTION: {
1359       ExprList *pList = pExpr->pList;    /* The argument list */
1360       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1361       int no_such_func = 0;       /* True if no such function exists */
1362       int wrong_num_args = 0;     /* True if wrong number of arguments */
1363       int is_agg = 0;             /* True if is an aggregate function */
1364       int i;
1365       int auth;                   /* Authorization to use the function */
1366       int nId;                    /* Number of characters in function name */
1367       const char *zId;            /* The function name. */
1368       FuncDef *pDef;              /* Information about the function */
1369       int enc = ENC(pParse->db);  /* The database encoding */
1370 
1371       zId = (char*)pExpr->token.z;
1372       nId = pExpr->token.n;
1373       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1374       if( pDef==0 ){
1375         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1376         if( pDef==0 ){
1377           no_such_func = 1;
1378         }else{
1379           wrong_num_args = 1;
1380         }
1381       }else{
1382         is_agg = pDef->xFunc==0;
1383       }
1384 #ifndef SQLITE_OMIT_AUTHORIZATION
1385       if( pDef ){
1386         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
1387         if( auth!=SQLITE_OK ){
1388           if( auth==SQLITE_DENY ){
1389             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
1390                                     pDef->zName);
1391             pNC->nErr++;
1392           }
1393           pExpr->op = TK_NULL;
1394           return 1;
1395         }
1396       }
1397 #endif
1398       if( is_agg && !pNC->allowAgg ){
1399         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1400         pNC->nErr++;
1401         is_agg = 0;
1402       }else if( no_such_func ){
1403         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1404         pNC->nErr++;
1405       }else if( wrong_num_args ){
1406         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1407              nId, zId);
1408         pNC->nErr++;
1409       }
1410       if( is_agg ){
1411         pExpr->op = TK_AGG_FUNCTION;
1412         pNC->hasAgg = 1;
1413       }
1414       if( is_agg ) pNC->allowAgg = 0;
1415       for(i=0; pNC->nErr==0 && i<n; i++){
1416         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1417       }
1418       if( is_agg ) pNC->allowAgg = 1;
1419       /* FIX ME:  Compute pExpr->affinity based on the expected return
1420       ** type of the function
1421       */
1422       return is_agg;
1423     }
1424 #ifndef SQLITE_OMIT_SUBQUERY
1425     case TK_SELECT:
1426     case TK_EXISTS:
1427 #endif
1428     case TK_IN: {
1429       if( pExpr->pSelect ){
1430         int nRef = pNC->nRef;
1431 #ifndef SQLITE_OMIT_CHECK
1432         if( pNC->isCheck ){
1433           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
1434         }
1435 #endif
1436         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1437         assert( pNC->nRef>=nRef );
1438         if( nRef!=pNC->nRef ){
1439           ExprSetProperty(pExpr, EP_VarSelect);
1440         }
1441       }
1442       break;
1443     }
1444 #ifndef SQLITE_OMIT_CHECK
1445     case TK_VARIABLE: {
1446       if( pNC->isCheck ){
1447         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
1448       }
1449       break;
1450     }
1451 #endif
1452   }
1453   return 0;
1454 }
1455 
1456 /*
1457 ** This routine walks an expression tree and resolves references to
1458 ** table columns.  Nodes of the form ID.ID or ID resolve into an
1459 ** index to the table in the table list and a column offset.  The
1460 ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1461 ** value is changed to the index of the referenced table in pTabList
1462 ** plus the "base" value.  The base value will ultimately become the
1463 ** VDBE cursor number for a cursor that is pointing into the referenced
1464 ** table.  The Expr.iColumn value is changed to the index of the column
1465 ** of the referenced table.  The Expr.iColumn value for the special
1466 ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1467 ** alias for ROWID.
1468 **
1469 ** Also resolve function names and check the functions for proper
1470 ** usage.  Make sure all function names are recognized and all functions
1471 ** have the correct number of arguments.  Leave an error message
1472 ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1473 **
1474 ** If the expression contains aggregate functions then set the EP_Agg
1475 ** property on the expression.
1476 */
1477 int sqlite3ExprResolveNames(
1478   NameContext *pNC,       /* Namespace to resolve expressions in. */
1479   Expr *pExpr             /* The expression to be analyzed. */
1480 ){
1481   int savedHasAgg;
1482   if( pExpr==0 ) return 0;
1483 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
1484   if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
1485     sqlite3ErrorMsg(pNC->pParse,
1486        "Expression tree is too large (maximum depth %d)",
1487        SQLITE_MAX_EXPR_DEPTH
1488     );
1489     return 1;
1490   }
1491   pNC->pParse->nHeight += pExpr->nHeight;
1492 #endif
1493   savedHasAgg = pNC->hasAgg;
1494   pNC->hasAgg = 0;
1495   walkExprTree(pExpr, nameResolverStep, pNC);
1496 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
1497   pNC->pParse->nHeight -= pExpr->nHeight;
1498 #endif
1499   if( pNC->nErr>0 ){
1500     ExprSetProperty(pExpr, EP_Error);
1501   }
1502   if( pNC->hasAgg ){
1503     ExprSetProperty(pExpr, EP_Agg);
1504   }else if( savedHasAgg ){
1505     pNC->hasAgg = 1;
1506   }
1507   return ExprHasProperty(pExpr, EP_Error);
1508 }
1509 
1510 /*
1511 ** A pointer instance of this structure is used to pass information
1512 ** through walkExprTree into codeSubqueryStep().
1513 */
1514 typedef struct QueryCoder QueryCoder;
1515 struct QueryCoder {
1516   Parse *pParse;       /* The parsing context */
1517   NameContext *pNC;    /* Namespace of first enclosing query */
1518 };
1519 
1520 
1521 /*
1522 ** Generate code for scalar subqueries used as an expression
1523 ** and IN operators.  Examples:
1524 **
1525 **     (SELECT a FROM b)          -- subquery
1526 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
1527 **     x IN (4,5,11)              -- IN operator with list on right-hand side
1528 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1529 **
1530 ** The pExpr parameter describes the expression that contains the IN
1531 ** operator or subquery.
1532 */
1533 #ifndef SQLITE_OMIT_SUBQUERY
1534 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
1535   int testAddr = 0;                       /* One-time test address */
1536   Vdbe *v = sqlite3GetVdbe(pParse);
1537   if( v==0 ) return;
1538 
1539 
1540   /* This code must be run in its entirety every time it is encountered
1541   ** if any of the following is true:
1542   **
1543   **    *  The right-hand side is a correlated subquery
1544   **    *  The right-hand side is an expression list containing variables
1545   **    *  We are inside a trigger
1546   **
1547   ** If all of the above are false, then we can run this code just once
1548   ** save the results, and reuse the same result on subsequent invocations.
1549   */
1550   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1551     int mem = pParse->nMem++;
1552     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
1553     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
1554     assert( testAddr>0 || pParse->db->mallocFailed );
1555     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1556   }
1557 
1558   switch( pExpr->op ){
1559     case TK_IN: {
1560       char affinity;
1561       KeyInfo keyInfo;
1562       int addr;        /* Address of OP_OpenEphemeral instruction */
1563 
1564       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1565 
1566       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1567       ** expression it is handled the same way. A virtual table is
1568       ** filled with single-field index keys representing the results
1569       ** from the SELECT or the <exprlist>.
1570       **
1571       ** If the 'x' expression is a column value, or the SELECT...
1572       ** statement returns a column value, then the affinity of that
1573       ** column is used to build the index keys. If both 'x' and the
1574       ** SELECT... statement are columns, then numeric affinity is used
1575       ** if either column has NUMERIC or INTEGER affinity. If neither
1576       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1577       ** is used.
1578       */
1579       pExpr->iTable = pParse->nTab++;
1580       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
1581       memset(&keyInfo, 0, sizeof(keyInfo));
1582       keyInfo.nField = 1;
1583       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1584 
1585       if( pExpr->pSelect ){
1586         /* Case 1:     expr IN (SELECT ...)
1587         **
1588         ** Generate code to write the results of the select into the temporary
1589         ** table allocated and opened above.
1590         */
1591         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1592         ExprList *pEList;
1593         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1594         if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
1595           return;
1596         }
1597         pEList = pExpr->pSelect->pEList;
1598         if( pEList && pEList->nExpr>0 ){
1599           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1600               pEList->a[0].pExpr);
1601         }
1602       }else if( pExpr->pList ){
1603         /* Case 2:     expr IN (exprlist)
1604         **
1605         ** For each expression, build an index key from the evaluation and
1606         ** store it in the temporary table. If <expr> is a column, then use
1607         ** that columns affinity when building index keys. If <expr> is not
1608         ** a column, use numeric affinity.
1609         */
1610         int i;
1611         ExprList *pList = pExpr->pList;
1612         struct ExprList_item *pItem;
1613 
1614         if( !affinity ){
1615           affinity = SQLITE_AFF_NONE;
1616         }
1617         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1618 
1619         /* Loop through each expression in <exprlist>. */
1620         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1621           Expr *pE2 = pItem->pExpr;
1622 
1623           /* If the expression is not constant then we will need to
1624           ** disable the test that was generated above that makes sure
1625           ** this code only executes once.  Because for a non-constant
1626           ** expression we need to rerun this code each time.
1627           */
1628           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
1629             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
1630             testAddr = 0;
1631           }
1632 
1633           /* Evaluate the expression and insert it into the temp table */
1634           sqlite3ExprCode(pParse, pE2);
1635           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1636           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1637         }
1638       }
1639       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1640       break;
1641     }
1642 
1643     case TK_EXISTS:
1644     case TK_SELECT: {
1645       /* This has to be a scalar SELECT.  Generate code to put the
1646       ** value of this select in a memory cell and record the number
1647       ** of the memory cell in iColumn.
1648       */
1649       static const Token one = { (u8*)"1", 0, 1 };
1650       Select *pSel;
1651       int iMem;
1652       int sop;
1653 
1654       pExpr->iColumn = iMem = pParse->nMem++;
1655       pSel = pExpr->pSelect;
1656       if( pExpr->op==TK_SELECT ){
1657         sop = SRT_Mem;
1658         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1659         VdbeComment((v, "# Init subquery result"));
1660       }else{
1661         sop = SRT_Exists;
1662         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1663         VdbeComment((v, "# Init EXISTS result"));
1664       }
1665       sqlite3ExprDelete(pSel->pLimit);
1666       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
1667       if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
1668         return;
1669       }
1670       break;
1671     }
1672   }
1673 
1674   if( testAddr ){
1675     sqlite3VdbeJumpHere(v, testAddr);
1676   }
1677 
1678   return;
1679 }
1680 #endif /* SQLITE_OMIT_SUBQUERY */
1681 
1682 /*
1683 ** Generate an instruction that will put the integer describe by
1684 ** text z[0..n-1] on the stack.
1685 */
1686 static void codeInteger(Vdbe *v, const char *z, int n){
1687   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
1688   if( z ){
1689     int i;
1690     if( sqlite3GetInt32(z, &i) ){
1691       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
1692     }else if( sqlite3FitsIn64Bits(z) ){
1693       sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1694     }else{
1695       sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1696     }
1697   }
1698 }
1699 
1700 
1701 /*
1702 ** Generate code that will extract the iColumn-th column from
1703 ** table pTab and push that column value on the stack.  There
1704 ** is an open cursor to pTab in iTable.  If iColumn<0 then
1705 ** code is generated that extracts the rowid.
1706 */
1707 void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
1708   if( iColumn<0 ){
1709     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
1710     sqlite3VdbeAddOp(v, op, iTable, 0);
1711   }else if( pTab==0 ){
1712     sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
1713   }else{
1714     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
1715     sqlite3VdbeAddOp(v, op, iTable, iColumn);
1716     sqlite3ColumnDefault(v, pTab, iColumn);
1717 #ifndef SQLITE_OMIT_FLOATING_POINT
1718     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
1719       sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
1720     }
1721 #endif
1722   }
1723 }
1724 
1725 /*
1726 ** Generate code into the current Vdbe to evaluate the given
1727 ** expression and leave the result on the top of stack.
1728 **
1729 ** This code depends on the fact that certain token values (ex: TK_EQ)
1730 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1731 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1732 ** the make process cause these values to align.  Assert()s in the code
1733 ** below verify that the numbers are aligned correctly.
1734 */
1735 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1736   Vdbe *v = pParse->pVdbe;
1737   int op;
1738   int stackChng = 1;    /* Amount of change to stack depth */
1739 
1740   if( v==0 ) return;
1741   if( pExpr==0 ){
1742     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1743     return;
1744   }
1745   op = pExpr->op;
1746   switch( op ){
1747     case TK_AGG_COLUMN: {
1748       AggInfo *pAggInfo = pExpr->pAggInfo;
1749       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
1750       if( !pAggInfo->directMode ){
1751         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
1752         break;
1753       }else if( pAggInfo->useSortingIdx ){
1754         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
1755                               pCol->iSorterColumn);
1756         break;
1757       }
1758       /* Otherwise, fall thru into the TK_COLUMN case */
1759     }
1760     case TK_COLUMN: {
1761       if( pExpr->iTable<0 ){
1762         /* This only happens when coding check constraints */
1763         assert( pParse->ckOffset>0 );
1764         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1765       }else{
1766         sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
1767       }
1768       break;
1769     }
1770     case TK_INTEGER: {
1771       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1772       break;
1773     }
1774     case TK_FLOAT:
1775     case TK_STRING: {
1776       assert( TK_FLOAT==OP_Real );
1777       assert( TK_STRING==OP_String8 );
1778       sqlite3DequoteExpr(pParse->db, pExpr);
1779       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1780       break;
1781     }
1782     case TK_NULL: {
1783       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1784       break;
1785     }
1786 #ifndef SQLITE_OMIT_BLOB_LITERAL
1787     case TK_BLOB: {
1788       int n;
1789       const char *z;
1790       assert( TK_BLOB==OP_HexBlob );
1791       n = pExpr->token.n - 3;
1792       z = (char*)pExpr->token.z + 2;
1793       assert( n>=0 );
1794       if( n==0 ){
1795         z = "";
1796       }
1797       sqlite3VdbeOp3(v, op, 0, 0, z, n);
1798       break;
1799     }
1800 #endif
1801     case TK_VARIABLE: {
1802       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1803       if( pExpr->token.n>1 ){
1804         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1805       }
1806       break;
1807     }
1808     case TK_REGISTER: {
1809       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
1810       break;
1811     }
1812 #ifndef SQLITE_OMIT_CAST
1813     case TK_CAST: {
1814       /* Expressions of the form:   CAST(pLeft AS token) */
1815       int aff, to_op;
1816       sqlite3ExprCode(pParse, pExpr->pLeft);
1817       aff = sqlite3AffinityType(&pExpr->token);
1818       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1819       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
1820       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
1821       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1822       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
1823       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
1824       sqlite3VdbeAddOp(v, to_op, 0, 0);
1825       stackChng = 0;
1826       break;
1827     }
1828 #endif /* SQLITE_OMIT_CAST */
1829     case TK_LT:
1830     case TK_LE:
1831     case TK_GT:
1832     case TK_GE:
1833     case TK_NE:
1834     case TK_EQ: {
1835       assert( TK_LT==OP_Lt );
1836       assert( TK_LE==OP_Le );
1837       assert( TK_GT==OP_Gt );
1838       assert( TK_GE==OP_Ge );
1839       assert( TK_EQ==OP_Eq );
1840       assert( TK_NE==OP_Ne );
1841       sqlite3ExprCode(pParse, pExpr->pLeft);
1842       sqlite3ExprCode(pParse, pExpr->pRight);
1843       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1844       stackChng = -1;
1845       break;
1846     }
1847     case TK_AND:
1848     case TK_OR:
1849     case TK_PLUS:
1850     case TK_STAR:
1851     case TK_MINUS:
1852     case TK_REM:
1853     case TK_BITAND:
1854     case TK_BITOR:
1855     case TK_SLASH:
1856     case TK_LSHIFT:
1857     case TK_RSHIFT:
1858     case TK_CONCAT: {
1859       assert( TK_AND==OP_And );
1860       assert( TK_OR==OP_Or );
1861       assert( TK_PLUS==OP_Add );
1862       assert( TK_MINUS==OP_Subtract );
1863       assert( TK_REM==OP_Remainder );
1864       assert( TK_BITAND==OP_BitAnd );
1865       assert( TK_BITOR==OP_BitOr );
1866       assert( TK_SLASH==OP_Divide );
1867       assert( TK_LSHIFT==OP_ShiftLeft );
1868       assert( TK_RSHIFT==OP_ShiftRight );
1869       assert( TK_CONCAT==OP_Concat );
1870       sqlite3ExprCode(pParse, pExpr->pLeft);
1871       sqlite3ExprCode(pParse, pExpr->pRight);
1872       sqlite3VdbeAddOp(v, op, 0, 0);
1873       stackChng = -1;
1874       break;
1875     }
1876     case TK_UMINUS: {
1877       Expr *pLeft = pExpr->pLeft;
1878       assert( pLeft );
1879       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1880         Token *p = &pLeft->token;
1881         char *z = sqlite3MPrintf(pParse->db, "-%.*s", p->n, p->z);
1882         if( pLeft->op==TK_FLOAT ){
1883           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1884         }else{
1885           codeInteger(v, z, p->n+1);
1886         }
1887         sqlite3_free(z);
1888         break;
1889       }
1890       /* Fall through into TK_NOT */
1891     }
1892     case TK_BITNOT:
1893     case TK_NOT: {
1894       assert( TK_BITNOT==OP_BitNot );
1895       assert( TK_NOT==OP_Not );
1896       sqlite3ExprCode(pParse, pExpr->pLeft);
1897       sqlite3VdbeAddOp(v, op, 0, 0);
1898       stackChng = 0;
1899       break;
1900     }
1901     case TK_ISNULL:
1902     case TK_NOTNULL: {
1903       int dest;
1904       assert( TK_ISNULL==OP_IsNull );
1905       assert( TK_NOTNULL==OP_NotNull );
1906       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1907       sqlite3ExprCode(pParse, pExpr->pLeft);
1908       dest = sqlite3VdbeCurrentAddr(v) + 2;
1909       sqlite3VdbeAddOp(v, op, 1, dest);
1910       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1911       stackChng = 0;
1912       break;
1913     }
1914     case TK_AGG_FUNCTION: {
1915       AggInfo *pInfo = pExpr->pAggInfo;
1916       if( pInfo==0 ){
1917         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
1918             &pExpr->span);
1919       }else{
1920         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
1921       }
1922       break;
1923     }
1924     case TK_CONST_FUNC:
1925     case TK_FUNCTION: {
1926       ExprList *pList = pExpr->pList;
1927       int nExpr = pList ? pList->nExpr : 0;
1928       FuncDef *pDef;
1929       int nId;
1930       const char *zId;
1931       int constMask = 0;
1932       int i;
1933       sqlite3 *db = pParse->db;
1934       u8 enc = ENC(db);
1935       CollSeq *pColl = 0;
1936 
1937       zId = (char*)pExpr->token.z;
1938       nId = pExpr->token.n;
1939       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
1940       assert( pDef!=0 );
1941       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1942 #ifndef SQLITE_OMIT_VIRTUALTABLE
1943       /* Possibly overload the function if the first argument is
1944       ** a virtual table column.
1945       **
1946       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1947       ** second argument, not the first, as the argument to test to
1948       ** see if it is a column in a virtual table.  This is done because
1949       ** the left operand of infix functions (the operand we want to
1950       ** control overloading) ends up as the second argument to the
1951       ** function.  The expression "A glob B" is equivalent to
1952       ** "glob(B,A).  We want to use the A in "A glob B" to test
1953       ** for function overloading.  But we use the B term in "glob(B,A)".
1954       */
1955       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
1956         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
1957       }else if( nExpr>0 ){
1958         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
1959       }
1960 #endif
1961       for(i=0; i<nExpr && i<32; i++){
1962         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
1963           constMask |= (1<<i);
1964         }
1965         if( pDef->needCollSeq && !pColl ){
1966           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1967         }
1968       }
1969       if( pDef->needCollSeq ){
1970         if( !pColl ) pColl = pParse->db->pDfltColl;
1971         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1972       }
1973       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1974       stackChng = 1-nExpr;
1975       break;
1976     }
1977 #ifndef SQLITE_OMIT_SUBQUERY
1978     case TK_EXISTS:
1979     case TK_SELECT: {
1980       if( pExpr->iColumn==0 ){
1981         sqlite3CodeSubselect(pParse, pExpr);
1982       }
1983       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1984       VdbeComment((v, "# load subquery result"));
1985       break;
1986     }
1987     case TK_IN: {
1988       int addr;
1989       char affinity;
1990       int ckOffset = pParse->ckOffset;
1991       sqlite3CodeSubselect(pParse, pExpr);
1992 
1993       /* Figure out the affinity to use to create a key from the results
1994       ** of the expression. affinityStr stores a static string suitable for
1995       ** P3 of OP_MakeRecord.
1996       */
1997       affinity = comparisonAffinity(pExpr);
1998 
1999       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
2000       pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
2001 
2002       /* Code the <expr> from "<expr> IN (...)". The temporary table
2003       ** pExpr->iTable contains the values that make up the (...) set.
2004       */
2005       sqlite3ExprCode(pParse, pExpr->pLeft);
2006       addr = sqlite3VdbeCurrentAddr(v);
2007       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
2008       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
2009       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
2010       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
2011       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
2012       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
2013       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
2014 
2015       break;
2016     }
2017 #endif
2018     case TK_BETWEEN: {
2019       Expr *pLeft = pExpr->pLeft;
2020       struct ExprList_item *pLItem = pExpr->pList->a;
2021       Expr *pRight = pLItem->pExpr;
2022       sqlite3ExprCode(pParse, pLeft);
2023       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2024       sqlite3ExprCode(pParse, pRight);
2025       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
2026       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
2027       pLItem++;
2028       pRight = pLItem->pExpr;
2029       sqlite3ExprCode(pParse, pRight);
2030       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
2031       sqlite3VdbeAddOp(v, OP_And, 0, 0);
2032       break;
2033     }
2034     case TK_UPLUS: {
2035       sqlite3ExprCode(pParse, pExpr->pLeft);
2036       stackChng = 0;
2037       break;
2038     }
2039     case TK_CASE: {
2040       int expr_end_label;
2041       int jumpInst;
2042       int nExpr;
2043       int i;
2044       ExprList *pEList;
2045       struct ExprList_item *aListelem;
2046 
2047       assert(pExpr->pList);
2048       assert((pExpr->pList->nExpr % 2) == 0);
2049       assert(pExpr->pList->nExpr > 0);
2050       pEList = pExpr->pList;
2051       aListelem = pEList->a;
2052       nExpr = pEList->nExpr;
2053       expr_end_label = sqlite3VdbeMakeLabel(v);
2054       if( pExpr->pLeft ){
2055         sqlite3ExprCode(pParse, pExpr->pLeft);
2056       }
2057       for(i=0; i<nExpr; i=i+2){
2058         sqlite3ExprCode(pParse, aListelem[i].pExpr);
2059         if( pExpr->pLeft ){
2060           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
2061           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
2062                                  OP_Ne, 0, 1);
2063           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2064         }else{
2065           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
2066         }
2067         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
2068         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
2069         sqlite3VdbeJumpHere(v, jumpInst);
2070       }
2071       if( pExpr->pLeft ){
2072         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2073       }
2074       if( pExpr->pRight ){
2075         sqlite3ExprCode(pParse, pExpr->pRight);
2076       }else{
2077         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
2078       }
2079       sqlite3VdbeResolveLabel(v, expr_end_label);
2080       break;
2081     }
2082 #ifndef SQLITE_OMIT_TRIGGER
2083     case TK_RAISE: {
2084       if( !pParse->trigStack ){
2085         sqlite3ErrorMsg(pParse,
2086                        "RAISE() may only be used within a trigger-program");
2087         return;
2088       }
2089       if( pExpr->iColumn!=OE_Ignore ){
2090          assert( pExpr->iColumn==OE_Rollback ||
2091                  pExpr->iColumn == OE_Abort ||
2092                  pExpr->iColumn == OE_Fail );
2093          sqlite3DequoteExpr(pParse->db, pExpr);
2094          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
2095                         (char*)pExpr->token.z, pExpr->token.n);
2096       } else {
2097          assert( pExpr->iColumn == OE_Ignore );
2098          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
2099          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
2100          VdbeComment((v, "# raise(IGNORE)"));
2101       }
2102       stackChng = 0;
2103       break;
2104     }
2105 #endif
2106   }
2107 
2108   if( pParse->ckOffset ){
2109     pParse->ckOffset += stackChng;
2110     assert( pParse->ckOffset );
2111   }
2112 }
2113 
2114 #ifndef SQLITE_OMIT_TRIGGER
2115 /*
2116 ** Generate code that evalutes the given expression and leaves the result
2117 ** on the stack.  See also sqlite3ExprCode().
2118 **
2119 ** This routine might also cache the result and modify the pExpr tree
2120 ** so that it will make use of the cached result on subsequent evaluations
2121 ** rather than evaluate the whole expression again.  Trivial expressions are
2122 ** not cached.  If the expression is cached, its result is stored in a
2123 ** memory location.
2124 */
2125 void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
2126   Vdbe *v = pParse->pVdbe;
2127   int iMem;
2128   int addr1, addr2;
2129   if( v==0 ) return;
2130   addr1 = sqlite3VdbeCurrentAddr(v);
2131   sqlite3ExprCode(pParse, pExpr);
2132   addr2 = sqlite3VdbeCurrentAddr(v);
2133   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
2134     iMem = pExpr->iTable = pParse->nMem++;
2135     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2136     pExpr->op = TK_REGISTER;
2137   }
2138 }
2139 #endif
2140 
2141 /*
2142 ** Generate code that pushes the value of every element of the given
2143 ** expression list onto the stack.
2144 **
2145 ** Return the number of elements pushed onto the stack.
2146 */
2147 int sqlite3ExprCodeExprList(
2148   Parse *pParse,     /* Parsing context */
2149   ExprList *pList    /* The expression list to be coded */
2150 ){
2151   struct ExprList_item *pItem;
2152   int i, n;
2153   if( pList==0 ) return 0;
2154   n = pList->nExpr;
2155   for(pItem=pList->a, i=n; i>0; i--, pItem++){
2156     sqlite3ExprCode(pParse, pItem->pExpr);
2157   }
2158   return n;
2159 }
2160 
2161 /*
2162 ** Generate code for a boolean expression such that a jump is made
2163 ** to the label "dest" if the expression is true but execution
2164 ** continues straight thru if the expression is false.
2165 **
2166 ** If the expression evaluates to NULL (neither true nor false), then
2167 ** take the jump if the jumpIfNull flag is true.
2168 **
2169 ** This code depends on the fact that certain token values (ex: TK_EQ)
2170 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2171 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
2172 ** the make process cause these values to align.  Assert()s in the code
2173 ** below verify that the numbers are aligned correctly.
2174 */
2175 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2176   Vdbe *v = pParse->pVdbe;
2177   int op = 0;
2178   int ckOffset = pParse->ckOffset;
2179   if( v==0 || pExpr==0 ) return;
2180   op = pExpr->op;
2181   switch( op ){
2182     case TK_AND: {
2183       int d2 = sqlite3VdbeMakeLabel(v);
2184       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
2185       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2186       sqlite3VdbeResolveLabel(v, d2);
2187       break;
2188     }
2189     case TK_OR: {
2190       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2191       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2192       break;
2193     }
2194     case TK_NOT: {
2195       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2196       break;
2197     }
2198     case TK_LT:
2199     case TK_LE:
2200     case TK_GT:
2201     case TK_GE:
2202     case TK_NE:
2203     case TK_EQ: {
2204       assert( TK_LT==OP_Lt );
2205       assert( TK_LE==OP_Le );
2206       assert( TK_GT==OP_Gt );
2207       assert( TK_GE==OP_Ge );
2208       assert( TK_EQ==OP_Eq );
2209       assert( TK_NE==OP_Ne );
2210       sqlite3ExprCode(pParse, pExpr->pLeft);
2211       sqlite3ExprCode(pParse, pExpr->pRight);
2212       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2213       break;
2214     }
2215     case TK_ISNULL:
2216     case TK_NOTNULL: {
2217       assert( TK_ISNULL==OP_IsNull );
2218       assert( TK_NOTNULL==OP_NotNull );
2219       sqlite3ExprCode(pParse, pExpr->pLeft);
2220       sqlite3VdbeAddOp(v, op, 1, dest);
2221       break;
2222     }
2223     case TK_BETWEEN: {
2224       /* The expression "x BETWEEN y AND z" is implemented as:
2225       **
2226       ** 1 IF (x < y) GOTO 3
2227       ** 2 IF (x <= z) GOTO <dest>
2228       ** 3 ...
2229       */
2230       int addr;
2231       Expr *pLeft = pExpr->pLeft;
2232       Expr *pRight = pExpr->pList->a[0].pExpr;
2233       sqlite3ExprCode(pParse, pLeft);
2234       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2235       sqlite3ExprCode(pParse, pRight);
2236       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
2237 
2238       pRight = pExpr->pList->a[1].pExpr;
2239       sqlite3ExprCode(pParse, pRight);
2240       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
2241 
2242       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2243       sqlite3VdbeJumpHere(v, addr);
2244       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2245       break;
2246     }
2247     default: {
2248       sqlite3ExprCode(pParse, pExpr);
2249       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
2250       break;
2251     }
2252   }
2253   pParse->ckOffset = ckOffset;
2254 }
2255 
2256 /*
2257 ** Generate code for a boolean expression such that a jump is made
2258 ** to the label "dest" if the expression is false but execution
2259 ** continues straight thru if the expression is true.
2260 **
2261 ** If the expression evaluates to NULL (neither true nor false) then
2262 ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
2263 */
2264 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2265   Vdbe *v = pParse->pVdbe;
2266   int op = 0;
2267   int ckOffset = pParse->ckOffset;
2268   if( v==0 || pExpr==0 ) return;
2269 
2270   /* The value of pExpr->op and op are related as follows:
2271   **
2272   **       pExpr->op            op
2273   **       ---------          ----------
2274   **       TK_ISNULL          OP_NotNull
2275   **       TK_NOTNULL         OP_IsNull
2276   **       TK_NE              OP_Eq
2277   **       TK_EQ              OP_Ne
2278   **       TK_GT              OP_Le
2279   **       TK_LE              OP_Gt
2280   **       TK_GE              OP_Lt
2281   **       TK_LT              OP_Ge
2282   **
2283   ** For other values of pExpr->op, op is undefined and unused.
2284   ** The value of TK_ and OP_ constants are arranged such that we
2285   ** can compute the mapping above using the following expression.
2286   ** Assert()s verify that the computation is correct.
2287   */
2288   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2289 
2290   /* Verify correct alignment of TK_ and OP_ constants
2291   */
2292   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2293   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2294   assert( pExpr->op!=TK_NE || op==OP_Eq );
2295   assert( pExpr->op!=TK_EQ || op==OP_Ne );
2296   assert( pExpr->op!=TK_LT || op==OP_Ge );
2297   assert( pExpr->op!=TK_LE || op==OP_Gt );
2298   assert( pExpr->op!=TK_GT || op==OP_Le );
2299   assert( pExpr->op!=TK_GE || op==OP_Lt );
2300 
2301   switch( pExpr->op ){
2302     case TK_AND: {
2303       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2304       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2305       break;
2306     }
2307     case TK_OR: {
2308       int d2 = sqlite3VdbeMakeLabel(v);
2309       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
2310       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2311       sqlite3VdbeResolveLabel(v, d2);
2312       break;
2313     }
2314     case TK_NOT: {
2315       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2316       break;
2317     }
2318     case TK_LT:
2319     case TK_LE:
2320     case TK_GT:
2321     case TK_GE:
2322     case TK_NE:
2323     case TK_EQ: {
2324       sqlite3ExprCode(pParse, pExpr->pLeft);
2325       sqlite3ExprCode(pParse, pExpr->pRight);
2326       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2327       break;
2328     }
2329     case TK_ISNULL:
2330     case TK_NOTNULL: {
2331       sqlite3ExprCode(pParse, pExpr->pLeft);
2332       sqlite3VdbeAddOp(v, op, 1, dest);
2333       break;
2334     }
2335     case TK_BETWEEN: {
2336       /* The expression is "x BETWEEN y AND z". It is implemented as:
2337       **
2338       ** 1 IF (x >= y) GOTO 3
2339       ** 2 GOTO <dest>
2340       ** 3 IF (x > z) GOTO <dest>
2341       */
2342       int addr;
2343       Expr *pLeft = pExpr->pLeft;
2344       Expr *pRight = pExpr->pList->a[0].pExpr;
2345       sqlite3ExprCode(pParse, pLeft);
2346       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2347       sqlite3ExprCode(pParse, pRight);
2348       addr = sqlite3VdbeCurrentAddr(v);
2349       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2350 
2351       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2352       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2353       pRight = pExpr->pList->a[1].pExpr;
2354       sqlite3ExprCode(pParse, pRight);
2355       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2356       break;
2357     }
2358     default: {
2359       sqlite3ExprCode(pParse, pExpr);
2360       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2361       break;
2362     }
2363   }
2364   pParse->ckOffset = ckOffset;
2365 }
2366 
2367 /*
2368 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
2369 ** if they are identical and return FALSE if they differ in any way.
2370 **
2371 ** Sometimes this routine will return FALSE even if the two expressions
2372 ** really are equivalent.  If we cannot prove that the expressions are
2373 ** identical, we return FALSE just to be safe.  So if this routine
2374 ** returns false, then you do not really know for certain if the two
2375 ** expressions are the same.  But if you get a TRUE return, then you
2376 ** can be sure the expressions are the same.  In the places where
2377 ** this routine is used, it does not hurt to get an extra FALSE - that
2378 ** just might result in some slightly slower code.  But returning
2379 ** an incorrect TRUE could lead to a malfunction.
2380 */
2381 int sqlite3ExprCompare(Expr *pA, Expr *pB){
2382   int i;
2383   if( pA==0||pB==0 ){
2384     return pB==pA;
2385   }
2386   if( pA->op!=pB->op ) return 0;
2387   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
2388   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
2389   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
2390   if( pA->pList ){
2391     if( pB->pList==0 ) return 0;
2392     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
2393     for(i=0; i<pA->pList->nExpr; i++){
2394       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
2395         return 0;
2396       }
2397     }
2398   }else if( pB->pList ){
2399     return 0;
2400   }
2401   if( pA->pSelect || pB->pSelect ) return 0;
2402   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
2403   if( pA->op!=TK_COLUMN && pA->token.z ){
2404     if( pB->token.z==0 ) return 0;
2405     if( pB->token.n!=pA->token.n ) return 0;
2406     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
2407       return 0;
2408     }
2409   }
2410   return 1;
2411 }
2412 
2413 
2414 /*
2415 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
2416 ** the new element.  Return a negative number if malloc fails.
2417 */
2418 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
2419   int i;
2420   pInfo->aCol = sqlite3ArrayAllocate(
2421        db,
2422        pInfo->aCol,
2423        sizeof(pInfo->aCol[0]),
2424        3,
2425        &pInfo->nColumn,
2426        &pInfo->nColumnAlloc,
2427        &i
2428   );
2429   return i;
2430 }
2431 
2432 /*
2433 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
2434 ** the new element.  Return a negative number if malloc fails.
2435 */
2436 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
2437   int i;
2438   pInfo->aFunc = sqlite3ArrayAllocate(
2439        db,
2440        pInfo->aFunc,
2441        sizeof(pInfo->aFunc[0]),
2442        3,
2443        &pInfo->nFunc,
2444        &pInfo->nFuncAlloc,
2445        &i
2446   );
2447   return i;
2448 }
2449 
2450 /*
2451 ** This is an xFunc for walkExprTree() used to implement
2452 ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2453 ** for additional information.
2454 **
2455 ** This routine analyzes the aggregate function at pExpr.
2456 */
2457 static int analyzeAggregate(void *pArg, Expr *pExpr){
2458   int i;
2459   NameContext *pNC = (NameContext *)pArg;
2460   Parse *pParse = pNC->pParse;
2461   SrcList *pSrcList = pNC->pSrcList;
2462   AggInfo *pAggInfo = pNC->pAggInfo;
2463 
2464   switch( pExpr->op ){
2465     case TK_AGG_COLUMN:
2466     case TK_COLUMN: {
2467       /* Check to see if the column is in one of the tables in the FROM
2468       ** clause of the aggregate query */
2469       if( pSrcList ){
2470         struct SrcList_item *pItem = pSrcList->a;
2471         for(i=0; i<pSrcList->nSrc; i++, pItem++){
2472           struct AggInfo_col *pCol;
2473           if( pExpr->iTable==pItem->iCursor ){
2474             /* If we reach this point, it means that pExpr refers to a table
2475             ** that is in the FROM clause of the aggregate query.
2476             **
2477             ** Make an entry for the column in pAggInfo->aCol[] if there
2478             ** is not an entry there already.
2479             */
2480             int k;
2481             pCol = pAggInfo->aCol;
2482             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
2483               if( pCol->iTable==pExpr->iTable &&
2484                   pCol->iColumn==pExpr->iColumn ){
2485                 break;
2486               }
2487             }
2488             if( (k>=pAggInfo->nColumn)
2489              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
2490             ){
2491               pCol = &pAggInfo->aCol[k];
2492               pCol->pTab = pExpr->pTab;
2493               pCol->iTable = pExpr->iTable;
2494               pCol->iColumn = pExpr->iColumn;
2495               pCol->iMem = pParse->nMem++;
2496               pCol->iSorterColumn = -1;
2497               pCol->pExpr = pExpr;
2498               if( pAggInfo->pGroupBy ){
2499                 int j, n;
2500                 ExprList *pGB = pAggInfo->pGroupBy;
2501                 struct ExprList_item *pTerm = pGB->a;
2502                 n = pGB->nExpr;
2503                 for(j=0; j<n; j++, pTerm++){
2504                   Expr *pE = pTerm->pExpr;
2505                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
2506                       pE->iColumn==pExpr->iColumn ){
2507                     pCol->iSorterColumn = j;
2508                     break;
2509                   }
2510                 }
2511               }
2512               if( pCol->iSorterColumn<0 ){
2513                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
2514               }
2515             }
2516             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
2517             ** because it was there before or because we just created it).
2518             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
2519             ** pAggInfo->aCol[] entry.
2520             */
2521             pExpr->pAggInfo = pAggInfo;
2522             pExpr->op = TK_AGG_COLUMN;
2523             pExpr->iAgg = k;
2524             break;
2525           } /* endif pExpr->iTable==pItem->iCursor */
2526         } /* end loop over pSrcList */
2527       }
2528       return 1;
2529     }
2530     case TK_AGG_FUNCTION: {
2531       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
2532       ** to be ignored */
2533       if( pNC->nDepth==0 ){
2534         /* Check to see if pExpr is a duplicate of another aggregate
2535         ** function that is already in the pAggInfo structure
2536         */
2537         struct AggInfo_func *pItem = pAggInfo->aFunc;
2538         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
2539           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
2540             break;
2541           }
2542         }
2543         if( i>=pAggInfo->nFunc ){
2544           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
2545           */
2546           u8 enc = ENC(pParse->db);
2547           i = addAggInfoFunc(pParse->db, pAggInfo);
2548           if( i>=0 ){
2549             pItem = &pAggInfo->aFunc[i];
2550             pItem->pExpr = pExpr;
2551             pItem->iMem = pParse->nMem++;
2552             pItem->pFunc = sqlite3FindFunction(pParse->db,
2553                    (char*)pExpr->token.z, pExpr->token.n,
2554                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2555             if( pExpr->flags & EP_Distinct ){
2556               pItem->iDistinct = pParse->nTab++;
2557             }else{
2558               pItem->iDistinct = -1;
2559             }
2560           }
2561         }
2562         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
2563         */
2564         pExpr->iAgg = i;
2565         pExpr->pAggInfo = pAggInfo;
2566         return 1;
2567       }
2568     }
2569   }
2570 
2571   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
2572   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
2573   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
2574   */
2575   if( pExpr->pSelect ){
2576     pNC->nDepth++;
2577     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2578     pNC->nDepth--;
2579   }
2580   return 0;
2581 }
2582 
2583 /*
2584 ** Analyze the given expression looking for aggregate functions and
2585 ** for variables that need to be added to the pParse->aAgg[] array.
2586 ** Make additional entries to the pParse->aAgg[] array as necessary.
2587 **
2588 ** This routine should only be called after the expression has been
2589 ** analyzed by sqlite3ExprResolveNames().
2590 **
2591 ** If errors are seen, leave an error message in zErrMsg and return
2592 ** the number of errors.
2593 */
2594 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2595   int nErr = pNC->pParse->nErr;
2596   walkExprTree(pExpr, analyzeAggregate, pNC);
2597   return pNC->pParse->nErr - nErr;
2598 }
2599 
2600 /*
2601 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
2602 ** expression list.  Return the number of errors.
2603 **
2604 ** If an error is found, the analysis is cut short.
2605 */
2606 int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
2607   struct ExprList_item *pItem;
2608   int i;
2609   int nErr = 0;
2610   if( pList ){
2611     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
2612       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
2613     }
2614   }
2615   return nErr;
2616 }
2617