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