xref: /sqlite-3.40.0/src/expr.c (revision a1644fd8)
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*a1644fd8Sdanielk1977 ** $Id: expr.c,v 1.309 2007/08/29 12:31:26 danielk1977 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_SELECT ){
39bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
40a37cdde0Sdanielk1977   }
41487e262fSdrh #ifndef SQLITE_OMIT_CAST
42487e262fSdrh   if( op==TK_CAST ){
438a51256cSdrh     return sqlite3AffinityType(&pExpr->token);
44487e262fSdrh   }
45487e262fSdrh #endif
46a37cdde0Sdanielk1977   return pExpr->affinity;
47a37cdde0Sdanielk1977 }
48a37cdde0Sdanielk1977 
4953db1458Sdrh /*
508b4c40d8Sdrh ** Set the collating sequence for expression pExpr to be the collating
518b4c40d8Sdrh ** sequence named by pToken.   Return a pointer to the revised expression.
52a34001c9Sdrh ** The collating sequence is marked as "explicit" using the EP_ExpCollate
53a34001c9Sdrh ** flag.  An explicit collating sequence will override implicit
54a34001c9Sdrh ** collating sequences.
558b4c40d8Sdrh */
568b4c40d8Sdrh Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
578b4c40d8Sdrh   CollSeq *pColl;
588b4c40d8Sdrh   if( pExpr==0 ) return 0;
598b4c40d8Sdrh   pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
608b4c40d8Sdrh   if( pColl ){
618b4c40d8Sdrh     pExpr->pColl = pColl;
628b4c40d8Sdrh     pExpr->flags |= EP_ExpCollate;
638b4c40d8Sdrh   }
648b4c40d8Sdrh   return pExpr;
658b4c40d8Sdrh }
668b4c40d8Sdrh 
678b4c40d8Sdrh /*
680202b29eSdanielk1977 ** Return the default collation sequence for the expression pExpr. If
690202b29eSdanielk1977 ** there is no default collation type, return 0.
700202b29eSdanielk1977 */
717cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
727cedc8d4Sdanielk1977   CollSeq *pColl = 0;
730202b29eSdanielk1977   if( pExpr ){
747e09fe0bSdrh     int op;
757cedc8d4Sdanielk1977     pColl = pExpr->pColl;
767e09fe0bSdrh     op = pExpr->op;
777e09fe0bSdrh     if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
787cedc8d4Sdanielk1977       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
790202b29eSdanielk1977     }
800202b29eSdanielk1977   }
817cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
827cedc8d4Sdanielk1977     pColl = 0;
837cedc8d4Sdanielk1977   }
847cedc8d4Sdanielk1977   return pColl;
850202b29eSdanielk1977 }
860202b29eSdanielk1977 
870202b29eSdanielk1977 /*
88626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
89626a879aSdrh ** type affinity of the other operand.  This routine returns the
9053db1458Sdrh ** type affinity that should be used for the comparison operator.
9153db1458Sdrh */
92e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
93bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
94e014a838Sdanielk1977   if( aff1 && aff2 ){
958df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
968df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
97e014a838Sdanielk1977     */
988a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
99e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
100e014a838Sdanielk1977     }else{
101e014a838Sdanielk1977       return SQLITE_AFF_NONE;
102e014a838Sdanielk1977     }
103e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
1045f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
1055f6a87b3Sdrh     ** results directly.
106e014a838Sdanielk1977     */
1075f6a87b3Sdrh     return SQLITE_AFF_NONE;
108e014a838Sdanielk1977   }else{
109e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
110fe05af87Sdrh     assert( aff1==0 || aff2==0 );
111e014a838Sdanielk1977     return (aff1 + aff2);
112e014a838Sdanielk1977   }
113e014a838Sdanielk1977 }
114e014a838Sdanielk1977 
11553db1458Sdrh /*
11653db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
11753db1458Sdrh ** be applied to both operands prior to doing the comparison.
11853db1458Sdrh */
119e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
120e014a838Sdanielk1977   char aff;
121e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
122e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
123e014a838Sdanielk1977           pExpr->op==TK_NE );
124e014a838Sdanielk1977   assert( pExpr->pLeft );
125bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
126e014a838Sdanielk1977   if( pExpr->pRight ){
127e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
128e014a838Sdanielk1977   }
129e014a838Sdanielk1977   else if( pExpr->pSelect ){
130e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
131e014a838Sdanielk1977   }
132e014a838Sdanielk1977   else if( !aff ){
133de087bd5Sdrh     aff = SQLITE_AFF_NONE;
134e014a838Sdanielk1977   }
135e014a838Sdanielk1977   return aff;
136e014a838Sdanielk1977 }
137e014a838Sdanielk1977 
138e014a838Sdanielk1977 /*
139e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
140e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
141e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
142e014a838Sdanielk1977 ** the comparison in pExpr.
143e014a838Sdanielk1977 */
144e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
145e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
1468a51256cSdrh   switch( aff ){
1478a51256cSdrh     case SQLITE_AFF_NONE:
1488a51256cSdrh       return 1;
1498a51256cSdrh     case SQLITE_AFF_TEXT:
1508a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
1518a51256cSdrh     default:
1528a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
1538a51256cSdrh   }
154e014a838Sdanielk1977 }
155e014a838Sdanielk1977 
156a37cdde0Sdanielk1977 /*
157a37cdde0Sdanielk1977 ** Return the P1 value that should be used for a binary comparison
158a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
159a37cdde0Sdanielk1977 ** If jumpIfNull is true, then set the low byte of the returned
160a37cdde0Sdanielk1977 ** P1 value to tell the opcode to jump if either expression
161a37cdde0Sdanielk1977 ** evaluates to NULL.
162a37cdde0Sdanielk1977 */
163e014a838Sdanielk1977 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
164bf3b721fSdanielk1977   char aff = sqlite3ExprAffinity(pExpr2);
165f0863fe5Sdrh   return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
166a37cdde0Sdanielk1977 }
167a37cdde0Sdanielk1977 
168a2e00042Sdrh /*
1690202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
1700202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
1710202b29eSdanielk1977 **
1720202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
1730202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
1740202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
1750202b29eSdanielk1977 ** type.
176bcbb04e5Sdanielk1977 **
177bcbb04e5Sdanielk1977 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
178bcbb04e5Sdanielk1977 ** it is not considered.
1790202b29eSdanielk1977 */
180bcbb04e5Sdanielk1977 CollSeq *sqlite3BinaryCompareCollSeq(
181bcbb04e5Sdanielk1977   Parse *pParse,
182bcbb04e5Sdanielk1977   Expr *pLeft,
183bcbb04e5Sdanielk1977   Expr *pRight
184bcbb04e5Sdanielk1977 ){
185ec41ddacSdrh   CollSeq *pColl;
186ec41ddacSdrh   assert( pLeft );
187ec41ddacSdrh   if( pLeft->flags & EP_ExpCollate ){
188ec41ddacSdrh     assert( pLeft->pColl );
189ec41ddacSdrh     pColl = pLeft->pColl;
190bcbb04e5Sdanielk1977   }else if( pRight && pRight->flags & EP_ExpCollate ){
191ec41ddacSdrh     assert( pRight->pColl );
192ec41ddacSdrh     pColl = pRight->pColl;
193ec41ddacSdrh   }else{
194ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
1950202b29eSdanielk1977     if( !pColl ){
1967cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
1970202b29eSdanielk1977     }
198ec41ddacSdrh   }
1990202b29eSdanielk1977   return pColl;
2000202b29eSdanielk1977 }
2010202b29eSdanielk1977 
2020202b29eSdanielk1977 /*
203be5c89acSdrh ** Generate code for a comparison operator.
204be5c89acSdrh */
205be5c89acSdrh static int codeCompare(
206be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
207be5c89acSdrh   Expr *pLeft,      /* The left operand */
208be5c89acSdrh   Expr *pRight,     /* The right operand */
209be5c89acSdrh   int opcode,       /* The comparison opcode */
210be5c89acSdrh   int dest,         /* Jump here if true.  */
211be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
212be5c89acSdrh ){
213be5c89acSdrh   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
214bcbb04e5Sdanielk1977   CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
215be5c89acSdrh   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
216be5c89acSdrh }
217be5c89acSdrh 
218be5c89acSdrh /*
219a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
22017435752Sdrh ** for this node is obtained from sqlite3_malloc().  The calling function
221a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
222a76b5dfcSdrh */
22317435752Sdrh Expr *sqlite3Expr(
224*a1644fd8Sdanielk1977   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
22517435752Sdrh   int op,                 /* Expression opcode */
22617435752Sdrh   Expr *pLeft,            /* Left operand */
22717435752Sdrh   Expr *pRight,           /* Right operand */
22817435752Sdrh   const Token *pToken     /* Argument token */
22917435752Sdrh ){
230a76b5dfcSdrh   Expr *pNew;
231*a1644fd8Sdanielk1977   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
232a76b5dfcSdrh   if( pNew==0 ){
233d5d56523Sdanielk1977     /* When malloc fails, delete pLeft and pRight. Expressions passed to
234d5d56523Sdanielk1977     ** this function must always be allocated with sqlite3Expr() for this
235d5d56523Sdanielk1977     ** reason.
236d5d56523Sdanielk1977     */
237d5d56523Sdanielk1977     sqlite3ExprDelete(pLeft);
238d5d56523Sdanielk1977     sqlite3ExprDelete(pRight);
239a76b5dfcSdrh     return 0;
240a76b5dfcSdrh   }
241a76b5dfcSdrh   pNew->op = op;
242a76b5dfcSdrh   pNew->pLeft = pLeft;
243a76b5dfcSdrh   pNew->pRight = pRight;
244a58fdfb1Sdanielk1977   pNew->iAgg = -1;
245a76b5dfcSdrh   if( pToken ){
2464b59ab5eSdrh     assert( pToken->dyn==0 );
247145716b3Sdrh     pNew->span = pNew->token = *pToken;
248a34001c9Sdrh   }else if( pLeft ){
249a34001c9Sdrh     if( pRight ){
2504adee20fSdanielk1977       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
2515ffb3ac8Sdrh       if( pRight->flags & EP_ExpCollate ){
252a34001c9Sdrh         pNew->flags |= EP_ExpCollate;
253a34001c9Sdrh         pNew->pColl = pRight->pColl;
254a34001c9Sdrh       }
255a34001c9Sdrh     }
2565ffb3ac8Sdrh     if( pLeft->flags & EP_ExpCollate ){
257a34001c9Sdrh       pNew->flags |= EP_ExpCollate;
258a34001c9Sdrh       pNew->pColl = pLeft->pColl;
259a34001c9Sdrh     }
260a76b5dfcSdrh   }
261fc976065Sdanielk1977 
262fc976065Sdanielk1977   sqlite3ExprSetHeight(pNew);
263a76b5dfcSdrh   return pNew;
264a76b5dfcSdrh }
265a76b5dfcSdrh 
266a76b5dfcSdrh /*
26717435752Sdrh ** Works like sqlite3Expr() except that it takes an extra Parse*
26817435752Sdrh ** argument and notifies the associated connection object if malloc fails.
269206f3d96Sdrh */
27017435752Sdrh Expr *sqlite3PExpr(
27117435752Sdrh   Parse *pParse,          /* Parsing context */
27217435752Sdrh   int op,                 /* Expression opcode */
27317435752Sdrh   Expr *pLeft,            /* Left operand */
27417435752Sdrh   Expr *pRight,           /* Right operand */
27517435752Sdrh   const Token *pToken     /* Argument token */
27617435752Sdrh ){
277*a1644fd8Sdanielk1977   return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
278206f3d96Sdrh }
279206f3d96Sdrh 
280206f3d96Sdrh /*
2814e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
2824e0cff60Sdrh ** that look like this:   #0 #1 #2 ...  These terms refer to elements
283288d37f1Sdrh ** on the stack.  "#0" means the top of the stack.
284288d37f1Sdrh ** "#1" means the next down on the stack.  And so forth.
2854e0cff60Sdrh **
2864e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
2874e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
2884e0cff60Sdrh ** The returns an expression that will code to extract the value from
2894e0cff60Sdrh ** that memory location as needed.
2904e0cff60Sdrh */
2914e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
2924e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
2934e0cff60Sdrh   Expr *p;
2944e0cff60Sdrh   int depth;
2954e0cff60Sdrh   if( pParse->nested==0 ){
2964e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
297*a1644fd8Sdanielk1977     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
2984e0cff60Sdrh   }
299bb7ac00bSdrh   if( v==0 ) return 0;
300*a1644fd8Sdanielk1977   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
30173c42a13Sdrh   if( p==0 ){
30273c42a13Sdrh     return 0;  /* Malloc failed */
30373c42a13Sdrh   }
3042646da7eSdrh   depth = atoi((char*)&pToken->z[1]);
3054e0cff60Sdrh   p->iTable = pParse->nMem++;
3064e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
3074e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
3084e0cff60Sdrh   return p;
3094e0cff60Sdrh }
3104e0cff60Sdrh 
3114e0cff60Sdrh /*
31291bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
31391bb0eedSdrh ** NULL, then just return the other expression.
31491bb0eedSdrh */
3151e536953Sdanielk1977 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
31691bb0eedSdrh   if( pLeft==0 ){
31791bb0eedSdrh     return pRight;
31891bb0eedSdrh   }else if( pRight==0 ){
31991bb0eedSdrh     return pLeft;
32091bb0eedSdrh   }else{
321*a1644fd8Sdanielk1977     Expr *p = sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
32217435752Sdrh     if( p==0 ){
32317435752Sdrh       db->mallocFailed = 1;
32417435752Sdrh     }
3251e536953Sdanielk1977     return p;
32691bb0eedSdrh   }
32791bb0eedSdrh }
32891bb0eedSdrh 
32991bb0eedSdrh /*
3306977fea8Sdrh ** Set the Expr.span field of the given expression to span all
331a76b5dfcSdrh ** text between the two given tokens.
332a76b5dfcSdrh */
3334adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
3344efc4754Sdrh   assert( pRight!=0 );
3354efc4754Sdrh   assert( pLeft!=0 );
336f3a65f7eSdrh   if( pExpr && pRight->z && pLeft->z ){
337ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
338145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
3396977fea8Sdrh       pExpr->span.z = pLeft->z;
34097903fefSdrh       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
3414b59ab5eSdrh     }else{
3426977fea8Sdrh       pExpr->span.z = 0;
3434b59ab5eSdrh     }
344a76b5dfcSdrh   }
345a76b5dfcSdrh }
346a76b5dfcSdrh 
347a76b5dfcSdrh /*
348a76b5dfcSdrh ** Construct a new expression node for a function with multiple
349a76b5dfcSdrh ** arguments.
350a76b5dfcSdrh */
35117435752Sdrh Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
352a76b5dfcSdrh   Expr *pNew;
3534b202ae2Sdanielk1977   assert( pToken );
35417435752Sdrh   pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) );
355a76b5dfcSdrh   if( pNew==0 ){
356d5d56523Sdanielk1977     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
357a76b5dfcSdrh     return 0;
358a76b5dfcSdrh   }
359a76b5dfcSdrh   pNew->op = TK_FUNCTION;
360a76b5dfcSdrh   pNew->pList = pList;
3614b59ab5eSdrh   assert( pToken->dyn==0 );
362a76b5dfcSdrh   pNew->token = *pToken;
3636977fea8Sdrh   pNew->span = pNew->token;
364fc976065Sdanielk1977 
365fc976065Sdanielk1977   sqlite3ExprSetHeight(pNew);
366a76b5dfcSdrh   return pNew;
367a76b5dfcSdrh }
368a76b5dfcSdrh 
369a76b5dfcSdrh /*
370fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
371fa6bc000Sdrh ** in the original SQL statement.
372fa6bc000Sdrh **
373fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
374fa6bc000Sdrh ** variable number.
375fa6bc000Sdrh **
376fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
377fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
378fa6bc000Sdrh ** the SQL statement comes from an external source.
379fa6bc000Sdrh **
380fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
381fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
382fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
383fa6bc000Sdrh ** assigned.
384fa6bc000Sdrh */
385fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
386fa6bc000Sdrh   Token *pToken;
38717435752Sdrh   sqlite3 *db = pParse->db;
38817435752Sdrh 
389fa6bc000Sdrh   if( pExpr==0 ) return;
390fa6bc000Sdrh   pToken = &pExpr->token;
391fa6bc000Sdrh   assert( pToken->n>=1 );
392fa6bc000Sdrh   assert( pToken->z!=0 );
393fa6bc000Sdrh   assert( pToken->z[0]!=0 );
394fa6bc000Sdrh   if( pToken->n==1 ){
395fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
396fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
397fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
398fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
399fa6bc000Sdrh     ** use it as the variable number */
400fa6bc000Sdrh     int i;
4012646da7eSdrh     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
402fa6bc000Sdrh     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
403fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
404fa6bc000Sdrh           SQLITE_MAX_VARIABLE_NUMBER);
405fa6bc000Sdrh     }
406fa6bc000Sdrh     if( i>pParse->nVar ){
407fa6bc000Sdrh       pParse->nVar = i;
408fa6bc000Sdrh     }
409fa6bc000Sdrh   }else{
410fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
411fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
412fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
413fa6bc000Sdrh     */
414fa6bc000Sdrh     int i, n;
415fa6bc000Sdrh     n = pToken->n;
416fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
417fa6bc000Sdrh       Expr *pE;
418fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
419fa6bc000Sdrh           && pE->token.n==n
420fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
421fa6bc000Sdrh         pExpr->iTable = pE->iTable;
422fa6bc000Sdrh         break;
423fa6bc000Sdrh       }
424fa6bc000Sdrh     }
425fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
426fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
427fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
428fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
42917435752Sdrh         pParse->apVarExpr =
43017435752Sdrh             sqlite3DbReallocOrFree(
43117435752Sdrh               db,
43217435752Sdrh               pParse->apVarExpr,
43317435752Sdrh               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
43417435752Sdrh             );
435fa6bc000Sdrh       }
43617435752Sdrh       if( !db->mallocFailed ){
437fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
438fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
439fa6bc000Sdrh       }
440fa6bc000Sdrh     }
441fa6bc000Sdrh   }
442832b2664Sdanielk1977   if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
443832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
444832b2664Sdanielk1977   }
445fa6bc000Sdrh }
446fa6bc000Sdrh 
447fa6bc000Sdrh /*
448a2e00042Sdrh ** Recursively delete an expression tree.
449a2e00042Sdrh */
4504adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
451a2e00042Sdrh   if( p==0 ) return;
45217435752Sdrh   if( p->span.dyn ) sqlite3_free((char*)p->span.z);
45317435752Sdrh   if( p->token.dyn ) sqlite3_free((char*)p->token.z);
4544adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
4554adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
4564adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
4574adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
45817435752Sdrh   sqlite3_free(p);
459a2e00042Sdrh }
460a2e00042Sdrh 
461d2687b77Sdrh /*
462d2687b77Sdrh ** The Expr.token field might be a string literal that is quoted.
463d2687b77Sdrh ** If so, remove the quotation marks.
464d2687b77Sdrh */
46517435752Sdrh void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
466d2687b77Sdrh   if( ExprHasAnyProperty(p, EP_Dequoted) ){
467d2687b77Sdrh     return;
468d2687b77Sdrh   }
469d2687b77Sdrh   ExprSetProperty(p, EP_Dequoted);
470d2687b77Sdrh   if( p->token.dyn==0 ){
47117435752Sdrh     sqlite3TokenCopy(db, &p->token, &p->token);
472d2687b77Sdrh   }
473d2687b77Sdrh   sqlite3Dequote((char*)p->token.z);
474d2687b77Sdrh }
475d2687b77Sdrh 
476a76b5dfcSdrh 
477a76b5dfcSdrh /*
478ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
479ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
480ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
481ff78bd2fSdrh ** without effecting the originals.
482ff78bd2fSdrh **
4834adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
4844adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
485ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
486ff78bd2fSdrh **
487ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
488ff78bd2fSdrh */
4891e536953Sdanielk1977 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
490ff78bd2fSdrh   Expr *pNew;
491ff78bd2fSdrh   if( p==0 ) return 0;
49217435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
493ff78bd2fSdrh   if( pNew==0 ) return 0;
4943b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
4956977fea8Sdrh   if( p->token.z!=0 ){
49617435752Sdrh     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
4974b59ab5eSdrh     pNew->token.dyn = 1;
4984b59ab5eSdrh   }else{
4994efc4754Sdrh     assert( pNew->token.z==0 );
5004b59ab5eSdrh   }
5016977fea8Sdrh   pNew->span.z = 0;
50217435752Sdrh   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
50317435752Sdrh   pNew->pRight = sqlite3ExprDup(db, p->pRight);
50417435752Sdrh   pNew->pList = sqlite3ExprListDup(db, p->pList);
50517435752Sdrh   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
506ff78bd2fSdrh   return pNew;
507ff78bd2fSdrh }
50817435752Sdrh void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
50917435752Sdrh   if( pTo->dyn ) sqlite3_free((char*)pTo->z);
5104b59ab5eSdrh   if( pFrom->z ){
5114b59ab5eSdrh     pTo->n = pFrom->n;
51217435752Sdrh     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
5134b59ab5eSdrh     pTo->dyn = 1;
5144b59ab5eSdrh   }else{
5154b59ab5eSdrh     pTo->z = 0;
5164b59ab5eSdrh   }
5174b59ab5eSdrh }
51817435752Sdrh ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
519ff78bd2fSdrh   ExprList *pNew;
520145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
521ff78bd2fSdrh   int i;
522ff78bd2fSdrh   if( p==0 ) return 0;
52317435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
524ff78bd2fSdrh   if( pNew==0 ) return 0;
52531dad9daSdanielk1977   pNew->iECursor = 0;
5264305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
52717435752Sdrh   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
528e0048400Sdanielk1977   if( pItem==0 ){
52917435752Sdrh     sqlite3_free(pNew);
530e0048400Sdanielk1977     return 0;
531e0048400Sdanielk1977   }
532145716b3Sdrh   pOldItem = p->a;
533145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
5344b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
53517435752Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
5366977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
5376977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
5384b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
5394b59ab5eSdrh       ** the names of columns in the result set needs this information */
54017435752Sdrh       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
5414b59ab5eSdrh     }
5421f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
5436f7adc8aSdrh             || pOldExpr->span.z==0
54417435752Sdrh             || db->mallocFailed );
54517435752Sdrh     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
546145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
547145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
5483e7bc9caSdrh     pItem->done = 0;
549ff78bd2fSdrh   }
550ff78bd2fSdrh   return pNew;
551ff78bd2fSdrh }
55293758c8dSdanielk1977 
55393758c8dSdanielk1977 /*
55493758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
55593758c8dSdanielk1977 ** the build, then none of the following routines, except for
55693758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
55793758c8dSdanielk1977 ** called with a NULL argument.
55893758c8dSdanielk1977 */
5596a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
5606a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
56117435752Sdrh SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
562ad3cab52Sdrh   SrcList *pNew;
563ad3cab52Sdrh   int i;
564113088ecSdrh   int nByte;
565ad3cab52Sdrh   if( p==0 ) return 0;
566113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
56717435752Sdrh   pNew = sqlite3DbMallocRaw(db, nByte );
568ad3cab52Sdrh   if( pNew==0 ) return 0;
5694305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
570ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
5714efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
5724efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
573ed8a3bb1Sdrh     Table *pTab;
57417435752Sdrh     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
57517435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
57617435752Sdrh     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
5774efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
5784efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
5791787ccabSdanielk1977     pNewItem->isPopulated = pOldItem->isPopulated;
580ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
581ed8a3bb1Sdrh     if( pTab ){
582ed8a3bb1Sdrh       pTab->nRef++;
583a1cb183dSdanielk1977     }
58417435752Sdrh     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
58517435752Sdrh     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
58617435752Sdrh     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
5876c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
588ad3cab52Sdrh   }
589ad3cab52Sdrh   return pNew;
590ad3cab52Sdrh }
59117435752Sdrh IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
592ff78bd2fSdrh   IdList *pNew;
593ff78bd2fSdrh   int i;
594ff78bd2fSdrh   if( p==0 ) return 0;
59517435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
596ff78bd2fSdrh   if( pNew==0 ) return 0;
5974305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
59817435752Sdrh   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
599d5d56523Sdanielk1977   if( pNew->a==0 ){
60017435752Sdrh     sqlite3_free(pNew);
601d5d56523Sdanielk1977     return 0;
602d5d56523Sdanielk1977   }
603ff78bd2fSdrh   for(i=0; i<p->nId; i++){
6044efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
6054efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
60617435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
6074efc4754Sdrh     pNewItem->idx = pOldItem->idx;
608ff78bd2fSdrh   }
609ff78bd2fSdrh   return pNew;
610ff78bd2fSdrh }
61117435752Sdrh Select *sqlite3SelectDup(sqlite3 *db, Select *p){
612ff78bd2fSdrh   Select *pNew;
613ff78bd2fSdrh   if( p==0 ) return 0;
61417435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
615ff78bd2fSdrh   if( pNew==0 ) return 0;
616ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
61717435752Sdrh   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
61817435752Sdrh   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
61917435752Sdrh   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
62017435752Sdrh   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
62117435752Sdrh   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
62217435752Sdrh   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
623ff78bd2fSdrh   pNew->op = p->op;
62417435752Sdrh   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
62517435752Sdrh   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
62617435752Sdrh   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
6277b58daeaSdrh   pNew->iLimit = -1;
6287b58daeaSdrh   pNew->iOffset = -1;
629a1cb183dSdanielk1977   pNew->isResolved = p->isResolved;
630a1cb183dSdanielk1977   pNew->isAgg = p->isAgg;
631b9bb7c18Sdrh   pNew->usesEphm = 0;
6328e647b81Sdrh   pNew->disallowOrderBy = 0;
6330342b1f5Sdrh   pNew->pRightmost = 0;
634b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
635b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
636b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
637ff78bd2fSdrh   return pNew;
638ff78bd2fSdrh }
63993758c8dSdanielk1977 #else
64017435752Sdrh Select *sqlite3SelectDup(sqlite3 *db, Select *p){
64193758c8dSdanielk1977   assert( p==0 );
64293758c8dSdanielk1977   return 0;
64393758c8dSdanielk1977 }
64493758c8dSdanielk1977 #endif
645ff78bd2fSdrh 
646ff78bd2fSdrh 
647ff78bd2fSdrh /*
648a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
649a76b5dfcSdrh ** initially NULL, then create a new expression list.
650a76b5dfcSdrh */
65117435752Sdrh ExprList *sqlite3ExprListAppend(
65217435752Sdrh   Parse *pParse,          /* Parsing context */
65317435752Sdrh   ExprList *pList,        /* List to which to append. Might be NULL */
65417435752Sdrh   Expr *pExpr,            /* Expression to be appended */
65517435752Sdrh   Token *pName            /* AS keyword for the expression */
65617435752Sdrh ){
65717435752Sdrh   sqlite3 *db = pParse->db;
658a76b5dfcSdrh   if( pList==0 ){
65917435752Sdrh     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
660a76b5dfcSdrh     if( pList==0 ){
661d5d56523Sdanielk1977       goto no_mem;
662a76b5dfcSdrh     }
6634efc4754Sdrh     assert( pList->nAlloc==0 );
664a76b5dfcSdrh   }
6654305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
666d5d56523Sdanielk1977     struct ExprList_item *a;
667d5d56523Sdanielk1977     int n = pList->nAlloc*2 + 4;
66817435752Sdrh     a = sqlite3_realloc(pList->a, n*sizeof(pList->a[0]));
669d5d56523Sdanielk1977     if( a==0 ){
670d5d56523Sdanielk1977       goto no_mem;
671a76b5dfcSdrh     }
672d5d56523Sdanielk1977     pList->a = a;
673d5d56523Sdanielk1977     pList->nAlloc = n;
674a76b5dfcSdrh   }
6754efc4754Sdrh   assert( pList->a!=0 );
6764efc4754Sdrh   if( pExpr || pName ){
6774efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
6784efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
67917435752Sdrh     pItem->zName = sqlite3NameFromToken(db, pName);
680e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
681a76b5dfcSdrh   }
682a76b5dfcSdrh   return pList;
683d5d56523Sdanielk1977 
684d5d56523Sdanielk1977 no_mem:
685d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
68617435752Sdrh   db->mallocFailed = 1;
687d5d56523Sdanielk1977   sqlite3ExprDelete(pExpr);
688d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
689d5d56523Sdanielk1977   return 0;
690a76b5dfcSdrh }
691a76b5dfcSdrh 
692a76b5dfcSdrh /*
6937a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
6947a15a4beSdanielk1977 ** leave an error message in pParse.
6957a15a4beSdanielk1977 */
6967a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
6977a15a4beSdanielk1977   Parse *pParse,
6987a15a4beSdanielk1977   ExprList *pEList,
6997a15a4beSdanielk1977   int iLimit,
7007a15a4beSdanielk1977   const char *zObject
7017a15a4beSdanielk1977 ){
702b4fc6794Sdanielk1977   if( pEList && pEList->nExpr>iLimit ){
7037a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
7047a15a4beSdanielk1977   }
7057a15a4beSdanielk1977 }
7067a15a4beSdanielk1977 
707fc976065Sdanielk1977 
708fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
709fc976065Sdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
710fc976065Sdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
711fc976065Sdanielk1977 ** of any expression tree referenced by the structure passed as the
712fc976065Sdanielk1977 ** first argument.
713fc976065Sdanielk1977 **
714fc976065Sdanielk1977 ** If this maximum height is greater than the current value pointed
715fc976065Sdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
716fc976065Sdanielk1977 ** value.
717fc976065Sdanielk1977 */
718fc976065Sdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
719fc976065Sdanielk1977   if( p ){
720fc976065Sdanielk1977     if( p->nHeight>*pnHeight ){
721fc976065Sdanielk1977       *pnHeight = p->nHeight;
722fc976065Sdanielk1977     }
723fc976065Sdanielk1977   }
724fc976065Sdanielk1977 }
725fc976065Sdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
726fc976065Sdanielk1977   if( p ){
727fc976065Sdanielk1977     int i;
728fc976065Sdanielk1977     for(i=0; i<p->nExpr; i++){
729fc976065Sdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
730fc976065Sdanielk1977     }
731fc976065Sdanielk1977   }
732fc976065Sdanielk1977 }
733fc976065Sdanielk1977 static void heightOfSelect(Select *p, int *pnHeight){
734fc976065Sdanielk1977   if( p ){
735fc976065Sdanielk1977     heightOfExpr(p->pWhere, pnHeight);
736fc976065Sdanielk1977     heightOfExpr(p->pHaving, pnHeight);
737fc976065Sdanielk1977     heightOfExpr(p->pLimit, pnHeight);
738fc976065Sdanielk1977     heightOfExpr(p->pOffset, pnHeight);
739fc976065Sdanielk1977     heightOfExprList(p->pEList, pnHeight);
740fc976065Sdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
741fc976065Sdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
742fc976065Sdanielk1977     heightOfSelect(p->pPrior, pnHeight);
743fc976065Sdanielk1977   }
744fc976065Sdanielk1977 }
745fc976065Sdanielk1977 
746fc976065Sdanielk1977 /*
747fc976065Sdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
748fc976065Sdanielk1977 ** argument. An expression with no children, Expr.pList or
749fc976065Sdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
750fc976065Sdanielk1977 ** has a height equal to the maximum height of any other
751fc976065Sdanielk1977 ** referenced Expr plus one.
752fc976065Sdanielk1977 */
753fc976065Sdanielk1977 void sqlite3ExprSetHeight(Expr *p){
754fc976065Sdanielk1977   int nHeight = 0;
755fc976065Sdanielk1977   heightOfExpr(p->pLeft, &nHeight);
756fc976065Sdanielk1977   heightOfExpr(p->pRight, &nHeight);
757fc976065Sdanielk1977   heightOfExprList(p->pList, &nHeight);
758fc976065Sdanielk1977   heightOfSelect(p->pSelect, &nHeight);
759fc976065Sdanielk1977   p->nHeight = nHeight + 1;
760fc976065Sdanielk1977 }
761fc976065Sdanielk1977 
762fc976065Sdanielk1977 /*
763fc976065Sdanielk1977 ** Return the maximum height of any expression tree referenced
764fc976065Sdanielk1977 ** by the select statement passed as an argument.
765fc976065Sdanielk1977 */
766fc976065Sdanielk1977 int sqlite3SelectExprHeight(Select *p){
767fc976065Sdanielk1977   int nHeight = 0;
768fc976065Sdanielk1977   heightOfSelect(p, &nHeight);
769fc976065Sdanielk1977   return nHeight;
770fc976065Sdanielk1977 }
771fc976065Sdanielk1977 #endif
772fc976065Sdanielk1977 
7737a15a4beSdanielk1977 /*
774a76b5dfcSdrh ** Delete an entire expression list.
775a76b5dfcSdrh */
7764adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
777a76b5dfcSdrh   int i;
778be5c89acSdrh   struct ExprList_item *pItem;
779a76b5dfcSdrh   if( pList==0 ) return;
7801bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
7811bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
782be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
783be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
78417435752Sdrh     sqlite3_free(pItem->zName);
785a76b5dfcSdrh   }
78617435752Sdrh   sqlite3_free(pList->a);
78717435752Sdrh   sqlite3_free(pList);
788a76b5dfcSdrh }
789a76b5dfcSdrh 
790a76b5dfcSdrh /*
791626a879aSdrh ** Walk an expression tree.  Call xFunc for each node visited.
79273b211abSdrh **
793626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
794626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
795626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
796626a879aSdrh ** the tree walk completely.
797626a879aSdrh **
798626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
799626a879aSdrh ** and 0 to continue.
80087abf5c0Sdrh **
80187abf5c0Sdrh ** NOTICE:  This routine does *not* descend into subqueries.
802626a879aSdrh */
803a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
804626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
805626a879aSdrh   int rc;
806626a879aSdrh   if( pExpr==0 ) return 0;
807626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
808626a879aSdrh   if( rc==0 ){
809626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
810626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
811a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
812626a879aSdrh   }
813626a879aSdrh   return rc>1;
814626a879aSdrh }
815626a879aSdrh 
816626a879aSdrh /*
817a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
818a58fdfb1Sdanielk1977 */
819a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
820a58fdfb1Sdanielk1977   int i;
821a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
822a58fdfb1Sdanielk1977   if( !p ) return 0;
823a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
824a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
825a58fdfb1Sdanielk1977   }
826a58fdfb1Sdanielk1977   return 0;
827a58fdfb1Sdanielk1977 }
828a58fdfb1Sdanielk1977 
829a58fdfb1Sdanielk1977 /*
830a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
831a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
832a58fdfb1Sdanielk1977 ** or OFFSET expressions..
833a58fdfb1Sdanielk1977 */
834a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
835a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
836a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
837a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
838a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
839a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
84015d7982aSdanielk1977   if( p->pPrior ){
84115d7982aSdanielk1977     walkSelectExpr(p->pPrior, xFunc, pArg);
84215d7982aSdanielk1977   }
843a58fdfb1Sdanielk1977   return 0;
844a58fdfb1Sdanielk1977 }
845a58fdfb1Sdanielk1977 
846a58fdfb1Sdanielk1977 
847a58fdfb1Sdanielk1977 /*
848626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
849626a879aSdrh **
850626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
85173b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
85273b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
85373b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
85473b211abSdrh ** then do nothing.
85573b211abSdrh **
85673b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
85773b211abSdrh ** the expression as constant, then we assume the whole expression
85873b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
859626a879aSdrh */
860626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
8610a168377Sdrh   int *pN = (int*)pArg;
8620a168377Sdrh 
8630a168377Sdrh   /* If *pArg is 3 then any term of the expression that comes from
8640a168377Sdrh   ** the ON or USING clauses of a join disqualifies the expression
8650a168377Sdrh   ** from being considered constant. */
8660a168377Sdrh   if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
8670a168377Sdrh     *pN = 0;
8680a168377Sdrh     return 2;
8690a168377Sdrh   }
8700a168377Sdrh 
871626a879aSdrh   switch( pExpr->op ){
872eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
873eb55bd2fSdrh     ** and *pArg==2 */
874eb55bd2fSdrh     case TK_FUNCTION:
8750a168377Sdrh       if( (*pN)==2 ) return 0;
876eb55bd2fSdrh       /* Fall through */
877626a879aSdrh     case TK_ID:
878626a879aSdrh     case TK_COLUMN:
879626a879aSdrh     case TK_DOT:
880626a879aSdrh     case TK_AGG_FUNCTION:
88113449892Sdrh     case TK_AGG_COLUMN:
882fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
883fe2093d7Sdrh     case TK_SELECT:
884fe2093d7Sdrh     case TK_EXISTS:
885fe2093d7Sdrh #endif
8860a168377Sdrh       *pN = 0;
887626a879aSdrh       return 2;
88887abf5c0Sdrh     case TK_IN:
88987abf5c0Sdrh       if( pExpr->pSelect ){
8900a168377Sdrh         *pN = 0;
89187abf5c0Sdrh         return 2;
89287abf5c0Sdrh       }
893626a879aSdrh     default:
894626a879aSdrh       return 0;
895626a879aSdrh   }
896626a879aSdrh }
897626a879aSdrh 
898626a879aSdrh /*
899fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
900eb55bd2fSdrh ** and 0 if it involves variables or function calls.
9012398937bSdrh **
9022398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
9032398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
9042398937bSdrh ** a constant.
905fef5208cSdrh */
9064adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
907626a879aSdrh   int isConst = 1;
908626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
909626a879aSdrh   return isConst;
910fef5208cSdrh }
911fef5208cSdrh 
912fef5208cSdrh /*
913eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
9140a168377Sdrh ** that does no originate from the ON or USING clauses of a join.
9150a168377Sdrh ** Return 0 if it involves variables or function calls or terms from
9160a168377Sdrh ** an ON or USING clause.
9170a168377Sdrh */
9180a168377Sdrh int sqlite3ExprIsConstantNotJoin(Expr *p){
9190a168377Sdrh   int isConst = 3;
9200a168377Sdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
9210a168377Sdrh   return isConst!=0;
9220a168377Sdrh }
9230a168377Sdrh 
9240a168377Sdrh /*
9250a168377Sdrh ** Walk an expression tree.  Return 1 if the expression is constant
926eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
927eb55bd2fSdrh ** are any variables.
928eb55bd2fSdrh **
929eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
930eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
931eb55bd2fSdrh ** a constant.
932eb55bd2fSdrh */
933eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
934eb55bd2fSdrh   int isConst = 2;
935eb55bd2fSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
936eb55bd2fSdrh   return isConst!=0;
937eb55bd2fSdrh }
938eb55bd2fSdrh 
939eb55bd2fSdrh /*
94073b211abSdrh ** If the expression p codes a constant integer that is small enough
941202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
942202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
943202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
944e4de1febSdrh */
9454adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
946e4de1febSdrh   switch( p->op ){
947e4de1febSdrh     case TK_INTEGER: {
9482646da7eSdrh       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
949e4de1febSdrh         return 1;
950e4de1febSdrh       }
951202b2df7Sdrh       break;
952202b2df7Sdrh     }
9534b59ab5eSdrh     case TK_UPLUS: {
9544adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
9554b59ab5eSdrh     }
956e4de1febSdrh     case TK_UMINUS: {
957e4de1febSdrh       int v;
9584adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
959e4de1febSdrh         *pValue = -v;
960e4de1febSdrh         return 1;
961e4de1febSdrh       }
962e4de1febSdrh       break;
963e4de1febSdrh     }
964e4de1febSdrh     default: break;
965e4de1febSdrh   }
966e4de1febSdrh   return 0;
967e4de1febSdrh }
968e4de1febSdrh 
969e4de1febSdrh /*
970c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
971c4a3c779Sdrh */
9724adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
9734adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
9744adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
9754adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
976c4a3c779Sdrh   return 0;
977c4a3c779Sdrh }
978c4a3c779Sdrh 
979c4a3c779Sdrh /*
9808141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
9818141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
9828141f61eSdrh ** expression node refer back to that source column.  The following changes
9838141f61eSdrh ** are made to pExpr:
9848141f61eSdrh **
9858141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
9868141f61eSdrh **                         the table.
9878141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
9888141f61eSdrh **                         from pSrcList.
9898141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
9908141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
9918141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
9928141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
9938141f61eSdrh **
9948141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
9958141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
9968141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
9978141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
9988141f61eSdrh ** means that the form of the name is Z and that columns from any table
9998141f61eSdrh ** can be used.
10008141f61eSdrh **
10018141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
10028141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
10038141f61eSdrh */
10048141f61eSdrh static int lookupName(
10058141f61eSdrh   Parse *pParse,       /* The parsing context */
10068141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
10078141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
10088141f61eSdrh   Token *pColumnToken, /* Name of the column. */
1009626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
10108141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
10118141f61eSdrh ){
10128141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
10138141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
10148141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
10158141f61eSdrh   int i, j;            /* Loop counters */
10168141f61eSdrh   int cnt = 0;         /* Number of matching column names */
10178141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
10189bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
101951669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
102051669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
102173b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
10228141f61eSdrh 
10238141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
102417435752Sdrh   zDb = sqlite3NameFromToken(db, pDbToken);
102517435752Sdrh   zTab = sqlite3NameFromToken(db, pTableToken);
102617435752Sdrh   zCol = sqlite3NameFromToken(db, pColumnToken);
102717435752Sdrh   if( db->mallocFailed ){
1028d5d56523Sdanielk1977     goto lookupname_end;
10298141f61eSdrh   }
10308141f61eSdrh 
10318141f61eSdrh   pExpr->iTable = -1;
1032626a879aSdrh   while( pNC && cnt==0 ){
1033ffe07b2dSdrh     ExprList *pEList;
1034626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
1035626a879aSdrh 
1036b3bce662Sdanielk1977     if( pSrcList ){
103751669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
103843617e9aSdrh         Table *pTab;
103943617e9aSdrh         int iDb;
10408141f61eSdrh         Column *pCol;
10418141f61eSdrh 
104243617e9aSdrh         pTab = pItem->pTab;
104343617e9aSdrh         assert( pTab!=0 );
104443617e9aSdrh         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
10458141f61eSdrh         assert( pTab->nCol>0 );
10468141f61eSdrh         if( zTab ){
10478141f61eSdrh           if( pItem->zAlias ){
10488141f61eSdrh             char *zTabName = pItem->zAlias;
10494adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
10508141f61eSdrh           }else{
10518141f61eSdrh             char *zTabName = pTab->zName;
10524adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1053da184236Sdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
10548141f61eSdrh               continue;
10558141f61eSdrh             }
10568141f61eSdrh           }
10578141f61eSdrh         }
10588141f61eSdrh         if( 0==(cntTab++) ){
10598141f61eSdrh           pExpr->iTable = pItem->iCursor;
1060da184236Sdanielk1977           pExpr->pSchema = pTab->pSchema;
106151669863Sdrh           pMatch = pItem;
10628141f61eSdrh         }
10638141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
10644adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1065b3bf556eSdanielk1977             const char *zColl = pTab->aCol[j].zColl;
1066873fac0cSdrh             IdList *pUsing;
10678141f61eSdrh             cnt++;
10688141f61eSdrh             pExpr->iTable = pItem->iCursor;
106951669863Sdrh             pMatch = pItem;
1070da184236Sdanielk1977             pExpr->pSchema = pTab->pSchema;
10718141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
10728141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
1073a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
10748b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1075b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
10768b4c40d8Sdrh             }
107761dfc31dSdrh             if( i<pSrcList->nSrc-1 ){
107861dfc31dSdrh               if( pItem[1].jointype & JT_NATURAL ){
1079355ef361Sdrh                 /* If this match occurred in the left table of a natural join,
1080355ef361Sdrh                 ** then skip the right table to avoid a duplicate match */
1081355ef361Sdrh                 pItem++;
1082355ef361Sdrh                 i++;
108361dfc31dSdrh               }else if( (pUsing = pItem[1].pUsing)!=0 ){
1084873fac0cSdrh                 /* If this match occurs on a column that is in the USING clause
1085873fac0cSdrh                 ** of a join, skip the search of the right table of the join
1086873fac0cSdrh                 ** to avoid a duplicate match there. */
1087873fac0cSdrh                 int k;
1088873fac0cSdrh                 for(k=0; k<pUsing->nId; k++){
1089873fac0cSdrh                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
1090873fac0cSdrh                     pItem++;
1091873fac0cSdrh                     i++;
1092873fac0cSdrh                     break;
1093873fac0cSdrh                   }
1094873fac0cSdrh                 }
1095873fac0cSdrh               }
109661dfc31dSdrh             }
10978141f61eSdrh             break;
10988141f61eSdrh           }
10998141f61eSdrh         }
11008141f61eSdrh       }
1101b3bce662Sdanielk1977     }
11028141f61eSdrh 
1103b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
11048141f61eSdrh     /* If we have not already resolved the name, then maybe
11058141f61eSdrh     ** it is a new.* or old.* trigger argument reference
11068141f61eSdrh     */
11078141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
11088141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
11098141f61eSdrh       Table *pTab = 0;
11104adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
11118141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
11128141f61eSdrh         assert( pTriggerStack->pTab );
11138141f61eSdrh         pTab = pTriggerStack->pTab;
11144adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
11158141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
11168141f61eSdrh         assert( pTriggerStack->pTab );
11178141f61eSdrh         pTab = pTriggerStack->pTab;
11188141f61eSdrh       }
11198141f61eSdrh 
11208141f61eSdrh       if( pTab ){
1121f0113000Sdanielk1977         int iCol;
11228141f61eSdrh         Column *pCol = pTab->aCol;
11238141f61eSdrh 
1124da184236Sdanielk1977         pExpr->pSchema = pTab->pSchema;
11258141f61eSdrh         cntTab++;
1126f0113000Sdanielk1977         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
11274adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1128f0113000Sdanielk1977             const char *zColl = pTab->aCol[iCol].zColl;
11298141f61eSdrh             cnt++;
1130f0113000Sdanielk1977             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1131f0113000Sdanielk1977             pExpr->affinity = pTab->aCol[iCol].affinity;
11328b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1133b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
11348b4c40d8Sdrh             }
1135aee18ef8Sdanielk1977             pExpr->pTab = pTab;
11368141f61eSdrh             break;
11378141f61eSdrh           }
11388141f61eSdrh         }
11398141f61eSdrh       }
11408141f61eSdrh     }
1141b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
11428141f61eSdrh 
11438141f61eSdrh     /*
11448141f61eSdrh     ** Perhaps the name is a reference to the ROWID
11458141f61eSdrh     */
11464adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
11478141f61eSdrh       cnt = 1;
11488141f61eSdrh       pExpr->iColumn = -1;
11498a51256cSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
11508141f61eSdrh     }
11518141f61eSdrh 
11528141f61eSdrh     /*
11538141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
11548141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
11558141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
11568141f61eSdrh     **
11578141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
11588141f61eSdrh     **
11598141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
11608141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
11618141f61eSdrh     ** Note that the expression in the result set should have already been
11628141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
11638141f61eSdrh     */
1164ffe07b2dSdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
11658141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
11668141f61eSdrh         char *zAs = pEList->a[j].zName;
11674adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
116836379e97Sdrh           Expr *pDup, *pOrig;
11698141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
11704f07e5fbSdrh           assert( pExpr->pList==0 );
11714f07e5fbSdrh           assert( pExpr->pSelect==0 );
117236379e97Sdrh           pOrig = pEList->a[j].pExpr;
117336379e97Sdrh           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
117436379e97Sdrh             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
117517435752Sdrh             sqlite3_free(zCol);
117636379e97Sdrh             return 2;
117736379e97Sdrh           }
11781e536953Sdanielk1977           pDup = sqlite3ExprDup(db, pOrig);
11794f07e5fbSdrh           if( pExpr->flags & EP_ExpCollate ){
11804f07e5fbSdrh             pDup->pColl = pExpr->pColl;
11814f07e5fbSdrh             pDup->flags |= EP_ExpCollate;
11824f07e5fbSdrh           }
118317435752Sdrh           if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z);
118417435752Sdrh           if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z);
11854f07e5fbSdrh           memcpy(pExpr, pDup, sizeof(*pExpr));
118617435752Sdrh           sqlite3_free(pDup);
118715ccce1cSdrh           cnt = 1;
1188c9cf6e3dSdanielk1977           pMatch = 0;
11898141f61eSdrh           assert( zTab==0 && zDb==0 );
119015ccce1cSdrh           goto lookupname_end_2;
11918141f61eSdrh         }
11928141f61eSdrh       }
11938141f61eSdrh     }
11948141f61eSdrh 
1195626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
1196626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
1197626a879aSdrh     */
1198626a879aSdrh     if( cnt==0 ){
1199626a879aSdrh       pNC = pNC->pNext;
1200626a879aSdrh     }
1201626a879aSdrh   }
1202626a879aSdrh 
12038141f61eSdrh   /*
12048141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
12058141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
12068141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
12078141f61eSdrh   ** case, we need to return right away and not make any changes to
12088141f61eSdrh   ** pExpr.
120915ccce1cSdrh   **
121015ccce1cSdrh   ** Because no reference was made to outer contexts, the pNC->nRef
121115ccce1cSdrh   ** fields are not changed in any context.
12128141f61eSdrh   */
12138141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
121417435752Sdrh     sqlite3_free(zCol);
12158141f61eSdrh     return 0;
12168141f61eSdrh   }
12178141f61eSdrh 
12188141f61eSdrh   /*
12198141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
12208141f61eSdrh   ** more matches.  Either way, we have an error.
12218141f61eSdrh   */
12228141f61eSdrh   if( cnt!=1 ){
12238141f61eSdrh     char *z = 0;
12248141f61eSdrh     char *zErr;
12258141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
12268141f61eSdrh     if( zDb ){
1227f93339deSdrh       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
12288141f61eSdrh     }else if( zTab ){
1229f93339deSdrh       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
12308141f61eSdrh     }else{
123117435752Sdrh       z = sqlite3StrDup(zCol);
12328141f61eSdrh     }
1233*a1644fd8Sdanielk1977     if( z ){
12344adee20fSdanielk1977       sqlite3ErrorMsg(pParse, zErr, z);
123517435752Sdrh       sqlite3_free(z);
123673b211abSdrh       pTopNC->nErr++;
1237*a1644fd8Sdanielk1977     }else{
1238*a1644fd8Sdanielk1977       db->mallocFailed = 1;
1239*a1644fd8Sdanielk1977     }
12408141f61eSdrh   }
12418141f61eSdrh 
124251669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
124351669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
124451669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
124551669863Sdrh   ** column number is greater than the number of bits in the bitmask
124651669863Sdrh   ** then set the high-order bit of the bitmask.
124751669863Sdrh   */
124851669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
124951669863Sdrh     int n = pExpr->iColumn;
125051669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
125151669863Sdrh       n = sizeof(Bitmask)*8-1;
125251669863Sdrh     }
125351669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
1254ca83ac51Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
125551669863Sdrh   }
125651669863Sdrh 
1257d5d56523Sdanielk1977 lookupname_end:
12588141f61eSdrh   /* Clean up and return
12598141f61eSdrh   */
126017435752Sdrh   sqlite3_free(zDb);
126117435752Sdrh   sqlite3_free(zTab);
12624adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
12638141f61eSdrh   pExpr->pLeft = 0;
12644adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
12658141f61eSdrh   pExpr->pRight = 0;
12668141f61eSdrh   pExpr->op = TK_COLUMN;
126715ccce1cSdrh lookupname_end_2:
126817435752Sdrh   sqlite3_free(zCol);
1269626a879aSdrh   if( cnt==1 ){
1270b3bce662Sdanielk1977     assert( pNC!=0 );
1271626a879aSdrh     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1272aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
1273aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
1274aee18ef8Sdanielk1977     }
127515ccce1cSdrh     /* Increment the nRef value on all name contexts from TopNC up to
127615ccce1cSdrh     ** the point where the name matched. */
127715ccce1cSdrh     for(;;){
127815ccce1cSdrh       assert( pTopNC!=0 );
127915ccce1cSdrh       pTopNC->nRef++;
128015ccce1cSdrh       if( pTopNC==pNC ) break;
128115ccce1cSdrh       pTopNC = pTopNC->pNext;
1282626a879aSdrh     }
128315ccce1cSdrh     return 0;
128415ccce1cSdrh   } else {
128515ccce1cSdrh     return 1;
128615ccce1cSdrh   }
12878141f61eSdrh }
12888141f61eSdrh 
12898141f61eSdrh /*
1290626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1291626a879aSdrh **
129273b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1293626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
129473b211abSdrh ** the tree or 2 to abort the tree walk.
129573b211abSdrh **
129673b211abSdrh ** This routine also does error checking and name resolution for
129773b211abSdrh ** function names.  The operator for aggregate functions is changed
129873b211abSdrh ** to TK_AGG_FUNCTION.
1299626a879aSdrh */
1300626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1301626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1302626a879aSdrh   Parse *pParse;
1303626a879aSdrh 
1304b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1305626a879aSdrh   assert( pNC!=0 );
1306626a879aSdrh   pParse = pNC->pParse;
1307b3bce662Sdanielk1977 
1308626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1309626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1310626a879aSdrh #ifndef NDEBUG
1311f0113000Sdanielk1977   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1312f0113000Sdanielk1977     SrcList *pSrcList = pNC->pSrcList;
1313940fac9dSdanielk1977     int i;
1314f0113000Sdanielk1977     for(i=0; i<pNC->pSrcList->nSrc; i++){
1315626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1316626a879aSdrh     }
1317626a879aSdrh   }
1318626a879aSdrh #endif
1319626a879aSdrh   switch( pExpr->op ){
1320626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1321626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1322626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1323626a879aSdrh     */
1324626a879aSdrh     case TK_STRING: {
1325626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1326626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1327626a879aSdrh     }
1328626a879aSdrh     /* A lone identifier is the name of a column.
1329626a879aSdrh     */
1330626a879aSdrh     case TK_ID: {
1331626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1332626a879aSdrh       return 1;
1333626a879aSdrh     }
1334626a879aSdrh 
1335626a879aSdrh     /* A table name and column name:     ID.ID
1336626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1337626a879aSdrh     */
1338626a879aSdrh     case TK_DOT: {
1339626a879aSdrh       Token *pColumn;
1340626a879aSdrh       Token *pTable;
1341626a879aSdrh       Token *pDb;
1342626a879aSdrh       Expr *pRight;
1343626a879aSdrh 
1344b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1345626a879aSdrh       pRight = pExpr->pRight;
1346626a879aSdrh       if( pRight->op==TK_ID ){
1347626a879aSdrh         pDb = 0;
1348626a879aSdrh         pTable = &pExpr->pLeft->token;
1349626a879aSdrh         pColumn = &pRight->token;
1350626a879aSdrh       }else{
1351626a879aSdrh         assert( pRight->op==TK_DOT );
1352626a879aSdrh         pDb = &pExpr->pLeft->token;
1353626a879aSdrh         pTable = &pRight->pLeft->token;
1354626a879aSdrh         pColumn = &pRight->pRight->token;
1355626a879aSdrh       }
1356626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1357626a879aSdrh       return 1;
1358626a879aSdrh     }
1359626a879aSdrh 
1360626a879aSdrh     /* Resolve function names
1361626a879aSdrh     */
1362b71090fdSdrh     case TK_CONST_FUNC:
1363626a879aSdrh     case TK_FUNCTION: {
1364626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1365626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1366626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1367626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1368626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1369626a879aSdrh       int i;
13705169bbc6Sdrh       int auth;                   /* Authorization to use the function */
1371626a879aSdrh       int nId;                    /* Number of characters in function name */
1372626a879aSdrh       const char *zId;            /* The function name. */
137373b211abSdrh       FuncDef *pDef;              /* Information about the function */
137414db2665Sdanielk1977       int enc = ENC(pParse->db);  /* The database encoding */
1375626a879aSdrh 
13762646da7eSdrh       zId = (char*)pExpr->token.z;
1377b71090fdSdrh       nId = pExpr->token.n;
1378626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1379626a879aSdrh       if( pDef==0 ){
1380626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1381626a879aSdrh         if( pDef==0 ){
1382626a879aSdrh           no_such_func = 1;
1383626a879aSdrh         }else{
1384626a879aSdrh           wrong_num_args = 1;
1385626a879aSdrh         }
1386626a879aSdrh       }else{
1387626a879aSdrh         is_agg = pDef->xFunc==0;
1388626a879aSdrh       }
13892fca7fefSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
13905169bbc6Sdrh       if( pDef ){
13915169bbc6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
13925169bbc6Sdrh         if( auth!=SQLITE_OK ){
13935169bbc6Sdrh           if( auth==SQLITE_DENY ){
13945169bbc6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
13955169bbc6Sdrh                                     pDef->zName);
13965169bbc6Sdrh             pNC->nErr++;
13975169bbc6Sdrh           }
13985169bbc6Sdrh           pExpr->op = TK_NULL;
13995169bbc6Sdrh           return 1;
14005169bbc6Sdrh         }
14015169bbc6Sdrh       }
1402b8b14219Sdrh #endif
1403626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1404626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1405626a879aSdrh         pNC->nErr++;
1406626a879aSdrh         is_agg = 0;
1407626a879aSdrh       }else if( no_such_func ){
1408626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1409626a879aSdrh         pNC->nErr++;
1410626a879aSdrh       }else if( wrong_num_args ){
1411626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1412626a879aSdrh              nId, zId);
1413626a879aSdrh         pNC->nErr++;
1414626a879aSdrh       }
1415626a879aSdrh       if( is_agg ){
1416626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1417626a879aSdrh         pNC->hasAgg = 1;
1418626a879aSdrh       }
141973b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1420626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
142173b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1422626a879aSdrh       }
142373b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1424626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1425626a879aSdrh       ** type of the function
1426626a879aSdrh       */
1427626a879aSdrh       return is_agg;
1428626a879aSdrh     }
1429b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1430b3bce662Sdanielk1977     case TK_SELECT:
1431b3bce662Sdanielk1977     case TK_EXISTS:
1432b3bce662Sdanielk1977 #endif
1433b3bce662Sdanielk1977     case TK_IN: {
1434b3bce662Sdanielk1977       if( pExpr->pSelect ){
14358a9f38feSdrh         int nRef = pNC->nRef;
143606f6541eSdrh #ifndef SQLITE_OMIT_CHECK
143706f6541eSdrh         if( pNC->isCheck ){
143806f6541eSdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
143906f6541eSdrh         }
144006f6541eSdrh #endif
1441b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1442b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1443b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1444b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1445b3bce662Sdanielk1977         }
1446b3bce662Sdanielk1977       }
14474284fb07Sdrh       break;
1448b3bce662Sdanielk1977     }
14494284fb07Sdrh #ifndef SQLITE_OMIT_CHECK
14504284fb07Sdrh     case TK_VARIABLE: {
14514284fb07Sdrh       if( pNC->isCheck ){
14524284fb07Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
14534284fb07Sdrh       }
14544284fb07Sdrh       break;
14554284fb07Sdrh     }
14564284fb07Sdrh #endif
1457626a879aSdrh   }
1458626a879aSdrh   return 0;
1459626a879aSdrh }
1460626a879aSdrh 
1461626a879aSdrh /*
1462cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1463967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1464aacc543eSdrh ** index to the table in the table list and a column offset.  The
1465aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1466aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1467832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1468aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1469aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1470aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1471aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1472aacc543eSdrh ** alias for ROWID.
147319a775c2Sdrh **
1474626a879aSdrh ** Also resolve function names and check the functions for proper
1475626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1476626a879aSdrh ** have the correct number of arguments.  Leave an error message
1477626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1478626a879aSdrh **
147973b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
148073b211abSdrh ** property on the expression.
1481626a879aSdrh */
1482626a879aSdrh int sqlite3ExprResolveNames(
1483b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1484b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1485626a879aSdrh ){
148613449892Sdrh   int savedHasAgg;
148773b211abSdrh   if( pExpr==0 ) return 0;
1488fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
1489fc976065Sdanielk1977   if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
1490fc976065Sdanielk1977     sqlite3ErrorMsg(pNC->pParse,
1491fc976065Sdanielk1977        "Expression tree is too large (maximum depth %d)",
1492fc976065Sdanielk1977        SQLITE_MAX_EXPR_DEPTH
1493fc976065Sdanielk1977     );
1494fc976065Sdanielk1977     return 1;
1495fc976065Sdanielk1977   }
1496fc976065Sdanielk1977   pNC->pParse->nHeight += pExpr->nHeight;
1497fc976065Sdanielk1977 #endif
149813449892Sdrh   savedHasAgg = pNC->hasAgg;
149913449892Sdrh   pNC->hasAgg = 0;
1500b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1501fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
1502fc976065Sdanielk1977   pNC->pParse->nHeight -= pExpr->nHeight;
1503fc976065Sdanielk1977 #endif
1504b3bce662Sdanielk1977   if( pNC->nErr>0 ){
150573b211abSdrh     ExprSetProperty(pExpr, EP_Error);
150673b211abSdrh   }
150713449892Sdrh   if( pNC->hasAgg ){
150813449892Sdrh     ExprSetProperty(pExpr, EP_Agg);
150913449892Sdrh   }else if( savedHasAgg ){
151013449892Sdrh     pNC->hasAgg = 1;
151113449892Sdrh   }
151273b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1513626a879aSdrh }
1514626a879aSdrh 
15151398ad36Sdrh /*
15161398ad36Sdrh ** A pointer instance of this structure is used to pass information
15171398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
15181398ad36Sdrh */
15191398ad36Sdrh typedef struct QueryCoder QueryCoder;
15201398ad36Sdrh struct QueryCoder {
15211398ad36Sdrh   Parse *pParse;       /* The parsing context */
15221398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
15231398ad36Sdrh };
15241398ad36Sdrh 
1525626a879aSdrh 
1526626a879aSdrh /*
15279cbe6352Sdrh ** Generate code for scalar subqueries used as an expression
15289cbe6352Sdrh ** and IN operators.  Examples:
1529626a879aSdrh **
15309cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
15319cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
15329cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
15339cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1534fef5208cSdrh **
15359cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
15369cbe6352Sdrh ** operator or subquery.
1537cce7d176Sdrh */
153851522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1539b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
154057dbd7b3Sdrh   int testAddr = 0;                       /* One-time test address */
1541b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1542b3bce662Sdanielk1977   if( v==0 ) return;
1543b3bce662Sdanielk1977 
1544fc976065Sdanielk1977 
154557dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
154657dbd7b3Sdrh   ** if any of the following is true:
154757dbd7b3Sdrh   **
154857dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
154957dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
155057dbd7b3Sdrh   **    *  We are inside a trigger
155157dbd7b3Sdrh   **
155257dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
155357dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1554b3bce662Sdanielk1977   */
1555b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1556b3bce662Sdanielk1977     int mem = pParse->nMem++;
1557b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
155857dbd7b3Sdrh     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
155917435752Sdrh     assert( testAddr>0 || pParse->db->mallocFailed );
1560d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1561b3bce662Sdanielk1977   }
1562b3bce662Sdanielk1977 
1563cce7d176Sdrh   switch( pExpr->op ){
1564fef5208cSdrh     case TK_IN: {
1565e014a838Sdanielk1977       char affinity;
1566d3d39e93Sdrh       KeyInfo keyInfo;
1567b9bb7c18Sdrh       int addr;        /* Address of OP_OpenEphemeral instruction */
1568d3d39e93Sdrh 
1569bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1570e014a838Sdanielk1977 
1571e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
157257dbd7b3Sdrh       ** expression it is handled the same way. A virtual table is
1573e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1574e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1575fef5208cSdrh       **
1576e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1577e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1578e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1579e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1580e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1581e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1582e014a838Sdanielk1977       ** is used.
1583fef5208cSdrh       */
1584832508b7Sdrh       pExpr->iTable = pParse->nTab++;
1585b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
1586d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1587d3d39e93Sdrh       keyInfo.nField = 1;
1588f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1589e014a838Sdanielk1977 
1590e014a838Sdanielk1977       if( pExpr->pSelect ){
1591e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1592e014a838Sdanielk1977         **
1593e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1594e014a838Sdanielk1977         ** table allocated and opened above.
1595e014a838Sdanielk1977         */
1596e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1597be5c89acSdrh         ExprList *pEList;
1598e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
159994ccde58Sdrh         if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
160094ccde58Sdrh           return;
160194ccde58Sdrh         }
1602be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1603be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
1604bcbb04e5Sdanielk1977           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1605be5c89acSdrh               pEList->a[0].pExpr);
16060202b29eSdanielk1977         }
1607fef5208cSdrh       }else if( pExpr->pList ){
1608fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1609fef5208cSdrh         **
1610e014a838Sdanielk1977         ** For each expression, build an index key from the evaluation and
1611e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1612e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1613e014a838Sdanielk1977         ** a column, use numeric affinity.
1614fef5208cSdrh         */
1615e014a838Sdanielk1977         int i;
161657dbd7b3Sdrh         ExprList *pList = pExpr->pList;
161757dbd7b3Sdrh         struct ExprList_item *pItem;
161857dbd7b3Sdrh 
1619e014a838Sdanielk1977         if( !affinity ){
16208159a35fSdrh           affinity = SQLITE_AFF_NONE;
1621e014a838Sdanielk1977         }
16220202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1623e014a838Sdanielk1977 
1624e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
162557dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
162657dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1627e014a838Sdanielk1977 
162857dbd7b3Sdrh           /* If the expression is not constant then we will need to
162957dbd7b3Sdrh           ** disable the test that was generated above that makes sure
163057dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
163157dbd7b3Sdrh           ** expression we need to rerun this code each time.
163257dbd7b3Sdrh           */
16336c30be8eSdrh           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
1634f8875400Sdrh             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
163557dbd7b3Sdrh             testAddr = 0;
16364794b980Sdrh           }
1637e014a838Sdanielk1977 
1638e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
16394adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
164094a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1641f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1642fef5208cSdrh         }
1643fef5208cSdrh       }
16440202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1645b3bce662Sdanielk1977       break;
1646fef5208cSdrh     }
1647fef5208cSdrh 
164851522cd3Sdrh     case TK_EXISTS:
164919a775c2Sdrh     case TK_SELECT: {
1650fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1651fef5208cSdrh       ** value of this select in a memory cell and record the number
1652967e8b73Sdrh       ** of the memory cell in iColumn.
1653fef5208cSdrh       */
16542646da7eSdrh       static const Token one = { (u8*)"1", 0, 1 };
165551522cd3Sdrh       Select *pSel;
1656ec7429aeSdrh       int iMem;
1657ec7429aeSdrh       int sop;
16581398ad36Sdrh 
1659ec7429aeSdrh       pExpr->iColumn = iMem = pParse->nMem++;
166051522cd3Sdrh       pSel = pExpr->pSelect;
166151522cd3Sdrh       if( pExpr->op==TK_SELECT ){
166251522cd3Sdrh         sop = SRT_Mem;
1663ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1664ec7429aeSdrh         VdbeComment((v, "# Init subquery result"));
166551522cd3Sdrh       }else{
166651522cd3Sdrh         sop = SRT_Exists;
1667ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1668ec7429aeSdrh         VdbeComment((v, "# Init EXISTS result"));
166951522cd3Sdrh       }
1670ec7429aeSdrh       sqlite3ExprDelete(pSel->pLimit);
1671*a1644fd8Sdanielk1977       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
167294ccde58Sdrh       if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
167394ccde58Sdrh         return;
167494ccde58Sdrh       }
1675b3bce662Sdanielk1977       break;
167619a775c2Sdrh     }
1677cce7d176Sdrh   }
1678b3bce662Sdanielk1977 
167957dbd7b3Sdrh   if( testAddr ){
1680d654be80Sdrh     sqlite3VdbeJumpHere(v, testAddr);
1681b3bce662Sdanielk1977   }
1682fc976065Sdanielk1977 
1683b3bce662Sdanielk1977   return;
1684cce7d176Sdrh }
168551522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1686cce7d176Sdrh 
1687cce7d176Sdrh /*
1688fec19aadSdrh ** Generate an instruction that will put the integer describe by
1689fec19aadSdrh ** text z[0..n-1] on the stack.
1690fec19aadSdrh */
1691fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1692abb6fcabSdrh   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
1693c9cf901dSdanielk1977   if( z ){
1694fec19aadSdrh     int i;
16956fec0762Sdrh     if( sqlite3GetInt32(z, &i) ){
16966fec0762Sdrh       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
16976fec0762Sdrh     }else if( sqlite3FitsIn64Bits(z) ){
169829dda4aeSdrh       sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1699fec19aadSdrh     }else{
1700fec19aadSdrh       sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1701fec19aadSdrh     }
1702fec19aadSdrh   }
1703c9cf901dSdanielk1977 }
1704fec19aadSdrh 
1705945498f3Sdrh 
1706945498f3Sdrh /*
1707945498f3Sdrh ** Generate code that will extract the iColumn-th column from
1708945498f3Sdrh ** table pTab and push that column value on the stack.  There
1709945498f3Sdrh ** is an open cursor to pTab in iTable.  If iColumn<0 then
1710945498f3Sdrh ** code is generated that extracts the rowid.
1711945498f3Sdrh */
1712945498f3Sdrh void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
1713945498f3Sdrh   if( iColumn<0 ){
1714945498f3Sdrh     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
1715945498f3Sdrh     sqlite3VdbeAddOp(v, op, iTable, 0);
1716945498f3Sdrh   }else if( pTab==0 ){
1717945498f3Sdrh     sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
1718945498f3Sdrh   }else{
1719945498f3Sdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
1720945498f3Sdrh     sqlite3VdbeAddOp(v, op, iTable, iColumn);
1721945498f3Sdrh     sqlite3ColumnDefault(v, pTab, iColumn);
1722945498f3Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
1723945498f3Sdrh     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
1724945498f3Sdrh       sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
1725945498f3Sdrh     }
1726945498f3Sdrh #endif
1727945498f3Sdrh   }
1728945498f3Sdrh }
1729945498f3Sdrh 
1730fec19aadSdrh /*
1731cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
17321ccde15dSdrh ** expression and leave the result on the top of stack.
1733f2bc013cSdrh **
1734f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1735f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1736f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1737f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1738f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1739cce7d176Sdrh */
17404adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1741cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1742cce7d176Sdrh   int op;
1743ffe07b2dSdrh   int stackChng = 1;    /* Amount of change to stack depth */
1744ffe07b2dSdrh 
17457977a17fSdanielk1977   if( v==0 ) return;
17467977a17fSdanielk1977   if( pExpr==0 ){
1747f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
17487977a17fSdanielk1977     return;
17497977a17fSdanielk1977   }
1750f2bc013cSdrh   op = pExpr->op;
1751f2bc013cSdrh   switch( op ){
175213449892Sdrh     case TK_AGG_COLUMN: {
175313449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
175413449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
175513449892Sdrh       if( !pAggInfo->directMode ){
175613449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
175713449892Sdrh         break;
175813449892Sdrh       }else if( pAggInfo->useSortingIdx ){
175913449892Sdrh         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
176013449892Sdrh                               pCol->iSorterColumn);
176113449892Sdrh         break;
176213449892Sdrh       }
176313449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
176413449892Sdrh     }
1765967e8b73Sdrh     case TK_COLUMN: {
1766ffe07b2dSdrh       if( pExpr->iTable<0 ){
1767ffe07b2dSdrh         /* This only happens when coding check constraints */
1768ffe07b2dSdrh         assert( pParse->ckOffset>0 );
1769ffe07b2dSdrh         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1770c4a3c779Sdrh       }else{
1771945498f3Sdrh         sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
17722282792aSdrh       }
1773cce7d176Sdrh       break;
1774cce7d176Sdrh     }
1775cce7d176Sdrh     case TK_INTEGER: {
17762646da7eSdrh       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1777fec19aadSdrh       break;
177851e9a445Sdrh     }
1779fec19aadSdrh     case TK_FLOAT:
1780fec19aadSdrh     case TK_STRING: {
1781f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1782f2bc013cSdrh       assert( TK_STRING==OP_String8 );
17831e536953Sdanielk1977       sqlite3DequoteExpr(pParse->db, pExpr);
17842646da7eSdrh       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1785cce7d176Sdrh       break;
1786cce7d176Sdrh     }
1787f0863fe5Sdrh     case TK_NULL: {
1788f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1789f0863fe5Sdrh       break;
1790f0863fe5Sdrh     }
17915338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1792c572ef7fSdanielk1977     case TK_BLOB: {
17936c8c6cecSdrh       int n;
17946c8c6cecSdrh       const char *z;
1795f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
17966c8c6cecSdrh       n = pExpr->token.n - 3;
17972646da7eSdrh       z = (char*)pExpr->token.z + 2;
17986c8c6cecSdrh       assert( n>=0 );
17996c8c6cecSdrh       if( n==0 ){
18006c8c6cecSdrh         z = "";
18016c8c6cecSdrh       }
18026c8c6cecSdrh       sqlite3VdbeOp3(v, op, 0, 0, z, n);
1803c572ef7fSdanielk1977       break;
1804c572ef7fSdanielk1977     }
18055338a5f7Sdanielk1977 #endif
180650457896Sdrh     case TK_VARIABLE: {
18074adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1808895d7472Sdrh       if( pExpr->token.n>1 ){
18092646da7eSdrh         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1810895d7472Sdrh       }
181150457896Sdrh       break;
181250457896Sdrh     }
18134e0cff60Sdrh     case TK_REGISTER: {
18144e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
18154e0cff60Sdrh       break;
18164e0cff60Sdrh     }
1817487e262fSdrh #ifndef SQLITE_OMIT_CAST
1818487e262fSdrh     case TK_CAST: {
1819487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
1820f0113000Sdanielk1977       int aff, to_op;
1821487e262fSdrh       sqlite3ExprCode(pParse, pExpr->pLeft);
18228a51256cSdrh       aff = sqlite3AffinityType(&pExpr->token);
1823f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1824f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
1825f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
1826f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1827f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
1828f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
1829f0113000Sdanielk1977       sqlite3VdbeAddOp(v, to_op, 0, 0);
1830ffe07b2dSdrh       stackChng = 0;
1831487e262fSdrh       break;
1832487e262fSdrh     }
1833487e262fSdrh #endif /* SQLITE_OMIT_CAST */
1834c9b84a1fSdrh     case TK_LT:
1835c9b84a1fSdrh     case TK_LE:
1836c9b84a1fSdrh     case TK_GT:
1837c9b84a1fSdrh     case TK_GE:
1838c9b84a1fSdrh     case TK_NE:
1839c9b84a1fSdrh     case TK_EQ: {
1840f2bc013cSdrh       assert( TK_LT==OP_Lt );
1841f2bc013cSdrh       assert( TK_LE==OP_Le );
1842f2bc013cSdrh       assert( TK_GT==OP_Gt );
1843f2bc013cSdrh       assert( TK_GE==OP_Ge );
1844f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1845f2bc013cSdrh       assert( TK_NE==OP_Ne );
1846a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1847a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1848be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1849ffe07b2dSdrh       stackChng = -1;
1850a37cdde0Sdanielk1977       break;
1851c9b84a1fSdrh     }
1852cce7d176Sdrh     case TK_AND:
1853cce7d176Sdrh     case TK_OR:
1854cce7d176Sdrh     case TK_PLUS:
1855cce7d176Sdrh     case TK_STAR:
1856cce7d176Sdrh     case TK_MINUS:
1857bf4133cbSdrh     case TK_REM:
1858bf4133cbSdrh     case TK_BITAND:
1859bf4133cbSdrh     case TK_BITOR:
186017c40294Sdrh     case TK_SLASH:
1861bf4133cbSdrh     case TK_LSHIFT:
1862855eb1cfSdrh     case TK_RSHIFT:
18630040077dSdrh     case TK_CONCAT: {
1864f2bc013cSdrh       assert( TK_AND==OP_And );
1865f2bc013cSdrh       assert( TK_OR==OP_Or );
1866f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1867f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1868f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1869f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1870f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1871f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1872f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1873f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1874f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
18754adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18764adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1877855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
1878ffe07b2dSdrh       stackChng = -1;
18790040077dSdrh       break;
18800040077dSdrh     }
1881cce7d176Sdrh     case TK_UMINUS: {
1882fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1883fec19aadSdrh       assert( pLeft );
1884fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1885fec19aadSdrh         Token *p = &pLeft->token;
18861e536953Sdanielk1977         char *z = sqlite3MPrintf(pParse->db, "-%.*s", p->n, p->z);
1887fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1888fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1889e6840900Sdrh         }else{
1890fec19aadSdrh           codeInteger(v, z, p->n+1);
1891e6840900Sdrh         }
189217435752Sdrh         sqlite3_free(z);
18936e142f54Sdrh         break;
18946e142f54Sdrh       }
18951ccde15dSdrh       /* Fall through into TK_NOT */
18966e142f54Sdrh     }
1897bf4133cbSdrh     case TK_BITNOT:
18986e142f54Sdrh     case TK_NOT: {
1899f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1900f2bc013cSdrh       assert( TK_NOT==OP_Not );
19014adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19024adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1903ffe07b2dSdrh       stackChng = 0;
1904cce7d176Sdrh       break;
1905cce7d176Sdrh     }
1906cce7d176Sdrh     case TK_ISNULL:
1907cce7d176Sdrh     case TK_NOTNULL: {
1908cce7d176Sdrh       int dest;
1909f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1910f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
19114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
19124adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19134adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
19144adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
19154adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1916ffe07b2dSdrh       stackChng = 0;
1917a37cdde0Sdanielk1977       break;
1918f2bc013cSdrh     }
19192282792aSdrh     case TK_AGG_FUNCTION: {
192013449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
19217e56e711Sdrh       if( pInfo==0 ){
19227e56e711Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
19237e56e711Sdrh             &pExpr->span);
19247e56e711Sdrh       }else{
192513449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
19267e56e711Sdrh       }
19272282792aSdrh       break;
19282282792aSdrh     }
1929b71090fdSdrh     case TK_CONST_FUNC:
1930cce7d176Sdrh     case TK_FUNCTION: {
1931cce7d176Sdrh       ExprList *pList = pExpr->pList;
193289425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
19330bce8354Sdrh       FuncDef *pDef;
19344b59ab5eSdrh       int nId;
19354b59ab5eSdrh       const char *zId;
193613449892Sdrh       int constMask = 0;
1937682f68b0Sdanielk1977       int i;
193817435752Sdrh       sqlite3 *db = pParse->db;
193917435752Sdrh       u8 enc = ENC(db);
1940dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
194117435752Sdrh 
19422646da7eSdrh       zId = (char*)pExpr->token.z;
1943b71090fdSdrh       nId = pExpr->token.n;
1944d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
19450bce8354Sdrh       assert( pDef!=0 );
1946f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1947b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1948a43fa227Sdrh       /* Possibly overload the function if the first argument is
1949a43fa227Sdrh       ** a virtual table column.
1950a43fa227Sdrh       **
1951a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1952a43fa227Sdrh       ** second argument, not the first, as the argument to test to
1953a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
1954a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
1955a43fa227Sdrh       ** control overloading) ends up as the second argument to the
1956a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
1957a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
1958a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
1959a43fa227Sdrh       */
19606a03a1c5Sdrh       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
196117435752Sdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
19626a03a1c5Sdrh       }else if( nExpr>0 ){
196317435752Sdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
1964b7f6f68fSdrh       }
1965b7f6f68fSdrh #endif
1966682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1967d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
196813449892Sdrh           constMask |= (1<<i);
1969d02eb1fdSdanielk1977         }
1970dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1971dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1972dc1bdc4fSdanielk1977         }
1973dc1bdc4fSdanielk1977       }
1974dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1975dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1976d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1977682f68b0Sdanielk1977       }
197813449892Sdrh       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1979ffe07b2dSdrh       stackChng = 1-nExpr;
19806ec2733bSdrh       break;
19816ec2733bSdrh     }
1982fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1983fe2093d7Sdrh     case TK_EXISTS:
198419a775c2Sdrh     case TK_SELECT: {
198541714d6fSdrh       if( pExpr->iColumn==0 ){
1986b3bce662Sdanielk1977         sqlite3CodeSubselect(pParse, pExpr);
198741714d6fSdrh       }
19884adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1989ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
199019a775c2Sdrh       break;
199119a775c2Sdrh     }
1992fef5208cSdrh     case TK_IN: {
1993fef5208cSdrh       int addr;
199494a11211Sdrh       char affinity;
1995afa5f680Sdrh       int ckOffset = pParse->ckOffset;
1996b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
1997e014a838Sdanielk1977 
1998e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1999e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
2000ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
2001e014a838Sdanielk1977       */
200294a11211Sdrh       affinity = comparisonAffinity(pExpr);
2003e014a838Sdanielk1977 
20044adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
2005cdbd8effSdanielk1977       pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
2006e014a838Sdanielk1977 
2007e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
2008e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
2009e014a838Sdanielk1977       */
20104adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20114adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
2012e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
20134adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
2014f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
2015e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
201694a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
2017e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
2018e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
2019e014a838Sdanielk1977 
2020fef5208cSdrh       break;
2021fef5208cSdrh     }
202293758c8dSdanielk1977 #endif
2023fef5208cSdrh     case TK_BETWEEN: {
2024be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2025be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
2026be5c89acSdrh       Expr *pRight = pLItem->pExpr;
2027be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
20284adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2029be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2030be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
20314adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
2032be5c89acSdrh       pLItem++;
2033be5c89acSdrh       pRight = pLItem->pExpr;
2034be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2035be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
20364adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
2037fef5208cSdrh       break;
2038fef5208cSdrh     }
20394f07e5fbSdrh     case TK_UPLUS: {
20404adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
2041ffe07b2dSdrh       stackChng = 0;
2042a2e00042Sdrh       break;
2043a2e00042Sdrh     }
204417a7f8ddSdrh     case TK_CASE: {
204517a7f8ddSdrh       int expr_end_label;
2046f5905aa7Sdrh       int jumpInst;
2047f5905aa7Sdrh       int nExpr;
204817a7f8ddSdrh       int i;
2049be5c89acSdrh       ExprList *pEList;
2050be5c89acSdrh       struct ExprList_item *aListelem;
205117a7f8ddSdrh 
205217a7f8ddSdrh       assert(pExpr->pList);
205317a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
205417a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
2055be5c89acSdrh       pEList = pExpr->pList;
2056be5c89acSdrh       aListelem = pEList->a;
2057be5c89acSdrh       nExpr = pEList->nExpr;
20584adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
205917a7f8ddSdrh       if( pExpr->pLeft ){
20604adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
2061cce7d176Sdrh       }
2062f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
2063be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
206417a7f8ddSdrh         if( pExpr->pLeft ){
20654adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
2066be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
2067be5c89acSdrh                                  OP_Ne, 0, 1);
20684adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2069f5905aa7Sdrh         }else{
20704adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
207117a7f8ddSdrh         }
2072be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
20734adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
2074d654be80Sdrh         sqlite3VdbeJumpHere(v, jumpInst);
207517a7f8ddSdrh       }
2076f570f011Sdrh       if( pExpr->pLeft ){
20774adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2078f570f011Sdrh       }
207917a7f8ddSdrh       if( pExpr->pRight ){
20804adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
208117a7f8ddSdrh       }else{
2082f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
208317a7f8ddSdrh       }
20844adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
20856f34903eSdanielk1977       break;
20866f34903eSdanielk1977     }
20875338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
20886f34903eSdanielk1977     case TK_RAISE: {
20896f34903eSdanielk1977       if( !pParse->trigStack ){
20904adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
2091da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
20926f34903eSdanielk1977         return;
20936f34903eSdanielk1977       }
2094ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
2095ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
20966f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
2097ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
20981e536953Sdanielk1977          sqlite3DequoteExpr(pParse->db, pExpr);
20994adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
21002646da7eSdrh                         (char*)pExpr->token.z, pExpr->token.n);
21016f34903eSdanielk1977       } else {
21026f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
2103344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
2104ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
2105ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
21066f34903eSdanielk1977       }
2107ffe07b2dSdrh       stackChng = 0;
2108ffe07b2dSdrh       break;
210917a7f8ddSdrh     }
21105338a5f7Sdanielk1977 #endif
2111ffe07b2dSdrh   }
2112ffe07b2dSdrh 
2113ffe07b2dSdrh   if( pParse->ckOffset ){
2114ffe07b2dSdrh     pParse->ckOffset += stackChng;
2115ffe07b2dSdrh     assert( pParse->ckOffset );
211617a7f8ddSdrh   }
2117cce7d176Sdrh }
2118cce7d176Sdrh 
211993758c8dSdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
2120cce7d176Sdrh /*
212125303780Sdrh ** Generate code that evalutes the given expression and leaves the result
212225303780Sdrh ** on the stack.  See also sqlite3ExprCode().
212325303780Sdrh **
212425303780Sdrh ** This routine might also cache the result and modify the pExpr tree
212525303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
212625303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
212725303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
212825303780Sdrh ** memory location.
212925303780Sdrh */
213025303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
213125303780Sdrh   Vdbe *v = pParse->pVdbe;
213225303780Sdrh   int iMem;
213325303780Sdrh   int addr1, addr2;
213425303780Sdrh   if( v==0 ) return;
213525303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
213625303780Sdrh   sqlite3ExprCode(pParse, pExpr);
213725303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
213825303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
213925303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
214025303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
214125303780Sdrh     pExpr->op = TK_REGISTER;
214225303780Sdrh   }
214325303780Sdrh }
214493758c8dSdanielk1977 #endif
214525303780Sdrh 
214625303780Sdrh /*
2147268380caSdrh ** Generate code that pushes the value of every element of the given
2148f9b596ebSdrh ** expression list onto the stack.
2149268380caSdrh **
2150268380caSdrh ** Return the number of elements pushed onto the stack.
2151268380caSdrh */
21524adee20fSdanielk1977 int sqlite3ExprCodeExprList(
2153268380caSdrh   Parse *pParse,     /* Parsing context */
2154f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
2155268380caSdrh ){
2156268380caSdrh   struct ExprList_item *pItem;
2157268380caSdrh   int i, n;
2158268380caSdrh   if( pList==0 ) return 0;
2159268380caSdrh   n = pList->nExpr;
2160c182d163Sdrh   for(pItem=pList->a, i=n; i>0; i--, pItem++){
21614adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
2162268380caSdrh   }
2163f9b596ebSdrh   return n;
2164268380caSdrh }
2165268380caSdrh 
2166268380caSdrh /*
2167cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
2168cce7d176Sdrh ** to the label "dest" if the expression is true but execution
2169cce7d176Sdrh ** continues straight thru if the expression is false.
2170f5905aa7Sdrh **
2171f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
2172f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
2173f2bc013cSdrh **
2174f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
2175f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2176f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
2177f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
2178f2bc013cSdrh ** below verify that the numbers are aligned correctly.
2179cce7d176Sdrh */
21804adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2181cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2182cce7d176Sdrh   int op = 0;
2183ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2184daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2185f2bc013cSdrh   op = pExpr->op;
2186f2bc013cSdrh   switch( op ){
2187cce7d176Sdrh     case TK_AND: {
21884adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
21894adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
21904adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
21914adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2192cce7d176Sdrh       break;
2193cce7d176Sdrh     }
2194cce7d176Sdrh     case TK_OR: {
21954adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
21964adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2197cce7d176Sdrh       break;
2198cce7d176Sdrh     }
2199cce7d176Sdrh     case TK_NOT: {
22004adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2201cce7d176Sdrh       break;
2202cce7d176Sdrh     }
2203cce7d176Sdrh     case TK_LT:
2204cce7d176Sdrh     case TK_LE:
2205cce7d176Sdrh     case TK_GT:
2206cce7d176Sdrh     case TK_GE:
2207cce7d176Sdrh     case TK_NE:
22080ac65892Sdrh     case TK_EQ: {
2209f2bc013cSdrh       assert( TK_LT==OP_Lt );
2210f2bc013cSdrh       assert( TK_LE==OP_Le );
2211f2bc013cSdrh       assert( TK_GT==OP_Gt );
2212f2bc013cSdrh       assert( TK_GE==OP_Ge );
2213f2bc013cSdrh       assert( TK_EQ==OP_Eq );
2214f2bc013cSdrh       assert( TK_NE==OP_Ne );
22154adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
22164adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2217be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2218cce7d176Sdrh       break;
2219cce7d176Sdrh     }
2220cce7d176Sdrh     case TK_ISNULL:
2221cce7d176Sdrh     case TK_NOTNULL: {
2222f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
2223f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
22244adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
22254adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2226cce7d176Sdrh       break;
2227cce7d176Sdrh     }
2228fef5208cSdrh     case TK_BETWEEN: {
22290202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
22300202b29eSdanielk1977       **
22310202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
22320202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
22330202b29eSdanielk1977       ** 3 ...
22340202b29eSdanielk1977       */
2235f5905aa7Sdrh       int addr;
2236be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2237be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2238be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
22394adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2240be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2241be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
22420202b29eSdanielk1977 
2243be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2244be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2245be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
22460202b29eSdanielk1977 
22474adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2248d654be80Sdrh       sqlite3VdbeJumpHere(v, addr);
22494adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2250fef5208cSdrh       break;
2251fef5208cSdrh     }
2252cce7d176Sdrh     default: {
22534adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
22544adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
2255cce7d176Sdrh       break;
2256cce7d176Sdrh     }
2257cce7d176Sdrh   }
2258ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2259cce7d176Sdrh }
2260cce7d176Sdrh 
2261cce7d176Sdrh /*
226266b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
2263cce7d176Sdrh ** to the label "dest" if the expression is false but execution
2264cce7d176Sdrh ** continues straight thru if the expression is true.
2265f5905aa7Sdrh **
2266f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
2267f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
2268cce7d176Sdrh */
22694adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2270cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2271cce7d176Sdrh   int op = 0;
2272ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2273daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2274f2bc013cSdrh 
2275f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
2276f2bc013cSdrh   **
2277f2bc013cSdrh   **       pExpr->op            op
2278f2bc013cSdrh   **       ---------          ----------
2279f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
2280f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
2281f2bc013cSdrh   **       TK_NE              OP_Eq
2282f2bc013cSdrh   **       TK_EQ              OP_Ne
2283f2bc013cSdrh   **       TK_GT              OP_Le
2284f2bc013cSdrh   **       TK_LE              OP_Gt
2285f2bc013cSdrh   **       TK_GE              OP_Lt
2286f2bc013cSdrh   **       TK_LT              OP_Ge
2287f2bc013cSdrh   **
2288f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
2289f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
2290f2bc013cSdrh   ** can compute the mapping above using the following expression.
2291f2bc013cSdrh   ** Assert()s verify that the computation is correct.
2292f2bc013cSdrh   */
2293f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2294f2bc013cSdrh 
2295f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
2296f2bc013cSdrh   */
2297f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2298f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2299f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
2300f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
2301f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
2302f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
2303f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
2304f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
2305f2bc013cSdrh 
2306cce7d176Sdrh   switch( pExpr->op ){
2307cce7d176Sdrh     case TK_AND: {
23084adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
23094adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2310cce7d176Sdrh       break;
2311cce7d176Sdrh     }
2312cce7d176Sdrh     case TK_OR: {
23134adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
23144adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
23154adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
23164adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2317cce7d176Sdrh       break;
2318cce7d176Sdrh     }
2319cce7d176Sdrh     case TK_NOT: {
23204adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2321cce7d176Sdrh       break;
2322cce7d176Sdrh     }
2323cce7d176Sdrh     case TK_LT:
2324cce7d176Sdrh     case TK_LE:
2325cce7d176Sdrh     case TK_GT:
2326cce7d176Sdrh     case TK_GE:
2327cce7d176Sdrh     case TK_NE:
2328cce7d176Sdrh     case TK_EQ: {
23294adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
23304adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2331be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2332cce7d176Sdrh       break;
2333cce7d176Sdrh     }
2334cce7d176Sdrh     case TK_ISNULL:
2335cce7d176Sdrh     case TK_NOTNULL: {
23364adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
23374adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2338cce7d176Sdrh       break;
2339cce7d176Sdrh     }
2340fef5208cSdrh     case TK_BETWEEN: {
23410202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
23420202b29eSdanielk1977       **
23430202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
23440202b29eSdanielk1977       ** 2 GOTO <dest>
23450202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
23460202b29eSdanielk1977       */
2347fef5208cSdrh       int addr;
2348be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2349be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2350be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
23514adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2352be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
23534adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
2354be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2355be5c89acSdrh 
23564adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
23574adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2358be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2359be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2360be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2361fef5208cSdrh       break;
2362fef5208cSdrh     }
2363cce7d176Sdrh     default: {
23644adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
23654adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2366cce7d176Sdrh       break;
2367cce7d176Sdrh     }
2368cce7d176Sdrh   }
2369ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2370cce7d176Sdrh }
23712282792aSdrh 
23722282792aSdrh /*
23732282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
23742282792aSdrh ** if they are identical and return FALSE if they differ in any way.
2375d40aab0eSdrh **
2376d40aab0eSdrh ** Sometimes this routine will return FALSE even if the two expressions
2377d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
2378d40aab0eSdrh ** identical, we return FALSE just to be safe.  So if this routine
2379d40aab0eSdrh ** returns false, then you do not really know for certain if the two
2380d40aab0eSdrh ** expressions are the same.  But if you get a TRUE return, then you
2381d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
2382d40aab0eSdrh ** this routine is used, it does not hurt to get an extra FALSE - that
2383d40aab0eSdrh ** just might result in some slightly slower code.  But returning
2384d40aab0eSdrh ** an incorrect TRUE could lead to a malfunction.
23852282792aSdrh */
23864adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
23872282792aSdrh   int i;
23884b202ae2Sdanielk1977   if( pA==0||pB==0 ){
23894b202ae2Sdanielk1977     return pB==pA;
23902282792aSdrh   }
23912282792aSdrh   if( pA->op!=pB->op ) return 0;
2392fd357974Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
23934adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
23944adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
23952282792aSdrh   if( pA->pList ){
23962282792aSdrh     if( pB->pList==0 ) return 0;
23972282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
23982282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
23994adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
24002282792aSdrh         return 0;
24012282792aSdrh       }
24022282792aSdrh     }
24032282792aSdrh   }else if( pB->pList ){
24042282792aSdrh     return 0;
24052282792aSdrh   }
24062282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
24072f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
2408dd73521bSdrh   if( pA->op!=TK_COLUMN && pA->token.z ){
24092282792aSdrh     if( pB->token.z==0 ) return 0;
24106977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
24112646da7eSdrh     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
24122646da7eSdrh       return 0;
24132646da7eSdrh     }
24142282792aSdrh   }
24152282792aSdrh   return 1;
24162282792aSdrh }
24172282792aSdrh 
241813449892Sdrh 
24192282792aSdrh /*
242013449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
242113449892Sdrh ** the new element.  Return a negative number if malloc fails.
24222282792aSdrh */
242317435752Sdrh static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
242413449892Sdrh   int i;
2425cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
242617435752Sdrh        db,
2427cf643729Sdrh        pInfo->aCol,
2428cf643729Sdrh        sizeof(pInfo->aCol[0]),
2429cf643729Sdrh        3,
2430cf643729Sdrh        &pInfo->nColumn,
2431cf643729Sdrh        &pInfo->nColumnAlloc,
2432cf643729Sdrh        &i
2433cf643729Sdrh   );
243413449892Sdrh   return i;
24352282792aSdrh }
243613449892Sdrh 
243713449892Sdrh /*
243813449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
243913449892Sdrh ** the new element.  Return a negative number if malloc fails.
244013449892Sdrh */
244117435752Sdrh static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
244213449892Sdrh   int i;
2443cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
244417435752Sdrh        db,
2445cf643729Sdrh        pInfo->aFunc,
2446cf643729Sdrh        sizeof(pInfo->aFunc[0]),
2447cf643729Sdrh        3,
2448cf643729Sdrh        &pInfo->nFunc,
2449cf643729Sdrh        &pInfo->nFuncAlloc,
2450cf643729Sdrh        &i
2451cf643729Sdrh   );
245213449892Sdrh   return i;
24532282792aSdrh }
24542282792aSdrh 
24552282792aSdrh /*
2456626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
2457626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2458626a879aSdrh ** for additional information.
24592282792aSdrh **
2460626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
24612282792aSdrh */
2462626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
24632282792aSdrh   int i;
2464a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
2465a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
2466a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
246713449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
246813449892Sdrh 
24692282792aSdrh   switch( pExpr->op ){
247089c69d00Sdrh     case TK_AGG_COLUMN:
2471967e8b73Sdrh     case TK_COLUMN: {
247213449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
247313449892Sdrh       ** clause of the aggregate query */
247413449892Sdrh       if( pSrcList ){
247513449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
247613449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
247713449892Sdrh           struct AggInfo_col *pCol;
247813449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
247913449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
248013449892Sdrh             ** that is in the FROM clause of the aggregate query.
248113449892Sdrh             **
248213449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
248313449892Sdrh             ** is not an entry there already.
248413449892Sdrh             */
24857f906d63Sdrh             int k;
248613449892Sdrh             pCol = pAggInfo->aCol;
24877f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
248813449892Sdrh               if( pCol->iTable==pExpr->iTable &&
248913449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
24902282792aSdrh                 break;
24912282792aSdrh               }
24922282792aSdrh             }
24931e536953Sdanielk1977             if( (k>=pAggInfo->nColumn)
24941e536953Sdanielk1977              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
24951e536953Sdanielk1977             ){
24967f906d63Sdrh               pCol = &pAggInfo->aCol[k];
24970817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
249813449892Sdrh               pCol->iTable = pExpr->iTable;
249913449892Sdrh               pCol->iColumn = pExpr->iColumn;
250013449892Sdrh               pCol->iMem = pParse->nMem++;
250113449892Sdrh               pCol->iSorterColumn = -1;
25025774b806Sdrh               pCol->pExpr = pExpr;
250313449892Sdrh               if( pAggInfo->pGroupBy ){
250413449892Sdrh                 int j, n;
250513449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
250613449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
250713449892Sdrh                 n = pGB->nExpr;
250813449892Sdrh                 for(j=0; j<n; j++, pTerm++){
250913449892Sdrh                   Expr *pE = pTerm->pExpr;
251013449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
251113449892Sdrh                       pE->iColumn==pExpr->iColumn ){
251213449892Sdrh                     pCol->iSorterColumn = j;
251313449892Sdrh                     break;
25142282792aSdrh                   }
251513449892Sdrh                 }
251613449892Sdrh               }
251713449892Sdrh               if( pCol->iSorterColumn<0 ){
251813449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
251913449892Sdrh               }
252013449892Sdrh             }
252113449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
252213449892Sdrh             ** because it was there before or because we just created it).
252313449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
252413449892Sdrh             ** pAggInfo->aCol[] entry.
252513449892Sdrh             */
252613449892Sdrh             pExpr->pAggInfo = pAggInfo;
252713449892Sdrh             pExpr->op = TK_AGG_COLUMN;
25287f906d63Sdrh             pExpr->iAgg = k;
252913449892Sdrh             break;
253013449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
253113449892Sdrh         } /* end loop over pSrcList */
2532a58fdfb1Sdanielk1977       }
2533626a879aSdrh       return 1;
25342282792aSdrh     }
25352282792aSdrh     case TK_AGG_FUNCTION: {
253613449892Sdrh       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
253713449892Sdrh       ** to be ignored */
2538a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
253913449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
254013449892Sdrh         ** function that is already in the pAggInfo structure
254113449892Sdrh         */
254213449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
254313449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
254413449892Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
25452282792aSdrh             break;
25462282792aSdrh           }
25472282792aSdrh         }
254813449892Sdrh         if( i>=pAggInfo->nFunc ){
254913449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
255013449892Sdrh           */
255114db2665Sdanielk1977           u8 enc = ENC(pParse->db);
25521e536953Sdanielk1977           i = addAggInfoFunc(pParse->db, pAggInfo);
255313449892Sdrh           if( i>=0 ){
255413449892Sdrh             pItem = &pAggInfo->aFunc[i];
255513449892Sdrh             pItem->pExpr = pExpr;
255613449892Sdrh             pItem->iMem = pParse->nMem++;
255713449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
25582646da7eSdrh                    (char*)pExpr->token.z, pExpr->token.n,
2559d8123366Sdanielk1977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2560fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
2561fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
2562fd357974Sdrh             }else{
2563fd357974Sdrh               pItem->iDistinct = -1;
2564fd357974Sdrh             }
25652282792aSdrh           }
256613449892Sdrh         }
256713449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
256813449892Sdrh         */
25692282792aSdrh         pExpr->iAgg = i;
257013449892Sdrh         pExpr->pAggInfo = pAggInfo;
2571626a879aSdrh         return 1;
25722282792aSdrh       }
25732282792aSdrh     }
2574a58fdfb1Sdanielk1977   }
257513449892Sdrh 
257613449892Sdrh   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
257713449892Sdrh   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
257813449892Sdrh   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
257913449892Sdrh   */
2580a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
2581a58fdfb1Sdanielk1977     pNC->nDepth++;
2582a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2583a58fdfb1Sdanielk1977     pNC->nDepth--;
2584a58fdfb1Sdanielk1977   }
2585626a879aSdrh   return 0;
25862282792aSdrh }
2587626a879aSdrh 
2588626a879aSdrh /*
2589626a879aSdrh ** Analyze the given expression looking for aggregate functions and
2590626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
2591626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
2592626a879aSdrh **
2593626a879aSdrh ** This routine should only be called after the expression has been
2594626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
2595626a879aSdrh **
2596626a879aSdrh ** If errors are seen, leave an error message in zErrMsg and return
2597626a879aSdrh ** the number of errors.
2598626a879aSdrh */
2599a58fdfb1Sdanielk1977 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2600a58fdfb1Sdanielk1977   int nErr = pNC->pParse->nErr;
2601a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
2602a58fdfb1Sdanielk1977   return pNC->pParse->nErr - nErr;
26032282792aSdrh }
26045d9a4af9Sdrh 
26055d9a4af9Sdrh /*
26065d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
26075d9a4af9Sdrh ** expression list.  Return the number of errors.
26085d9a4af9Sdrh **
26095d9a4af9Sdrh ** If an error is found, the analysis is cut short.
26105d9a4af9Sdrh */
26115d9a4af9Sdrh int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
26125d9a4af9Sdrh   struct ExprList_item *pItem;
26135d9a4af9Sdrh   int i;
26145d9a4af9Sdrh   int nErr = 0;
26155d9a4af9Sdrh   if( pList ){
26165d9a4af9Sdrh     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
26175d9a4af9Sdrh       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
26185d9a4af9Sdrh     }
26195d9a4af9Sdrh   }
26205d9a4af9Sdrh   return nErr;
26215d9a4af9Sdrh }
2622