xref: /sqlite-3.40.0/src/expr.c (revision 7c68d60b)
1 /*
2 ** Copyright (c) 1999, 2000 D. Richard Hipp
3 **
4 ** This program is free software; you can redistribute it and/or
5 ** modify it under the terms of the GNU General Public
6 ** License as published by the Free Software Foundation; either
7 ** version 2 of the License, or (at your option) any later version.
8 **
9 ** This program is distributed in the hope that it will be useful,
10 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 ** General Public License for more details.
13 **
14 ** You should have received a copy of the GNU General Public
15 ** License along with this library; if not, write to the
16 ** Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 ** Boston, MA  02111-1307, USA.
18 **
19 ** Author contact information:
20 **   [email protected]
21 **   http://www.hwaci.com/drh/
22 **
23 *************************************************************************
24 ** This file contains routines used for analyzing expressions and
25 ** for generating VDBE code that evaluates expressions.
26 **
27 ** $Id: expr.c,v 1.19 2000/08/28 15:51:44 drh Exp $
28 */
29 #include "sqliteInt.h"
30 
31 /*
32 ** Walk an expression tree.  Return 1 if the expression is constant
33 ** and 0 if it involves variables.
34 */
35 static int isConstant(Expr *p){
36   switch( p->op ){
37     case TK_ID:
38     case TK_COLUMN:
39     case TK_DOT:
40       return 0;
41     default: {
42       if( p->pLeft && !isConstant(p->pLeft) ) return 0;
43       if( p->pRight && !isConstant(p->pRight) ) return 0;
44       if( p->pList ){
45         int i;
46         for(i=0; i<p->pList->nExpr; i++){
47           if( !isConstant(p->pList->a[i].pExpr) ) return 0;
48         }
49       }
50       break;
51     }
52   }
53   return 1;
54 }
55 
56 /*
57 ** Walk the expression tree and process operators of the form:
58 **
59 **       expr IN (SELECT ...)
60 **
61 ** These operators have to be processed before column names are
62 ** resolved because each such operator increments pParse->nTab
63 ** to reserve cursor numbers for its own use.  But pParse->nTab
64 ** needs to be constant once we begin resolving column names.
65 **
66 ** Actually, the processing of IN-SELECT is only started by this
67 ** routine.  This routine allocates a cursor number to the IN-SELECT
68 ** and then moves on.  The code generation is done by
69 ** sqliteExprResolveIds() which must be called afterwards.
70 */
71 void sqliteExprResolveInSelect(Parse *pParse, Expr *pExpr){
72   if( pExpr==0 ) return;
73   if( pExpr->op==TK_IN && pExpr->pSelect!=0 ){
74     pExpr->iTable = pParse->nTab++;
75   }else{
76     if( pExpr->pLeft ) sqliteExprResolveInSelect(pParse, pExpr->pLeft);
77     if( pExpr->pRight ) sqliteExprResolveInSelect(pParse, pExpr->pRight);
78     if( pExpr->pList ){
79       int i;
80       ExprList *pList = pExpr->pList;
81       for(i=0; i<pList->nExpr; i++){
82         sqliteExprResolveInSelect(pParse, pList->a[i].pExpr);
83       }
84     }
85   }
86 }
87 
88 /*
89 ** This routine walks an expression tree and resolves references to
90 ** table columns.  Nodes of the form ID.ID or ID resolve into an
91 ** index to the table in the table list and a column offset.  The opcode
92 ** for such nodes is changed to TK_COLUMN.  The iTable value is changed
93 ** to the index of the referenced table in pTabList plus the pParse->nTab
94 ** value.  The iColumn value is changed to the index of the column of the
95 ** referenced table.
96 **
97 ** We also check for instances of the IN operator.  IN comes in two
98 ** forms:
99 **
100 **           expr IN (exprlist)
101 ** and
102 **           expr IN (SELECT ...)
103 **
104 ** The first form is handled by creating a set holding the list
105 ** of allowed values.  The second form causes the SELECT to generate
106 ** a temporary table.
107 **
108 ** This routine also looks for scalar SELECTs that are part of an expression.
109 ** If it finds any, it generates code to write the value of that select
110 ** into a memory cell.
111 **
112 ** Unknown columns or tables provoke an error.  The function returns
113 ** the number of errors seen and leaves an error message on pParse->zErrMsg.
114 */
115 int sqliteExprResolveIds(Parse *pParse, IdList *pTabList, Expr *pExpr){
116   if( pExpr==0 ) return 0;
117   switch( pExpr->op ){
118     /* A lone identifier */
119     case TK_ID: {
120       int cnt = 0;   /* Number of matches */
121       int i;         /* Loop counter */
122       char *z = sqliteStrNDup(pExpr->token.z, pExpr->token.n);
123       for(i=0; i<pTabList->nId; i++){
124         int j;
125         Table *pTab = pTabList->a[i].pTab;
126         if( pTab==0 ) continue;
127         for(j=0; j<pTab->nCol; j++){
128           if( sqliteStrICmp(pTab->aCol[j].zName, z)==0 ){
129             cnt++;
130             pExpr->iTable = i + pParse->nTab;
131             pExpr->iColumn = j;
132           }
133         }
134       }
135       sqliteFree(z);
136       if( cnt==0 ){
137         sqliteSetNString(&pParse->zErrMsg, "no such column: ", -1,
138           pExpr->token.z, pExpr->token.n, 0);
139         pParse->nErr++;
140         return 1;
141       }else if( cnt>1 ){
142         sqliteSetNString(&pParse->zErrMsg, "ambiguous column name: ", -1,
143           pExpr->token.z, pExpr->token.n, 0);
144         pParse->nErr++;
145         return 1;
146       }
147       pExpr->op = TK_COLUMN;
148       break;
149     }
150 
151     /* A table name and column name:  ID.ID */
152     case TK_DOT: {
153       int cnt = 0;             /* Number of matches */
154       int i;                   /* Loop counter */
155       Expr *pLeft, *pRight;    /* Left and right subbranches of the expr */
156       char *zLeft, *zRight;    /* Text of an identifier */
157 
158       pLeft = pExpr->pLeft;
159       pRight = pExpr->pRight;
160       assert( pLeft && pLeft->op==TK_ID );
161       assert( pRight && pRight->op==TK_ID );
162       zLeft = sqliteStrNDup(pLeft->token.z, pLeft->token.n);
163       zRight = sqliteStrNDup(pRight->token.z, pRight->token.n);
164       for(i=0; i<pTabList->nId; i++){
165         int j;
166         char *zTab;
167         Table *pTab = pTabList->a[i].pTab;
168         if( pTab==0 ) continue;
169         if( pTabList->a[i].zAlias ){
170           zTab = pTabList->a[i].zAlias;
171         }else{
172           zTab = pTab->zName;
173         }
174         if( sqliteStrICmp(zTab, zLeft)!=0 ) continue;
175         for(j=0; j<pTab->nCol; j++){
176           if( sqliteStrICmp(pTab->aCol[j].zName, zRight)==0 ){
177             cnt++;
178             pExpr->iTable = i + pParse->nTab;
179             pExpr->iColumn = j;
180           }
181         }
182       }
183       sqliteFree(zLeft);
184       sqliteFree(zRight);
185       if( cnt==0 ){
186         sqliteSetNString(&pParse->zErrMsg, "no such column: ", -1,
187           pLeft->token.z, pLeft->token.n, ".", 1,
188           pRight->token.z, pRight->token.n, 0);
189         pParse->nErr++;
190         return 1;
191       }else if( cnt>1 ){
192         sqliteSetNString(&pParse->zErrMsg, "ambiguous column name: ", -1,
193           pLeft->token.z, pLeft->token.n, ".", 1,
194           pRight->token.z, pRight->token.n, 0);
195         pParse->nErr++;
196         return 1;
197       }
198       sqliteExprDelete(pLeft);
199       pExpr->pLeft = 0;
200       sqliteExprDelete(pRight);
201       pExpr->pRight = 0;
202       pExpr->op = TK_COLUMN;
203       break;
204     }
205 
206     case TK_IN: {
207       Vdbe *v = sqliteGetVdbe(pParse);
208       if( v==0 ) return 1;
209       if( sqliteExprResolveIds(pParse, pTabList, pExpr->pLeft) ){
210         return 1;
211       }
212       if( pExpr->pSelect ){
213         /* Case 1:     expr IN (SELECT ...)
214         **
215         ** Generate code to write the results of the select into a temporary
216         ** table.  The cursor number of the temporary table has already
217         ** been put in iTable by sqliteExprResolveInSelect().
218         */
219         sqliteVdbeAddOp(v, OP_Open, pExpr->iTable, 1, 0, 0);
220         if( sqliteSelect(pParse, pExpr->pSelect, SRT_Set, pExpr->iTable) );
221       }else if( pExpr->pList ){
222         /* Case 2:     expr IN (exprlist)
223         **
224         ** Create a set to put the exprlist values in.  The Set id is stored
225         ** in iTable.
226         */
227         int i, iSet;
228         for(i=0; i<pExpr->pList->nExpr; i++){
229           Expr *pE2 = pExpr->pList->a[i].pExpr;
230           if( !isConstant(pE2) ){
231             sqliteSetString(&pParse->zErrMsg,
232               "right-hand side of IN operator must be constant", 0);
233             pParse->nErr++;
234             return 1;
235           }
236           if( sqliteExprCheck(pParse, pE2, 0, 0) ){
237             return 1;
238           }
239         }
240         iSet = pExpr->iTable = pParse->nSet++;
241         for(i=0; i<pExpr->pList->nExpr; i++){
242           Expr *pE2 = pExpr->pList->a[i].pExpr;
243           switch( pE2->op ){
244             case TK_FLOAT:
245             case TK_INTEGER:
246             case TK_STRING: {
247               int addr = sqliteVdbeAddOp(v, OP_SetInsert, iSet, 0, 0, 0);
248               sqliteVdbeChangeP3(v, addr, pE2->token.z, pE2->token.n);
249               sqliteVdbeDequoteP3(v, addr);
250               break;
251             }
252             default: {
253               sqliteExprCode(pParse, pE2);
254               sqliteVdbeAddOp(v, OP_SetInsert, iSet, 0, 0, 0);
255               break;
256             }
257           }
258         }
259       }
260       break;
261     }
262 
263     case TK_SELECT: {
264       /* This has to be a scalar SELECT.  Generate code to put the
265       ** value of this select in a memory cell and record the number
266       ** of the memory cell in iColumn.
267       */
268       pExpr->iColumn = pParse->nMem++;
269       if( sqliteSelect(pParse, pExpr->pSelect, SRT_Mem, pExpr->iColumn) ){
270         return 1;
271       }
272       break;
273     }
274 
275     /* For all else, just recursively walk the tree */
276     default: {
277       if( pExpr->pLeft
278       && sqliteExprResolveIds(pParse, pTabList, pExpr->pLeft) ){
279         return 1;
280       }
281       if( pExpr->pRight
282       && sqliteExprResolveIds(pParse, pTabList, pExpr->pRight) ){
283         return 1;
284       }
285       if( pExpr->pList ){
286         int i;
287         ExprList *pList = pExpr->pList;
288         for(i=0; i<pList->nExpr; i++){
289           if( sqliteExprResolveIds(pParse, pTabList, pList->a[i].pExpr) ){
290             return 1;
291           }
292         }
293       }
294     }
295   }
296   return 0;
297 }
298 
299 #if 0 /* NOT USED */
300 /*
301 ** Compare a token against a string.  Return TRUE if they match.
302 */
303 static int sqliteTokenCmp(Token *pToken, const char *zStr){
304   int n = strlen(zStr);
305   if( n!=pToken->n ) return 0;
306   return sqliteStrNICmp(pToken->z, zStr, n)==0;
307 }
308 #endif
309 
310 /*
311 ** Convert a function name into its integer identifier.  Return the
312 ** identifier.  Return FN_Unknown if the function name is unknown.
313 */
314 int sqliteFuncId(Token *pToken){
315   static const struct {
316      char *zName;
317      int len;
318      int id;
319   } aFunc[] = {
320      { "count",  5, FN_Count },
321      { "min",    3, FN_Min   },
322      { "max",    3, FN_Max   },
323      { "sum",    3, FN_Sum   },
324      { "avg",    3, FN_Avg   },
325      { "fcnt",   4, FN_Fcnt  },  /* Used for testing only */
326      { "length", 6, FN_Length},
327      { "substr", 6, FN_Substr},
328   };
329   int i;
330   for(i=0; i<ArraySize(aFunc); i++){
331     if( aFunc[i].len==pToken->n
332      && sqliteStrNICmp(pToken->z, aFunc[i].zName, aFunc[i].len)==0 ){
333        return aFunc[i].id;
334     }
335   }
336   return FN_Unknown;
337 }
338 
339 /*
340 ** Error check the functions in an expression.  Make sure all
341 ** function names are recognized and all functions have the correct
342 ** number of arguments.  Leave an error message in pParse->zErrMsg
343 ** if anything is amiss.  Return the number of errors.
344 **
345 ** if pIsAgg is not null and this expression is an aggregate function
346 ** (like count(*) or max(value)) then write a 1 into *pIsAgg.
347 */
348 int sqliteExprCheck(Parse *pParse, Expr *pExpr, int allowAgg, int *pIsAgg){
349   int nErr = 0;
350   if( pExpr==0 ) return 0;
351   switch( pExpr->op ){
352     case TK_FUNCTION: {
353       int id = sqliteFuncId(&pExpr->token);
354       int n = pExpr->pList ? pExpr->pList->nExpr : 0;
355       int no_such_func = 0;
356       int too_many_args = 0;
357       int too_few_args = 0;
358       int is_agg = 0;
359       int i;
360       pExpr->iColumn = id;
361       switch( id ){
362         case FN_Unknown: {
363           no_such_func = 1;
364           break;
365         }
366         case FN_Count: {
367           no_such_func = !allowAgg;
368           too_many_args = n>1;
369           is_agg = 1;
370           break;
371         }
372         case FN_Max:
373         case FN_Min: {
374           too_few_args = allowAgg ? n<1 : n<2;
375           is_agg = n==1;
376           break;
377         }
378         case FN_Avg:
379         case FN_Sum: {
380           no_such_func = !allowAgg;
381           too_many_args = n>1;
382           too_few_args = n<1;
383           is_agg = 1;
384           break;
385         }
386         case FN_Length: {
387           too_few_args = n<1;
388           too_many_args = n>1;
389           break;
390         }
391         case FN_Substr: {
392           too_few_args = n<3;
393           too_many_args = n>3;
394           break;
395         }
396         /* The "fcnt(*)" function always returns the number of fetch
397         ** operations that have occurred so far while processing the
398         ** SQL statement.  This information can be used by test procedures
399         ** to verify that indices are being used properly to minimize
400         ** searching.  All arguments to fcnt() are ignored.  fcnt() has
401         ** no use (other than testing) that we are aware of.
402         */
403         case FN_Fcnt: {
404           n = 0;
405           break;
406         }
407 
408         default: break;
409       }
410       if( no_such_func ){
411         sqliteSetNString(&pParse->zErrMsg, "no such function: ", -1,
412            pExpr->token.z, pExpr->token.n, 0);
413         pParse->nErr++;
414         nErr++;
415       }else if( too_many_args ){
416         sqliteSetNString(&pParse->zErrMsg, "too many arguments to function ",-1,
417            pExpr->token.z, pExpr->token.n, "()", 2, 0);
418         pParse->nErr++;
419         nErr++;
420       }else if( too_few_args ){
421         sqliteSetNString(&pParse->zErrMsg, "too few arguments to function ",-1,
422            pExpr->token.z, pExpr->token.n, "()", 2, 0);
423         pParse->nErr++;
424         nErr++;
425       }
426       if( is_agg ) pExpr->op = TK_AGG_FUNCTION;
427       if( is_agg && pIsAgg ) *pIsAgg = 1;
428       for(i=0; nErr==0 && i<n; i++){
429         nErr = sqliteExprCheck(pParse, pExpr->pList->a[i].pExpr,
430                                allowAgg && !is_agg, pIsAgg);
431       }
432     }
433     default: {
434       if( pExpr->pLeft ){
435         nErr = sqliteExprCheck(pParse, pExpr->pLeft, allowAgg, pIsAgg);
436       }
437       if( nErr==0 && pExpr->pRight ){
438         nErr = sqliteExprCheck(pParse, pExpr->pRight, allowAgg, pIsAgg);
439       }
440       if( nErr==0 && pExpr->pList ){
441         int n = pExpr->pList->nExpr;
442         int i;
443         for(i=0; nErr==0 && i<n; i++){
444           Expr *pE2 = pExpr->pList->a[i].pExpr;
445           nErr = sqliteExprCheck(pParse, pE2, allowAgg, pIsAgg);
446         }
447       }
448       break;
449     }
450   }
451   return nErr;
452 }
453 
454 /*
455 ** Generate code into the current Vdbe to evaluate the given
456 ** expression and leave the result on the top of stack.
457 */
458 void sqliteExprCode(Parse *pParse, Expr *pExpr){
459   Vdbe *v = pParse->pVdbe;
460   int op;
461   switch( pExpr->op ){
462     case TK_PLUS:     op = OP_Add;      break;
463     case TK_MINUS:    op = OP_Subtract; break;
464     case TK_STAR:     op = OP_Multiply; break;
465     case TK_SLASH:    op = OP_Divide;   break;
466     case TK_AND:      op = OP_And;      break;
467     case TK_OR:       op = OP_Or;       break;
468     case TK_LT:       op = OP_Lt;       break;
469     case TK_LE:       op = OP_Le;       break;
470     case TK_GT:       op = OP_Gt;       break;
471     case TK_GE:       op = OP_Ge;       break;
472     case TK_NE:       op = OP_Ne;       break;
473     case TK_EQ:       op = OP_Eq;       break;
474     case TK_LIKE:     op = OP_Like;     break;
475     case TK_GLOB:     op = OP_Glob;     break;
476     case TK_ISNULL:   op = OP_IsNull;   break;
477     case TK_NOTNULL:  op = OP_NotNull;  break;
478     case TK_NOT:      op = OP_Not;      break;
479     case TK_UMINUS:   op = OP_Negative; break;
480     default: break;
481   }
482   switch( pExpr->op ){
483     case TK_COLUMN: {
484       if( pParse->useAgg ){
485         sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg, 0, 0);
486       }else{
487         sqliteVdbeAddOp(v, OP_Field, pExpr->iTable, pExpr->iColumn, 0, 0);
488       }
489       break;
490     }
491     case TK_INTEGER: {
492       int i = atoi(pExpr->token.z);
493       sqliteVdbeAddOp(v, OP_Integer, i, 0, 0, 0);
494       break;
495     }
496     case TK_FLOAT: {
497       int addr = sqliteVdbeAddOp(v, OP_String, 0, 0, 0, 0);
498       sqliteVdbeChangeP3(v, addr, pExpr->token.z, pExpr->token.n);
499       break;
500     }
501     case TK_STRING: {
502       int addr = sqliteVdbeAddOp(v, OP_String, 0, 0, 0, 0);
503       sqliteVdbeChangeP3(v, addr, pExpr->token.z, pExpr->token.n);
504       sqliteVdbeDequoteP3(v, addr);
505       break;
506     }
507     case TK_NULL: {
508       sqliteVdbeAddOp(v, OP_Null, 0, 0, 0, 0);
509       break;
510     }
511     case TK_AND:
512     case TK_OR:
513     case TK_PLUS:
514     case TK_STAR:
515     case TK_MINUS:
516     case TK_SLASH: {
517       sqliteExprCode(pParse, pExpr->pLeft);
518       sqliteExprCode(pParse, pExpr->pRight);
519       sqliteVdbeAddOp(v, op, 0, 0, 0, 0);
520       break;
521     }
522     case TK_CONCAT: {
523       sqliteExprCode(pParse, pExpr->pLeft);
524       sqliteExprCode(pParse, pExpr->pRight);
525       sqliteVdbeAddOp(v, OP_Concat, 2, 0, 0, 0);
526       break;
527     }
528     case TK_LT:
529     case TK_LE:
530     case TK_GT:
531     case TK_GE:
532     case TK_NE:
533     case TK_EQ:
534     case TK_LIKE:
535     case TK_GLOB: {
536       int dest;
537       sqliteVdbeAddOp(v, OP_Integer, 1, 0, 0, 0);
538       sqliteExprCode(pParse, pExpr->pLeft);
539       sqliteExprCode(pParse, pExpr->pRight);
540       dest = sqliteVdbeCurrentAddr(v) + 2;
541       sqliteVdbeAddOp(v, op, 0, dest, 0, 0);
542       sqliteVdbeAddOp(v, OP_AddImm, -1, 0, 0, 0);
543       break;
544     }
545     case TK_UMINUS: {
546       assert( pExpr->pLeft );
547       if( pExpr->pLeft->op==TK_INTEGER ){
548         int i = atoi(pExpr->pLeft->token.z);
549         sqliteVdbeAddOp(v, OP_Integer, -i, 0, 0, 0);
550         break;
551       }else if( pExpr->pLeft->op==TK_FLOAT ){
552         Token *p = &pExpr->pLeft->token;
553         char *z = sqliteMalloc( p->n + 2 );
554         sprintf(z, "-%.*s", p->n, p->z);
555         sqliteVdbeAddOp(v, OP_String, 0, 0, z, 0);
556         sqliteFree(z);
557         break;
558       }
559       /* Fall through into TK_NOT */
560     }
561     case TK_NOT: {
562       sqliteExprCode(pParse, pExpr->pLeft);
563       sqliteVdbeAddOp(v, op, 0, 0, 0, 0);
564       break;
565     }
566     case TK_ISNULL:
567     case TK_NOTNULL: {
568       int dest;
569       sqliteVdbeAddOp(v, OP_Integer, 1, 0, 0, 0);
570       sqliteExprCode(pParse, pExpr->pLeft);
571       dest = sqliteVdbeCurrentAddr(v) + 2;
572       sqliteVdbeAddOp(v, op, 0, dest, 0, 0);
573       sqliteVdbeAddOp(v, OP_AddImm, -1, 0, 0, 0);
574       break;
575     }
576     case TK_AGG_FUNCTION: {
577       sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg, 0, 0);
578       if( pExpr->iColumn==FN_Avg ){
579         assert( pParse->iAggCount>=0 && pParse->iAggCount<pParse->nAgg );
580         sqliteVdbeAddOp(v, OP_AggGet, 0, pParse->iAggCount, 0, 0);
581         sqliteVdbeAddOp(v, OP_Divide, 0, 0, 0, 0);
582       }
583       break;
584     }
585     case TK_FUNCTION: {
586       int id = pExpr->iColumn;
587       int op;
588       int i;
589       ExprList *pList = pExpr->pList;
590       switch( id ){
591         case FN_Fcnt: {
592           sqliteVdbeAddOp(v, OP_Fcnt, 0, 0, 0, 0);
593           break;
594         }
595         case FN_Min:
596         case FN_Max: {
597           op = id==FN_Min ? OP_Min : OP_Max;
598           for(i=0; i<pList->nExpr; i++){
599             sqliteExprCode(pParse, pList->a[i].pExpr);
600             if( i>0 ){
601               sqliteVdbeAddOp(v, op, 0, 0, 0, 0);
602             }
603           }
604           break;
605         }
606         case FN_Length: {
607           sqliteExprCode(pParse, pList->a[0].pExpr);
608           sqliteVdbeAddOp(v, OP_Strlen, 0, 0, 0, 0);
609           break;
610         }
611         case FN_Substr: {
612           for(i=0; i<pList->nExpr; i++){
613             sqliteExprCode(pParse, pList->a[i].pExpr);
614           }
615           sqliteVdbeAddOp(v, OP_Substr, 0, 0, 0, 0);
616           break;
617         }
618         default: {
619           /* Can't happen! */
620           break;
621         }
622       }
623       break;
624     }
625     case TK_SELECT: {
626       sqliteVdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0, 0, 0);
627       break;
628     }
629     case TK_IN: {
630       int addr;
631       sqliteVdbeAddOp(v, OP_Integer, 1, 0, 0, 0);
632       sqliteExprCode(pParse, pExpr->pLeft);
633       addr = sqliteVdbeCurrentAddr(v);
634       if( pExpr->pSelect ){
635         sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, addr+2, 0, 0);
636       }else{
637         sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, addr+2, 0, 0);
638       }
639       sqliteVdbeAddOp(v, OP_AddImm, -1, 0, 0, 0);
640       break;
641     }
642     case TK_BETWEEN: {
643       int lbl = sqliteVdbeMakeLabel(v);
644       sqliteVdbeAddOp(v, OP_Integer, 0, 0, 0, 0);
645       sqliteExprIfFalse(pParse, pExpr, lbl);
646       sqliteVdbeAddOp(v, OP_AddImm, 1, 0, 0, 0);
647       sqliteVdbeResolveLabel(v, lbl);
648       break;
649     }
650   }
651   return;
652 }
653 
654 /*
655 ** Generate code for a boolean expression such that a jump is made
656 ** to the label "dest" if the expression is true but execution
657 ** continues straight thru if the expression is false.
658 */
659 void sqliteExprIfTrue(Parse *pParse, Expr *pExpr, int dest){
660   Vdbe *v = pParse->pVdbe;
661   int op = 0;
662   switch( pExpr->op ){
663     case TK_LT:       op = OP_Lt;       break;
664     case TK_LE:       op = OP_Le;       break;
665     case TK_GT:       op = OP_Gt;       break;
666     case TK_GE:       op = OP_Ge;       break;
667     case TK_NE:       op = OP_Ne;       break;
668     case TK_EQ:       op = OP_Eq;       break;
669     case TK_LIKE:     op = OP_Like;     break;
670     case TK_GLOB:     op = OP_Glob;     break;
671     case TK_ISNULL:   op = OP_IsNull;   break;
672     case TK_NOTNULL:  op = OP_NotNull;  break;
673     default:  break;
674   }
675   switch( pExpr->op ){
676     case TK_AND: {
677       int d2 = sqliteVdbeMakeLabel(v);
678       sqliteExprIfFalse(pParse, pExpr->pLeft, d2);
679       sqliteExprIfTrue(pParse, pExpr->pRight, dest);
680       sqliteVdbeResolveLabel(v, d2);
681       break;
682     }
683     case TK_OR: {
684       sqliteExprIfTrue(pParse, pExpr->pLeft, dest);
685       sqliteExprIfTrue(pParse, pExpr->pRight, dest);
686       break;
687     }
688     case TK_NOT: {
689       sqliteExprIfFalse(pParse, pExpr->pLeft, dest);
690       break;
691     }
692     case TK_LT:
693     case TK_LE:
694     case TK_GT:
695     case TK_GE:
696     case TK_NE:
697     case TK_EQ:
698     case TK_LIKE:
699     case TK_GLOB: {
700       sqliteExprCode(pParse, pExpr->pLeft);
701       sqliteExprCode(pParse, pExpr->pRight);
702       sqliteVdbeAddOp(v, op, 0, dest, 0, 0);
703       break;
704     }
705     case TK_ISNULL:
706     case TK_NOTNULL: {
707       sqliteExprCode(pParse, pExpr->pLeft);
708       sqliteVdbeAddOp(v, op, 0, dest, 0, 0);
709       break;
710     }
711     case TK_IN: {
712       sqliteExprCode(pParse, pExpr->pLeft);
713       if( pExpr->pSelect ){
714         sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, dest, 0, 0);
715       }else{
716         sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, dest, 0, 0);
717       }
718       break;
719     }
720     case TK_BETWEEN: {
721       int lbl = sqliteVdbeMakeLabel(v);
722       sqliteExprCode(pParse, pExpr->pLeft);
723       sqliteVdbeAddOp(v, OP_Dup, 0, 0, 0, 0);
724       sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
725       sqliteVdbeAddOp(v, OP_Lt, 0, lbl, 0, 0);
726       sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
727       sqliteVdbeAddOp(v, OP_Le, 0, dest, 0, 0);
728       sqliteVdbeAddOp(v, OP_Integer, 0, 0, 0, 0);
729       sqliteVdbeAddOp(v, OP_Pop, 1, 0, 0, lbl);
730       break;
731     }
732     default: {
733       sqliteExprCode(pParse, pExpr);
734       sqliteVdbeAddOp(v, OP_If, 0, dest, 0, 0);
735       break;
736     }
737   }
738 }
739 
740 /*
741 ** Generate code for boolean expression such that a jump is made
742 ** to the label "dest" if the expression is false but execution
743 ** continues straight thru if the expression is true.
744 */
745 void sqliteExprIfFalse(Parse *pParse, Expr *pExpr, int dest){
746   Vdbe *v = pParse->pVdbe;
747   int op = 0;
748   switch( pExpr->op ){
749     case TK_LT:       op = OP_Ge;       break;
750     case TK_LE:       op = OP_Gt;       break;
751     case TK_GT:       op = OP_Le;       break;
752     case TK_GE:       op = OP_Lt;       break;
753     case TK_NE:       op = OP_Eq;       break;
754     case TK_EQ:       op = OP_Ne;       break;
755     case TK_LIKE:     op = OP_Like;     break;
756     case TK_GLOB:     op = OP_Glob;     break;
757     case TK_ISNULL:   op = OP_NotNull;  break;
758     case TK_NOTNULL:  op = OP_IsNull;   break;
759     default:  break;
760   }
761   switch( pExpr->op ){
762     case TK_AND: {
763       sqliteExprIfFalse(pParse, pExpr->pLeft, dest);
764       sqliteExprIfFalse(pParse, pExpr->pRight, dest);
765       break;
766     }
767     case TK_OR: {
768       int d2 = sqliteVdbeMakeLabel(v);
769       sqliteExprIfTrue(pParse, pExpr->pLeft, d2);
770       sqliteExprIfFalse(pParse, pExpr->pRight, dest);
771       sqliteVdbeResolveLabel(v, d2);
772       break;
773     }
774     case TK_NOT: {
775       sqliteExprIfTrue(pParse, pExpr->pLeft, dest);
776       break;
777     }
778     case TK_LT:
779     case TK_LE:
780     case TK_GT:
781     case TK_GE:
782     case TK_NE:
783     case TK_EQ: {
784       sqliteExprCode(pParse, pExpr->pLeft);
785       sqliteExprCode(pParse, pExpr->pRight);
786       sqliteVdbeAddOp(v, op, 0, dest, 0, 0);
787       break;
788     }
789     case TK_LIKE:
790     case TK_GLOB: {
791       sqliteExprCode(pParse, pExpr->pLeft);
792       sqliteExprCode(pParse, pExpr->pRight);
793       sqliteVdbeAddOp(v, op, 1, dest, 0, 0);
794       break;
795     }
796     case TK_ISNULL:
797     case TK_NOTNULL: {
798       sqliteExprCode(pParse, pExpr->pLeft);
799       sqliteVdbeAddOp(v, op, 0, dest, 0, 0);
800       break;
801     }
802     case TK_IN: {
803       sqliteExprCode(pParse, pExpr->pLeft);
804       if( pExpr->pSelect ){
805         sqliteVdbeAddOp(v, OP_NotFound, pExpr->iTable, dest, 0, 0);
806       }else{
807         sqliteVdbeAddOp(v, OP_SetNotFound, pExpr->iTable, dest, 0, 0);
808       }
809       break;
810     }
811     case TK_BETWEEN: {
812       int addr;
813       sqliteExprCode(pParse, pExpr->pLeft);
814       sqliteVdbeAddOp(v, OP_Dup, 0, 0, 0, 0);
815       sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
816       addr = sqliteVdbeCurrentAddr(v);
817       sqliteVdbeAddOp(v, OP_Ge, 0, addr+3, 0, 0);
818       sqliteVdbeAddOp(v, OP_Pop, 1, 0, 0, 0);
819       sqliteVdbeAddOp(v, OP_Goto, 0, dest, 0, 0);
820       sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
821       sqliteVdbeAddOp(v, OP_Gt, 0, dest, 0, 0);
822       break;
823     }
824     default: {
825       sqliteExprCode(pParse, pExpr);
826       sqliteVdbeAddOp(v, OP_Not, 0, 0, 0, 0);
827       sqliteVdbeAddOp(v, OP_If, 0, dest, 0, 0);
828       break;
829     }
830   }
831 }
832 
833 /*
834 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
835 ** if they are identical and return FALSE if they differ in any way.
836 */
837 int sqliteExprCompare(Expr *pA, Expr *pB){
838   int i;
839   if( pA==0 ){
840     return pB==0;
841   }else if( pB==0 ){
842     return 0;
843   }
844   if( pA->op!=pB->op ) return 0;
845   if( !sqliteExprCompare(pA->pLeft, pB->pLeft) ) return 0;
846   if( !sqliteExprCompare(pA->pRight, pB->pRight) ) return 0;
847   if( pA->pList ){
848     if( pB->pList==0 ) return 0;
849     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
850     for(i=0; i<pA->pList->nExpr; i++){
851       if( !sqliteExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
852         return 0;
853       }
854     }
855   }else if( pB->pList ){
856     return 0;
857   }
858   if( pA->pSelect || pB->pSelect ) return 0;
859   if( pA->token.z ){
860     if( pB->token.z==0 ) return 0;
861     if( pB->token.n!=pA->token.n ) return 0;
862     if( sqliteStrNICmp(pA->token.z, pB->token.z, pA->token.n)!=0 ) return 0;
863   }
864   return 1;
865 }
866 
867 /*
868 ** Add a new element to the pParse->aAgg[] array and return its index.
869 */
870 static int appendAggInfo(Parse *pParse){
871   if( (pParse->nAgg & 0x7)==0 ){
872     int amt = pParse->nAgg + 8;
873     pParse->aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
874     if( pParse->aAgg==0 ){
875       sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
876       pParse->nErr++;
877       return -1;
878     }
879   }
880   memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
881   return pParse->nAgg++;
882 }
883 
884 /*
885 ** Analyze the given expression looking for aggregate functions and
886 ** for variables that need to be added to the pParse->aAgg[] array.
887 ** Make additional entries to the pParse->aAgg[] array as necessary.
888 **
889 ** This routine should only be called after the expression has been
890 ** analyzed by sqliteExprResolveIds() and sqliteExprCheck().
891 **
892 ** If errors are seen, leave an error message in zErrMsg and return
893 ** the number of errors.
894 */
895 int sqliteExprAnalyzeAggregates(Parse *pParse, Expr *pExpr){
896   int i;
897   AggExpr *aAgg;
898   int nErr = 0;
899 
900   if( pExpr==0 ) return 0;
901   switch( pExpr->op ){
902     case TK_COLUMN: {
903       aAgg = pParse->aAgg;
904       for(i=0; i<pParse->nAgg; i++){
905         if( aAgg[i].isAgg ) continue;
906         if( aAgg[i].pExpr->iTable==pExpr->iTable
907          && aAgg[i].pExpr->iColumn==pExpr->iColumn ){
908           break;
909         }
910       }
911       if( i>=pParse->nAgg ){
912         i = appendAggInfo(pParse);
913         if( i<0 ) return 1;
914         pParse->aAgg[i].isAgg = 0;
915         pParse->aAgg[i].pExpr = pExpr;
916       }
917       pExpr->iAgg = i;
918       break;
919     }
920     case TK_AGG_FUNCTION: {
921       if( pExpr->iColumn==FN_Count || pExpr->iColumn==FN_Avg ){
922         if( pParse->iAggCount>=0 ){
923           i = pParse->iAggCount;
924         }else{
925           i = appendAggInfo(pParse);
926           if( i<0 ) return 1;
927           pParse->aAgg[i].isAgg = 1;
928           pParse->aAgg[i].pExpr = 0;
929           pParse->iAggCount = i;
930         }
931         if( pExpr->iColumn==FN_Count ){
932           pExpr->iAgg = i;
933           break;
934         }
935       }
936       aAgg = pParse->aAgg;
937       for(i=0; i<pParse->nAgg; i++){
938         if( !aAgg[i].isAgg ) continue;
939         if( sqliteExprCompare(aAgg[i].pExpr, pExpr) ){
940           break;
941         }
942       }
943       if( i>=pParse->nAgg ){
944         i = appendAggInfo(pParse);
945         if( i<0 ) return 1;
946         pParse->aAgg[i].isAgg = 1;
947         pParse->aAgg[i].pExpr = pExpr;
948       }
949       pExpr->iAgg = i;
950       break;
951     }
952     default: {
953       if( pExpr->pLeft ){
954         nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pLeft);
955       }
956       if( nErr==0 && pExpr->pRight ){
957         nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pRight);
958       }
959       if( nErr==0 && pExpr->pList ){
960         int n = pExpr->pList->nExpr;
961         int i;
962         for(i=0; nErr==0 && i<n; i++){
963           nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pList->a[i].pExpr);
964         }
965       }
966       break;
967     }
968   }
969   return nErr;
970 }
971