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