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