xref: /sqlite-3.40.0/src/expr.c (revision ec41ddac)
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*ec41ddacSdrh ** $Id: expr.c,v 1.275 2007/02/07 13:09:46 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
1804738cb9Sdrh #include <ctype.h>
19a2e00042Sdrh 
20e014a838Sdanielk1977 /*
21e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
22e014a838Sdanielk1977 **
23e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
24e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
25e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
26e014a838Sdanielk1977 ** indicating no affinity for the expression.
27e014a838Sdanielk1977 **
28e014a838Sdanielk1977 ** i.e. the WHERE clause expresssions in the following statements all
29e014a838Sdanielk1977 ** have an affinity:
30e014a838Sdanielk1977 **
31e014a838Sdanielk1977 ** CREATE TABLE t1(a);
32e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
33e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
34e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
35e014a838Sdanielk1977 */
36bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
37487e262fSdrh   int op = pExpr->op;
38487e262fSdrh   if( op==TK_AS ){
39bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pLeft);
40a37cdde0Sdanielk1977   }
41487e262fSdrh   if( op==TK_SELECT ){
42bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
43a37cdde0Sdanielk1977   }
44487e262fSdrh #ifndef SQLITE_OMIT_CAST
45487e262fSdrh   if( op==TK_CAST ){
468a51256cSdrh     return sqlite3AffinityType(&pExpr->token);
47487e262fSdrh   }
48487e262fSdrh #endif
49a37cdde0Sdanielk1977   return pExpr->affinity;
50a37cdde0Sdanielk1977 }
51a37cdde0Sdanielk1977 
5253db1458Sdrh /*
538b4c40d8Sdrh ** Set the collating sequence for expression pExpr to be the collating
548b4c40d8Sdrh ** sequence named by pToken.   Return a pointer to the revised expression.
55a34001c9Sdrh ** The collating sequence is marked as "explicit" using the EP_ExpCollate
56a34001c9Sdrh ** flag.  An explicit collating sequence will override implicit
57a34001c9Sdrh ** collating sequences.
588b4c40d8Sdrh */
598b4c40d8Sdrh Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
608b4c40d8Sdrh   CollSeq *pColl;
618b4c40d8Sdrh   if( pExpr==0 ) return 0;
628b4c40d8Sdrh   pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
638b4c40d8Sdrh   if( pColl ){
648b4c40d8Sdrh     pExpr->pColl = pColl;
658b4c40d8Sdrh     pExpr->flags |= EP_ExpCollate;
668b4c40d8Sdrh   }
678b4c40d8Sdrh   return pExpr;
688b4c40d8Sdrh }
698b4c40d8Sdrh 
708b4c40d8Sdrh /*
710202b29eSdanielk1977 ** Return the default collation sequence for the expression pExpr. If
720202b29eSdanielk1977 ** there is no default collation type, return 0.
730202b29eSdanielk1977 */
747cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
757cedc8d4Sdanielk1977   CollSeq *pColl = 0;
760202b29eSdanielk1977   if( pExpr ){
777cedc8d4Sdanielk1977     pColl = pExpr->pColl;
78487e262fSdrh     if( (pExpr->op==TK_AS || pExpr->op==TK_CAST) && !pColl ){
797cedc8d4Sdanielk1977       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
800202b29eSdanielk1977     }
810202b29eSdanielk1977   }
827cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
837cedc8d4Sdanielk1977     pColl = 0;
847cedc8d4Sdanielk1977   }
857cedc8d4Sdanielk1977   return pColl;
860202b29eSdanielk1977 }
870202b29eSdanielk1977 
880202b29eSdanielk1977 /*
89626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
90626a879aSdrh ** type affinity of the other operand.  This routine returns the
9153db1458Sdrh ** type affinity that should be used for the comparison operator.
9253db1458Sdrh */
93e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
94bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
95e014a838Sdanielk1977   if( aff1 && aff2 ){
968df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
978df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
98e014a838Sdanielk1977     */
998a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
100e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
101e014a838Sdanielk1977     }else{
102e014a838Sdanielk1977       return SQLITE_AFF_NONE;
103e014a838Sdanielk1977     }
104e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
1055f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
1065f6a87b3Sdrh     ** results directly.
107e014a838Sdanielk1977     */
1085f6a87b3Sdrh     return SQLITE_AFF_NONE;
109e014a838Sdanielk1977   }else{
110e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
111fe05af87Sdrh     assert( aff1==0 || aff2==0 );
112e014a838Sdanielk1977     return (aff1 + aff2);
113e014a838Sdanielk1977   }
114e014a838Sdanielk1977 }
115e014a838Sdanielk1977 
11653db1458Sdrh /*
11753db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
11853db1458Sdrh ** be applied to both operands prior to doing the comparison.
11953db1458Sdrh */
120e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
121e014a838Sdanielk1977   char aff;
122e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
123e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
124e014a838Sdanielk1977           pExpr->op==TK_NE );
125e014a838Sdanielk1977   assert( pExpr->pLeft );
126bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
127e014a838Sdanielk1977   if( pExpr->pRight ){
128e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
129e014a838Sdanielk1977   }
130e014a838Sdanielk1977   else if( pExpr->pSelect ){
131e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
132e014a838Sdanielk1977   }
133e014a838Sdanielk1977   else if( !aff ){
134e014a838Sdanielk1977     aff = SQLITE_AFF_NUMERIC;
135e014a838Sdanielk1977   }
136e014a838Sdanielk1977   return aff;
137e014a838Sdanielk1977 }
138e014a838Sdanielk1977 
139e014a838Sdanielk1977 /*
140e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
141e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
142e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
143e014a838Sdanielk1977 ** the comparison in pExpr.
144e014a838Sdanielk1977 */
145e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
146e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
1478a51256cSdrh   switch( aff ){
1488a51256cSdrh     case SQLITE_AFF_NONE:
1498a51256cSdrh       return 1;
1508a51256cSdrh     case SQLITE_AFF_TEXT:
1518a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
1528a51256cSdrh     default:
1538a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
1548a51256cSdrh   }
155e014a838Sdanielk1977 }
156e014a838Sdanielk1977 
157a37cdde0Sdanielk1977 /*
158a37cdde0Sdanielk1977 ** Return the P1 value that should be used for a binary comparison
159a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
160a37cdde0Sdanielk1977 ** If jumpIfNull is true, then set the low byte of the returned
161a37cdde0Sdanielk1977 ** P1 value to tell the opcode to jump if either expression
162a37cdde0Sdanielk1977 ** evaluates to NULL.
163a37cdde0Sdanielk1977 */
164e014a838Sdanielk1977 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
165bf3b721fSdanielk1977   char aff = sqlite3ExprAffinity(pExpr2);
166f0863fe5Sdrh   return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
167a37cdde0Sdanielk1977 }
168a37cdde0Sdanielk1977 
169a2e00042Sdrh /*
1700202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
1710202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
1720202b29eSdanielk1977 **
1730202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
1740202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
1750202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
1760202b29eSdanielk1977 ** type.
1770202b29eSdanielk1977 */
1787cedc8d4Sdanielk1977 static CollSeq* binaryCompareCollSeq(Parse *pParse, Expr *pLeft, Expr *pRight){
179*ec41ddacSdrh   CollSeq *pColl;
180*ec41ddacSdrh   assert( pLeft );
181*ec41ddacSdrh   assert( pRight );
182*ec41ddacSdrh   if( pLeft->flags & EP_ExpCollate ){
183*ec41ddacSdrh     assert( pLeft->pColl );
184*ec41ddacSdrh     pColl = pLeft->pColl;
185*ec41ddacSdrh   }else if( pRight->flags & EP_ExpCollate ){
186*ec41ddacSdrh     assert( pRight->pColl );
187*ec41ddacSdrh     pColl = pRight->pColl;
188*ec41ddacSdrh   }else{
189*ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
1900202b29eSdanielk1977     if( !pColl ){
1917cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
1920202b29eSdanielk1977     }
193*ec41ddacSdrh   }
1940202b29eSdanielk1977   return pColl;
1950202b29eSdanielk1977 }
1960202b29eSdanielk1977 
1970202b29eSdanielk1977 /*
198be5c89acSdrh ** Generate code for a comparison operator.
199be5c89acSdrh */
200be5c89acSdrh static int codeCompare(
201be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
202be5c89acSdrh   Expr *pLeft,      /* The left operand */
203be5c89acSdrh   Expr *pRight,     /* The right operand */
204be5c89acSdrh   int opcode,       /* The comparison opcode */
205be5c89acSdrh   int dest,         /* Jump here if true.  */
206be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
207be5c89acSdrh ){
208be5c89acSdrh   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
209be5c89acSdrh   CollSeq *p3 = binaryCompareCollSeq(pParse, pLeft, pRight);
210be5c89acSdrh   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
211be5c89acSdrh }
212be5c89acSdrh 
213be5c89acSdrh /*
214a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
215a76b5dfcSdrh ** for this node is obtained from sqliteMalloc().  The calling function
216a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
217a76b5dfcSdrh */
218e4e72072Sdrh Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
219a76b5dfcSdrh   Expr *pNew;
220a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
221a76b5dfcSdrh   if( pNew==0 ){
222d5d56523Sdanielk1977     /* When malloc fails, delete pLeft and pRight. Expressions passed to
223d5d56523Sdanielk1977     ** this function must always be allocated with sqlite3Expr() for this
224d5d56523Sdanielk1977     ** reason.
225d5d56523Sdanielk1977     */
226d5d56523Sdanielk1977     sqlite3ExprDelete(pLeft);
227d5d56523Sdanielk1977     sqlite3ExprDelete(pRight);
228a76b5dfcSdrh     return 0;
229a76b5dfcSdrh   }
230a76b5dfcSdrh   pNew->op = op;
231a76b5dfcSdrh   pNew->pLeft = pLeft;
232a76b5dfcSdrh   pNew->pRight = pRight;
233a58fdfb1Sdanielk1977   pNew->iAgg = -1;
234a76b5dfcSdrh   if( pToken ){
2354b59ab5eSdrh     assert( pToken->dyn==0 );
236145716b3Sdrh     pNew->span = pNew->token = *pToken;
237a34001c9Sdrh   }else if( pLeft ){
238a34001c9Sdrh     if( pRight ){
2394adee20fSdanielk1977       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
240a34001c9Sdrh       if( pRight->flags && EP_ExpCollate ){
241a34001c9Sdrh         pNew->flags |= EP_ExpCollate;
242a34001c9Sdrh         pNew->pColl = pRight->pColl;
243a34001c9Sdrh       }
244a34001c9Sdrh     }
245a34001c9Sdrh     if( pLeft->flags && EP_ExpCollate ){
246a34001c9Sdrh       pNew->flags |= EP_ExpCollate;
247a34001c9Sdrh       pNew->pColl = pLeft->pColl;
248a34001c9Sdrh     }
249a76b5dfcSdrh   }
250a76b5dfcSdrh   return pNew;
251a76b5dfcSdrh }
252a76b5dfcSdrh 
253a76b5dfcSdrh /*
254206f3d96Sdrh ** Works like sqlite3Expr() but frees its pLeft and pRight arguments
255206f3d96Sdrh ** if it fails due to a malloc problem.
256206f3d96Sdrh */
257206f3d96Sdrh Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
258206f3d96Sdrh   Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
259206f3d96Sdrh   if( pNew==0 ){
260206f3d96Sdrh     sqlite3ExprDelete(pLeft);
261206f3d96Sdrh     sqlite3ExprDelete(pRight);
262206f3d96Sdrh   }
263206f3d96Sdrh   return pNew;
264206f3d96Sdrh }
265206f3d96Sdrh 
266206f3d96Sdrh /*
2674e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
2684e0cff60Sdrh ** that look like this:   #0 #1 #2 ...  These terms refer to elements
269288d37f1Sdrh ** on the stack.  "#0" means the top of the stack.
270288d37f1Sdrh ** "#1" means the next down on the stack.  And so forth.
2714e0cff60Sdrh **
2724e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
2734e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
2744e0cff60Sdrh ** The returns an expression that will code to extract the value from
2754e0cff60Sdrh ** that memory location as needed.
2764e0cff60Sdrh */
2774e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
2784e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
2794e0cff60Sdrh   Expr *p;
2804e0cff60Sdrh   int depth;
2814e0cff60Sdrh   if( pParse->nested==0 ){
2824e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
2834e0cff60Sdrh     return 0;
2844e0cff60Sdrh   }
285bb7ac00bSdrh   if( v==0 ) return 0;
2864e0cff60Sdrh   p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
28773c42a13Sdrh   if( p==0 ){
28873c42a13Sdrh     return 0;  /* Malloc failed */
28973c42a13Sdrh   }
2902646da7eSdrh   depth = atoi((char*)&pToken->z[1]);
2914e0cff60Sdrh   p->iTable = pParse->nMem++;
2924e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
2934e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
2944e0cff60Sdrh   return p;
2954e0cff60Sdrh }
2964e0cff60Sdrh 
2974e0cff60Sdrh /*
29891bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
29991bb0eedSdrh ** NULL, then just return the other expression.
30091bb0eedSdrh */
30191bb0eedSdrh Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
30291bb0eedSdrh   if( pLeft==0 ){
30391bb0eedSdrh     return pRight;
30491bb0eedSdrh   }else if( pRight==0 ){
30591bb0eedSdrh     return pLeft;
30691bb0eedSdrh   }else{
30791bb0eedSdrh     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
30891bb0eedSdrh   }
30991bb0eedSdrh }
31091bb0eedSdrh 
31191bb0eedSdrh /*
3126977fea8Sdrh ** Set the Expr.span field of the given expression to span all
313a76b5dfcSdrh ** text between the two given tokens.
314a76b5dfcSdrh */
3154adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
3164efc4754Sdrh   assert( pRight!=0 );
3174efc4754Sdrh   assert( pLeft!=0 );
3189e12800dSdanielk1977   if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
319ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
320145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
3216977fea8Sdrh       pExpr->span.z = pLeft->z;
32297903fefSdrh       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
3234b59ab5eSdrh     }else{
3246977fea8Sdrh       pExpr->span.z = 0;
3254b59ab5eSdrh     }
326a76b5dfcSdrh   }
327a76b5dfcSdrh }
328a76b5dfcSdrh 
329a76b5dfcSdrh /*
330a76b5dfcSdrh ** Construct a new expression node for a function with multiple
331a76b5dfcSdrh ** arguments.
332a76b5dfcSdrh */
3334adee20fSdanielk1977 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
334a76b5dfcSdrh   Expr *pNew;
3354b202ae2Sdanielk1977   assert( pToken );
336a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
337a76b5dfcSdrh   if( pNew==0 ){
338d5d56523Sdanielk1977     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
339a76b5dfcSdrh     return 0;
340a76b5dfcSdrh   }
341a76b5dfcSdrh   pNew->op = TK_FUNCTION;
342a76b5dfcSdrh   pNew->pList = pList;
3434b59ab5eSdrh   assert( pToken->dyn==0 );
344a76b5dfcSdrh   pNew->token = *pToken;
3456977fea8Sdrh   pNew->span = pNew->token;
346a76b5dfcSdrh   return pNew;
347a76b5dfcSdrh }
348a76b5dfcSdrh 
349a76b5dfcSdrh /*
350fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
351fa6bc000Sdrh ** in the original SQL statement.
352fa6bc000Sdrh **
353fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
354fa6bc000Sdrh ** variable number.
355fa6bc000Sdrh **
356fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
357fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
358fa6bc000Sdrh ** the SQL statement comes from an external source.
359fa6bc000Sdrh **
360fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
361fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
362fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
363fa6bc000Sdrh ** assigned.
364fa6bc000Sdrh */
365fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
366fa6bc000Sdrh   Token *pToken;
367fa6bc000Sdrh   if( pExpr==0 ) return;
368fa6bc000Sdrh   pToken = &pExpr->token;
369fa6bc000Sdrh   assert( pToken->n>=1 );
370fa6bc000Sdrh   assert( pToken->z!=0 );
371fa6bc000Sdrh   assert( pToken->z[0]!=0 );
372fa6bc000Sdrh   if( pToken->n==1 ){
373fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
374fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
375fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
376fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
377fa6bc000Sdrh     ** use it as the variable number */
378fa6bc000Sdrh     int i;
3792646da7eSdrh     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
380fa6bc000Sdrh     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
381fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
382fa6bc000Sdrh           SQLITE_MAX_VARIABLE_NUMBER);
383fa6bc000Sdrh     }
384fa6bc000Sdrh     if( i>pParse->nVar ){
385fa6bc000Sdrh       pParse->nVar = i;
386fa6bc000Sdrh     }
387fa6bc000Sdrh   }else{
388fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
389fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
390fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
391fa6bc000Sdrh     */
392fa6bc000Sdrh     int i, n;
393fa6bc000Sdrh     n = pToken->n;
394fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
395fa6bc000Sdrh       Expr *pE;
396fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
397fa6bc000Sdrh           && pE->token.n==n
398fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
399fa6bc000Sdrh         pExpr->iTable = pE->iTable;
400fa6bc000Sdrh         break;
401fa6bc000Sdrh       }
402fa6bc000Sdrh     }
403fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
404fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
405fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
406fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
407e7259296Sdanielk1977         sqliteReallocOrFree((void**)&pParse->apVarExpr,
408fa6bc000Sdrh                        pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
409fa6bc000Sdrh       }
4109e12800dSdanielk1977       if( !sqlite3MallocFailed() ){
411fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
412fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
413fa6bc000Sdrh       }
414fa6bc000Sdrh     }
415fa6bc000Sdrh   }
416fa6bc000Sdrh }
417fa6bc000Sdrh 
418fa6bc000Sdrh /*
419a2e00042Sdrh ** Recursively delete an expression tree.
420a2e00042Sdrh */
4214adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
422a2e00042Sdrh   if( p==0 ) return;
4234efc4754Sdrh   if( p->span.dyn ) sqliteFree((char*)p->span.z);
4244efc4754Sdrh   if( p->token.dyn ) sqliteFree((char*)p->token.z);
4254adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
4264adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
4274adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
4284adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
429a2e00042Sdrh   sqliteFree(p);
430a2e00042Sdrh }
431a2e00042Sdrh 
432d2687b77Sdrh /*
433d2687b77Sdrh ** The Expr.token field might be a string literal that is quoted.
434d2687b77Sdrh ** If so, remove the quotation marks.
435d2687b77Sdrh */
436d2687b77Sdrh void sqlite3DequoteExpr(Expr *p){
437d2687b77Sdrh   if( ExprHasAnyProperty(p, EP_Dequoted) ){
438d2687b77Sdrh     return;
439d2687b77Sdrh   }
440d2687b77Sdrh   ExprSetProperty(p, EP_Dequoted);
441d2687b77Sdrh   if( p->token.dyn==0 ){
442d2687b77Sdrh     sqlite3TokenCopy(&p->token, &p->token);
443d2687b77Sdrh   }
444d2687b77Sdrh   sqlite3Dequote((char*)p->token.z);
445d2687b77Sdrh }
446d2687b77Sdrh 
447a76b5dfcSdrh 
448a76b5dfcSdrh /*
449ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
450ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
451ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
452ff78bd2fSdrh ** without effecting the originals.
453ff78bd2fSdrh **
4544adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
4554adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
456ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
457ff78bd2fSdrh **
458ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
459ff78bd2fSdrh */
4604adee20fSdanielk1977 Expr *sqlite3ExprDup(Expr *p){
461ff78bd2fSdrh   Expr *pNew;
462ff78bd2fSdrh   if( p==0 ) return 0;
463fcb78a49Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
464ff78bd2fSdrh   if( pNew==0 ) return 0;
4653b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
4666977fea8Sdrh   if( p->token.z!=0 ){
4672646da7eSdrh     pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
4684b59ab5eSdrh     pNew->token.dyn = 1;
4694b59ab5eSdrh   }else{
4704efc4754Sdrh     assert( pNew->token.z==0 );
4714b59ab5eSdrh   }
4726977fea8Sdrh   pNew->span.z = 0;
4734adee20fSdanielk1977   pNew->pLeft = sqlite3ExprDup(p->pLeft);
4744adee20fSdanielk1977   pNew->pRight = sqlite3ExprDup(p->pRight);
4754adee20fSdanielk1977   pNew->pList = sqlite3ExprListDup(p->pList);
4764adee20fSdanielk1977   pNew->pSelect = sqlite3SelectDup(p->pSelect);
477aee18ef8Sdanielk1977   pNew->pTab = p->pTab;
478ff78bd2fSdrh   return pNew;
479ff78bd2fSdrh }
4804adee20fSdanielk1977 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
4814b59ab5eSdrh   if( pTo->dyn ) sqliteFree((char*)pTo->z);
4824b59ab5eSdrh   if( pFrom->z ){
4834b59ab5eSdrh     pTo->n = pFrom->n;
4842646da7eSdrh     pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
4854b59ab5eSdrh     pTo->dyn = 1;
4864b59ab5eSdrh   }else{
4874b59ab5eSdrh     pTo->z = 0;
4884b59ab5eSdrh   }
4894b59ab5eSdrh }
4904adee20fSdanielk1977 ExprList *sqlite3ExprListDup(ExprList *p){
491ff78bd2fSdrh   ExprList *pNew;
492145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
493ff78bd2fSdrh   int i;
494ff78bd2fSdrh   if( p==0 ) return 0;
495ff78bd2fSdrh   pNew = sqliteMalloc( sizeof(*pNew) );
496ff78bd2fSdrh   if( pNew==0 ) return 0;
4974305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
4983e7bc9caSdrh   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
499e0048400Sdanielk1977   if( pItem==0 ){
500e0048400Sdanielk1977     sqliteFree(pNew);
501e0048400Sdanielk1977     return 0;
502e0048400Sdanielk1977   }
503145716b3Sdrh   pOldItem = p->a;
504145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
5054b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
506145716b3Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
5076977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
5086977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
5094b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
5104b59ab5eSdrh       ** the names of columns in the result set needs this information */
5114adee20fSdanielk1977       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
5124b59ab5eSdrh     }
5131f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
5146f7adc8aSdrh             || pOldExpr->span.z==0
5159e12800dSdanielk1977             || sqlite3MallocFailed() );
516145716b3Sdrh     pItem->zName = sqliteStrDup(pOldItem->zName);
517145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
518145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
5193e7bc9caSdrh     pItem->done = 0;
520ff78bd2fSdrh   }
521ff78bd2fSdrh   return pNew;
522ff78bd2fSdrh }
52393758c8dSdanielk1977 
52493758c8dSdanielk1977 /*
52593758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
52693758c8dSdanielk1977 ** the build, then none of the following routines, except for
52793758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
52893758c8dSdanielk1977 ** called with a NULL argument.
52993758c8dSdanielk1977 */
5306a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
5316a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
5324adee20fSdanielk1977 SrcList *sqlite3SrcListDup(SrcList *p){
533ad3cab52Sdrh   SrcList *pNew;
534ad3cab52Sdrh   int i;
535113088ecSdrh   int nByte;
536ad3cab52Sdrh   if( p==0 ) return 0;
537113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
5384efc4754Sdrh   pNew = sqliteMallocRaw( nByte );
539ad3cab52Sdrh   if( pNew==0 ) return 0;
5404305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
541ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
5424efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
5434efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
544ed8a3bb1Sdrh     Table *pTab;
5454efc4754Sdrh     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
5464efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5474efc4754Sdrh     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
5484efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
5494efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
5501787ccabSdanielk1977     pNewItem->isPopulated = pOldItem->isPopulated;
551ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
552ed8a3bb1Sdrh     if( pTab ){
553ed8a3bb1Sdrh       pTab->nRef++;
554a1cb183dSdanielk1977     }
5554adee20fSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
5564adee20fSdanielk1977     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
5574adee20fSdanielk1977     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
5586c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
559ad3cab52Sdrh   }
560ad3cab52Sdrh   return pNew;
561ad3cab52Sdrh }
5624adee20fSdanielk1977 IdList *sqlite3IdListDup(IdList *p){
563ff78bd2fSdrh   IdList *pNew;
564ff78bd2fSdrh   int i;
565ff78bd2fSdrh   if( p==0 ) return 0;
5664efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*pNew) );
567ff78bd2fSdrh   if( pNew==0 ) return 0;
5684305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
5694efc4754Sdrh   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
570d5d56523Sdanielk1977   if( pNew->a==0 ){
571d5d56523Sdanielk1977     sqliteFree(pNew);
572d5d56523Sdanielk1977     return 0;
573d5d56523Sdanielk1977   }
574ff78bd2fSdrh   for(i=0; i<p->nId; i++){
5754efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
5764efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
5774efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5784efc4754Sdrh     pNewItem->idx = pOldItem->idx;
579ff78bd2fSdrh   }
580ff78bd2fSdrh   return pNew;
581ff78bd2fSdrh }
5824adee20fSdanielk1977 Select *sqlite3SelectDup(Select *p){
583ff78bd2fSdrh   Select *pNew;
584ff78bd2fSdrh   if( p==0 ) return 0;
5854efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
586ff78bd2fSdrh   if( pNew==0 ) return 0;
587ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
5884adee20fSdanielk1977   pNew->pEList = sqlite3ExprListDup(p->pEList);
5894adee20fSdanielk1977   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
5904adee20fSdanielk1977   pNew->pWhere = sqlite3ExprDup(p->pWhere);
5914adee20fSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
5924adee20fSdanielk1977   pNew->pHaving = sqlite3ExprDup(p->pHaving);
5934adee20fSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
594ff78bd2fSdrh   pNew->op = p->op;
5954adee20fSdanielk1977   pNew->pPrior = sqlite3SelectDup(p->pPrior);
596a2dc3b1aSdanielk1977   pNew->pLimit = sqlite3ExprDup(p->pLimit);
597a2dc3b1aSdanielk1977   pNew->pOffset = sqlite3ExprDup(p->pOffset);
5987b58daeaSdrh   pNew->iLimit = -1;
5997b58daeaSdrh   pNew->iOffset = -1;
600a1cb183dSdanielk1977   pNew->isResolved = p->isResolved;
601a1cb183dSdanielk1977   pNew->isAgg = p->isAgg;
602b9bb7c18Sdrh   pNew->usesEphm = 0;
6038e647b81Sdrh   pNew->disallowOrderBy = 0;
6040342b1f5Sdrh   pNew->pRightmost = 0;
605b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
606b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
607b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
608ff78bd2fSdrh   return pNew;
609ff78bd2fSdrh }
61093758c8dSdanielk1977 #else
61193758c8dSdanielk1977 Select *sqlite3SelectDup(Select *p){
61293758c8dSdanielk1977   assert( p==0 );
61393758c8dSdanielk1977   return 0;
61493758c8dSdanielk1977 }
61593758c8dSdanielk1977 #endif
616ff78bd2fSdrh 
617ff78bd2fSdrh 
618ff78bd2fSdrh /*
619a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
620a76b5dfcSdrh ** initially NULL, then create a new expression list.
621a76b5dfcSdrh */
6224adee20fSdanielk1977 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
623a76b5dfcSdrh   if( pList==0 ){
624a76b5dfcSdrh     pList = sqliteMalloc( sizeof(ExprList) );
625a76b5dfcSdrh     if( pList==0 ){
626d5d56523Sdanielk1977       goto no_mem;
627a76b5dfcSdrh     }
6284efc4754Sdrh     assert( pList->nAlloc==0 );
629a76b5dfcSdrh   }
6304305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
631d5d56523Sdanielk1977     struct ExprList_item *a;
632d5d56523Sdanielk1977     int n = pList->nAlloc*2 + 4;
633d5d56523Sdanielk1977     a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
634d5d56523Sdanielk1977     if( a==0 ){
635d5d56523Sdanielk1977       goto no_mem;
636a76b5dfcSdrh     }
637d5d56523Sdanielk1977     pList->a = a;
638d5d56523Sdanielk1977     pList->nAlloc = n;
639a76b5dfcSdrh   }
6404efc4754Sdrh   assert( pList->a!=0 );
6414efc4754Sdrh   if( pExpr || pName ){
6424efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
6434efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
644a99db3b6Sdrh     pItem->zName = sqlite3NameFromToken(pName);
645e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
646a76b5dfcSdrh   }
647a76b5dfcSdrh   return pList;
648d5d56523Sdanielk1977 
649d5d56523Sdanielk1977 no_mem:
650d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
651d5d56523Sdanielk1977   sqlite3ExprDelete(pExpr);
652d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
653d5d56523Sdanielk1977   return 0;
654a76b5dfcSdrh }
655a76b5dfcSdrh 
656a76b5dfcSdrh /*
657a76b5dfcSdrh ** Delete an entire expression list.
658a76b5dfcSdrh */
6594adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
660a76b5dfcSdrh   int i;
661be5c89acSdrh   struct ExprList_item *pItem;
662a76b5dfcSdrh   if( pList==0 ) return;
6631bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
6641bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
665be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
666be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
667be5c89acSdrh     sqliteFree(pItem->zName);
668a76b5dfcSdrh   }
669a76b5dfcSdrh   sqliteFree(pList->a);
670a76b5dfcSdrh   sqliteFree(pList);
671a76b5dfcSdrh }
672a76b5dfcSdrh 
673a76b5dfcSdrh /*
674626a879aSdrh ** Walk an expression tree.  Call xFunc for each node visited.
67573b211abSdrh **
676626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
677626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
678626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
679626a879aSdrh ** the tree walk completely.
680626a879aSdrh **
681626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
682626a879aSdrh ** and 0 to continue.
68387abf5c0Sdrh **
68487abf5c0Sdrh ** NOTICE:  This routine does *not* descend into subqueries.
685626a879aSdrh */
686a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
687626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
688626a879aSdrh   int rc;
689626a879aSdrh   if( pExpr==0 ) return 0;
690626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
691626a879aSdrh   if( rc==0 ){
692626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
693626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
694a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
695626a879aSdrh   }
696626a879aSdrh   return rc>1;
697626a879aSdrh }
698626a879aSdrh 
699626a879aSdrh /*
700a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
701a58fdfb1Sdanielk1977 */
702a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
703a58fdfb1Sdanielk1977   int i;
704a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
705a58fdfb1Sdanielk1977   if( !p ) return 0;
706a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
707a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
708a58fdfb1Sdanielk1977   }
709a58fdfb1Sdanielk1977   return 0;
710a58fdfb1Sdanielk1977 }
711a58fdfb1Sdanielk1977 
712a58fdfb1Sdanielk1977 /*
713a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
714a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
715a58fdfb1Sdanielk1977 ** or OFFSET expressions..
716a58fdfb1Sdanielk1977 */
717a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
718a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
719a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
720a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
721a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
722a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
723a58fdfb1Sdanielk1977   return 0;
724a58fdfb1Sdanielk1977 }
725a58fdfb1Sdanielk1977 
726a58fdfb1Sdanielk1977 
727a58fdfb1Sdanielk1977 /*
728626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
729626a879aSdrh **
730626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
73173b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
73273b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
73373b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
73473b211abSdrh ** then do nothing.
73573b211abSdrh **
73673b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
73773b211abSdrh ** the expression as constant, then we assume the whole expression
73873b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
739626a879aSdrh */
740626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
741626a879aSdrh   switch( pExpr->op ){
742eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
743eb55bd2fSdrh     ** and *pArg==2 */
744eb55bd2fSdrh     case TK_FUNCTION:
745eb55bd2fSdrh       if( *((int*)pArg)==2 ) return 0;
746eb55bd2fSdrh       /* Fall through */
747626a879aSdrh     case TK_ID:
748626a879aSdrh     case TK_COLUMN:
749626a879aSdrh     case TK_DOT:
750626a879aSdrh     case TK_AGG_FUNCTION:
75113449892Sdrh     case TK_AGG_COLUMN:
752fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
753fe2093d7Sdrh     case TK_SELECT:
754fe2093d7Sdrh     case TK_EXISTS:
755fe2093d7Sdrh #endif
756626a879aSdrh       *((int*)pArg) = 0;
757626a879aSdrh       return 2;
75887abf5c0Sdrh     case TK_IN:
75987abf5c0Sdrh       if( pExpr->pSelect ){
76087abf5c0Sdrh         *((int*)pArg) = 0;
76187abf5c0Sdrh         return 2;
76287abf5c0Sdrh       }
763626a879aSdrh     default:
764626a879aSdrh       return 0;
765626a879aSdrh   }
766626a879aSdrh }
767626a879aSdrh 
768626a879aSdrh /*
769fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
770eb55bd2fSdrh ** and 0 if it involves variables or function calls.
7712398937bSdrh **
7722398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
7732398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
7742398937bSdrh ** a constant.
775fef5208cSdrh */
7764adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
777626a879aSdrh   int isConst = 1;
778626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
779626a879aSdrh   return isConst;
780fef5208cSdrh }
781fef5208cSdrh 
782fef5208cSdrh /*
783eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
784eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
785eb55bd2fSdrh ** are any variables.
786eb55bd2fSdrh **
787eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
788eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
789eb55bd2fSdrh ** a constant.
790eb55bd2fSdrh */
791eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
792eb55bd2fSdrh   int isConst = 2;
793eb55bd2fSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
794eb55bd2fSdrh   return isConst!=0;
795eb55bd2fSdrh }
796eb55bd2fSdrh 
797eb55bd2fSdrh /*
79873b211abSdrh ** If the expression p codes a constant integer that is small enough
799202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
800202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
801202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
802e4de1febSdrh */
8034adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
804e4de1febSdrh   switch( p->op ){
805e4de1febSdrh     case TK_INTEGER: {
8062646da7eSdrh       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
807e4de1febSdrh         return 1;
808e4de1febSdrh       }
809202b2df7Sdrh       break;
810202b2df7Sdrh     }
8114b59ab5eSdrh     case TK_UPLUS: {
8124adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
8134b59ab5eSdrh     }
814e4de1febSdrh     case TK_UMINUS: {
815e4de1febSdrh       int v;
8164adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
817e4de1febSdrh         *pValue = -v;
818e4de1febSdrh         return 1;
819e4de1febSdrh       }
820e4de1febSdrh       break;
821e4de1febSdrh     }
822e4de1febSdrh     default: break;
823e4de1febSdrh   }
824e4de1febSdrh   return 0;
825e4de1febSdrh }
826e4de1febSdrh 
827e4de1febSdrh /*
828c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
829c4a3c779Sdrh */
8304adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
8314adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
8324adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
8334adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
834c4a3c779Sdrh   return 0;
835c4a3c779Sdrh }
836c4a3c779Sdrh 
837c4a3c779Sdrh /*
8388141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
8398141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
8408141f61eSdrh ** expression node refer back to that source column.  The following changes
8418141f61eSdrh ** are made to pExpr:
8428141f61eSdrh **
8438141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
8448141f61eSdrh **                         the table.
8458141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
8468141f61eSdrh **                         from pSrcList.
8478141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
8488141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
8498141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
8508141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
8518141f61eSdrh **
8528141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
8538141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
8548141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
8558141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
8568141f61eSdrh ** means that the form of the name is Z and that columns from any table
8578141f61eSdrh ** can be used.
8588141f61eSdrh **
8598141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
8608141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
8618141f61eSdrh */
8628141f61eSdrh static int lookupName(
8638141f61eSdrh   Parse *pParse,       /* The parsing context */
8648141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
8658141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
8668141f61eSdrh   Token *pColumnToken, /* Name of the column. */
867626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
8688141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
8698141f61eSdrh ){
8708141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
8718141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
8728141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
8738141f61eSdrh   int i, j;            /* Loop counters */
8748141f61eSdrh   int cnt = 0;         /* Number of matching column names */
8758141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
8769bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
87751669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
87851669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
87973b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
8808141f61eSdrh 
8818141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
882a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
883a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
884a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
8859e12800dSdanielk1977   if( sqlite3MallocFailed() ){
886d5d56523Sdanielk1977     goto lookupname_end;
8878141f61eSdrh   }
8888141f61eSdrh 
8898141f61eSdrh   pExpr->iTable = -1;
890626a879aSdrh   while( pNC && cnt==0 ){
891ffe07b2dSdrh     ExprList *pEList;
892626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
893626a879aSdrh 
894b3bce662Sdanielk1977     if( pSrcList ){
89551669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
89643617e9aSdrh         Table *pTab;
89743617e9aSdrh         int iDb;
8988141f61eSdrh         Column *pCol;
8998141f61eSdrh 
90043617e9aSdrh         pTab = pItem->pTab;
90143617e9aSdrh         assert( pTab!=0 );
90243617e9aSdrh         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
9038141f61eSdrh         assert( pTab->nCol>0 );
9048141f61eSdrh         if( zTab ){
9058141f61eSdrh           if( pItem->zAlias ){
9068141f61eSdrh             char *zTabName = pItem->zAlias;
9074adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
9088141f61eSdrh           }else{
9098141f61eSdrh             char *zTabName = pTab->zName;
9104adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
911da184236Sdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
9128141f61eSdrh               continue;
9138141f61eSdrh             }
9148141f61eSdrh           }
9158141f61eSdrh         }
9168141f61eSdrh         if( 0==(cntTab++) ){
9178141f61eSdrh           pExpr->iTable = pItem->iCursor;
918da184236Sdanielk1977           pExpr->pSchema = pTab->pSchema;
91951669863Sdrh           pMatch = pItem;
9208141f61eSdrh         }
9218141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
9224adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
923b3bf556eSdanielk1977             const char *zColl = pTab->aCol[j].zColl;
924873fac0cSdrh             IdList *pUsing;
9258141f61eSdrh             cnt++;
9268141f61eSdrh             pExpr->iTable = pItem->iCursor;
92751669863Sdrh             pMatch = pItem;
928da184236Sdanielk1977             pExpr->pSchema = pTab->pSchema;
9298141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
9308141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
931a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
9328b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
933b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
9348b4c40d8Sdrh             }
93561dfc31dSdrh             if( i<pSrcList->nSrc-1 ){
93661dfc31dSdrh               if( pItem[1].jointype & JT_NATURAL ){
937355ef361Sdrh                 /* If this match occurred in the left table of a natural join,
938355ef361Sdrh                 ** then skip the right table to avoid a duplicate match */
939355ef361Sdrh                 pItem++;
940355ef361Sdrh                 i++;
94161dfc31dSdrh               }else if( (pUsing = pItem[1].pUsing)!=0 ){
942873fac0cSdrh                 /* If this match occurs on a column that is in the USING clause
943873fac0cSdrh                 ** of a join, skip the search of the right table of the join
944873fac0cSdrh                 ** to avoid a duplicate match there. */
945873fac0cSdrh                 int k;
946873fac0cSdrh                 for(k=0; k<pUsing->nId; k++){
947873fac0cSdrh                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
948873fac0cSdrh                     pItem++;
949873fac0cSdrh                     i++;
950873fac0cSdrh                     break;
951873fac0cSdrh                   }
952873fac0cSdrh                 }
953873fac0cSdrh               }
95461dfc31dSdrh             }
9558141f61eSdrh             break;
9568141f61eSdrh           }
9578141f61eSdrh         }
9588141f61eSdrh       }
959b3bce662Sdanielk1977     }
9608141f61eSdrh 
961b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
9628141f61eSdrh     /* If we have not already resolved the name, then maybe
9638141f61eSdrh     ** it is a new.* or old.* trigger argument reference
9648141f61eSdrh     */
9658141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
9668141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
9678141f61eSdrh       Table *pTab = 0;
9684adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
9698141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
9708141f61eSdrh         assert( pTriggerStack->pTab );
9718141f61eSdrh         pTab = pTriggerStack->pTab;
9724adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
9738141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
9748141f61eSdrh         assert( pTriggerStack->pTab );
9758141f61eSdrh         pTab = pTriggerStack->pTab;
9768141f61eSdrh       }
9778141f61eSdrh 
9788141f61eSdrh       if( pTab ){
979f0113000Sdanielk1977         int iCol;
9808141f61eSdrh         Column *pCol = pTab->aCol;
9818141f61eSdrh 
982da184236Sdanielk1977         pExpr->pSchema = pTab->pSchema;
9838141f61eSdrh         cntTab++;
984f0113000Sdanielk1977         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
9854adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
986f0113000Sdanielk1977             const char *zColl = pTab->aCol[iCol].zColl;
9878141f61eSdrh             cnt++;
988f0113000Sdanielk1977             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
989f0113000Sdanielk1977             pExpr->affinity = pTab->aCol[iCol].affinity;
9908b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
991b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
9928b4c40d8Sdrh             }
993aee18ef8Sdanielk1977             pExpr->pTab = pTab;
9948141f61eSdrh             break;
9958141f61eSdrh           }
9968141f61eSdrh         }
9978141f61eSdrh       }
9988141f61eSdrh     }
999b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
10008141f61eSdrh 
10018141f61eSdrh     /*
10028141f61eSdrh     ** Perhaps the name is a reference to the ROWID
10038141f61eSdrh     */
10044adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
10058141f61eSdrh       cnt = 1;
10068141f61eSdrh       pExpr->iColumn = -1;
10078a51256cSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
10088141f61eSdrh     }
10098141f61eSdrh 
10108141f61eSdrh     /*
10118141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
10128141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
10138141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
10148141f61eSdrh     **
10158141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
10168141f61eSdrh     **
10178141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
10188141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
10198141f61eSdrh     ** Note that the expression in the result set should have already been
10208141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
10218141f61eSdrh     */
1022ffe07b2dSdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
10238141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
10248141f61eSdrh         char *zAs = pEList->a[j].zName;
10254adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
10268141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
10278141f61eSdrh           pExpr->op = TK_AS;
10288141f61eSdrh           pExpr->iColumn = j;
10294adee20fSdanielk1977           pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
103015ccce1cSdrh           cnt = 1;
10318141f61eSdrh           assert( zTab==0 && zDb==0 );
103215ccce1cSdrh           goto lookupname_end_2;
10338141f61eSdrh         }
10348141f61eSdrh       }
10358141f61eSdrh     }
10368141f61eSdrh 
1037626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
1038626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
1039626a879aSdrh     */
1040626a879aSdrh     if( cnt==0 ){
1041626a879aSdrh       pNC = pNC->pNext;
1042626a879aSdrh     }
1043626a879aSdrh   }
1044626a879aSdrh 
10458141f61eSdrh   /*
10468141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
10478141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
10488141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
10498141f61eSdrh   ** case, we need to return right away and not make any changes to
10508141f61eSdrh   ** pExpr.
105115ccce1cSdrh   **
105215ccce1cSdrh   ** Because no reference was made to outer contexts, the pNC->nRef
105315ccce1cSdrh   ** fields are not changed in any context.
10548141f61eSdrh   */
10558141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
10568141f61eSdrh     sqliteFree(zCol);
10578141f61eSdrh     return 0;
10588141f61eSdrh   }
10598141f61eSdrh 
10608141f61eSdrh   /*
10618141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
10628141f61eSdrh   ** more matches.  Either way, we have an error.
10638141f61eSdrh   */
10648141f61eSdrh   if( cnt!=1 ){
10658141f61eSdrh     char *z = 0;
10668141f61eSdrh     char *zErr;
10678141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
10688141f61eSdrh     if( zDb ){
1069f93339deSdrh       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
10708141f61eSdrh     }else if( zTab ){
1071f93339deSdrh       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
10728141f61eSdrh     }else{
10738141f61eSdrh       z = sqliteStrDup(zCol);
10748141f61eSdrh     }
10754adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
10768141f61eSdrh     sqliteFree(z);
107773b211abSdrh     pTopNC->nErr++;
10788141f61eSdrh   }
10798141f61eSdrh 
108051669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
108151669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
108251669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
108351669863Sdrh   ** column number is greater than the number of bits in the bitmask
108451669863Sdrh   ** then set the high-order bit of the bitmask.
108551669863Sdrh   */
108651669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
108751669863Sdrh     int n = pExpr->iColumn;
108851669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
108951669863Sdrh       n = sizeof(Bitmask)*8-1;
109051669863Sdrh     }
109151669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
1092ca83ac51Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
109351669863Sdrh   }
109451669863Sdrh 
1095d5d56523Sdanielk1977 lookupname_end:
10968141f61eSdrh   /* Clean up and return
10978141f61eSdrh   */
10988141f61eSdrh   sqliteFree(zDb);
10998141f61eSdrh   sqliteFree(zTab);
11004adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
11018141f61eSdrh   pExpr->pLeft = 0;
11024adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
11038141f61eSdrh   pExpr->pRight = 0;
11048141f61eSdrh   pExpr->op = TK_COLUMN;
110515ccce1cSdrh lookupname_end_2:
110615ccce1cSdrh   sqliteFree(zCol);
1107626a879aSdrh   if( cnt==1 ){
1108b3bce662Sdanielk1977     assert( pNC!=0 );
1109626a879aSdrh     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1110aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
1111aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
1112aee18ef8Sdanielk1977     }
111315ccce1cSdrh     /* Increment the nRef value on all name contexts from TopNC up to
111415ccce1cSdrh     ** the point where the name matched. */
111515ccce1cSdrh     for(;;){
111615ccce1cSdrh       assert( pTopNC!=0 );
111715ccce1cSdrh       pTopNC->nRef++;
111815ccce1cSdrh       if( pTopNC==pNC ) break;
111915ccce1cSdrh       pTopNC = pTopNC->pNext;
1120626a879aSdrh     }
112115ccce1cSdrh     return 0;
112215ccce1cSdrh   } else {
112315ccce1cSdrh     return 1;
112415ccce1cSdrh   }
11258141f61eSdrh }
11268141f61eSdrh 
11278141f61eSdrh /*
1128626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1129626a879aSdrh **
113073b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1131626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
113273b211abSdrh ** the tree or 2 to abort the tree walk.
113373b211abSdrh **
113473b211abSdrh ** This routine also does error checking and name resolution for
113573b211abSdrh ** function names.  The operator for aggregate functions is changed
113673b211abSdrh ** to TK_AGG_FUNCTION.
1137626a879aSdrh */
1138626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1139626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1140626a879aSdrh   Parse *pParse;
1141626a879aSdrh 
1142b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1143626a879aSdrh   assert( pNC!=0 );
1144626a879aSdrh   pParse = pNC->pParse;
1145b3bce662Sdanielk1977 
1146626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1147626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1148626a879aSdrh #ifndef NDEBUG
1149f0113000Sdanielk1977   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1150f0113000Sdanielk1977     SrcList *pSrcList = pNC->pSrcList;
1151940fac9dSdanielk1977     int i;
1152f0113000Sdanielk1977     for(i=0; i<pNC->pSrcList->nSrc; i++){
1153626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1154626a879aSdrh     }
1155626a879aSdrh   }
1156626a879aSdrh #endif
1157626a879aSdrh   switch( pExpr->op ){
1158626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1159626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1160626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1161626a879aSdrh     */
1162626a879aSdrh     case TK_STRING: {
1163626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1164626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1165626a879aSdrh     }
1166626a879aSdrh     /* A lone identifier is the name of a column.
1167626a879aSdrh     */
1168626a879aSdrh     case TK_ID: {
1169626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1170626a879aSdrh       return 1;
1171626a879aSdrh     }
1172626a879aSdrh 
1173626a879aSdrh     /* A table name and column name:     ID.ID
1174626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1175626a879aSdrh     */
1176626a879aSdrh     case TK_DOT: {
1177626a879aSdrh       Token *pColumn;
1178626a879aSdrh       Token *pTable;
1179626a879aSdrh       Token *pDb;
1180626a879aSdrh       Expr *pRight;
1181626a879aSdrh 
1182b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1183626a879aSdrh       pRight = pExpr->pRight;
1184626a879aSdrh       if( pRight->op==TK_ID ){
1185626a879aSdrh         pDb = 0;
1186626a879aSdrh         pTable = &pExpr->pLeft->token;
1187626a879aSdrh         pColumn = &pRight->token;
1188626a879aSdrh       }else{
1189626a879aSdrh         assert( pRight->op==TK_DOT );
1190626a879aSdrh         pDb = &pExpr->pLeft->token;
1191626a879aSdrh         pTable = &pRight->pLeft->token;
1192626a879aSdrh         pColumn = &pRight->pRight->token;
1193626a879aSdrh       }
1194626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1195626a879aSdrh       return 1;
1196626a879aSdrh     }
1197626a879aSdrh 
1198626a879aSdrh     /* Resolve function names
1199626a879aSdrh     */
1200b71090fdSdrh     case TK_CONST_FUNC:
1201626a879aSdrh     case TK_FUNCTION: {
1202626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1203626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1204626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1205626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1206626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1207626a879aSdrh       int i;
12085169bbc6Sdrh       int auth;                   /* Authorization to use the function */
1209626a879aSdrh       int nId;                    /* Number of characters in function name */
1210626a879aSdrh       const char *zId;            /* The function name. */
121173b211abSdrh       FuncDef *pDef;              /* Information about the function */
121214db2665Sdanielk1977       int enc = ENC(pParse->db);  /* The database encoding */
1213626a879aSdrh 
12142646da7eSdrh       zId = (char*)pExpr->token.z;
1215b71090fdSdrh       nId = pExpr->token.n;
1216626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1217626a879aSdrh       if( pDef==0 ){
1218626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1219626a879aSdrh         if( pDef==0 ){
1220626a879aSdrh           no_such_func = 1;
1221626a879aSdrh         }else{
1222626a879aSdrh           wrong_num_args = 1;
1223626a879aSdrh         }
1224626a879aSdrh       }else{
1225626a879aSdrh         is_agg = pDef->xFunc==0;
1226626a879aSdrh       }
12272fca7fefSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
12285169bbc6Sdrh       if( pDef ){
12295169bbc6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
12305169bbc6Sdrh         if( auth!=SQLITE_OK ){
12315169bbc6Sdrh           if( auth==SQLITE_DENY ){
12325169bbc6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
12335169bbc6Sdrh                                     pDef->zName);
12345169bbc6Sdrh             pNC->nErr++;
12355169bbc6Sdrh           }
12365169bbc6Sdrh           pExpr->op = TK_NULL;
12375169bbc6Sdrh           return 1;
12385169bbc6Sdrh         }
12395169bbc6Sdrh       }
1240b8b14219Sdrh #endif
1241626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1242626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1243626a879aSdrh         pNC->nErr++;
1244626a879aSdrh         is_agg = 0;
1245626a879aSdrh       }else if( no_such_func ){
1246626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1247626a879aSdrh         pNC->nErr++;
1248626a879aSdrh       }else if( wrong_num_args ){
1249626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1250626a879aSdrh              nId, zId);
1251626a879aSdrh         pNC->nErr++;
1252626a879aSdrh       }
1253626a879aSdrh       if( is_agg ){
1254626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1255626a879aSdrh         pNC->hasAgg = 1;
1256626a879aSdrh       }
125773b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1258626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
125973b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1260626a879aSdrh       }
126173b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1262626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1263626a879aSdrh       ** type of the function
1264626a879aSdrh       */
1265626a879aSdrh       return is_agg;
1266626a879aSdrh     }
1267b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1268b3bce662Sdanielk1977     case TK_SELECT:
1269b3bce662Sdanielk1977     case TK_EXISTS:
1270b3bce662Sdanielk1977 #endif
1271b3bce662Sdanielk1977     case TK_IN: {
1272b3bce662Sdanielk1977       if( pExpr->pSelect ){
12738a9f38feSdrh         int nRef = pNC->nRef;
127406f6541eSdrh #ifndef SQLITE_OMIT_CHECK
127506f6541eSdrh         if( pNC->isCheck ){
127606f6541eSdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
127706f6541eSdrh         }
127806f6541eSdrh #endif
1279b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1280b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1281b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1282b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1283b3bce662Sdanielk1977         }
1284b3bce662Sdanielk1977       }
12854284fb07Sdrh       break;
1286b3bce662Sdanielk1977     }
12874284fb07Sdrh #ifndef SQLITE_OMIT_CHECK
12884284fb07Sdrh     case TK_VARIABLE: {
12894284fb07Sdrh       if( pNC->isCheck ){
12904284fb07Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
12914284fb07Sdrh       }
12924284fb07Sdrh       break;
12934284fb07Sdrh     }
12944284fb07Sdrh #endif
1295626a879aSdrh   }
1296626a879aSdrh   return 0;
1297626a879aSdrh }
1298626a879aSdrh 
1299626a879aSdrh /*
1300cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1301967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1302aacc543eSdrh ** index to the table in the table list and a column offset.  The
1303aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1304aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1305832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1306aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1307aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1308aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1309aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1310aacc543eSdrh ** alias for ROWID.
131119a775c2Sdrh **
1312626a879aSdrh ** Also resolve function names and check the functions for proper
1313626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1314626a879aSdrh ** have the correct number of arguments.  Leave an error message
1315626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1316626a879aSdrh **
131773b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
131873b211abSdrh ** property on the expression.
1319626a879aSdrh */
1320626a879aSdrh int sqlite3ExprResolveNames(
1321b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1322b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1323626a879aSdrh ){
132413449892Sdrh   int savedHasAgg;
132573b211abSdrh   if( pExpr==0 ) return 0;
132613449892Sdrh   savedHasAgg = pNC->hasAgg;
132713449892Sdrh   pNC->hasAgg = 0;
1328b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1329b3bce662Sdanielk1977   if( pNC->nErr>0 ){
133073b211abSdrh     ExprSetProperty(pExpr, EP_Error);
133173b211abSdrh   }
133213449892Sdrh   if( pNC->hasAgg ){
133313449892Sdrh     ExprSetProperty(pExpr, EP_Agg);
133413449892Sdrh   }else if( savedHasAgg ){
133513449892Sdrh     pNC->hasAgg = 1;
133613449892Sdrh   }
133773b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1338626a879aSdrh }
1339626a879aSdrh 
13401398ad36Sdrh /*
13411398ad36Sdrh ** A pointer instance of this structure is used to pass information
13421398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
13431398ad36Sdrh */
13441398ad36Sdrh typedef struct QueryCoder QueryCoder;
13451398ad36Sdrh struct QueryCoder {
13461398ad36Sdrh   Parse *pParse;       /* The parsing context */
13471398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
13481398ad36Sdrh };
13491398ad36Sdrh 
1350626a879aSdrh 
1351626a879aSdrh /*
13529cbe6352Sdrh ** Generate code for scalar subqueries used as an expression
13539cbe6352Sdrh ** and IN operators.  Examples:
1354626a879aSdrh **
13559cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
13569cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
13579cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
13589cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1359fef5208cSdrh **
13609cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
13619cbe6352Sdrh ** operator or subquery.
1362cce7d176Sdrh */
136351522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1364b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
136557dbd7b3Sdrh   int testAddr = 0;                       /* One-time test address */
1366b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1367b3bce662Sdanielk1977   if( v==0 ) return;
1368b3bce662Sdanielk1977 
136957dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
137057dbd7b3Sdrh   ** if any of the following is true:
137157dbd7b3Sdrh   **
137257dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
137357dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
137457dbd7b3Sdrh   **    *  We are inside a trigger
137557dbd7b3Sdrh   **
137657dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
137757dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1378b3bce662Sdanielk1977   */
1379b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1380b3bce662Sdanielk1977     int mem = pParse->nMem++;
1381b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
138257dbd7b3Sdrh     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
13839e12800dSdanielk1977     assert( testAddr>0 || sqlite3MallocFailed() );
1384d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1385b3bce662Sdanielk1977   }
1386b3bce662Sdanielk1977 
1387cce7d176Sdrh   switch( pExpr->op ){
1388fef5208cSdrh     case TK_IN: {
1389e014a838Sdanielk1977       char affinity;
1390d3d39e93Sdrh       KeyInfo keyInfo;
1391b9bb7c18Sdrh       int addr;        /* Address of OP_OpenEphemeral instruction */
1392d3d39e93Sdrh 
1393bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1394e014a838Sdanielk1977 
1395e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
139657dbd7b3Sdrh       ** expression it is handled the same way. A virtual table is
1397e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1398e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1399fef5208cSdrh       **
1400e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1401e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1402e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1403e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1404e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1405e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1406e014a838Sdanielk1977       ** is used.
1407fef5208cSdrh       */
1408832508b7Sdrh       pExpr->iTable = pParse->nTab++;
1409b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
1410d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1411d3d39e93Sdrh       keyInfo.nField = 1;
1412f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1413e014a838Sdanielk1977 
1414e014a838Sdanielk1977       if( pExpr->pSelect ){
1415e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1416e014a838Sdanielk1977         **
1417e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1418e014a838Sdanielk1977         ** table allocated and opened above.
1419e014a838Sdanielk1977         */
1420e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1421be5c89acSdrh         ExprList *pEList;
1422e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1423b3bce662Sdanielk1977         sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
1424be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1425be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
14267cedc8d4Sdanielk1977           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
1427be5c89acSdrh               pEList->a[0].pExpr);
14280202b29eSdanielk1977         }
1429fef5208cSdrh       }else if( pExpr->pList ){
1430fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1431fef5208cSdrh         **
1432e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
1433e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1434e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1435e014a838Sdanielk1977         ** a column, use numeric affinity.
1436fef5208cSdrh         */
1437e014a838Sdanielk1977         int i;
143857dbd7b3Sdrh         ExprList *pList = pExpr->pList;
143957dbd7b3Sdrh         struct ExprList_item *pItem;
144057dbd7b3Sdrh 
1441e014a838Sdanielk1977         if( !affinity ){
14428159a35fSdrh           affinity = SQLITE_AFF_NONE;
1443e014a838Sdanielk1977         }
14440202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1445e014a838Sdanielk1977 
1446e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
144757dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
144857dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1449e014a838Sdanielk1977 
145057dbd7b3Sdrh           /* If the expression is not constant then we will need to
145157dbd7b3Sdrh           ** disable the test that was generated above that makes sure
145257dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
145357dbd7b3Sdrh           ** expression we need to rerun this code each time.
145457dbd7b3Sdrh           */
14556c30be8eSdrh           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
1456f8875400Sdrh             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
145757dbd7b3Sdrh             testAddr = 0;
14584794b980Sdrh           }
1459e014a838Sdanielk1977 
1460e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
14614adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
146294a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1463f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1464fef5208cSdrh         }
1465fef5208cSdrh       }
14660202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1467b3bce662Sdanielk1977       break;
1468fef5208cSdrh     }
1469fef5208cSdrh 
147051522cd3Sdrh     case TK_EXISTS:
147119a775c2Sdrh     case TK_SELECT: {
1472fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1473fef5208cSdrh       ** value of this select in a memory cell and record the number
1474967e8b73Sdrh       ** of the memory cell in iColumn.
1475fef5208cSdrh       */
14762646da7eSdrh       static const Token one = { (u8*)"1", 0, 1 };
147751522cd3Sdrh       Select *pSel;
1478ec7429aeSdrh       int iMem;
1479ec7429aeSdrh       int sop;
14801398ad36Sdrh 
1481ec7429aeSdrh       pExpr->iColumn = iMem = pParse->nMem++;
148251522cd3Sdrh       pSel = pExpr->pSelect;
148351522cd3Sdrh       if( pExpr->op==TK_SELECT ){
148451522cd3Sdrh         sop = SRT_Mem;
1485ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1486ec7429aeSdrh         VdbeComment((v, "# Init subquery result"));
148751522cd3Sdrh       }else{
148851522cd3Sdrh         sop = SRT_Exists;
1489ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1490ec7429aeSdrh         VdbeComment((v, "# Init EXISTS result"));
149151522cd3Sdrh       }
1492ec7429aeSdrh       sqlite3ExprDelete(pSel->pLimit);
1493ec7429aeSdrh       pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
1494ec7429aeSdrh       sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0);
1495b3bce662Sdanielk1977       break;
149619a775c2Sdrh     }
1497cce7d176Sdrh   }
1498b3bce662Sdanielk1977 
149957dbd7b3Sdrh   if( testAddr ){
1500d654be80Sdrh     sqlite3VdbeJumpHere(v, testAddr);
1501b3bce662Sdanielk1977   }
1502b3bce662Sdanielk1977   return;
1503cce7d176Sdrh }
150451522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1505cce7d176Sdrh 
1506cce7d176Sdrh /*
1507fec19aadSdrh ** Generate an instruction that will put the integer describe by
1508fec19aadSdrh ** text z[0..n-1] on the stack.
1509fec19aadSdrh */
1510fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1511fec19aadSdrh   int i;
15126fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
15136fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
15146fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
151529dda4aeSdrh     sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1516fec19aadSdrh   }else{
1517fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1518fec19aadSdrh   }
1519fec19aadSdrh }
1520fec19aadSdrh 
1521fec19aadSdrh /*
1522cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
15231ccde15dSdrh ** expression and leave the result on the top of stack.
1524f2bc013cSdrh **
1525f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1526f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1527f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1528f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1529f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1530cce7d176Sdrh */
15314adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1532cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1533cce7d176Sdrh   int op;
1534ffe07b2dSdrh   int stackChng = 1;    /* Amount of change to stack depth */
1535ffe07b2dSdrh 
15367977a17fSdanielk1977   if( v==0 ) return;
15377977a17fSdanielk1977   if( pExpr==0 ){
1538f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
15397977a17fSdanielk1977     return;
15407977a17fSdanielk1977   }
1541f2bc013cSdrh   op = pExpr->op;
1542f2bc013cSdrh   switch( op ){
154313449892Sdrh     case TK_AGG_COLUMN: {
154413449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
154513449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
154613449892Sdrh       if( !pAggInfo->directMode ){
154713449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
154813449892Sdrh         break;
154913449892Sdrh       }else if( pAggInfo->useSortingIdx ){
155013449892Sdrh         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
155113449892Sdrh                               pCol->iSorterColumn);
155213449892Sdrh         break;
155313449892Sdrh       }
155413449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
155513449892Sdrh     }
1556967e8b73Sdrh     case TK_COLUMN: {
1557ffe07b2dSdrh       if( pExpr->iTable<0 ){
1558ffe07b2dSdrh         /* This only happens when coding check constraints */
1559ffe07b2dSdrh         assert( pParse->ckOffset>0 );
1560ffe07b2dSdrh         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1561ffe07b2dSdrh       }else if( pExpr->iColumn>=0 ){
15628a51256cSdrh         Table *pTab = pExpr->pTab;
15638a51256cSdrh         int iCol = pExpr->iColumn;
15644cbdda9eSdrh         int op = (pTab && IsVirtual(pTab)) ? OP_VColumn : OP_Column;
15657dabaa12Sdanielk1977         sqlite3VdbeAddOp(v, op, pExpr->iTable, iCol);
15668a51256cSdrh         sqlite3ColumnDefault(v, pTab, iCol);
15678a51256cSdrh #ifndef SQLITE_OMIT_FLOATING_POINT
15688a51256cSdrh         if( pTab && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
15698a51256cSdrh           sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
15708a51256cSdrh         }
15718a51256cSdrh #endif
1572c4a3c779Sdrh       }else{
15737dabaa12Sdanielk1977         Table *pTab = pExpr->pTab;
15744cbdda9eSdrh         int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
15757dabaa12Sdanielk1977         sqlite3VdbeAddOp(v, op, pExpr->iTable, 0);
15762282792aSdrh       }
1577cce7d176Sdrh       break;
1578cce7d176Sdrh     }
1579cce7d176Sdrh     case TK_INTEGER: {
15802646da7eSdrh       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1581fec19aadSdrh       break;
158251e9a445Sdrh     }
1583fec19aadSdrh     case TK_FLOAT:
1584fec19aadSdrh     case TK_STRING: {
1585f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1586f2bc013cSdrh       assert( TK_STRING==OP_String8 );
1587d2687b77Sdrh       sqlite3DequoteExpr(pExpr);
15882646da7eSdrh       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1589cce7d176Sdrh       break;
1590cce7d176Sdrh     }
1591f0863fe5Sdrh     case TK_NULL: {
1592f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1593f0863fe5Sdrh       break;
1594f0863fe5Sdrh     }
15955338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1596c572ef7fSdanielk1977     case TK_BLOB: {
15976c8c6cecSdrh       int n;
15986c8c6cecSdrh       const char *z;
1599f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
16006c8c6cecSdrh       n = pExpr->token.n - 3;
16012646da7eSdrh       z = (char*)pExpr->token.z + 2;
16026c8c6cecSdrh       assert( n>=0 );
16036c8c6cecSdrh       if( n==0 ){
16046c8c6cecSdrh         z = "";
16056c8c6cecSdrh       }
16066c8c6cecSdrh       sqlite3VdbeOp3(v, op, 0, 0, z, n);
1607c572ef7fSdanielk1977       break;
1608c572ef7fSdanielk1977     }
16095338a5f7Sdanielk1977 #endif
161050457896Sdrh     case TK_VARIABLE: {
16114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1612895d7472Sdrh       if( pExpr->token.n>1 ){
16132646da7eSdrh         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1614895d7472Sdrh       }
161550457896Sdrh       break;
161650457896Sdrh     }
16174e0cff60Sdrh     case TK_REGISTER: {
16184e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
16194e0cff60Sdrh       break;
16204e0cff60Sdrh     }
1621487e262fSdrh #ifndef SQLITE_OMIT_CAST
1622487e262fSdrh     case TK_CAST: {
1623487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
1624f0113000Sdanielk1977       int aff, to_op;
1625487e262fSdrh       sqlite3ExprCode(pParse, pExpr->pLeft);
16268a51256cSdrh       aff = sqlite3AffinityType(&pExpr->token);
1627f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1628f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
1629f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
1630f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1631f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
1632f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
1633f0113000Sdanielk1977       sqlite3VdbeAddOp(v, to_op, 0, 0);
1634ffe07b2dSdrh       stackChng = 0;
1635487e262fSdrh       break;
1636487e262fSdrh     }
1637487e262fSdrh #endif /* SQLITE_OMIT_CAST */
1638c9b84a1fSdrh     case TK_LT:
1639c9b84a1fSdrh     case TK_LE:
1640c9b84a1fSdrh     case TK_GT:
1641c9b84a1fSdrh     case TK_GE:
1642c9b84a1fSdrh     case TK_NE:
1643c9b84a1fSdrh     case TK_EQ: {
1644f2bc013cSdrh       assert( TK_LT==OP_Lt );
1645f2bc013cSdrh       assert( TK_LE==OP_Le );
1646f2bc013cSdrh       assert( TK_GT==OP_Gt );
1647f2bc013cSdrh       assert( TK_GE==OP_Ge );
1648f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1649f2bc013cSdrh       assert( TK_NE==OP_Ne );
1650a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1651a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1652be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1653ffe07b2dSdrh       stackChng = -1;
1654a37cdde0Sdanielk1977       break;
1655c9b84a1fSdrh     }
1656cce7d176Sdrh     case TK_AND:
1657cce7d176Sdrh     case TK_OR:
1658cce7d176Sdrh     case TK_PLUS:
1659cce7d176Sdrh     case TK_STAR:
1660cce7d176Sdrh     case TK_MINUS:
1661bf4133cbSdrh     case TK_REM:
1662bf4133cbSdrh     case TK_BITAND:
1663bf4133cbSdrh     case TK_BITOR:
166417c40294Sdrh     case TK_SLASH:
1665bf4133cbSdrh     case TK_LSHIFT:
1666855eb1cfSdrh     case TK_RSHIFT:
16670040077dSdrh     case TK_CONCAT: {
1668f2bc013cSdrh       assert( TK_AND==OP_And );
1669f2bc013cSdrh       assert( TK_OR==OP_Or );
1670f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1671f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1672f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1673f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1674f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1675f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1676f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1677f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1678f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
16794adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16804adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1681855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
1682ffe07b2dSdrh       stackChng = -1;
16830040077dSdrh       break;
16840040077dSdrh     }
1685cce7d176Sdrh     case TK_UMINUS: {
1686fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1687fec19aadSdrh       assert( pLeft );
1688fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1689fec19aadSdrh         Token *p = &pLeft->token;
16909267bdceSdrh         char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
1691fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1692fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1693e6840900Sdrh         }else{
1694fec19aadSdrh           codeInteger(v, z, p->n+1);
1695e6840900Sdrh         }
16966e142f54Sdrh         sqliteFree(z);
16976e142f54Sdrh         break;
16986e142f54Sdrh       }
16991ccde15dSdrh       /* Fall through into TK_NOT */
17006e142f54Sdrh     }
1701bf4133cbSdrh     case TK_BITNOT:
17026e142f54Sdrh     case TK_NOT: {
1703f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1704f2bc013cSdrh       assert( TK_NOT==OP_Not );
17054adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17064adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1707ffe07b2dSdrh       stackChng = 0;
1708cce7d176Sdrh       break;
1709cce7d176Sdrh     }
1710cce7d176Sdrh     case TK_ISNULL:
1711cce7d176Sdrh     case TK_NOTNULL: {
1712cce7d176Sdrh       int dest;
1713f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1714f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
17154adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
17164adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17174adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
17184adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
17194adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1720ffe07b2dSdrh       stackChng = 0;
1721a37cdde0Sdanielk1977       break;
1722f2bc013cSdrh     }
17232282792aSdrh     case TK_AGG_FUNCTION: {
172413449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
17257e56e711Sdrh       if( pInfo==0 ){
17267e56e711Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
17277e56e711Sdrh             &pExpr->span);
17287e56e711Sdrh       }else{
172913449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
17307e56e711Sdrh       }
17312282792aSdrh       break;
17322282792aSdrh     }
1733b71090fdSdrh     case TK_CONST_FUNC:
1734cce7d176Sdrh     case TK_FUNCTION: {
1735cce7d176Sdrh       ExprList *pList = pExpr->pList;
173689425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
17370bce8354Sdrh       FuncDef *pDef;
17384b59ab5eSdrh       int nId;
17394b59ab5eSdrh       const char *zId;
174013449892Sdrh       int constMask = 0;
1741682f68b0Sdanielk1977       int i;
174214db2665Sdanielk1977       u8 enc = ENC(pParse->db);
1743dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
17442646da7eSdrh       zId = (char*)pExpr->token.z;
1745b71090fdSdrh       nId = pExpr->token.n;
1746d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
17470bce8354Sdrh       assert( pDef!=0 );
1748f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1749b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1750a43fa227Sdrh       /* Possibly overload the function if the first argument is
1751a43fa227Sdrh       ** a virtual table column.
1752a43fa227Sdrh       **
1753a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1754a43fa227Sdrh       ** second argument, not the first, as the argument to test to
1755a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
1756a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
1757a43fa227Sdrh       ** control overloading) ends up as the second argument to the
1758a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
1759a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
1760a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
1761a43fa227Sdrh       */
17626a03a1c5Sdrh       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
17636a03a1c5Sdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[1].pExpr);
17646a03a1c5Sdrh       }else if( nExpr>0 ){
1765b7f6f68fSdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[0].pExpr);
1766b7f6f68fSdrh       }
1767b7f6f68fSdrh #endif
1768682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1769d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
177013449892Sdrh           constMask |= (1<<i);
1771d02eb1fdSdanielk1977         }
1772dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1773dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1774dc1bdc4fSdanielk1977         }
1775dc1bdc4fSdanielk1977       }
1776dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1777dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1778d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1779682f68b0Sdanielk1977       }
178013449892Sdrh       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1781ffe07b2dSdrh       stackChng = 1-nExpr;
17826ec2733bSdrh       break;
17836ec2733bSdrh     }
1784fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1785fe2093d7Sdrh     case TK_EXISTS:
178619a775c2Sdrh     case TK_SELECT: {
178741714d6fSdrh       if( pExpr->iColumn==0 ){
1788b3bce662Sdanielk1977         sqlite3CodeSubselect(pParse, pExpr);
178941714d6fSdrh       }
17904adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1791ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
179219a775c2Sdrh       break;
179319a775c2Sdrh     }
1794fef5208cSdrh     case TK_IN: {
1795fef5208cSdrh       int addr;
179694a11211Sdrh       char affinity;
1797afa5f680Sdrh       int ckOffset = pParse->ckOffset;
1798b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
1799e014a838Sdanielk1977 
1800e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1801e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1802ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1803e014a838Sdanielk1977       */
180494a11211Sdrh       affinity = comparisonAffinity(pExpr);
1805e014a838Sdanielk1977 
18064adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1807afa5f680Sdrh       pParse->ckOffset = ckOffset+1;
1808e014a838Sdanielk1977 
1809e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1810e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1811e014a838Sdanielk1977       */
18124adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18134adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1814e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
18154adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
1816f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1817e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
181894a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
1819e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1820e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1821e014a838Sdanielk1977 
1822fef5208cSdrh       break;
1823fef5208cSdrh     }
182493758c8dSdanielk1977 #endif
1825fef5208cSdrh     case TK_BETWEEN: {
1826be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1827be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1828be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1829be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
18304adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1831be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1832be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
18334adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1834be5c89acSdrh       pLItem++;
1835be5c89acSdrh       pRight = pLItem->pExpr;
1836be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1837be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
18384adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1839fef5208cSdrh       break;
1840fef5208cSdrh     }
184151e9a445Sdrh     case TK_UPLUS:
1842a2e00042Sdrh     case TK_AS: {
18434adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1844ffe07b2dSdrh       stackChng = 0;
1845a2e00042Sdrh       break;
1846a2e00042Sdrh     }
184717a7f8ddSdrh     case TK_CASE: {
184817a7f8ddSdrh       int expr_end_label;
1849f5905aa7Sdrh       int jumpInst;
1850f5905aa7Sdrh       int nExpr;
185117a7f8ddSdrh       int i;
1852be5c89acSdrh       ExprList *pEList;
1853be5c89acSdrh       struct ExprList_item *aListelem;
185417a7f8ddSdrh 
185517a7f8ddSdrh       assert(pExpr->pList);
185617a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
185717a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1858be5c89acSdrh       pEList = pExpr->pList;
1859be5c89acSdrh       aListelem = pEList->a;
1860be5c89acSdrh       nExpr = pEList->nExpr;
18614adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
186217a7f8ddSdrh       if( pExpr->pLeft ){
18634adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1864cce7d176Sdrh       }
1865f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1866be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
186717a7f8ddSdrh         if( pExpr->pLeft ){
18684adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1869be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1870be5c89acSdrh                                  OP_Ne, 0, 1);
18714adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1872f5905aa7Sdrh         }else{
18734adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
187417a7f8ddSdrh         }
1875be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
18764adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
1877d654be80Sdrh         sqlite3VdbeJumpHere(v, jumpInst);
187817a7f8ddSdrh       }
1879f570f011Sdrh       if( pExpr->pLeft ){
18804adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1881f570f011Sdrh       }
188217a7f8ddSdrh       if( pExpr->pRight ){
18834adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
188417a7f8ddSdrh       }else{
1885f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
188617a7f8ddSdrh       }
18874adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
18886f34903eSdanielk1977       break;
18896f34903eSdanielk1977     }
18905338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
18916f34903eSdanielk1977     case TK_RAISE: {
18926f34903eSdanielk1977       if( !pParse->trigStack ){
18934adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1894da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
18956f34903eSdanielk1977 	return;
18966f34903eSdanielk1977       }
1897ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
1898ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
18996f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
1900ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
1901d2687b77Sdrh          sqlite3DequoteExpr(pExpr);
19024adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
19032646da7eSdrh                         (char*)pExpr->token.z, pExpr->token.n);
19046f34903eSdanielk1977       } else {
19056f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
1906344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
1907ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
1908ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
19096f34903eSdanielk1977       }
1910ffe07b2dSdrh       stackChng = 0;
1911ffe07b2dSdrh       break;
191217a7f8ddSdrh     }
19135338a5f7Sdanielk1977 #endif
1914ffe07b2dSdrh   }
1915ffe07b2dSdrh 
1916ffe07b2dSdrh   if( pParse->ckOffset ){
1917ffe07b2dSdrh     pParse->ckOffset += stackChng;
1918ffe07b2dSdrh     assert( pParse->ckOffset );
191917a7f8ddSdrh   }
1920cce7d176Sdrh }
1921cce7d176Sdrh 
192293758c8dSdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
1923cce7d176Sdrh /*
192425303780Sdrh ** Generate code that evalutes the given expression and leaves the result
192525303780Sdrh ** on the stack.  See also sqlite3ExprCode().
192625303780Sdrh **
192725303780Sdrh ** This routine might also cache the result and modify the pExpr tree
192825303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
192925303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
193025303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
193125303780Sdrh ** memory location.
193225303780Sdrh */
193325303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
193425303780Sdrh   Vdbe *v = pParse->pVdbe;
193525303780Sdrh   int iMem;
193625303780Sdrh   int addr1, addr2;
193725303780Sdrh   if( v==0 ) return;
193825303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
193925303780Sdrh   sqlite3ExprCode(pParse, pExpr);
194025303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
194125303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
194225303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
194325303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
194425303780Sdrh     pExpr->op = TK_REGISTER;
194525303780Sdrh   }
194625303780Sdrh }
194793758c8dSdanielk1977 #endif
194825303780Sdrh 
194925303780Sdrh /*
1950268380caSdrh ** Generate code that pushes the value of every element of the given
1951f9b596ebSdrh ** expression list onto the stack.
1952268380caSdrh **
1953268380caSdrh ** Return the number of elements pushed onto the stack.
1954268380caSdrh */
19554adee20fSdanielk1977 int sqlite3ExprCodeExprList(
1956268380caSdrh   Parse *pParse,     /* Parsing context */
1957f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
1958268380caSdrh ){
1959268380caSdrh   struct ExprList_item *pItem;
1960268380caSdrh   int i, n;
1961268380caSdrh   if( pList==0 ) return 0;
1962268380caSdrh   n = pList->nExpr;
1963c182d163Sdrh   for(pItem=pList->a, i=n; i>0; i--, pItem++){
19644adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
1965268380caSdrh   }
1966f9b596ebSdrh   return n;
1967268380caSdrh }
1968268380caSdrh 
1969268380caSdrh /*
1970cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
1971cce7d176Sdrh ** to the label "dest" if the expression is true but execution
1972cce7d176Sdrh ** continues straight thru if the expression is false.
1973f5905aa7Sdrh **
1974f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
1975f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
1976f2bc013cSdrh **
1977f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1978f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1979f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1980f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1981f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1982cce7d176Sdrh */
19834adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1984cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1985cce7d176Sdrh   int op = 0;
1986ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
1987daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1988f2bc013cSdrh   op = pExpr->op;
1989f2bc013cSdrh   switch( op ){
1990cce7d176Sdrh     case TK_AND: {
19914adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
19924adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
19934adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
19944adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1995cce7d176Sdrh       break;
1996cce7d176Sdrh     }
1997cce7d176Sdrh     case TK_OR: {
19984adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
19994adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2000cce7d176Sdrh       break;
2001cce7d176Sdrh     }
2002cce7d176Sdrh     case TK_NOT: {
20034adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2004cce7d176Sdrh       break;
2005cce7d176Sdrh     }
2006cce7d176Sdrh     case TK_LT:
2007cce7d176Sdrh     case TK_LE:
2008cce7d176Sdrh     case TK_GT:
2009cce7d176Sdrh     case TK_GE:
2010cce7d176Sdrh     case TK_NE:
20110ac65892Sdrh     case TK_EQ: {
2012f2bc013cSdrh       assert( TK_LT==OP_Lt );
2013f2bc013cSdrh       assert( TK_LE==OP_Le );
2014f2bc013cSdrh       assert( TK_GT==OP_Gt );
2015f2bc013cSdrh       assert( TK_GE==OP_Ge );
2016f2bc013cSdrh       assert( TK_EQ==OP_Eq );
2017f2bc013cSdrh       assert( TK_NE==OP_Ne );
20184adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20194adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2020be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2021cce7d176Sdrh       break;
2022cce7d176Sdrh     }
2023cce7d176Sdrh     case TK_ISNULL:
2024cce7d176Sdrh     case TK_NOTNULL: {
2025f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
2026f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
20274adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20284adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2029cce7d176Sdrh       break;
2030cce7d176Sdrh     }
2031fef5208cSdrh     case TK_BETWEEN: {
20320202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
20330202b29eSdanielk1977       **
20340202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
20350202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
20360202b29eSdanielk1977       ** 3 ...
20370202b29eSdanielk1977       */
2038f5905aa7Sdrh       int addr;
2039be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2040be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2041be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
20424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2043be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2044be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
20450202b29eSdanielk1977 
2046be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2047be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2048be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
20490202b29eSdanielk1977 
20504adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2051d654be80Sdrh       sqlite3VdbeJumpHere(v, addr);
20524adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2053fef5208cSdrh       break;
2054fef5208cSdrh     }
2055cce7d176Sdrh     default: {
20564adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
20574adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
2058cce7d176Sdrh       break;
2059cce7d176Sdrh     }
2060cce7d176Sdrh   }
2061ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2062cce7d176Sdrh }
2063cce7d176Sdrh 
2064cce7d176Sdrh /*
206566b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
2066cce7d176Sdrh ** to the label "dest" if the expression is false but execution
2067cce7d176Sdrh ** continues straight thru if the expression is true.
2068f5905aa7Sdrh **
2069f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
2070f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
2071cce7d176Sdrh */
20724adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2073cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2074cce7d176Sdrh   int op = 0;
2075ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2076daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2077f2bc013cSdrh 
2078f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
2079f2bc013cSdrh   **
2080f2bc013cSdrh   **       pExpr->op            op
2081f2bc013cSdrh   **       ---------          ----------
2082f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
2083f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
2084f2bc013cSdrh   **       TK_NE              OP_Eq
2085f2bc013cSdrh   **       TK_EQ              OP_Ne
2086f2bc013cSdrh   **       TK_GT              OP_Le
2087f2bc013cSdrh   **       TK_LE              OP_Gt
2088f2bc013cSdrh   **       TK_GE              OP_Lt
2089f2bc013cSdrh   **       TK_LT              OP_Ge
2090f2bc013cSdrh   **
2091f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
2092f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
2093f2bc013cSdrh   ** can compute the mapping above using the following expression.
2094f2bc013cSdrh   ** Assert()s verify that the computation is correct.
2095f2bc013cSdrh   */
2096f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2097f2bc013cSdrh 
2098f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
2099f2bc013cSdrh   */
2100f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2101f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2102f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
2103f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
2104f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
2105f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
2106f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
2107f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
2108f2bc013cSdrh 
2109cce7d176Sdrh   switch( pExpr->op ){
2110cce7d176Sdrh     case TK_AND: {
21114adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
21124adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2113cce7d176Sdrh       break;
2114cce7d176Sdrh     }
2115cce7d176Sdrh     case TK_OR: {
21164adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
21174adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
21184adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
21194adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2120cce7d176Sdrh       break;
2121cce7d176Sdrh     }
2122cce7d176Sdrh     case TK_NOT: {
21234adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2124cce7d176Sdrh       break;
2125cce7d176Sdrh     }
2126cce7d176Sdrh     case TK_LT:
2127cce7d176Sdrh     case TK_LE:
2128cce7d176Sdrh     case TK_GT:
2129cce7d176Sdrh     case TK_GE:
2130cce7d176Sdrh     case TK_NE:
2131cce7d176Sdrh     case TK_EQ: {
21324adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
21334adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2134be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2135cce7d176Sdrh       break;
2136cce7d176Sdrh     }
2137cce7d176Sdrh     case TK_ISNULL:
2138cce7d176Sdrh     case TK_NOTNULL: {
21394adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
21404adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2141cce7d176Sdrh       break;
2142cce7d176Sdrh     }
2143fef5208cSdrh     case TK_BETWEEN: {
21440202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
21450202b29eSdanielk1977       **
21460202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
21470202b29eSdanielk1977       ** 2 GOTO <dest>
21480202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
21490202b29eSdanielk1977       */
2150fef5208cSdrh       int addr;
2151be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2152be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2153be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
21544adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2155be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
21564adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
2157be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2158be5c89acSdrh 
21594adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
21604adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2161be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2162be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2163be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2164fef5208cSdrh       break;
2165fef5208cSdrh     }
2166cce7d176Sdrh     default: {
21674adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
21684adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2169cce7d176Sdrh       break;
2170cce7d176Sdrh     }
2171cce7d176Sdrh   }
2172ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2173cce7d176Sdrh }
21742282792aSdrh 
21752282792aSdrh /*
21762282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
21772282792aSdrh ** if they are identical and return FALSE if they differ in any way.
21782282792aSdrh */
21794adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
21802282792aSdrh   int i;
21814b202ae2Sdanielk1977   if( pA==0||pB==0 ){
21824b202ae2Sdanielk1977     return pB==pA;
21832282792aSdrh   }
21842282792aSdrh   if( pA->op!=pB->op ) return 0;
2185fd357974Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
21864adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
21874adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
21882282792aSdrh   if( pA->pList ){
21892282792aSdrh     if( pB->pList==0 ) return 0;
21902282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
21912282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
21924adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
21932282792aSdrh         return 0;
21942282792aSdrh       }
21952282792aSdrh     }
21962282792aSdrh   }else if( pB->pList ){
21972282792aSdrh     return 0;
21982282792aSdrh   }
21992282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
22002f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
22012282792aSdrh   if( pA->token.z ){
22022282792aSdrh     if( pB->token.z==0 ) return 0;
22036977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
22042646da7eSdrh     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
22052646da7eSdrh       return 0;
22062646da7eSdrh     }
22072282792aSdrh   }
22082282792aSdrh   return 1;
22092282792aSdrh }
22102282792aSdrh 
221113449892Sdrh 
22122282792aSdrh /*
221313449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
221413449892Sdrh ** the new element.  Return a negative number if malloc fails.
22152282792aSdrh */
221613449892Sdrh static int addAggInfoColumn(AggInfo *pInfo){
221713449892Sdrh   int i;
221813449892Sdrh   i = sqlite3ArrayAllocate((void**)&pInfo->aCol, sizeof(pInfo->aCol[0]), 3);
221913449892Sdrh   if( i<0 ){
22202282792aSdrh     return -1;
22212282792aSdrh   }
222213449892Sdrh   return i;
22232282792aSdrh }
222413449892Sdrh 
222513449892Sdrh /*
222613449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
222713449892Sdrh ** the new element.  Return a negative number if malloc fails.
222813449892Sdrh */
222913449892Sdrh static int addAggInfoFunc(AggInfo *pInfo){
223013449892Sdrh   int i;
223113449892Sdrh   i = sqlite3ArrayAllocate((void**)&pInfo->aFunc, sizeof(pInfo->aFunc[0]), 2);
223213449892Sdrh   if( i<0 ){
223313449892Sdrh     return -1;
223413449892Sdrh   }
223513449892Sdrh   return i;
22362282792aSdrh }
22372282792aSdrh 
22382282792aSdrh /*
2239626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
2240626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2241626a879aSdrh ** for additional information.
22422282792aSdrh **
2243626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
22442282792aSdrh */
2245626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
22462282792aSdrh   int i;
2247a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
2248a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
2249a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
225013449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
225113449892Sdrh 
22522282792aSdrh 
22532282792aSdrh   switch( pExpr->op ){
225489c69d00Sdrh     case TK_AGG_COLUMN:
2255967e8b73Sdrh     case TK_COLUMN: {
225613449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
225713449892Sdrh       ** clause of the aggregate query */
225813449892Sdrh       if( pSrcList ){
225913449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
226013449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
226113449892Sdrh           struct AggInfo_col *pCol;
226213449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
226313449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
226413449892Sdrh             ** that is in the FROM clause of the aggregate query.
226513449892Sdrh             **
226613449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
226713449892Sdrh             ** is not an entry there already.
226813449892Sdrh             */
226913449892Sdrh             pCol = pAggInfo->aCol;
227013449892Sdrh             for(i=0; i<pAggInfo->nColumn; i++, pCol++){
227113449892Sdrh               if( pCol->iTable==pExpr->iTable &&
227213449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
22732282792aSdrh                 break;
22742282792aSdrh               }
22752282792aSdrh             }
227613449892Sdrh             if( i>=pAggInfo->nColumn && (i = addAggInfoColumn(pAggInfo))>=0 ){
227713449892Sdrh               pCol = &pAggInfo->aCol[i];
227813449892Sdrh               pCol->iTable = pExpr->iTable;
227913449892Sdrh               pCol->iColumn = pExpr->iColumn;
228013449892Sdrh               pCol->iMem = pParse->nMem++;
228113449892Sdrh               pCol->iSorterColumn = -1;
22825774b806Sdrh               pCol->pExpr = pExpr;
228313449892Sdrh               if( pAggInfo->pGroupBy ){
228413449892Sdrh                 int j, n;
228513449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
228613449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
228713449892Sdrh                 n = pGB->nExpr;
228813449892Sdrh                 for(j=0; j<n; j++, pTerm++){
228913449892Sdrh                   Expr *pE = pTerm->pExpr;
229013449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
229113449892Sdrh                       pE->iColumn==pExpr->iColumn ){
229213449892Sdrh                     pCol->iSorterColumn = j;
229313449892Sdrh                     break;
22942282792aSdrh                   }
229513449892Sdrh                 }
229613449892Sdrh               }
229713449892Sdrh               if( pCol->iSorterColumn<0 ){
229813449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
229913449892Sdrh               }
230013449892Sdrh             }
230113449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
230213449892Sdrh             ** because it was there before or because we just created it).
230313449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
230413449892Sdrh             ** pAggInfo->aCol[] entry.
230513449892Sdrh             */
230613449892Sdrh             pExpr->pAggInfo = pAggInfo;
230713449892Sdrh             pExpr->op = TK_AGG_COLUMN;
2308aaf88729Sdrh             pExpr->iAgg = i;
230913449892Sdrh             break;
231013449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
231113449892Sdrh         } /* end loop over pSrcList */
2312a58fdfb1Sdanielk1977       }
2313626a879aSdrh       return 1;
23142282792aSdrh     }
23152282792aSdrh     case TK_AGG_FUNCTION: {
231613449892Sdrh       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
231713449892Sdrh       ** to be ignored */
2318a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
231913449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
232013449892Sdrh         ** function that is already in the pAggInfo structure
232113449892Sdrh         */
232213449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
232313449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
232413449892Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
23252282792aSdrh             break;
23262282792aSdrh           }
23272282792aSdrh         }
232813449892Sdrh         if( i>=pAggInfo->nFunc ){
232913449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
233013449892Sdrh           */
233114db2665Sdanielk1977           u8 enc = ENC(pParse->db);
233213449892Sdrh           i = addAggInfoFunc(pAggInfo);
233313449892Sdrh           if( i>=0 ){
233413449892Sdrh             pItem = &pAggInfo->aFunc[i];
233513449892Sdrh             pItem->pExpr = pExpr;
233613449892Sdrh             pItem->iMem = pParse->nMem++;
233713449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
23382646da7eSdrh                    (char*)pExpr->token.z, pExpr->token.n,
2339d8123366Sdanielk1977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2340fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
2341fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
2342fd357974Sdrh             }else{
2343fd357974Sdrh               pItem->iDistinct = -1;
2344fd357974Sdrh             }
23452282792aSdrh           }
234613449892Sdrh         }
234713449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
234813449892Sdrh         */
23492282792aSdrh         pExpr->iAgg = i;
235013449892Sdrh         pExpr->pAggInfo = pAggInfo;
2351626a879aSdrh         return 1;
23522282792aSdrh       }
23532282792aSdrh     }
2354a58fdfb1Sdanielk1977   }
235513449892Sdrh 
235613449892Sdrh   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
235713449892Sdrh   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
235813449892Sdrh   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
235913449892Sdrh   */
2360a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
2361a58fdfb1Sdanielk1977     pNC->nDepth++;
2362a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2363a58fdfb1Sdanielk1977     pNC->nDepth--;
2364a58fdfb1Sdanielk1977   }
2365626a879aSdrh   return 0;
23662282792aSdrh }
2367626a879aSdrh 
2368626a879aSdrh /*
2369626a879aSdrh ** Analyze the given expression looking for aggregate functions and
2370626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
2371626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
2372626a879aSdrh **
2373626a879aSdrh ** This routine should only be called after the expression has been
2374626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
2375626a879aSdrh **
2376626a879aSdrh ** If errors are seen, leave an error message in zErrMsg and return
2377626a879aSdrh ** the number of errors.
2378626a879aSdrh */
2379a58fdfb1Sdanielk1977 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2380a58fdfb1Sdanielk1977   int nErr = pNC->pParse->nErr;
2381a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
2382a58fdfb1Sdanielk1977   return pNC->pParse->nErr - nErr;
23832282792aSdrh }
23845d9a4af9Sdrh 
23855d9a4af9Sdrh /*
23865d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
23875d9a4af9Sdrh ** expression list.  Return the number of errors.
23885d9a4af9Sdrh **
23895d9a4af9Sdrh ** If an error is found, the analysis is cut short.
23905d9a4af9Sdrh */
23915d9a4af9Sdrh int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
23925d9a4af9Sdrh   struct ExprList_item *pItem;
23935d9a4af9Sdrh   int i;
23945d9a4af9Sdrh   int nErr = 0;
23955d9a4af9Sdrh   if( pList ){
23965d9a4af9Sdrh     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
23975d9a4af9Sdrh       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
23985d9a4af9Sdrh     }
23995d9a4af9Sdrh   }
24005d9a4af9Sdrh   return nErr;
24015d9a4af9Sdrh }
2402