xref: /sqlite-3.40.0/src/expr.c (revision afa5f680)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
121ccde15dSdrh ** This file contains routines used for analyzing expressions and
13b19a2bc6Sdrh ** for generating VDBE code that evaluates expressions in SQLite.
14cce7d176Sdrh **
15*afa5f680Sdrh ** $Id: expr.c,v 1.253 2006/01/30 14:36:59 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
1804738cb9Sdrh #include <ctype.h>
19a2e00042Sdrh 
20e014a838Sdanielk1977 /*
21e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
22e014a838Sdanielk1977 **
23e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
24e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
25e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
26e014a838Sdanielk1977 ** indicating no affinity for the expression.
27e014a838Sdanielk1977 **
28e014a838Sdanielk1977 ** i.e. the WHERE clause expresssions in the following statements all
29e014a838Sdanielk1977 ** have an affinity:
30e014a838Sdanielk1977 **
31e014a838Sdanielk1977 ** CREATE TABLE t1(a);
32e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
33e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
34e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
35e014a838Sdanielk1977 */
36bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
37487e262fSdrh   int op = pExpr->op;
38487e262fSdrh   if( op==TK_AS ){
39bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pLeft);
40a37cdde0Sdanielk1977   }
41487e262fSdrh   if( op==TK_SELECT ){
42bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
43a37cdde0Sdanielk1977   }
44487e262fSdrh #ifndef SQLITE_OMIT_CAST
45487e262fSdrh   if( op==TK_CAST ){
468a51256cSdrh     return sqlite3AffinityType(&pExpr->token);
47487e262fSdrh   }
48487e262fSdrh #endif
49a37cdde0Sdanielk1977   return pExpr->affinity;
50a37cdde0Sdanielk1977 }
51a37cdde0Sdanielk1977 
5253db1458Sdrh /*
530202b29eSdanielk1977 ** Return the default collation sequence for the expression pExpr. If
540202b29eSdanielk1977 ** there is no default collation type, return 0.
550202b29eSdanielk1977 */
567cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
577cedc8d4Sdanielk1977   CollSeq *pColl = 0;
580202b29eSdanielk1977   if( pExpr ){
597cedc8d4Sdanielk1977     pColl = pExpr->pColl;
60487e262fSdrh     if( (pExpr->op==TK_AS || pExpr->op==TK_CAST) && !pColl ){
617cedc8d4Sdanielk1977       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
620202b29eSdanielk1977     }
630202b29eSdanielk1977   }
647cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
657cedc8d4Sdanielk1977     pColl = 0;
667cedc8d4Sdanielk1977   }
677cedc8d4Sdanielk1977   return pColl;
680202b29eSdanielk1977 }
690202b29eSdanielk1977 
700202b29eSdanielk1977 /*
71626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
72626a879aSdrh ** type affinity of the other operand.  This routine returns the
7353db1458Sdrh ** type affinity that should be used for the comparison operator.
7453db1458Sdrh */
75e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
76bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
77e014a838Sdanielk1977   if( aff1 && aff2 ){
788df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
798df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
80e014a838Sdanielk1977     */
818a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
82e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
83e014a838Sdanielk1977     }else{
84e014a838Sdanielk1977       return SQLITE_AFF_NONE;
85e014a838Sdanielk1977     }
86e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
875f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
885f6a87b3Sdrh     ** results directly.
89e014a838Sdanielk1977     */
905f6a87b3Sdrh     return SQLITE_AFF_NONE;
91e014a838Sdanielk1977   }else{
92e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
93fe05af87Sdrh     assert( aff1==0 || aff2==0 );
94e014a838Sdanielk1977     return (aff1 + aff2);
95e014a838Sdanielk1977   }
96e014a838Sdanielk1977 }
97e014a838Sdanielk1977 
9853db1458Sdrh /*
9953db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
10053db1458Sdrh ** be applied to both operands prior to doing the comparison.
10153db1458Sdrh */
102e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
103e014a838Sdanielk1977   char aff;
104e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
105e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
106e014a838Sdanielk1977           pExpr->op==TK_NE );
107e014a838Sdanielk1977   assert( pExpr->pLeft );
108bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
109e014a838Sdanielk1977   if( pExpr->pRight ){
110e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
111e014a838Sdanielk1977   }
112e014a838Sdanielk1977   else if( pExpr->pSelect ){
113e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
114e014a838Sdanielk1977   }
115e014a838Sdanielk1977   else if( !aff ){
116e014a838Sdanielk1977     aff = SQLITE_AFF_NUMERIC;
117e014a838Sdanielk1977   }
118e014a838Sdanielk1977   return aff;
119e014a838Sdanielk1977 }
120e014a838Sdanielk1977 
121e014a838Sdanielk1977 /*
122e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
123e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
124e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
125e014a838Sdanielk1977 ** the comparison in pExpr.
126e014a838Sdanielk1977 */
127e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
128e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
1298a51256cSdrh   switch( aff ){
1308a51256cSdrh     case SQLITE_AFF_NONE:
1318a51256cSdrh       return 1;
1328a51256cSdrh     case SQLITE_AFF_TEXT:
1338a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
1348a51256cSdrh     default:
1358a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
1368a51256cSdrh   }
137e014a838Sdanielk1977 }
138e014a838Sdanielk1977 
139a37cdde0Sdanielk1977 /*
140a37cdde0Sdanielk1977 ** Return the P1 value that should be used for a binary comparison
141a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
142a37cdde0Sdanielk1977 ** If jumpIfNull is true, then set the low byte of the returned
143a37cdde0Sdanielk1977 ** P1 value to tell the opcode to jump if either expression
144a37cdde0Sdanielk1977 ** evaluates to NULL.
145a37cdde0Sdanielk1977 */
146e014a838Sdanielk1977 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
147bf3b721fSdanielk1977   char aff = sqlite3ExprAffinity(pExpr2);
148f0863fe5Sdrh   return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
149a37cdde0Sdanielk1977 }
150a37cdde0Sdanielk1977 
151a2e00042Sdrh /*
1520202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
1530202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
1540202b29eSdanielk1977 **
1550202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
1560202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
1570202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
1580202b29eSdanielk1977 ** type.
1590202b29eSdanielk1977 */
1607cedc8d4Sdanielk1977 static CollSeq* binaryCompareCollSeq(Parse *pParse, Expr *pLeft, Expr *pRight){
1617cedc8d4Sdanielk1977   CollSeq *pColl = sqlite3ExprCollSeq(pParse, pLeft);
1620202b29eSdanielk1977   if( !pColl ){
1637cedc8d4Sdanielk1977     pColl = sqlite3ExprCollSeq(pParse, pRight);
1640202b29eSdanielk1977   }
1650202b29eSdanielk1977   return pColl;
1660202b29eSdanielk1977 }
1670202b29eSdanielk1977 
1680202b29eSdanielk1977 /*
169be5c89acSdrh ** Generate code for a comparison operator.
170be5c89acSdrh */
171be5c89acSdrh static int codeCompare(
172be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
173be5c89acSdrh   Expr *pLeft,      /* The left operand */
174be5c89acSdrh   Expr *pRight,     /* The right operand */
175be5c89acSdrh   int opcode,       /* The comparison opcode */
176be5c89acSdrh   int dest,         /* Jump here if true.  */
177be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
178be5c89acSdrh ){
179be5c89acSdrh   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
180be5c89acSdrh   CollSeq *p3 = binaryCompareCollSeq(pParse, pLeft, pRight);
181be5c89acSdrh   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
182be5c89acSdrh }
183be5c89acSdrh 
184be5c89acSdrh /*
185a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
186a76b5dfcSdrh ** for this node is obtained from sqliteMalloc().  The calling function
187a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
188a76b5dfcSdrh */
189e4e72072Sdrh Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
190a76b5dfcSdrh   Expr *pNew;
191a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
192a76b5dfcSdrh   if( pNew==0 ){
193d5d56523Sdanielk1977     /* When malloc fails, delete pLeft and pRight. Expressions passed to
194d5d56523Sdanielk1977     ** this function must always be allocated with sqlite3Expr() for this
195d5d56523Sdanielk1977     ** reason.
196d5d56523Sdanielk1977     */
197d5d56523Sdanielk1977     sqlite3ExprDelete(pLeft);
198d5d56523Sdanielk1977     sqlite3ExprDelete(pRight);
199a76b5dfcSdrh     return 0;
200a76b5dfcSdrh   }
201a76b5dfcSdrh   pNew->op = op;
202a76b5dfcSdrh   pNew->pLeft = pLeft;
203a76b5dfcSdrh   pNew->pRight = pRight;
204a58fdfb1Sdanielk1977   pNew->iAgg = -1;
205a76b5dfcSdrh   if( pToken ){
2064b59ab5eSdrh     assert( pToken->dyn==0 );
207145716b3Sdrh     pNew->span = pNew->token = *pToken;
208145716b3Sdrh   }else if( pLeft && pRight ){
2094adee20fSdanielk1977     sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
210a76b5dfcSdrh   }
211a76b5dfcSdrh   return pNew;
212a76b5dfcSdrh }
213a76b5dfcSdrh 
214a76b5dfcSdrh /*
2154e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
2164e0cff60Sdrh ** that look like this:   #0 #1 #2 ...  These terms refer to elements
217288d37f1Sdrh ** on the stack.  "#0" means the top of the stack.
218288d37f1Sdrh ** "#1" means the next down on the stack.  And so forth.
2194e0cff60Sdrh **
2204e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
2214e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
2224e0cff60Sdrh ** The returns an expression that will code to extract the value from
2234e0cff60Sdrh ** that memory location as needed.
2244e0cff60Sdrh */
2254e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
2264e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
2274e0cff60Sdrh   Expr *p;
2284e0cff60Sdrh   int depth;
2294e0cff60Sdrh   if( pParse->nested==0 ){
2304e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
2314e0cff60Sdrh     return 0;
2324e0cff60Sdrh   }
233bb7ac00bSdrh   if( v==0 ) return 0;
2344e0cff60Sdrh   p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
23573c42a13Sdrh   if( p==0 ){
23673c42a13Sdrh     return 0;  /* Malloc failed */
23773c42a13Sdrh   }
2382646da7eSdrh   depth = atoi((char*)&pToken->z[1]);
2394e0cff60Sdrh   p->iTable = pParse->nMem++;
2404e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
2414e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
2424e0cff60Sdrh   return p;
2434e0cff60Sdrh }
2444e0cff60Sdrh 
2454e0cff60Sdrh /*
24691bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
24791bb0eedSdrh ** NULL, then just return the other expression.
24891bb0eedSdrh */
24991bb0eedSdrh Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
25091bb0eedSdrh   if( pLeft==0 ){
25191bb0eedSdrh     return pRight;
25291bb0eedSdrh   }else if( pRight==0 ){
25391bb0eedSdrh     return pLeft;
25491bb0eedSdrh   }else{
25591bb0eedSdrh     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
25691bb0eedSdrh   }
25791bb0eedSdrh }
25891bb0eedSdrh 
25991bb0eedSdrh /*
2606977fea8Sdrh ** Set the Expr.span field of the given expression to span all
261a76b5dfcSdrh ** text between the two given tokens.
262a76b5dfcSdrh */
2634adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
2644efc4754Sdrh   assert( pRight!=0 );
2654efc4754Sdrh   assert( pLeft!=0 );
2669e12800dSdanielk1977   if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
267ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
268145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
2696977fea8Sdrh       pExpr->span.z = pLeft->z;
27097903fefSdrh       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
2714b59ab5eSdrh     }else{
2726977fea8Sdrh       pExpr->span.z = 0;
2734b59ab5eSdrh     }
274a76b5dfcSdrh   }
275a76b5dfcSdrh }
276a76b5dfcSdrh 
277a76b5dfcSdrh /*
278a76b5dfcSdrh ** Construct a new expression node for a function with multiple
279a76b5dfcSdrh ** arguments.
280a76b5dfcSdrh */
2814adee20fSdanielk1977 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
282a76b5dfcSdrh   Expr *pNew;
2834b202ae2Sdanielk1977   assert( pToken );
284a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
285a76b5dfcSdrh   if( pNew==0 ){
286d5d56523Sdanielk1977     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
287a76b5dfcSdrh     return 0;
288a76b5dfcSdrh   }
289a76b5dfcSdrh   pNew->op = TK_FUNCTION;
290a76b5dfcSdrh   pNew->pList = pList;
2914b59ab5eSdrh   assert( pToken->dyn==0 );
292a76b5dfcSdrh   pNew->token = *pToken;
2936977fea8Sdrh   pNew->span = pNew->token;
294a76b5dfcSdrh   return pNew;
295a76b5dfcSdrh }
296a76b5dfcSdrh 
297a76b5dfcSdrh /*
298fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
299fa6bc000Sdrh ** in the original SQL statement.
300fa6bc000Sdrh **
301fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
302fa6bc000Sdrh ** variable number.
303fa6bc000Sdrh **
304fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
305fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
306fa6bc000Sdrh ** the SQL statement comes from an external source.
307fa6bc000Sdrh **
308fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
309fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
310fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
311fa6bc000Sdrh ** assigned.
312fa6bc000Sdrh */
313fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
314fa6bc000Sdrh   Token *pToken;
315fa6bc000Sdrh   if( pExpr==0 ) return;
316fa6bc000Sdrh   pToken = &pExpr->token;
317fa6bc000Sdrh   assert( pToken->n>=1 );
318fa6bc000Sdrh   assert( pToken->z!=0 );
319fa6bc000Sdrh   assert( pToken->z[0]!=0 );
320fa6bc000Sdrh   if( pToken->n==1 ){
321fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
322fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
323fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
324fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
325fa6bc000Sdrh     ** use it as the variable number */
326fa6bc000Sdrh     int i;
3272646da7eSdrh     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
328fa6bc000Sdrh     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
329fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
330fa6bc000Sdrh           SQLITE_MAX_VARIABLE_NUMBER);
331fa6bc000Sdrh     }
332fa6bc000Sdrh     if( i>pParse->nVar ){
333fa6bc000Sdrh       pParse->nVar = i;
334fa6bc000Sdrh     }
335fa6bc000Sdrh   }else{
336fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
337fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
338fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
339fa6bc000Sdrh     */
340fa6bc000Sdrh     int i, n;
341fa6bc000Sdrh     n = pToken->n;
342fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
343fa6bc000Sdrh       Expr *pE;
344fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
345fa6bc000Sdrh           && pE->token.n==n
346fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
347fa6bc000Sdrh         pExpr->iTable = pE->iTable;
348fa6bc000Sdrh         break;
349fa6bc000Sdrh       }
350fa6bc000Sdrh     }
351fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
352fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
353fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
354fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
355e7259296Sdanielk1977         sqliteReallocOrFree((void**)&pParse->apVarExpr,
356fa6bc000Sdrh                        pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
357fa6bc000Sdrh       }
3589e12800dSdanielk1977       if( !sqlite3MallocFailed() ){
359fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
360fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
361fa6bc000Sdrh       }
362fa6bc000Sdrh     }
363fa6bc000Sdrh   }
364fa6bc000Sdrh }
365fa6bc000Sdrh 
366fa6bc000Sdrh /*
367a2e00042Sdrh ** Recursively delete an expression tree.
368a2e00042Sdrh */
3694adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
370a2e00042Sdrh   if( p==0 ) return;
3714efc4754Sdrh   if( p->span.dyn ) sqliteFree((char*)p->span.z);
3724efc4754Sdrh   if( p->token.dyn ) sqliteFree((char*)p->token.z);
3734adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
3744adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
3754adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
3764adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
377a2e00042Sdrh   sqliteFree(p);
378a2e00042Sdrh }
379a2e00042Sdrh 
380d2687b77Sdrh /*
381d2687b77Sdrh ** The Expr.token field might be a string literal that is quoted.
382d2687b77Sdrh ** If so, remove the quotation marks.
383d2687b77Sdrh */
384d2687b77Sdrh void sqlite3DequoteExpr(Expr *p){
385d2687b77Sdrh   if( ExprHasAnyProperty(p, EP_Dequoted) ){
386d2687b77Sdrh     return;
387d2687b77Sdrh   }
388d2687b77Sdrh   ExprSetProperty(p, EP_Dequoted);
389d2687b77Sdrh   if( p->token.dyn==0 ){
390d2687b77Sdrh     sqlite3TokenCopy(&p->token, &p->token);
391d2687b77Sdrh   }
392d2687b77Sdrh   sqlite3Dequote((char*)p->token.z);
393d2687b77Sdrh }
394d2687b77Sdrh 
395a76b5dfcSdrh 
396a76b5dfcSdrh /*
397ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
398ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
399ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
400ff78bd2fSdrh ** without effecting the originals.
401ff78bd2fSdrh **
4024adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
4034adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
404ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
405ff78bd2fSdrh **
406ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
407ff78bd2fSdrh */
4084adee20fSdanielk1977 Expr *sqlite3ExprDup(Expr *p){
409ff78bd2fSdrh   Expr *pNew;
410ff78bd2fSdrh   if( p==0 ) return 0;
411fcb78a49Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
412ff78bd2fSdrh   if( pNew==0 ) return 0;
4133b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
4146977fea8Sdrh   if( p->token.z!=0 ){
4152646da7eSdrh     pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
4164b59ab5eSdrh     pNew->token.dyn = 1;
4174b59ab5eSdrh   }else{
4184efc4754Sdrh     assert( pNew->token.z==0 );
4194b59ab5eSdrh   }
4206977fea8Sdrh   pNew->span.z = 0;
4214adee20fSdanielk1977   pNew->pLeft = sqlite3ExprDup(p->pLeft);
4224adee20fSdanielk1977   pNew->pRight = sqlite3ExprDup(p->pRight);
4234adee20fSdanielk1977   pNew->pList = sqlite3ExprListDup(p->pList);
4244adee20fSdanielk1977   pNew->pSelect = sqlite3SelectDup(p->pSelect);
425aee18ef8Sdanielk1977   pNew->pTab = p->pTab;
426ff78bd2fSdrh   return pNew;
427ff78bd2fSdrh }
4284adee20fSdanielk1977 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
4294b59ab5eSdrh   if( pTo->dyn ) sqliteFree((char*)pTo->z);
4304b59ab5eSdrh   if( pFrom->z ){
4314b59ab5eSdrh     pTo->n = pFrom->n;
4322646da7eSdrh     pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
4334b59ab5eSdrh     pTo->dyn = 1;
4344b59ab5eSdrh   }else{
4354b59ab5eSdrh     pTo->z = 0;
4364b59ab5eSdrh   }
4374b59ab5eSdrh }
4384adee20fSdanielk1977 ExprList *sqlite3ExprListDup(ExprList *p){
439ff78bd2fSdrh   ExprList *pNew;
440145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
441ff78bd2fSdrh   int i;
442ff78bd2fSdrh   if( p==0 ) return 0;
443ff78bd2fSdrh   pNew = sqliteMalloc( sizeof(*pNew) );
444ff78bd2fSdrh   if( pNew==0 ) return 0;
4454305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
4463e7bc9caSdrh   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
447e0048400Sdanielk1977   if( pItem==0 ){
448e0048400Sdanielk1977     sqliteFree(pNew);
449e0048400Sdanielk1977     return 0;
450e0048400Sdanielk1977   }
451145716b3Sdrh   pOldItem = p->a;
452145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
4534b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
454145716b3Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
4556977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
4566977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
4574b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
4584b59ab5eSdrh       ** the names of columns in the result set needs this information */
4594adee20fSdanielk1977       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
4604b59ab5eSdrh     }
4611f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
4626f7adc8aSdrh             || pOldExpr->span.z==0
4639e12800dSdanielk1977             || sqlite3MallocFailed() );
464145716b3Sdrh     pItem->zName = sqliteStrDup(pOldItem->zName);
465145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
466145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
4673e7bc9caSdrh     pItem->done = 0;
468ff78bd2fSdrh   }
469ff78bd2fSdrh   return pNew;
470ff78bd2fSdrh }
47193758c8dSdanielk1977 
47293758c8dSdanielk1977 /*
47393758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
47493758c8dSdanielk1977 ** the build, then none of the following routines, except for
47593758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
47693758c8dSdanielk1977 ** called with a NULL argument.
47793758c8dSdanielk1977 */
4786a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
4796a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
4804adee20fSdanielk1977 SrcList *sqlite3SrcListDup(SrcList *p){
481ad3cab52Sdrh   SrcList *pNew;
482ad3cab52Sdrh   int i;
483113088ecSdrh   int nByte;
484ad3cab52Sdrh   if( p==0 ) return 0;
485113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
4864efc4754Sdrh   pNew = sqliteMallocRaw( nByte );
487ad3cab52Sdrh   if( pNew==0 ) return 0;
4884305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
489ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
4904efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
4914efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
492ed8a3bb1Sdrh     Table *pTab;
4934efc4754Sdrh     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
4944efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
4954efc4754Sdrh     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
4964efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
4974efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
498ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
499ed8a3bb1Sdrh     if( pTab ){
500ed8a3bb1Sdrh       pTab->nRef++;
501a1cb183dSdanielk1977     }
5024adee20fSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
5034adee20fSdanielk1977     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
5044adee20fSdanielk1977     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
5056c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
506ad3cab52Sdrh   }
507ad3cab52Sdrh   return pNew;
508ad3cab52Sdrh }
5094adee20fSdanielk1977 IdList *sqlite3IdListDup(IdList *p){
510ff78bd2fSdrh   IdList *pNew;
511ff78bd2fSdrh   int i;
512ff78bd2fSdrh   if( p==0 ) return 0;
5134efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*pNew) );
514ff78bd2fSdrh   if( pNew==0 ) return 0;
5154305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
5164efc4754Sdrh   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
517d5d56523Sdanielk1977   if( pNew->a==0 ){
518d5d56523Sdanielk1977     sqliteFree(pNew);
519d5d56523Sdanielk1977     return 0;
520d5d56523Sdanielk1977   }
521ff78bd2fSdrh   for(i=0; i<p->nId; i++){
5224efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
5234efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
5244efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5254efc4754Sdrh     pNewItem->idx = pOldItem->idx;
526ff78bd2fSdrh   }
527ff78bd2fSdrh   return pNew;
528ff78bd2fSdrh }
5294adee20fSdanielk1977 Select *sqlite3SelectDup(Select *p){
530ff78bd2fSdrh   Select *pNew;
531ff78bd2fSdrh   if( p==0 ) return 0;
5324efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
533ff78bd2fSdrh   if( pNew==0 ) return 0;
534ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
5354adee20fSdanielk1977   pNew->pEList = sqlite3ExprListDup(p->pEList);
5364adee20fSdanielk1977   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
5374adee20fSdanielk1977   pNew->pWhere = sqlite3ExprDup(p->pWhere);
5384adee20fSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
5394adee20fSdanielk1977   pNew->pHaving = sqlite3ExprDup(p->pHaving);
5404adee20fSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
541ff78bd2fSdrh   pNew->op = p->op;
5424adee20fSdanielk1977   pNew->pPrior = sqlite3SelectDup(p->pPrior);
543a2dc3b1aSdanielk1977   pNew->pLimit = sqlite3ExprDup(p->pLimit);
544a2dc3b1aSdanielk1977   pNew->pOffset = sqlite3ExprDup(p->pOffset);
5457b58daeaSdrh   pNew->iLimit = -1;
5467b58daeaSdrh   pNew->iOffset = -1;
547a1cb183dSdanielk1977   pNew->isResolved = p->isResolved;
548a1cb183dSdanielk1977   pNew->isAgg = p->isAgg;
5498e647b81Sdrh   pNew->usesVirt = 0;
5508e647b81Sdrh   pNew->disallowOrderBy = 0;
5510342b1f5Sdrh   pNew->pRightmost = 0;
5520342b1f5Sdrh   pNew->addrOpenVirt[0] = -1;
5530342b1f5Sdrh   pNew->addrOpenVirt[1] = -1;
5540342b1f5Sdrh   pNew->addrOpenVirt[2] = -1;
555ff78bd2fSdrh   return pNew;
556ff78bd2fSdrh }
55793758c8dSdanielk1977 #else
55893758c8dSdanielk1977 Select *sqlite3SelectDup(Select *p){
55993758c8dSdanielk1977   assert( p==0 );
56093758c8dSdanielk1977   return 0;
56193758c8dSdanielk1977 }
56293758c8dSdanielk1977 #endif
563ff78bd2fSdrh 
564ff78bd2fSdrh 
565ff78bd2fSdrh /*
566a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
567a76b5dfcSdrh ** initially NULL, then create a new expression list.
568a76b5dfcSdrh */
5694adee20fSdanielk1977 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
570a76b5dfcSdrh   if( pList==0 ){
571a76b5dfcSdrh     pList = sqliteMalloc( sizeof(ExprList) );
572a76b5dfcSdrh     if( pList==0 ){
573d5d56523Sdanielk1977       goto no_mem;
574a76b5dfcSdrh     }
5754efc4754Sdrh     assert( pList->nAlloc==0 );
576a76b5dfcSdrh   }
5774305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
578d5d56523Sdanielk1977     struct ExprList_item *a;
579d5d56523Sdanielk1977     int n = pList->nAlloc*2 + 4;
580d5d56523Sdanielk1977     a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
581d5d56523Sdanielk1977     if( a==0 ){
582d5d56523Sdanielk1977       goto no_mem;
583a76b5dfcSdrh     }
584d5d56523Sdanielk1977     pList->a = a;
585d5d56523Sdanielk1977     pList->nAlloc = n;
586a76b5dfcSdrh   }
5874efc4754Sdrh   assert( pList->a!=0 );
5884efc4754Sdrh   if( pExpr || pName ){
5894efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
5904efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
591a99db3b6Sdrh     pItem->zName = sqlite3NameFromToken(pName);
592e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
593a76b5dfcSdrh   }
594a76b5dfcSdrh   return pList;
595d5d56523Sdanielk1977 
596d5d56523Sdanielk1977 no_mem:
597d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
598d5d56523Sdanielk1977   sqlite3ExprDelete(pExpr);
599d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
600d5d56523Sdanielk1977   return 0;
601a76b5dfcSdrh }
602a76b5dfcSdrh 
603a76b5dfcSdrh /*
604a76b5dfcSdrh ** Delete an entire expression list.
605a76b5dfcSdrh */
6064adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
607a76b5dfcSdrh   int i;
608be5c89acSdrh   struct ExprList_item *pItem;
609a76b5dfcSdrh   if( pList==0 ) return;
6101bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
6111bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
612be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
613be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
614be5c89acSdrh     sqliteFree(pItem->zName);
615a76b5dfcSdrh   }
616a76b5dfcSdrh   sqliteFree(pList->a);
617a76b5dfcSdrh   sqliteFree(pList);
618a76b5dfcSdrh }
619a76b5dfcSdrh 
620a76b5dfcSdrh /*
621626a879aSdrh ** Walk an expression tree.  Call xFunc for each node visited.
62273b211abSdrh **
623626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
624626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
625626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
626626a879aSdrh ** the tree walk completely.
627626a879aSdrh **
628626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
629626a879aSdrh ** and 0 to continue.
63087abf5c0Sdrh **
63187abf5c0Sdrh ** NOTICE:  This routine does *not* descend into subqueries.
632626a879aSdrh */
633a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
634626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
635626a879aSdrh   int rc;
636626a879aSdrh   if( pExpr==0 ) return 0;
637626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
638626a879aSdrh   if( rc==0 ){
639626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
640626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
641a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
642626a879aSdrh   }
643626a879aSdrh   return rc>1;
644626a879aSdrh }
645626a879aSdrh 
646626a879aSdrh /*
647a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
648a58fdfb1Sdanielk1977 */
649a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
650a58fdfb1Sdanielk1977   int i;
651a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
652a58fdfb1Sdanielk1977   if( !p ) return 0;
653a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
654a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
655a58fdfb1Sdanielk1977   }
656a58fdfb1Sdanielk1977   return 0;
657a58fdfb1Sdanielk1977 }
658a58fdfb1Sdanielk1977 
659a58fdfb1Sdanielk1977 /*
660a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
661a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
662a58fdfb1Sdanielk1977 ** or OFFSET expressions..
663a58fdfb1Sdanielk1977 */
664a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
665a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
666a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
667a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
668a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
669a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
670a58fdfb1Sdanielk1977   return 0;
671a58fdfb1Sdanielk1977 }
672a58fdfb1Sdanielk1977 
673a58fdfb1Sdanielk1977 
674a58fdfb1Sdanielk1977 /*
675626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
676626a879aSdrh **
677626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
67873b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
67973b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
68073b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
68173b211abSdrh ** then do nothing.
68273b211abSdrh **
68373b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
68473b211abSdrh ** the expression as constant, then we assume the whole expression
68573b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
686626a879aSdrh */
687626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
688626a879aSdrh   switch( pExpr->op ){
689eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
690eb55bd2fSdrh     ** and *pArg==2 */
691eb55bd2fSdrh     case TK_FUNCTION:
692eb55bd2fSdrh       if( *((int*)pArg)==2 ) return 0;
693eb55bd2fSdrh       /* Fall through */
694626a879aSdrh     case TK_ID:
695626a879aSdrh     case TK_COLUMN:
696626a879aSdrh     case TK_DOT:
697626a879aSdrh     case TK_AGG_FUNCTION:
69813449892Sdrh     case TK_AGG_COLUMN:
699fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
700fe2093d7Sdrh     case TK_SELECT:
701fe2093d7Sdrh     case TK_EXISTS:
702fe2093d7Sdrh #endif
703626a879aSdrh       *((int*)pArg) = 0;
704626a879aSdrh       return 2;
70587abf5c0Sdrh     case TK_IN:
70687abf5c0Sdrh       if( pExpr->pSelect ){
70787abf5c0Sdrh         *((int*)pArg) = 0;
70887abf5c0Sdrh         return 2;
70987abf5c0Sdrh       }
710626a879aSdrh     default:
711626a879aSdrh       return 0;
712626a879aSdrh   }
713626a879aSdrh }
714626a879aSdrh 
715626a879aSdrh /*
716fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
717eb55bd2fSdrh ** and 0 if it involves variables or function calls.
7182398937bSdrh **
7192398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
7202398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
7212398937bSdrh ** a constant.
722fef5208cSdrh */
7234adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
724626a879aSdrh   int isConst = 1;
725626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
726626a879aSdrh   return isConst;
727fef5208cSdrh }
728fef5208cSdrh 
729fef5208cSdrh /*
730eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
731eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
732eb55bd2fSdrh ** are any variables.
733eb55bd2fSdrh **
734eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
735eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
736eb55bd2fSdrh ** a constant.
737eb55bd2fSdrh */
738eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
739eb55bd2fSdrh   int isConst = 2;
740eb55bd2fSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
741eb55bd2fSdrh   return isConst!=0;
742eb55bd2fSdrh }
743eb55bd2fSdrh 
744eb55bd2fSdrh /*
74573b211abSdrh ** If the expression p codes a constant integer that is small enough
746202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
747202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
748202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
749e4de1febSdrh */
7504adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
751e4de1febSdrh   switch( p->op ){
752e4de1febSdrh     case TK_INTEGER: {
7532646da7eSdrh       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
754e4de1febSdrh         return 1;
755e4de1febSdrh       }
756202b2df7Sdrh       break;
757202b2df7Sdrh     }
7584b59ab5eSdrh     case TK_UPLUS: {
7594adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
7604b59ab5eSdrh     }
761e4de1febSdrh     case TK_UMINUS: {
762e4de1febSdrh       int v;
7634adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
764e4de1febSdrh         *pValue = -v;
765e4de1febSdrh         return 1;
766e4de1febSdrh       }
767e4de1febSdrh       break;
768e4de1febSdrh     }
769e4de1febSdrh     default: break;
770e4de1febSdrh   }
771e4de1febSdrh   return 0;
772e4de1febSdrh }
773e4de1febSdrh 
774e4de1febSdrh /*
775c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
776c4a3c779Sdrh */
7774adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
7784adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
7794adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
7804adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
781c4a3c779Sdrh   return 0;
782c4a3c779Sdrh }
783c4a3c779Sdrh 
784c4a3c779Sdrh /*
7858141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
7868141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
7878141f61eSdrh ** expression node refer back to that source column.  The following changes
7888141f61eSdrh ** are made to pExpr:
7898141f61eSdrh **
7908141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
7918141f61eSdrh **                         the table.
7928141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
7938141f61eSdrh **                         from pSrcList.
7948141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
7958141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
7968141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
7978141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
7988141f61eSdrh **
7998141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
8008141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
8018141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
8028141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
8038141f61eSdrh ** means that the form of the name is Z and that columns from any table
8048141f61eSdrh ** can be used.
8058141f61eSdrh **
8068141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
8078141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
8088141f61eSdrh */
8098141f61eSdrh static int lookupName(
8108141f61eSdrh   Parse *pParse,       /* The parsing context */
8118141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
8128141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
8138141f61eSdrh   Token *pColumnToken, /* Name of the column. */
814626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
8158141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
8168141f61eSdrh ){
8178141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
8188141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
8198141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
8208141f61eSdrh   int i, j;            /* Loop counters */
8218141f61eSdrh   int cnt = 0;         /* Number of matching column names */
8228141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
8239bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
82451669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
82551669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
82673b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
8278141f61eSdrh 
8288141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
829a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
830a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
831a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
8329e12800dSdanielk1977   if( sqlite3MallocFailed() ){
833d5d56523Sdanielk1977     goto lookupname_end;
8348141f61eSdrh   }
8358141f61eSdrh 
8368141f61eSdrh   pExpr->iTable = -1;
837626a879aSdrh   while( pNC && cnt==0 ){
838ffe07b2dSdrh     ExprList *pEList;
839626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
840626a879aSdrh 
841b3bce662Sdanielk1977     if( pSrcList ){
84251669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
8438141f61eSdrh         Table *pTab = pItem->pTab;
844da184236Sdanielk1977         int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
8458141f61eSdrh         Column *pCol;
8468141f61eSdrh 
8478141f61eSdrh         if( pTab==0 ) continue;
8488141f61eSdrh         assert( pTab->nCol>0 );
8498141f61eSdrh         if( zTab ){
8508141f61eSdrh           if( pItem->zAlias ){
8518141f61eSdrh             char *zTabName = pItem->zAlias;
8524adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
8538141f61eSdrh           }else{
8548141f61eSdrh             char *zTabName = pTab->zName;
8554adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
856da184236Sdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
8578141f61eSdrh               continue;
8588141f61eSdrh             }
8598141f61eSdrh           }
8608141f61eSdrh         }
8618141f61eSdrh         if( 0==(cntTab++) ){
8628141f61eSdrh           pExpr->iTable = pItem->iCursor;
863da184236Sdanielk1977           pExpr->pSchema = pTab->pSchema;
86451669863Sdrh           pMatch = pItem;
8658141f61eSdrh         }
8668141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
8674adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
868b3bf556eSdanielk1977             const char *zColl = pTab->aCol[j].zColl;
869873fac0cSdrh             IdList *pUsing;
8708141f61eSdrh             cnt++;
8718141f61eSdrh             pExpr->iTable = pItem->iCursor;
87251669863Sdrh             pMatch = pItem;
873da184236Sdanielk1977             pExpr->pSchema = pTab->pSchema;
8748141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
8758141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
876a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
877b3bf556eSdanielk1977             pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
878355ef361Sdrh             if( pItem->jointype & JT_NATURAL ){
879355ef361Sdrh               /* If this match occurred in the left table of a natural join,
880355ef361Sdrh               ** then skip the right table to avoid a duplicate match */
881355ef361Sdrh               pItem++;
882355ef361Sdrh               i++;
883355ef361Sdrh             }
884873fac0cSdrh             if( (pUsing = pItem->pUsing)!=0 ){
885873fac0cSdrh               /* If this match occurs on a column that is in the USING clause
886873fac0cSdrh               ** of a join, skip the search of the right table of the join
887873fac0cSdrh               ** to avoid a duplicate match there. */
888873fac0cSdrh               int k;
889873fac0cSdrh               for(k=0; k<pUsing->nId; k++){
890873fac0cSdrh                 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
891873fac0cSdrh                   pItem++;
892873fac0cSdrh                   i++;
893873fac0cSdrh                   break;
894873fac0cSdrh                 }
895873fac0cSdrh               }
896873fac0cSdrh             }
8978141f61eSdrh             break;
8988141f61eSdrh           }
8998141f61eSdrh         }
9008141f61eSdrh       }
901b3bce662Sdanielk1977     }
9028141f61eSdrh 
903b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
9048141f61eSdrh     /* If we have not already resolved the name, then maybe
9058141f61eSdrh     ** it is a new.* or old.* trigger argument reference
9068141f61eSdrh     */
9078141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
9088141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
9098141f61eSdrh       Table *pTab = 0;
9104adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
9118141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
9128141f61eSdrh         assert( pTriggerStack->pTab );
9138141f61eSdrh         pTab = pTriggerStack->pTab;
9144adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
9158141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
9168141f61eSdrh         assert( pTriggerStack->pTab );
9178141f61eSdrh         pTab = pTriggerStack->pTab;
9188141f61eSdrh       }
9198141f61eSdrh 
9208141f61eSdrh       if( pTab ){
921f0113000Sdanielk1977         int iCol;
9228141f61eSdrh         Column *pCol = pTab->aCol;
9238141f61eSdrh 
924da184236Sdanielk1977         pExpr->pSchema = pTab->pSchema;
9258141f61eSdrh         cntTab++;
926f0113000Sdanielk1977         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
9274adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
928f0113000Sdanielk1977             const char *zColl = pTab->aCol[iCol].zColl;
9298141f61eSdrh             cnt++;
930f0113000Sdanielk1977             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
931f0113000Sdanielk1977             pExpr->affinity = pTab->aCol[iCol].affinity;
932b3bf556eSdanielk1977             pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
933aee18ef8Sdanielk1977             pExpr->pTab = pTab;
9348141f61eSdrh             break;
9358141f61eSdrh           }
9368141f61eSdrh         }
9378141f61eSdrh       }
9388141f61eSdrh     }
939b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
9408141f61eSdrh 
9418141f61eSdrh     /*
9428141f61eSdrh     ** Perhaps the name is a reference to the ROWID
9438141f61eSdrh     */
9444adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
9458141f61eSdrh       cnt = 1;
9468141f61eSdrh       pExpr->iColumn = -1;
9478a51256cSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
9488141f61eSdrh     }
9498141f61eSdrh 
9508141f61eSdrh     /*
9518141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
9528141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
9538141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
9548141f61eSdrh     **
9558141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
9568141f61eSdrh     **
9578141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
9588141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
9598141f61eSdrh     ** Note that the expression in the result set should have already been
9608141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
9618141f61eSdrh     */
962ffe07b2dSdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
9638141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
9648141f61eSdrh         char *zAs = pEList->a[j].zName;
9654adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
9668141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
9678141f61eSdrh           pExpr->op = TK_AS;
9688141f61eSdrh           pExpr->iColumn = j;
9694adee20fSdanielk1977           pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
97015ccce1cSdrh           cnt = 1;
9718141f61eSdrh           assert( zTab==0 && zDb==0 );
97215ccce1cSdrh           goto lookupname_end_2;
9738141f61eSdrh         }
9748141f61eSdrh       }
9758141f61eSdrh     }
9768141f61eSdrh 
977626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
978626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
979626a879aSdrh     */
980626a879aSdrh     if( cnt==0 ){
981626a879aSdrh       pNC = pNC->pNext;
982626a879aSdrh     }
983626a879aSdrh   }
984626a879aSdrh 
9858141f61eSdrh   /*
9868141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
9878141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
9888141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
9898141f61eSdrh   ** case, we need to return right away and not make any changes to
9908141f61eSdrh   ** pExpr.
99115ccce1cSdrh   **
99215ccce1cSdrh   ** Because no reference was made to outer contexts, the pNC->nRef
99315ccce1cSdrh   ** fields are not changed in any context.
9948141f61eSdrh   */
9958141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
9968141f61eSdrh     sqliteFree(zCol);
9978141f61eSdrh     return 0;
9988141f61eSdrh   }
9998141f61eSdrh 
10008141f61eSdrh   /*
10018141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
10028141f61eSdrh   ** more matches.  Either way, we have an error.
10038141f61eSdrh   */
10048141f61eSdrh   if( cnt!=1 ){
10058141f61eSdrh     char *z = 0;
10068141f61eSdrh     char *zErr;
10078141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
10088141f61eSdrh     if( zDb ){
1009f93339deSdrh       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
10108141f61eSdrh     }else if( zTab ){
1011f93339deSdrh       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
10128141f61eSdrh     }else{
10138141f61eSdrh       z = sqliteStrDup(zCol);
10148141f61eSdrh     }
10154adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
10168141f61eSdrh     sqliteFree(z);
101773b211abSdrh     pTopNC->nErr++;
10188141f61eSdrh   }
10198141f61eSdrh 
102051669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
102151669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
102251669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
102351669863Sdrh   ** column number is greater than the number of bits in the bitmask
102451669863Sdrh   ** then set the high-order bit of the bitmask.
102551669863Sdrh   */
102651669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
102751669863Sdrh     int n = pExpr->iColumn;
102851669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
102951669863Sdrh       n = sizeof(Bitmask)*8-1;
103051669863Sdrh     }
103151669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
103251669863Sdrh     pMatch->colUsed |= 1<<n;
103351669863Sdrh   }
103451669863Sdrh 
1035d5d56523Sdanielk1977 lookupname_end:
10368141f61eSdrh   /* Clean up and return
10378141f61eSdrh   */
10388141f61eSdrh   sqliteFree(zDb);
10398141f61eSdrh   sqliteFree(zTab);
10404adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
10418141f61eSdrh   pExpr->pLeft = 0;
10424adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
10438141f61eSdrh   pExpr->pRight = 0;
10448141f61eSdrh   pExpr->op = TK_COLUMN;
104515ccce1cSdrh lookupname_end_2:
104615ccce1cSdrh   sqliteFree(zCol);
1047626a879aSdrh   if( cnt==1 ){
1048b3bce662Sdanielk1977     assert( pNC!=0 );
1049626a879aSdrh     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1050aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
1051aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
1052aee18ef8Sdanielk1977     }
105315ccce1cSdrh     /* Increment the nRef value on all name contexts from TopNC up to
105415ccce1cSdrh     ** the point where the name matched. */
105515ccce1cSdrh     for(;;){
105615ccce1cSdrh       assert( pTopNC!=0 );
105715ccce1cSdrh       pTopNC->nRef++;
105815ccce1cSdrh       if( pTopNC==pNC ) break;
105915ccce1cSdrh       pTopNC = pTopNC->pNext;
1060626a879aSdrh     }
106115ccce1cSdrh     return 0;
106215ccce1cSdrh   } else {
106315ccce1cSdrh     return 1;
106415ccce1cSdrh   }
10658141f61eSdrh }
10668141f61eSdrh 
10678141f61eSdrh /*
1068626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1069626a879aSdrh **
107073b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1071626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
107273b211abSdrh ** the tree or 2 to abort the tree walk.
107373b211abSdrh **
107473b211abSdrh ** This routine also does error checking and name resolution for
107573b211abSdrh ** function names.  The operator for aggregate functions is changed
107673b211abSdrh ** to TK_AGG_FUNCTION.
1077626a879aSdrh */
1078626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1079626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1080626a879aSdrh   Parse *pParse;
1081626a879aSdrh 
1082b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1083626a879aSdrh   assert( pNC!=0 );
1084626a879aSdrh   pParse = pNC->pParse;
1085b3bce662Sdanielk1977 
1086626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1087626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1088626a879aSdrh #ifndef NDEBUG
1089f0113000Sdanielk1977   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1090f0113000Sdanielk1977     SrcList *pSrcList = pNC->pSrcList;
1091940fac9dSdanielk1977     int i;
1092f0113000Sdanielk1977     for(i=0; i<pNC->pSrcList->nSrc; i++){
1093626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1094626a879aSdrh     }
1095626a879aSdrh   }
1096626a879aSdrh #endif
1097626a879aSdrh   switch( pExpr->op ){
1098626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1099626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1100626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1101626a879aSdrh     */
1102626a879aSdrh     case TK_STRING: {
1103626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1104626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1105626a879aSdrh     }
1106626a879aSdrh     /* A lone identifier is the name of a column.
1107626a879aSdrh     */
1108626a879aSdrh     case TK_ID: {
1109626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1110626a879aSdrh       return 1;
1111626a879aSdrh     }
1112626a879aSdrh 
1113626a879aSdrh     /* A table name and column name:     ID.ID
1114626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1115626a879aSdrh     */
1116626a879aSdrh     case TK_DOT: {
1117626a879aSdrh       Token *pColumn;
1118626a879aSdrh       Token *pTable;
1119626a879aSdrh       Token *pDb;
1120626a879aSdrh       Expr *pRight;
1121626a879aSdrh 
1122b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1123626a879aSdrh       pRight = pExpr->pRight;
1124626a879aSdrh       if( pRight->op==TK_ID ){
1125626a879aSdrh         pDb = 0;
1126626a879aSdrh         pTable = &pExpr->pLeft->token;
1127626a879aSdrh         pColumn = &pRight->token;
1128626a879aSdrh       }else{
1129626a879aSdrh         assert( pRight->op==TK_DOT );
1130626a879aSdrh         pDb = &pExpr->pLeft->token;
1131626a879aSdrh         pTable = &pRight->pLeft->token;
1132626a879aSdrh         pColumn = &pRight->pRight->token;
1133626a879aSdrh       }
1134626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1135626a879aSdrh       return 1;
1136626a879aSdrh     }
1137626a879aSdrh 
1138626a879aSdrh     /* Resolve function names
1139626a879aSdrh     */
1140b71090fdSdrh     case TK_CONST_FUNC:
1141626a879aSdrh     case TK_FUNCTION: {
1142626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1143626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1144626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1145626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1146626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1147626a879aSdrh       int i;
1148626a879aSdrh       int nId;                    /* Number of characters in function name */
1149626a879aSdrh       const char *zId;            /* The function name. */
115073b211abSdrh       FuncDef *pDef;              /* Information about the function */
115114db2665Sdanielk1977       int enc = ENC(pParse->db);  /* The database encoding */
1152626a879aSdrh 
11532646da7eSdrh       zId = (char*)pExpr->token.z;
1154b71090fdSdrh       nId = pExpr->token.n;
1155626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1156626a879aSdrh       if( pDef==0 ){
1157626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1158626a879aSdrh         if( pDef==0 ){
1159626a879aSdrh           no_such_func = 1;
1160626a879aSdrh         }else{
1161626a879aSdrh           wrong_num_args = 1;
1162626a879aSdrh         }
1163626a879aSdrh       }else{
1164626a879aSdrh         is_agg = pDef->xFunc==0;
1165626a879aSdrh       }
1166626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1167626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1168626a879aSdrh         pNC->nErr++;
1169626a879aSdrh         is_agg = 0;
1170626a879aSdrh       }else if( no_such_func ){
1171626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1172626a879aSdrh         pNC->nErr++;
1173626a879aSdrh       }else if( wrong_num_args ){
1174626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1175626a879aSdrh              nId, zId);
1176626a879aSdrh         pNC->nErr++;
1177626a879aSdrh       }
1178626a879aSdrh       if( is_agg ){
1179626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1180626a879aSdrh         pNC->hasAgg = 1;
1181626a879aSdrh       }
118273b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1183626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
118473b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1185626a879aSdrh       }
118673b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1187626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1188626a879aSdrh       ** type of the function
1189626a879aSdrh       */
1190626a879aSdrh       return is_agg;
1191626a879aSdrh     }
1192b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1193b3bce662Sdanielk1977     case TK_SELECT:
1194b3bce662Sdanielk1977     case TK_EXISTS:
1195b3bce662Sdanielk1977 #endif
1196b3bce662Sdanielk1977     case TK_IN: {
1197b3bce662Sdanielk1977       if( pExpr->pSelect ){
11988a9f38feSdrh         int nRef = pNC->nRef;
119906f6541eSdrh #ifndef SQLITE_OMIT_CHECK
120006f6541eSdrh         if( pNC->isCheck ){
120106f6541eSdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
120206f6541eSdrh         }
120306f6541eSdrh #endif
1204b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1205b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1206b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1207b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1208b3bce662Sdanielk1977         }
1209b3bce662Sdanielk1977       }
12104284fb07Sdrh       break;
1211b3bce662Sdanielk1977     }
12124284fb07Sdrh #ifndef SQLITE_OMIT_CHECK
12134284fb07Sdrh     case TK_VARIABLE: {
12144284fb07Sdrh       if( pNC->isCheck ){
12154284fb07Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
12164284fb07Sdrh       }
12174284fb07Sdrh       break;
12184284fb07Sdrh     }
12194284fb07Sdrh #endif
1220626a879aSdrh   }
1221626a879aSdrh   return 0;
1222626a879aSdrh }
1223626a879aSdrh 
1224626a879aSdrh /*
1225cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1226967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1227aacc543eSdrh ** index to the table in the table list and a column offset.  The
1228aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1229aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1230832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1231aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1232aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1233aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1234aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1235aacc543eSdrh ** alias for ROWID.
123619a775c2Sdrh **
1237626a879aSdrh ** Also resolve function names and check the functions for proper
1238626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1239626a879aSdrh ** have the correct number of arguments.  Leave an error message
1240626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1241626a879aSdrh **
124273b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
124373b211abSdrh ** property on the expression.
1244626a879aSdrh */
1245626a879aSdrh int sqlite3ExprResolveNames(
1246b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1247b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1248626a879aSdrh ){
124913449892Sdrh   int savedHasAgg;
125073b211abSdrh   if( pExpr==0 ) return 0;
125113449892Sdrh   savedHasAgg = pNC->hasAgg;
125213449892Sdrh   pNC->hasAgg = 0;
1253b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1254b3bce662Sdanielk1977   if( pNC->nErr>0 ){
125573b211abSdrh     ExprSetProperty(pExpr, EP_Error);
125673b211abSdrh   }
125713449892Sdrh   if( pNC->hasAgg ){
125813449892Sdrh     ExprSetProperty(pExpr, EP_Agg);
125913449892Sdrh   }else if( savedHasAgg ){
126013449892Sdrh     pNC->hasAgg = 1;
126113449892Sdrh   }
126273b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1263626a879aSdrh }
1264626a879aSdrh 
12651398ad36Sdrh /*
12661398ad36Sdrh ** A pointer instance of this structure is used to pass information
12671398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
12681398ad36Sdrh */
12691398ad36Sdrh typedef struct QueryCoder QueryCoder;
12701398ad36Sdrh struct QueryCoder {
12711398ad36Sdrh   Parse *pParse;       /* The parsing context */
12721398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
12731398ad36Sdrh };
12741398ad36Sdrh 
1275626a879aSdrh 
1276626a879aSdrh /*
12779cbe6352Sdrh ** Generate code for scalar subqueries used as an expression
12789cbe6352Sdrh ** and IN operators.  Examples:
1279626a879aSdrh **
12809cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
12819cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
12829cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
12839cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1284fef5208cSdrh **
12859cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
12869cbe6352Sdrh ** operator or subquery.
1287cce7d176Sdrh */
128851522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1289b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
129057dbd7b3Sdrh   int testAddr = 0;                       /* One-time test address */
1291b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1292b3bce662Sdanielk1977   if( v==0 ) return;
1293b3bce662Sdanielk1977 
129457dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
129557dbd7b3Sdrh   ** if any of the following is true:
129657dbd7b3Sdrh   **
129757dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
129857dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
129957dbd7b3Sdrh   **    *  We are inside a trigger
130057dbd7b3Sdrh   **
130157dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
130257dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1303b3bce662Sdanielk1977   */
1304b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1305b3bce662Sdanielk1977     int mem = pParse->nMem++;
1306b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
130757dbd7b3Sdrh     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
13089e12800dSdanielk1977     assert( testAddr>0 || sqlite3MallocFailed() );
1309d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1310b3bce662Sdanielk1977   }
1311b3bce662Sdanielk1977 
1312cce7d176Sdrh   switch( pExpr->op ){
1313fef5208cSdrh     case TK_IN: {
1314e014a838Sdanielk1977       char affinity;
1315d3d39e93Sdrh       KeyInfo keyInfo;
13169170dd7eSdrh       int addr;        /* Address of OP_OpenVirtual instruction */
1317d3d39e93Sdrh 
1318bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1319e014a838Sdanielk1977 
1320e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
132157dbd7b3Sdrh       ** expression it is handled the same way. A virtual table is
1322e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1323e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1324fef5208cSdrh       **
1325e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1326e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1327e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1328e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1329e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1330e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1331e014a838Sdanielk1977       ** is used.
1332fef5208cSdrh       */
1333832508b7Sdrh       pExpr->iTable = pParse->nTab++;
13349170dd7eSdrh       addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, pExpr->iTable, 0);
1335d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1336d3d39e93Sdrh       keyInfo.nField = 1;
1337f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1338e014a838Sdanielk1977 
1339e014a838Sdanielk1977       if( pExpr->pSelect ){
1340e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1341e014a838Sdanielk1977         **
1342e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1343e014a838Sdanielk1977         ** table allocated and opened above.
1344e014a838Sdanielk1977         */
1345e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1346be5c89acSdrh         ExprList *pEList;
1347e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1348b3bce662Sdanielk1977         sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
1349be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1350be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
13517cedc8d4Sdanielk1977           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
1352be5c89acSdrh               pEList->a[0].pExpr);
13530202b29eSdanielk1977         }
1354fef5208cSdrh       }else if( pExpr->pList ){
1355fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1356fef5208cSdrh         **
1357e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
1358e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1359e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1360e014a838Sdanielk1977         ** a column, use numeric affinity.
1361fef5208cSdrh         */
1362e014a838Sdanielk1977         int i;
136357dbd7b3Sdrh         ExprList *pList = pExpr->pList;
136457dbd7b3Sdrh         struct ExprList_item *pItem;
136557dbd7b3Sdrh 
1366e014a838Sdanielk1977         if( !affinity ){
1367e014a838Sdanielk1977           affinity = SQLITE_AFF_NUMERIC;
1368e014a838Sdanielk1977         }
13690202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1370e014a838Sdanielk1977 
1371e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
137257dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
137357dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1374e014a838Sdanielk1977 
137557dbd7b3Sdrh           /* If the expression is not constant then we will need to
137657dbd7b3Sdrh           ** disable the test that was generated above that makes sure
137757dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
137857dbd7b3Sdrh           ** expression we need to rerun this code each time.
137957dbd7b3Sdrh           */
13806c30be8eSdrh           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
138157dbd7b3Sdrh             VdbeOp *aOp = sqlite3VdbeGetOp(v, testAddr-1);
1382f0113000Sdanielk1977             int j;
1383f0113000Sdanielk1977             for(j=0; j<3; j++){
1384f0113000Sdanielk1977               aOp[j].opcode = OP_Noop;
138557dbd7b3Sdrh             }
138657dbd7b3Sdrh             testAddr = 0;
13874794b980Sdrh           }
1388e014a838Sdanielk1977 
1389e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
13904adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
139194a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1392f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1393fef5208cSdrh         }
1394fef5208cSdrh       }
13950202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1396b3bce662Sdanielk1977       break;
1397fef5208cSdrh     }
1398fef5208cSdrh 
139951522cd3Sdrh     case TK_EXISTS:
140019a775c2Sdrh     case TK_SELECT: {
1401fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1402fef5208cSdrh       ** value of this select in a memory cell and record the number
1403967e8b73Sdrh       ** of the memory cell in iColumn.
1404fef5208cSdrh       */
14052646da7eSdrh       static const Token one = { (u8*)"1", 0, 1 };
140651522cd3Sdrh       Select *pSel;
1407ec7429aeSdrh       int iMem;
1408ec7429aeSdrh       int sop;
14091398ad36Sdrh 
1410ec7429aeSdrh       pExpr->iColumn = iMem = pParse->nMem++;
141151522cd3Sdrh       pSel = pExpr->pSelect;
141251522cd3Sdrh       if( pExpr->op==TK_SELECT ){
141351522cd3Sdrh         sop = SRT_Mem;
1414ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1415ec7429aeSdrh         VdbeComment((v, "# Init subquery result"));
141651522cd3Sdrh       }else{
141751522cd3Sdrh         sop = SRT_Exists;
1418ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1419ec7429aeSdrh         VdbeComment((v, "# Init EXISTS result"));
142051522cd3Sdrh       }
1421ec7429aeSdrh       sqlite3ExprDelete(pSel->pLimit);
1422ec7429aeSdrh       pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
1423ec7429aeSdrh       sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0);
1424b3bce662Sdanielk1977       break;
142519a775c2Sdrh     }
1426cce7d176Sdrh   }
1427b3bce662Sdanielk1977 
142857dbd7b3Sdrh   if( testAddr ){
1429d654be80Sdrh     sqlite3VdbeJumpHere(v, testAddr);
1430b3bce662Sdanielk1977   }
1431b3bce662Sdanielk1977   return;
1432cce7d176Sdrh }
143351522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1434cce7d176Sdrh 
1435cce7d176Sdrh /*
1436fec19aadSdrh ** Generate an instruction that will put the integer describe by
1437fec19aadSdrh ** text z[0..n-1] on the stack.
1438fec19aadSdrh */
1439fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1440fec19aadSdrh   int i;
14416fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
14426fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
14436fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
144429dda4aeSdrh     sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1445fec19aadSdrh   }else{
1446fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1447fec19aadSdrh   }
1448fec19aadSdrh }
1449fec19aadSdrh 
1450fec19aadSdrh /*
1451cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
14521ccde15dSdrh ** expression and leave the result on the top of stack.
1453f2bc013cSdrh **
1454f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1455f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1456f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1457f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1458f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1459cce7d176Sdrh */
14604adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1461cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1462cce7d176Sdrh   int op;
1463ffe07b2dSdrh   int stackChng = 1;    /* Amount of change to stack depth */
1464ffe07b2dSdrh 
14657977a17fSdanielk1977   if( v==0 ) return;
14667977a17fSdanielk1977   if( pExpr==0 ){
1467f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
14687977a17fSdanielk1977     return;
14697977a17fSdanielk1977   }
1470f2bc013cSdrh   op = pExpr->op;
1471f2bc013cSdrh   switch( op ){
147213449892Sdrh     case TK_AGG_COLUMN: {
147313449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
147413449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
147513449892Sdrh       if( !pAggInfo->directMode ){
147613449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
147713449892Sdrh         break;
147813449892Sdrh       }else if( pAggInfo->useSortingIdx ){
147913449892Sdrh         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
148013449892Sdrh                               pCol->iSorterColumn);
148113449892Sdrh         break;
148213449892Sdrh       }
148313449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
148413449892Sdrh     }
1485967e8b73Sdrh     case TK_COLUMN: {
1486ffe07b2dSdrh       if( pExpr->iTable<0 ){
1487ffe07b2dSdrh         /* This only happens when coding check constraints */
1488ffe07b2dSdrh         assert( pParse->ckOffset>0 );
1489ffe07b2dSdrh         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1490ffe07b2dSdrh       }else if( pExpr->iColumn>=0 ){
14918a51256cSdrh         Table *pTab = pExpr->pTab;
14928a51256cSdrh         int iCol = pExpr->iColumn;
14938a51256cSdrh         sqlite3VdbeAddOp(v, OP_Column, pExpr->iTable, iCol);
14948a51256cSdrh         sqlite3ColumnDefault(v, pTab, iCol);
14958a51256cSdrh #ifndef SQLITE_OMIT_FLOATING_POINT
14968a51256cSdrh         if( pTab && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
14978a51256cSdrh           sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
14988a51256cSdrh         }
14998a51256cSdrh #endif
1500c4a3c779Sdrh       }else{
1501f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Rowid, pExpr->iTable, 0);
15022282792aSdrh       }
1503cce7d176Sdrh       break;
1504cce7d176Sdrh     }
1505cce7d176Sdrh     case TK_INTEGER: {
15062646da7eSdrh       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1507fec19aadSdrh       break;
150851e9a445Sdrh     }
1509fec19aadSdrh     case TK_FLOAT:
1510fec19aadSdrh     case TK_STRING: {
1511f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1512f2bc013cSdrh       assert( TK_STRING==OP_String8 );
1513d2687b77Sdrh       sqlite3DequoteExpr(pExpr);
15142646da7eSdrh       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1515cce7d176Sdrh       break;
1516cce7d176Sdrh     }
1517f0863fe5Sdrh     case TK_NULL: {
1518f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1519f0863fe5Sdrh       break;
1520f0863fe5Sdrh     }
15215338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1522c572ef7fSdanielk1977     case TK_BLOB: {
15236c8c6cecSdrh       int n;
15246c8c6cecSdrh       const char *z;
1525f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
15266c8c6cecSdrh       n = pExpr->token.n - 3;
15272646da7eSdrh       z = (char*)pExpr->token.z + 2;
15286c8c6cecSdrh       assert( n>=0 );
15296c8c6cecSdrh       if( n==0 ){
15306c8c6cecSdrh         z = "";
15316c8c6cecSdrh       }
15326c8c6cecSdrh       sqlite3VdbeOp3(v, op, 0, 0, z, n);
1533c572ef7fSdanielk1977       break;
1534c572ef7fSdanielk1977     }
15355338a5f7Sdanielk1977 #endif
153650457896Sdrh     case TK_VARIABLE: {
15374adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1538895d7472Sdrh       if( pExpr->token.n>1 ){
15392646da7eSdrh         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1540895d7472Sdrh       }
154150457896Sdrh       break;
154250457896Sdrh     }
15434e0cff60Sdrh     case TK_REGISTER: {
15444e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
15454e0cff60Sdrh       break;
15464e0cff60Sdrh     }
1547487e262fSdrh #ifndef SQLITE_OMIT_CAST
1548487e262fSdrh     case TK_CAST: {
1549487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
1550f0113000Sdanielk1977       int aff, to_op;
1551487e262fSdrh       sqlite3ExprCode(pParse, pExpr->pLeft);
15528a51256cSdrh       aff = sqlite3AffinityType(&pExpr->token);
1553f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1554f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
1555f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
1556f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1557f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
1558f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
1559f0113000Sdanielk1977       sqlite3VdbeAddOp(v, to_op, 0, 0);
1560ffe07b2dSdrh       stackChng = 0;
1561487e262fSdrh       break;
1562487e262fSdrh     }
1563487e262fSdrh #endif /* SQLITE_OMIT_CAST */
1564c9b84a1fSdrh     case TK_LT:
1565c9b84a1fSdrh     case TK_LE:
1566c9b84a1fSdrh     case TK_GT:
1567c9b84a1fSdrh     case TK_GE:
1568c9b84a1fSdrh     case TK_NE:
1569c9b84a1fSdrh     case TK_EQ: {
1570f2bc013cSdrh       assert( TK_LT==OP_Lt );
1571f2bc013cSdrh       assert( TK_LE==OP_Le );
1572f2bc013cSdrh       assert( TK_GT==OP_Gt );
1573f2bc013cSdrh       assert( TK_GE==OP_Ge );
1574f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1575f2bc013cSdrh       assert( TK_NE==OP_Ne );
1576a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1577a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1578be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1579ffe07b2dSdrh       stackChng = -1;
1580a37cdde0Sdanielk1977       break;
1581c9b84a1fSdrh     }
1582cce7d176Sdrh     case TK_AND:
1583cce7d176Sdrh     case TK_OR:
1584cce7d176Sdrh     case TK_PLUS:
1585cce7d176Sdrh     case TK_STAR:
1586cce7d176Sdrh     case TK_MINUS:
1587bf4133cbSdrh     case TK_REM:
1588bf4133cbSdrh     case TK_BITAND:
1589bf4133cbSdrh     case TK_BITOR:
159017c40294Sdrh     case TK_SLASH:
1591bf4133cbSdrh     case TK_LSHIFT:
1592855eb1cfSdrh     case TK_RSHIFT:
15930040077dSdrh     case TK_CONCAT: {
1594f2bc013cSdrh       assert( TK_AND==OP_And );
1595f2bc013cSdrh       assert( TK_OR==OP_Or );
1596f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1597f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1598f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1599f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1600f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1601f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1602f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1603f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1604f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
16054adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16064adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1607855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
1608ffe07b2dSdrh       stackChng = -1;
16090040077dSdrh       break;
16100040077dSdrh     }
1611cce7d176Sdrh     case TK_UMINUS: {
1612fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1613fec19aadSdrh       assert( pLeft );
1614fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1615fec19aadSdrh         Token *p = &pLeft->token;
16169267bdceSdrh         char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
1617fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1618fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1619e6840900Sdrh         }else{
1620fec19aadSdrh           codeInteger(v, z, p->n+1);
1621e6840900Sdrh         }
16226e142f54Sdrh         sqliteFree(z);
16236e142f54Sdrh         break;
16246e142f54Sdrh       }
16251ccde15dSdrh       /* Fall through into TK_NOT */
16266e142f54Sdrh     }
1627bf4133cbSdrh     case TK_BITNOT:
16286e142f54Sdrh     case TK_NOT: {
1629f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1630f2bc013cSdrh       assert( TK_NOT==OP_Not );
16314adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16324adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1633ffe07b2dSdrh       stackChng = 0;
1634cce7d176Sdrh       break;
1635cce7d176Sdrh     }
1636cce7d176Sdrh     case TK_ISNULL:
1637cce7d176Sdrh     case TK_NOTNULL: {
1638cce7d176Sdrh       int dest;
1639f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1640f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
16414adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
16424adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16434adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
16444adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
16454adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1646ffe07b2dSdrh       stackChng = 0;
1647a37cdde0Sdanielk1977       break;
1648f2bc013cSdrh     }
16492282792aSdrh     case TK_AGG_FUNCTION: {
165013449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
16517e56e711Sdrh       if( pInfo==0 ){
16527e56e711Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
16537e56e711Sdrh             &pExpr->span);
16547e56e711Sdrh       }else{
165513449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
16567e56e711Sdrh       }
16572282792aSdrh       break;
16582282792aSdrh     }
1659b71090fdSdrh     case TK_CONST_FUNC:
1660cce7d176Sdrh     case TK_FUNCTION: {
1661cce7d176Sdrh       ExprList *pList = pExpr->pList;
166289425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
16630bce8354Sdrh       FuncDef *pDef;
16644b59ab5eSdrh       int nId;
16654b59ab5eSdrh       const char *zId;
166613449892Sdrh       int constMask = 0;
1667682f68b0Sdanielk1977       int i;
166814db2665Sdanielk1977       u8 enc = ENC(pParse->db);
1669dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
16702646da7eSdrh       zId = (char*)pExpr->token.z;
1671b71090fdSdrh       nId = pExpr->token.n;
1672d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
16730bce8354Sdrh       assert( pDef!=0 );
1674f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1675682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1676d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
167713449892Sdrh           constMask |= (1<<i);
1678d02eb1fdSdanielk1977         }
1679dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1680dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1681dc1bdc4fSdanielk1977         }
1682dc1bdc4fSdanielk1977       }
1683dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1684dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1685d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1686682f68b0Sdanielk1977       }
168713449892Sdrh       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1688ffe07b2dSdrh       stackChng = 1-nExpr;
16896ec2733bSdrh       break;
16906ec2733bSdrh     }
1691fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1692fe2093d7Sdrh     case TK_EXISTS:
169319a775c2Sdrh     case TK_SELECT: {
1694b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
16954adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1696ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
169719a775c2Sdrh       break;
169819a775c2Sdrh     }
1699fef5208cSdrh     case TK_IN: {
1700fef5208cSdrh       int addr;
170194a11211Sdrh       char affinity;
1702*afa5f680Sdrh       int ckOffset = pParse->ckOffset;
1703b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
1704e014a838Sdanielk1977 
1705e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1706e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1707ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1708e014a838Sdanielk1977       */
170994a11211Sdrh       affinity = comparisonAffinity(pExpr);
1710e014a838Sdanielk1977 
17114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1712*afa5f680Sdrh       pParse->ckOffset = ckOffset+1;
1713e014a838Sdanielk1977 
1714e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1715e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1716e014a838Sdanielk1977       */
17174adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17184adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1719e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
17204adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
1721f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1722e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
172394a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
1724e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1725e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1726e014a838Sdanielk1977 
1727fef5208cSdrh       break;
1728fef5208cSdrh     }
172993758c8dSdanielk1977 #endif
1730fef5208cSdrh     case TK_BETWEEN: {
1731be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1732be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1733be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1734be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
17354adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1736be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1737be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
17384adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1739be5c89acSdrh       pLItem++;
1740be5c89acSdrh       pRight = pLItem->pExpr;
1741be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1742be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
17434adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1744fef5208cSdrh       break;
1745fef5208cSdrh     }
174651e9a445Sdrh     case TK_UPLUS:
1747a2e00042Sdrh     case TK_AS: {
17484adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1749ffe07b2dSdrh       stackChng = 0;
1750a2e00042Sdrh       break;
1751a2e00042Sdrh     }
175217a7f8ddSdrh     case TK_CASE: {
175317a7f8ddSdrh       int expr_end_label;
1754f5905aa7Sdrh       int jumpInst;
1755f5905aa7Sdrh       int nExpr;
175617a7f8ddSdrh       int i;
1757be5c89acSdrh       ExprList *pEList;
1758be5c89acSdrh       struct ExprList_item *aListelem;
175917a7f8ddSdrh 
176017a7f8ddSdrh       assert(pExpr->pList);
176117a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
176217a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1763be5c89acSdrh       pEList = pExpr->pList;
1764be5c89acSdrh       aListelem = pEList->a;
1765be5c89acSdrh       nExpr = pEList->nExpr;
17664adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
176717a7f8ddSdrh       if( pExpr->pLeft ){
17684adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1769cce7d176Sdrh       }
1770f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1771be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
177217a7f8ddSdrh         if( pExpr->pLeft ){
17734adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1774be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1775be5c89acSdrh                                  OP_Ne, 0, 1);
17764adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1777f5905aa7Sdrh         }else{
17784adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
177917a7f8ddSdrh         }
1780be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
17814adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
1782d654be80Sdrh         sqlite3VdbeJumpHere(v, jumpInst);
178317a7f8ddSdrh       }
1784f570f011Sdrh       if( pExpr->pLeft ){
17854adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1786f570f011Sdrh       }
178717a7f8ddSdrh       if( pExpr->pRight ){
17884adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
178917a7f8ddSdrh       }else{
1790f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
179117a7f8ddSdrh       }
17924adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
17936f34903eSdanielk1977       break;
17946f34903eSdanielk1977     }
17955338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
17966f34903eSdanielk1977     case TK_RAISE: {
17976f34903eSdanielk1977       if( !pParse->trigStack ){
17984adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1799da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
18006f34903eSdanielk1977 	return;
18016f34903eSdanielk1977       }
1802ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
1803ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
18046f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
1805ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
1806d2687b77Sdrh          sqlite3DequoteExpr(pExpr);
18074adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
18082646da7eSdrh                         (char*)pExpr->token.z, pExpr->token.n);
18096f34903eSdanielk1977       } else {
18106f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
1811344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
1812ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
1813ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
18146f34903eSdanielk1977       }
1815ffe07b2dSdrh       stackChng = 0;
1816ffe07b2dSdrh       break;
181717a7f8ddSdrh     }
18185338a5f7Sdanielk1977 #endif
1819ffe07b2dSdrh   }
1820ffe07b2dSdrh 
1821ffe07b2dSdrh   if( pParse->ckOffset ){
1822ffe07b2dSdrh     pParse->ckOffset += stackChng;
1823ffe07b2dSdrh     assert( pParse->ckOffset );
182417a7f8ddSdrh   }
1825cce7d176Sdrh }
1826cce7d176Sdrh 
182793758c8dSdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
1828cce7d176Sdrh /*
182925303780Sdrh ** Generate code that evalutes the given expression and leaves the result
183025303780Sdrh ** on the stack.  See also sqlite3ExprCode().
183125303780Sdrh **
183225303780Sdrh ** This routine might also cache the result and modify the pExpr tree
183325303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
183425303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
183525303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
183625303780Sdrh ** memory location.
183725303780Sdrh */
183825303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
183925303780Sdrh   Vdbe *v = pParse->pVdbe;
184025303780Sdrh   int iMem;
184125303780Sdrh   int addr1, addr2;
184225303780Sdrh   if( v==0 ) return;
184325303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
184425303780Sdrh   sqlite3ExprCode(pParse, pExpr);
184525303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
184625303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
184725303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
184825303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
184925303780Sdrh     pExpr->op = TK_REGISTER;
185025303780Sdrh   }
185125303780Sdrh }
185293758c8dSdanielk1977 #endif
185325303780Sdrh 
185425303780Sdrh /*
1855268380caSdrh ** Generate code that pushes the value of every element of the given
1856f9b596ebSdrh ** expression list onto the stack.
1857268380caSdrh **
1858268380caSdrh ** Return the number of elements pushed onto the stack.
1859268380caSdrh */
18604adee20fSdanielk1977 int sqlite3ExprCodeExprList(
1861268380caSdrh   Parse *pParse,     /* Parsing context */
1862f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
1863268380caSdrh ){
1864268380caSdrh   struct ExprList_item *pItem;
1865268380caSdrh   int i, n;
1866268380caSdrh   if( pList==0 ) return 0;
1867268380caSdrh   n = pList->nExpr;
1868c182d163Sdrh   for(pItem=pList->a, i=n; i>0; i--, pItem++){
18694adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
1870268380caSdrh   }
1871f9b596ebSdrh   return n;
1872268380caSdrh }
1873268380caSdrh 
1874268380caSdrh /*
1875cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
1876cce7d176Sdrh ** to the label "dest" if the expression is true but execution
1877cce7d176Sdrh ** continues straight thru if the expression is false.
1878f5905aa7Sdrh **
1879f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
1880f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
1881f2bc013cSdrh **
1882f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1883f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1884f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1885f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1886f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1887cce7d176Sdrh */
18884adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1889cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1890cce7d176Sdrh   int op = 0;
1891ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
1892daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1893f2bc013cSdrh   op = pExpr->op;
1894f2bc013cSdrh   switch( op ){
1895cce7d176Sdrh     case TK_AND: {
18964adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
18974adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
18984adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
18994adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1900cce7d176Sdrh       break;
1901cce7d176Sdrh     }
1902cce7d176Sdrh     case TK_OR: {
19034adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
19044adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1905cce7d176Sdrh       break;
1906cce7d176Sdrh     }
1907cce7d176Sdrh     case TK_NOT: {
19084adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1909cce7d176Sdrh       break;
1910cce7d176Sdrh     }
1911cce7d176Sdrh     case TK_LT:
1912cce7d176Sdrh     case TK_LE:
1913cce7d176Sdrh     case TK_GT:
1914cce7d176Sdrh     case TK_GE:
1915cce7d176Sdrh     case TK_NE:
19160ac65892Sdrh     case TK_EQ: {
1917f2bc013cSdrh       assert( TK_LT==OP_Lt );
1918f2bc013cSdrh       assert( TK_LE==OP_Le );
1919f2bc013cSdrh       assert( TK_GT==OP_Gt );
1920f2bc013cSdrh       assert( TK_GE==OP_Ge );
1921f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1922f2bc013cSdrh       assert( TK_NE==OP_Ne );
19234adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19244adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1925be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
1926cce7d176Sdrh       break;
1927cce7d176Sdrh     }
1928cce7d176Sdrh     case TK_ISNULL:
1929cce7d176Sdrh     case TK_NOTNULL: {
1930f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1931f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
19324adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19334adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
1934cce7d176Sdrh       break;
1935cce7d176Sdrh     }
1936fef5208cSdrh     case TK_BETWEEN: {
19370202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
19380202b29eSdanielk1977       **
19390202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
19400202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
19410202b29eSdanielk1977       ** 3 ...
19420202b29eSdanielk1977       */
1943f5905aa7Sdrh       int addr;
1944be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1945be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
1946be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
19474adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1948be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1949be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
19500202b29eSdanielk1977 
1951be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
1952be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1953be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
19540202b29eSdanielk1977 
19554adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
1956d654be80Sdrh       sqlite3VdbeJumpHere(v, addr);
19574adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1958fef5208cSdrh       break;
1959fef5208cSdrh     }
1960cce7d176Sdrh     default: {
19614adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
19624adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
1963cce7d176Sdrh       break;
1964cce7d176Sdrh     }
1965cce7d176Sdrh   }
1966ffe07b2dSdrh   pParse->ckOffset = ckOffset;
1967cce7d176Sdrh }
1968cce7d176Sdrh 
1969cce7d176Sdrh /*
197066b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
1971cce7d176Sdrh ** to the label "dest" if the expression is false but execution
1972cce7d176Sdrh ** continues straight thru if the expression is true.
1973f5905aa7Sdrh **
1974f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
1975f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
1976cce7d176Sdrh */
19774adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1978cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1979cce7d176Sdrh   int op = 0;
1980ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
1981daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1982f2bc013cSdrh 
1983f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
1984f2bc013cSdrh   **
1985f2bc013cSdrh   **       pExpr->op            op
1986f2bc013cSdrh   **       ---------          ----------
1987f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
1988f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
1989f2bc013cSdrh   **       TK_NE              OP_Eq
1990f2bc013cSdrh   **       TK_EQ              OP_Ne
1991f2bc013cSdrh   **       TK_GT              OP_Le
1992f2bc013cSdrh   **       TK_LE              OP_Gt
1993f2bc013cSdrh   **       TK_GE              OP_Lt
1994f2bc013cSdrh   **       TK_LT              OP_Ge
1995f2bc013cSdrh   **
1996f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
1997f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
1998f2bc013cSdrh   ** can compute the mapping above using the following expression.
1999f2bc013cSdrh   ** Assert()s verify that the computation is correct.
2000f2bc013cSdrh   */
2001f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2002f2bc013cSdrh 
2003f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
2004f2bc013cSdrh   */
2005f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2006f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2007f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
2008f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
2009f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
2010f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
2011f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
2012f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
2013f2bc013cSdrh 
2014cce7d176Sdrh   switch( pExpr->op ){
2015cce7d176Sdrh     case TK_AND: {
20164adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
20174adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2018cce7d176Sdrh       break;
2019cce7d176Sdrh     }
2020cce7d176Sdrh     case TK_OR: {
20214adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
20224adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
20234adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
20244adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2025cce7d176Sdrh       break;
2026cce7d176Sdrh     }
2027cce7d176Sdrh     case TK_NOT: {
20284adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2029cce7d176Sdrh       break;
2030cce7d176Sdrh     }
2031cce7d176Sdrh     case TK_LT:
2032cce7d176Sdrh     case TK_LE:
2033cce7d176Sdrh     case TK_GT:
2034cce7d176Sdrh     case TK_GE:
2035cce7d176Sdrh     case TK_NE:
2036cce7d176Sdrh     case TK_EQ: {
20374adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20384adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2039be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2040cce7d176Sdrh       break;
2041cce7d176Sdrh     }
2042cce7d176Sdrh     case TK_ISNULL:
2043cce7d176Sdrh     case TK_NOTNULL: {
20444adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20454adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2046cce7d176Sdrh       break;
2047cce7d176Sdrh     }
2048fef5208cSdrh     case TK_BETWEEN: {
20490202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
20500202b29eSdanielk1977       **
20510202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
20520202b29eSdanielk1977       ** 2 GOTO <dest>
20530202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
20540202b29eSdanielk1977       */
2055fef5208cSdrh       int addr;
2056be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2057be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2058be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
20594adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2060be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
20614adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
2062be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2063be5c89acSdrh 
20644adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
20654adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2066be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2067be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2068be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2069fef5208cSdrh       break;
2070fef5208cSdrh     }
2071cce7d176Sdrh     default: {
20724adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
20734adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2074cce7d176Sdrh       break;
2075cce7d176Sdrh     }
2076cce7d176Sdrh   }
2077ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2078cce7d176Sdrh }
20792282792aSdrh 
20802282792aSdrh /*
20812282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
20822282792aSdrh ** if they are identical and return FALSE if they differ in any way.
20832282792aSdrh */
20844adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
20852282792aSdrh   int i;
20864b202ae2Sdanielk1977   if( pA==0||pB==0 ){
20874b202ae2Sdanielk1977     return pB==pA;
20882282792aSdrh   }
20892282792aSdrh   if( pA->op!=pB->op ) return 0;
2090fd357974Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
20914adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
20924adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
20932282792aSdrh   if( pA->pList ){
20942282792aSdrh     if( pB->pList==0 ) return 0;
20952282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
20962282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
20974adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
20982282792aSdrh         return 0;
20992282792aSdrh       }
21002282792aSdrh     }
21012282792aSdrh   }else if( pB->pList ){
21022282792aSdrh     return 0;
21032282792aSdrh   }
21042282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
21052f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
21062282792aSdrh   if( pA->token.z ){
21072282792aSdrh     if( pB->token.z==0 ) return 0;
21086977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
21092646da7eSdrh     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
21102646da7eSdrh       return 0;
21112646da7eSdrh     }
21122282792aSdrh   }
21132282792aSdrh   return 1;
21142282792aSdrh }
21152282792aSdrh 
211613449892Sdrh 
21172282792aSdrh /*
211813449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
211913449892Sdrh ** the new element.  Return a negative number if malloc fails.
21202282792aSdrh */
212113449892Sdrh static int addAggInfoColumn(AggInfo *pInfo){
212213449892Sdrh   int i;
212313449892Sdrh   i = sqlite3ArrayAllocate((void**)&pInfo->aCol, sizeof(pInfo->aCol[0]), 3);
212413449892Sdrh   if( i<0 ){
21252282792aSdrh     return -1;
21262282792aSdrh   }
212713449892Sdrh   return i;
21282282792aSdrh }
212913449892Sdrh 
213013449892Sdrh /*
213113449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
213213449892Sdrh ** the new element.  Return a negative number if malloc fails.
213313449892Sdrh */
213413449892Sdrh static int addAggInfoFunc(AggInfo *pInfo){
213513449892Sdrh   int i;
213613449892Sdrh   i = sqlite3ArrayAllocate((void**)&pInfo->aFunc, sizeof(pInfo->aFunc[0]), 2);
213713449892Sdrh   if( i<0 ){
213813449892Sdrh     return -1;
213913449892Sdrh   }
214013449892Sdrh   return i;
21412282792aSdrh }
21422282792aSdrh 
21432282792aSdrh /*
2144626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
2145626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2146626a879aSdrh ** for additional information.
21472282792aSdrh **
2148626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
21492282792aSdrh */
2150626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
21512282792aSdrh   int i;
2152a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
2153a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
2154a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
215513449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
215613449892Sdrh 
21572282792aSdrh 
21582282792aSdrh   switch( pExpr->op ){
2159967e8b73Sdrh     case TK_COLUMN: {
216013449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
216113449892Sdrh       ** clause of the aggregate query */
216213449892Sdrh       if( pSrcList ){
216313449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
216413449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
216513449892Sdrh           struct AggInfo_col *pCol;
216613449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
216713449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
216813449892Sdrh             ** that is in the FROM clause of the aggregate query.
216913449892Sdrh             **
217013449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
217113449892Sdrh             ** is not an entry there already.
217213449892Sdrh             */
217313449892Sdrh             pCol = pAggInfo->aCol;
217413449892Sdrh             for(i=0; i<pAggInfo->nColumn; i++, pCol++){
217513449892Sdrh               if( pCol->iTable==pExpr->iTable &&
217613449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
21772282792aSdrh                 break;
21782282792aSdrh               }
21792282792aSdrh             }
218013449892Sdrh             if( i>=pAggInfo->nColumn && (i = addAggInfoColumn(pAggInfo))>=0 ){
218113449892Sdrh               pCol = &pAggInfo->aCol[i];
218213449892Sdrh               pCol->iTable = pExpr->iTable;
218313449892Sdrh               pCol->iColumn = pExpr->iColumn;
218413449892Sdrh               pCol->iMem = pParse->nMem++;
218513449892Sdrh               pCol->iSorterColumn = -1;
21865774b806Sdrh               pCol->pExpr = pExpr;
218713449892Sdrh               if( pAggInfo->pGroupBy ){
218813449892Sdrh                 int j, n;
218913449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
219013449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
219113449892Sdrh                 n = pGB->nExpr;
219213449892Sdrh                 for(j=0; j<n; j++, pTerm++){
219313449892Sdrh                   Expr *pE = pTerm->pExpr;
219413449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
219513449892Sdrh                       pE->iColumn==pExpr->iColumn ){
219613449892Sdrh                     pCol->iSorterColumn = j;
219713449892Sdrh                     break;
21982282792aSdrh                   }
219913449892Sdrh                 }
220013449892Sdrh               }
220113449892Sdrh               if( pCol->iSorterColumn<0 ){
220213449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
220313449892Sdrh               }
220413449892Sdrh             }
220513449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
220613449892Sdrh             ** because it was there before or because we just created it).
220713449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
220813449892Sdrh             ** pAggInfo->aCol[] entry.
220913449892Sdrh             */
221013449892Sdrh             pExpr->pAggInfo = pAggInfo;
221113449892Sdrh             pExpr->op = TK_AGG_COLUMN;
2212aaf88729Sdrh             pExpr->iAgg = i;
221313449892Sdrh             break;
221413449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
221513449892Sdrh         } /* end loop over pSrcList */
2216a58fdfb1Sdanielk1977       }
2217626a879aSdrh       return 1;
22182282792aSdrh     }
22192282792aSdrh     case TK_AGG_FUNCTION: {
222013449892Sdrh       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
222113449892Sdrh       ** to be ignored */
2222a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
222313449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
222413449892Sdrh         ** function that is already in the pAggInfo structure
222513449892Sdrh         */
222613449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
222713449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
222813449892Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
22292282792aSdrh             break;
22302282792aSdrh           }
22312282792aSdrh         }
223213449892Sdrh         if( i>=pAggInfo->nFunc ){
223313449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
223413449892Sdrh           */
223514db2665Sdanielk1977           u8 enc = ENC(pParse->db);
223613449892Sdrh           i = addAggInfoFunc(pAggInfo);
223713449892Sdrh           if( i>=0 ){
223813449892Sdrh             pItem = &pAggInfo->aFunc[i];
223913449892Sdrh             pItem->pExpr = pExpr;
224013449892Sdrh             pItem->iMem = pParse->nMem++;
224113449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
22422646da7eSdrh                    (char*)pExpr->token.z, pExpr->token.n,
2243d8123366Sdanielk1977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2244fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
2245fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
2246fd357974Sdrh             }else{
2247fd357974Sdrh               pItem->iDistinct = -1;
2248fd357974Sdrh             }
22492282792aSdrh           }
225013449892Sdrh         }
225113449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
225213449892Sdrh         */
22532282792aSdrh         pExpr->iAgg = i;
225413449892Sdrh         pExpr->pAggInfo = pAggInfo;
2255626a879aSdrh         return 1;
22562282792aSdrh       }
22572282792aSdrh     }
2258a58fdfb1Sdanielk1977   }
225913449892Sdrh 
226013449892Sdrh   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
226113449892Sdrh   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
226213449892Sdrh   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
226313449892Sdrh   */
2264a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
2265a58fdfb1Sdanielk1977     pNC->nDepth++;
2266a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2267a58fdfb1Sdanielk1977     pNC->nDepth--;
2268a58fdfb1Sdanielk1977   }
2269626a879aSdrh   return 0;
22702282792aSdrh }
2271626a879aSdrh 
2272626a879aSdrh /*
2273626a879aSdrh ** Analyze the given expression looking for aggregate functions and
2274626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
2275626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
2276626a879aSdrh **
2277626a879aSdrh ** This routine should only be called after the expression has been
2278626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
2279626a879aSdrh **
2280626a879aSdrh ** If errors are seen, leave an error message in zErrMsg and return
2281626a879aSdrh ** the number of errors.
2282626a879aSdrh */
2283a58fdfb1Sdanielk1977 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2284a58fdfb1Sdanielk1977   int nErr = pNC->pParse->nErr;
2285a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
2286a58fdfb1Sdanielk1977   return pNC->pParse->nErr - nErr;
22872282792aSdrh }
22885d9a4af9Sdrh 
22895d9a4af9Sdrh /*
22905d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
22915d9a4af9Sdrh ** expression list.  Return the number of errors.
22925d9a4af9Sdrh **
22935d9a4af9Sdrh ** If an error is found, the analysis is cut short.
22945d9a4af9Sdrh */
22955d9a4af9Sdrh int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
22965d9a4af9Sdrh   struct ExprList_item *pItem;
22975d9a4af9Sdrh   int i;
22985d9a4af9Sdrh   int nErr = 0;
22995d9a4af9Sdrh   if( pList ){
23005d9a4af9Sdrh     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
23015d9a4af9Sdrh       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
23025d9a4af9Sdrh     }
23035d9a4af9Sdrh   }
23045d9a4af9Sdrh   return nErr;
23055d9a4af9Sdrh }
2306