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