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