xref: /sqlite-3.40.0/src/expr.c (revision b4fc6794)
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*b4fc6794Sdanielk1977 ** $Id: expr.c,v 1.287 2007/05/08 18:04:46 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
1804738cb9Sdrh #include <ctype.h>
19a2e00042Sdrh 
20e014a838Sdanielk1977 /*
21e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
22e014a838Sdanielk1977 **
23e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
24e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
25e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
26e014a838Sdanielk1977 ** indicating no affinity for the expression.
27e014a838Sdanielk1977 **
28e014a838Sdanielk1977 ** i.e. the WHERE clause expresssions in the following statements all
29e014a838Sdanielk1977 ** have an affinity:
30e014a838Sdanielk1977 **
31e014a838Sdanielk1977 ** CREATE TABLE t1(a);
32e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
33e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
34e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
35e014a838Sdanielk1977 */
36bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
37487e262fSdrh   int op = pExpr->op;
38487e262fSdrh   if( op==TK_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 ){
134de087bd5Sdrh     aff = SQLITE_AFF_NONE;
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){
179ec41ddacSdrh   CollSeq *pColl;
180ec41ddacSdrh   assert( pLeft );
181ec41ddacSdrh   assert( pRight );
182ec41ddacSdrh   if( pLeft->flags & EP_ExpCollate ){
183ec41ddacSdrh     assert( pLeft->pColl );
184ec41ddacSdrh     pColl = pLeft->pColl;
185ec41ddacSdrh   }else if( pRight->flags & EP_ExpCollate ){
186ec41ddacSdrh     assert( pRight->pColl );
187ec41ddacSdrh     pColl = pRight->pColl;
188ec41ddacSdrh   }else{
189ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
1900202b29eSdanielk1977     if( !pColl ){
1917cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
1920202b29eSdanielk1977     }
193ec41ddacSdrh   }
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);
2405ffb3ac8Sdrh       if( pRight->flags & EP_ExpCollate ){
241a34001c9Sdrh         pNew->flags |= EP_ExpCollate;
242a34001c9Sdrh         pNew->pColl = pRight->pColl;
243a34001c9Sdrh       }
244a34001c9Sdrh     }
2455ffb3ac8Sdrh     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;
407cf643729Sdrh         pParse->apVarExpr = sqliteReallocOrFree(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 /*
6577a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
6587a15a4beSdanielk1977 ** leave an error message in pParse.
6597a15a4beSdanielk1977 */
6607a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
6617a15a4beSdanielk1977   Parse *pParse,
6627a15a4beSdanielk1977   ExprList *pEList,
6637a15a4beSdanielk1977   int iLimit,
6647a15a4beSdanielk1977   const char *zObject
6657a15a4beSdanielk1977 ){
666*b4fc6794Sdanielk1977   if( pEList && pEList->nExpr>iLimit ){
6677a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
6687a15a4beSdanielk1977   }
6697a15a4beSdanielk1977 }
6707a15a4beSdanielk1977 
6717a15a4beSdanielk1977 /*
672a76b5dfcSdrh ** Delete an entire expression list.
673a76b5dfcSdrh */
6744adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
675a76b5dfcSdrh   int i;
676be5c89acSdrh   struct ExprList_item *pItem;
677a76b5dfcSdrh   if( pList==0 ) return;
6781bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
6791bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
680be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
681be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
682be5c89acSdrh     sqliteFree(pItem->zName);
683a76b5dfcSdrh   }
684a76b5dfcSdrh   sqliteFree(pList->a);
685a76b5dfcSdrh   sqliteFree(pList);
686a76b5dfcSdrh }
687a76b5dfcSdrh 
688a76b5dfcSdrh /*
689626a879aSdrh ** Walk an expression tree.  Call xFunc for each node visited.
69073b211abSdrh **
691626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
692626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
693626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
694626a879aSdrh ** the tree walk completely.
695626a879aSdrh **
696626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
697626a879aSdrh ** and 0 to continue.
69887abf5c0Sdrh **
69987abf5c0Sdrh ** NOTICE:  This routine does *not* descend into subqueries.
700626a879aSdrh */
701a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
702626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
703626a879aSdrh   int rc;
704626a879aSdrh   if( pExpr==0 ) return 0;
705626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
706626a879aSdrh   if( rc==0 ){
707626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
708626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
709a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
710626a879aSdrh   }
711626a879aSdrh   return rc>1;
712626a879aSdrh }
713626a879aSdrh 
714626a879aSdrh /*
715a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
716a58fdfb1Sdanielk1977 */
717a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
718a58fdfb1Sdanielk1977   int i;
719a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
720a58fdfb1Sdanielk1977   if( !p ) return 0;
721a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
722a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
723a58fdfb1Sdanielk1977   }
724a58fdfb1Sdanielk1977   return 0;
725a58fdfb1Sdanielk1977 }
726a58fdfb1Sdanielk1977 
727a58fdfb1Sdanielk1977 /*
728a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
729a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
730a58fdfb1Sdanielk1977 ** or OFFSET expressions..
731a58fdfb1Sdanielk1977 */
732a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
733a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
734a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
735a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
736a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
737a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
738a58fdfb1Sdanielk1977   return 0;
739a58fdfb1Sdanielk1977 }
740a58fdfb1Sdanielk1977 
741a58fdfb1Sdanielk1977 
742a58fdfb1Sdanielk1977 /*
743626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
744626a879aSdrh **
745626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
74673b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
74773b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
74873b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
74973b211abSdrh ** then do nothing.
75073b211abSdrh **
75173b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
75273b211abSdrh ** the expression as constant, then we assume the whole expression
75373b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
754626a879aSdrh */
755626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
756626a879aSdrh   switch( pExpr->op ){
757eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
758eb55bd2fSdrh     ** and *pArg==2 */
759eb55bd2fSdrh     case TK_FUNCTION:
760eb55bd2fSdrh       if( *((int*)pArg)==2 ) return 0;
761eb55bd2fSdrh       /* Fall through */
762626a879aSdrh     case TK_ID:
763626a879aSdrh     case TK_COLUMN:
764626a879aSdrh     case TK_DOT:
765626a879aSdrh     case TK_AGG_FUNCTION:
76613449892Sdrh     case TK_AGG_COLUMN:
767fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
768fe2093d7Sdrh     case TK_SELECT:
769fe2093d7Sdrh     case TK_EXISTS:
770fe2093d7Sdrh #endif
771626a879aSdrh       *((int*)pArg) = 0;
772626a879aSdrh       return 2;
77387abf5c0Sdrh     case TK_IN:
77487abf5c0Sdrh       if( pExpr->pSelect ){
77587abf5c0Sdrh         *((int*)pArg) = 0;
77687abf5c0Sdrh         return 2;
77787abf5c0Sdrh       }
778626a879aSdrh     default:
779626a879aSdrh       return 0;
780626a879aSdrh   }
781626a879aSdrh }
782626a879aSdrh 
783626a879aSdrh /*
784fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
785eb55bd2fSdrh ** and 0 if it involves variables or function calls.
7862398937bSdrh **
7872398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
7882398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
7892398937bSdrh ** a constant.
790fef5208cSdrh */
7914adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
792626a879aSdrh   int isConst = 1;
793626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
794626a879aSdrh   return isConst;
795fef5208cSdrh }
796fef5208cSdrh 
797fef5208cSdrh /*
798eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
799eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
800eb55bd2fSdrh ** are any variables.
801eb55bd2fSdrh **
802eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
803eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
804eb55bd2fSdrh ** a constant.
805eb55bd2fSdrh */
806eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
807eb55bd2fSdrh   int isConst = 2;
808eb55bd2fSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
809eb55bd2fSdrh   return isConst!=0;
810eb55bd2fSdrh }
811eb55bd2fSdrh 
812eb55bd2fSdrh /*
81373b211abSdrh ** If the expression p codes a constant integer that is small enough
814202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
815202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
816202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
817e4de1febSdrh */
8184adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
819e4de1febSdrh   switch( p->op ){
820e4de1febSdrh     case TK_INTEGER: {
8212646da7eSdrh       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
822e4de1febSdrh         return 1;
823e4de1febSdrh       }
824202b2df7Sdrh       break;
825202b2df7Sdrh     }
8264b59ab5eSdrh     case TK_UPLUS: {
8274adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
8284b59ab5eSdrh     }
829e4de1febSdrh     case TK_UMINUS: {
830e4de1febSdrh       int v;
8314adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
832e4de1febSdrh         *pValue = -v;
833e4de1febSdrh         return 1;
834e4de1febSdrh       }
835e4de1febSdrh       break;
836e4de1febSdrh     }
837e4de1febSdrh     default: break;
838e4de1febSdrh   }
839e4de1febSdrh   return 0;
840e4de1febSdrh }
841e4de1febSdrh 
842e4de1febSdrh /*
843c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
844c4a3c779Sdrh */
8454adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
8464adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
8474adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
8484adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
849c4a3c779Sdrh   return 0;
850c4a3c779Sdrh }
851c4a3c779Sdrh 
852c4a3c779Sdrh /*
8538141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
8548141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
8558141f61eSdrh ** expression node refer back to that source column.  The following changes
8568141f61eSdrh ** are made to pExpr:
8578141f61eSdrh **
8588141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
8598141f61eSdrh **                         the table.
8608141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
8618141f61eSdrh **                         from pSrcList.
8628141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
8638141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
8648141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
8658141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
8668141f61eSdrh **
8678141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
8688141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
8698141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
8708141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
8718141f61eSdrh ** means that the form of the name is Z and that columns from any table
8728141f61eSdrh ** can be used.
8738141f61eSdrh **
8748141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
8758141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
8768141f61eSdrh */
8778141f61eSdrh static int lookupName(
8788141f61eSdrh   Parse *pParse,       /* The parsing context */
8798141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
8808141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
8818141f61eSdrh   Token *pColumnToken, /* Name of the column. */
882626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
8838141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
8848141f61eSdrh ){
8858141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
8868141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
8878141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
8888141f61eSdrh   int i, j;            /* Loop counters */
8898141f61eSdrh   int cnt = 0;         /* Number of matching column names */
8908141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
8919bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
89251669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
89351669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
89473b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
8958141f61eSdrh 
8968141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
897a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
898a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
899a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
9009e12800dSdanielk1977   if( sqlite3MallocFailed() ){
901d5d56523Sdanielk1977     goto lookupname_end;
9028141f61eSdrh   }
9038141f61eSdrh 
9048141f61eSdrh   pExpr->iTable = -1;
905626a879aSdrh   while( pNC && cnt==0 ){
906ffe07b2dSdrh     ExprList *pEList;
907626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
908626a879aSdrh 
909b3bce662Sdanielk1977     if( pSrcList ){
91051669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
91143617e9aSdrh         Table *pTab;
91243617e9aSdrh         int iDb;
9138141f61eSdrh         Column *pCol;
9148141f61eSdrh 
91543617e9aSdrh         pTab = pItem->pTab;
91643617e9aSdrh         assert( pTab!=0 );
91743617e9aSdrh         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
9188141f61eSdrh         assert( pTab->nCol>0 );
9198141f61eSdrh         if( zTab ){
9208141f61eSdrh           if( pItem->zAlias ){
9218141f61eSdrh             char *zTabName = pItem->zAlias;
9224adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
9238141f61eSdrh           }else{
9248141f61eSdrh             char *zTabName = pTab->zName;
9254adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
926da184236Sdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
9278141f61eSdrh               continue;
9288141f61eSdrh             }
9298141f61eSdrh           }
9308141f61eSdrh         }
9318141f61eSdrh         if( 0==(cntTab++) ){
9328141f61eSdrh           pExpr->iTable = pItem->iCursor;
933da184236Sdanielk1977           pExpr->pSchema = pTab->pSchema;
93451669863Sdrh           pMatch = pItem;
9358141f61eSdrh         }
9368141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
9374adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
938b3bf556eSdanielk1977             const char *zColl = pTab->aCol[j].zColl;
939873fac0cSdrh             IdList *pUsing;
9408141f61eSdrh             cnt++;
9418141f61eSdrh             pExpr->iTable = pItem->iCursor;
94251669863Sdrh             pMatch = pItem;
943da184236Sdanielk1977             pExpr->pSchema = pTab->pSchema;
9448141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
9458141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
946a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
9478b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
948b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
9498b4c40d8Sdrh             }
95061dfc31dSdrh             if( i<pSrcList->nSrc-1 ){
95161dfc31dSdrh               if( pItem[1].jointype & JT_NATURAL ){
952355ef361Sdrh                 /* If this match occurred in the left table of a natural join,
953355ef361Sdrh                 ** then skip the right table to avoid a duplicate match */
954355ef361Sdrh                 pItem++;
955355ef361Sdrh                 i++;
95661dfc31dSdrh               }else if( (pUsing = pItem[1].pUsing)!=0 ){
957873fac0cSdrh                 /* If this match occurs on a column that is in the USING clause
958873fac0cSdrh                 ** of a join, skip the search of the right table of the join
959873fac0cSdrh                 ** to avoid a duplicate match there. */
960873fac0cSdrh                 int k;
961873fac0cSdrh                 for(k=0; k<pUsing->nId; k++){
962873fac0cSdrh                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
963873fac0cSdrh                     pItem++;
964873fac0cSdrh                     i++;
965873fac0cSdrh                     break;
966873fac0cSdrh                   }
967873fac0cSdrh                 }
968873fac0cSdrh               }
96961dfc31dSdrh             }
9708141f61eSdrh             break;
9718141f61eSdrh           }
9728141f61eSdrh         }
9738141f61eSdrh       }
974b3bce662Sdanielk1977     }
9758141f61eSdrh 
976b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
9778141f61eSdrh     /* If we have not already resolved the name, then maybe
9788141f61eSdrh     ** it is a new.* or old.* trigger argument reference
9798141f61eSdrh     */
9808141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
9818141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
9828141f61eSdrh       Table *pTab = 0;
9834adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
9848141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
9858141f61eSdrh         assert( pTriggerStack->pTab );
9868141f61eSdrh         pTab = pTriggerStack->pTab;
9874adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
9888141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
9898141f61eSdrh         assert( pTriggerStack->pTab );
9908141f61eSdrh         pTab = pTriggerStack->pTab;
9918141f61eSdrh       }
9928141f61eSdrh 
9938141f61eSdrh       if( pTab ){
994f0113000Sdanielk1977         int iCol;
9958141f61eSdrh         Column *pCol = pTab->aCol;
9968141f61eSdrh 
997da184236Sdanielk1977         pExpr->pSchema = pTab->pSchema;
9988141f61eSdrh         cntTab++;
999f0113000Sdanielk1977         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
10004adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1001f0113000Sdanielk1977             const char *zColl = pTab->aCol[iCol].zColl;
10028141f61eSdrh             cnt++;
1003f0113000Sdanielk1977             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1004f0113000Sdanielk1977             pExpr->affinity = pTab->aCol[iCol].affinity;
10058b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1006b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
10078b4c40d8Sdrh             }
1008aee18ef8Sdanielk1977             pExpr->pTab = pTab;
10098141f61eSdrh             break;
10108141f61eSdrh           }
10118141f61eSdrh         }
10128141f61eSdrh       }
10138141f61eSdrh     }
1014b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
10158141f61eSdrh 
10168141f61eSdrh     /*
10178141f61eSdrh     ** Perhaps the name is a reference to the ROWID
10188141f61eSdrh     */
10194adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
10208141f61eSdrh       cnt = 1;
10218141f61eSdrh       pExpr->iColumn = -1;
10228a51256cSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
10238141f61eSdrh     }
10248141f61eSdrh 
10258141f61eSdrh     /*
10268141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
10278141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
10288141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
10298141f61eSdrh     **
10308141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
10318141f61eSdrh     **
10328141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
10338141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
10348141f61eSdrh     ** Note that the expression in the result set should have already been
10358141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
10368141f61eSdrh     */
1037ffe07b2dSdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
10388141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
10398141f61eSdrh         char *zAs = pEList->a[j].zName;
10404adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
10418141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
10428141f61eSdrh           pExpr->op = TK_AS;
10438141f61eSdrh           pExpr->iColumn = j;
10444adee20fSdanielk1977           pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
104515ccce1cSdrh           cnt = 1;
10468141f61eSdrh           assert( zTab==0 && zDb==0 );
104715ccce1cSdrh           goto lookupname_end_2;
10488141f61eSdrh         }
10498141f61eSdrh       }
10508141f61eSdrh     }
10518141f61eSdrh 
1052626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
1053626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
1054626a879aSdrh     */
1055626a879aSdrh     if( cnt==0 ){
1056626a879aSdrh       pNC = pNC->pNext;
1057626a879aSdrh     }
1058626a879aSdrh   }
1059626a879aSdrh 
10608141f61eSdrh   /*
10618141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
10628141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
10638141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
10648141f61eSdrh   ** case, we need to return right away and not make any changes to
10658141f61eSdrh   ** pExpr.
106615ccce1cSdrh   **
106715ccce1cSdrh   ** Because no reference was made to outer contexts, the pNC->nRef
106815ccce1cSdrh   ** fields are not changed in any context.
10698141f61eSdrh   */
10708141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
10718141f61eSdrh     sqliteFree(zCol);
10728141f61eSdrh     return 0;
10738141f61eSdrh   }
10748141f61eSdrh 
10758141f61eSdrh   /*
10768141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
10778141f61eSdrh   ** more matches.  Either way, we have an error.
10788141f61eSdrh   */
10798141f61eSdrh   if( cnt!=1 ){
10808141f61eSdrh     char *z = 0;
10818141f61eSdrh     char *zErr;
10828141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
10838141f61eSdrh     if( zDb ){
1084f93339deSdrh       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
10858141f61eSdrh     }else if( zTab ){
1086f93339deSdrh       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
10878141f61eSdrh     }else{
10888141f61eSdrh       z = sqliteStrDup(zCol);
10898141f61eSdrh     }
10904adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
10918141f61eSdrh     sqliteFree(z);
109273b211abSdrh     pTopNC->nErr++;
10938141f61eSdrh   }
10948141f61eSdrh 
109551669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
109651669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
109751669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
109851669863Sdrh   ** column number is greater than the number of bits in the bitmask
109951669863Sdrh   ** then set the high-order bit of the bitmask.
110051669863Sdrh   */
110151669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
110251669863Sdrh     int n = pExpr->iColumn;
110351669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
110451669863Sdrh       n = sizeof(Bitmask)*8-1;
110551669863Sdrh     }
110651669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
1107ca83ac51Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
110851669863Sdrh   }
110951669863Sdrh 
1110d5d56523Sdanielk1977 lookupname_end:
11118141f61eSdrh   /* Clean up and return
11128141f61eSdrh   */
11138141f61eSdrh   sqliteFree(zDb);
11148141f61eSdrh   sqliteFree(zTab);
11154adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
11168141f61eSdrh   pExpr->pLeft = 0;
11174adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
11188141f61eSdrh   pExpr->pRight = 0;
11198141f61eSdrh   pExpr->op = TK_COLUMN;
112015ccce1cSdrh lookupname_end_2:
112115ccce1cSdrh   sqliteFree(zCol);
1122626a879aSdrh   if( cnt==1 ){
1123b3bce662Sdanielk1977     assert( pNC!=0 );
1124626a879aSdrh     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1125aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
1126aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
1127aee18ef8Sdanielk1977     }
112815ccce1cSdrh     /* Increment the nRef value on all name contexts from TopNC up to
112915ccce1cSdrh     ** the point where the name matched. */
113015ccce1cSdrh     for(;;){
113115ccce1cSdrh       assert( pTopNC!=0 );
113215ccce1cSdrh       pTopNC->nRef++;
113315ccce1cSdrh       if( pTopNC==pNC ) break;
113415ccce1cSdrh       pTopNC = pTopNC->pNext;
1135626a879aSdrh     }
113615ccce1cSdrh     return 0;
113715ccce1cSdrh   } else {
113815ccce1cSdrh     return 1;
113915ccce1cSdrh   }
11408141f61eSdrh }
11418141f61eSdrh 
11428141f61eSdrh /*
1143626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1144626a879aSdrh **
114573b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1146626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
114773b211abSdrh ** the tree or 2 to abort the tree walk.
114873b211abSdrh **
114973b211abSdrh ** This routine also does error checking and name resolution for
115073b211abSdrh ** function names.  The operator for aggregate functions is changed
115173b211abSdrh ** to TK_AGG_FUNCTION.
1152626a879aSdrh */
1153626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1154626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1155626a879aSdrh   Parse *pParse;
1156626a879aSdrh 
1157b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1158626a879aSdrh   assert( pNC!=0 );
1159626a879aSdrh   pParse = pNC->pParse;
1160b3bce662Sdanielk1977 
1161626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1162626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1163626a879aSdrh #ifndef NDEBUG
1164f0113000Sdanielk1977   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1165f0113000Sdanielk1977     SrcList *pSrcList = pNC->pSrcList;
1166940fac9dSdanielk1977     int i;
1167f0113000Sdanielk1977     for(i=0; i<pNC->pSrcList->nSrc; i++){
1168626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1169626a879aSdrh     }
1170626a879aSdrh   }
1171626a879aSdrh #endif
1172626a879aSdrh   switch( pExpr->op ){
1173626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1174626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1175626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1176626a879aSdrh     */
1177626a879aSdrh     case TK_STRING: {
1178626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1179626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1180626a879aSdrh     }
1181626a879aSdrh     /* A lone identifier is the name of a column.
1182626a879aSdrh     */
1183626a879aSdrh     case TK_ID: {
1184626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1185626a879aSdrh       return 1;
1186626a879aSdrh     }
1187626a879aSdrh 
1188626a879aSdrh     /* A table name and column name:     ID.ID
1189626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1190626a879aSdrh     */
1191626a879aSdrh     case TK_DOT: {
1192626a879aSdrh       Token *pColumn;
1193626a879aSdrh       Token *pTable;
1194626a879aSdrh       Token *pDb;
1195626a879aSdrh       Expr *pRight;
1196626a879aSdrh 
1197b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1198626a879aSdrh       pRight = pExpr->pRight;
1199626a879aSdrh       if( pRight->op==TK_ID ){
1200626a879aSdrh         pDb = 0;
1201626a879aSdrh         pTable = &pExpr->pLeft->token;
1202626a879aSdrh         pColumn = &pRight->token;
1203626a879aSdrh       }else{
1204626a879aSdrh         assert( pRight->op==TK_DOT );
1205626a879aSdrh         pDb = &pExpr->pLeft->token;
1206626a879aSdrh         pTable = &pRight->pLeft->token;
1207626a879aSdrh         pColumn = &pRight->pRight->token;
1208626a879aSdrh       }
1209626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1210626a879aSdrh       return 1;
1211626a879aSdrh     }
1212626a879aSdrh 
1213626a879aSdrh     /* Resolve function names
1214626a879aSdrh     */
1215b71090fdSdrh     case TK_CONST_FUNC:
1216626a879aSdrh     case TK_FUNCTION: {
1217626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1218626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1219626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1220626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1221626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1222626a879aSdrh       int i;
12235169bbc6Sdrh       int auth;                   /* Authorization to use the function */
1224626a879aSdrh       int nId;                    /* Number of characters in function name */
1225626a879aSdrh       const char *zId;            /* The function name. */
122673b211abSdrh       FuncDef *pDef;              /* Information about the function */
122714db2665Sdanielk1977       int enc = ENC(pParse->db);  /* The database encoding */
1228626a879aSdrh 
12292646da7eSdrh       zId = (char*)pExpr->token.z;
1230b71090fdSdrh       nId = pExpr->token.n;
1231626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1232626a879aSdrh       if( pDef==0 ){
1233626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1234626a879aSdrh         if( pDef==0 ){
1235626a879aSdrh           no_such_func = 1;
1236626a879aSdrh         }else{
1237626a879aSdrh           wrong_num_args = 1;
1238626a879aSdrh         }
1239626a879aSdrh       }else{
1240626a879aSdrh         is_agg = pDef->xFunc==0;
1241626a879aSdrh       }
12422fca7fefSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
12435169bbc6Sdrh       if( pDef ){
12445169bbc6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
12455169bbc6Sdrh         if( auth!=SQLITE_OK ){
12465169bbc6Sdrh           if( auth==SQLITE_DENY ){
12475169bbc6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
12485169bbc6Sdrh                                     pDef->zName);
12495169bbc6Sdrh             pNC->nErr++;
12505169bbc6Sdrh           }
12515169bbc6Sdrh           pExpr->op = TK_NULL;
12525169bbc6Sdrh           return 1;
12535169bbc6Sdrh         }
12545169bbc6Sdrh       }
1255b8b14219Sdrh #endif
1256626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1257626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1258626a879aSdrh         pNC->nErr++;
1259626a879aSdrh         is_agg = 0;
1260626a879aSdrh       }else if( no_such_func ){
1261626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1262626a879aSdrh         pNC->nErr++;
1263626a879aSdrh       }else if( wrong_num_args ){
1264626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1265626a879aSdrh              nId, zId);
1266626a879aSdrh         pNC->nErr++;
1267626a879aSdrh       }
1268626a879aSdrh       if( is_agg ){
1269626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1270626a879aSdrh         pNC->hasAgg = 1;
1271626a879aSdrh       }
127273b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1273626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
127473b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1275626a879aSdrh       }
127673b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1277626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1278626a879aSdrh       ** type of the function
1279626a879aSdrh       */
1280626a879aSdrh       return is_agg;
1281626a879aSdrh     }
1282b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1283b3bce662Sdanielk1977     case TK_SELECT:
1284b3bce662Sdanielk1977     case TK_EXISTS:
1285b3bce662Sdanielk1977 #endif
1286b3bce662Sdanielk1977     case TK_IN: {
1287b3bce662Sdanielk1977       if( pExpr->pSelect ){
12888a9f38feSdrh         int nRef = pNC->nRef;
128906f6541eSdrh #ifndef SQLITE_OMIT_CHECK
129006f6541eSdrh         if( pNC->isCheck ){
129106f6541eSdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
129206f6541eSdrh         }
129306f6541eSdrh #endif
1294b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1295b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1296b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1297b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1298b3bce662Sdanielk1977         }
1299b3bce662Sdanielk1977       }
13004284fb07Sdrh       break;
1301b3bce662Sdanielk1977     }
13024284fb07Sdrh #ifndef SQLITE_OMIT_CHECK
13034284fb07Sdrh     case TK_VARIABLE: {
13044284fb07Sdrh       if( pNC->isCheck ){
13054284fb07Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
13064284fb07Sdrh       }
13074284fb07Sdrh       break;
13084284fb07Sdrh     }
13094284fb07Sdrh #endif
1310626a879aSdrh   }
1311626a879aSdrh   return 0;
1312626a879aSdrh }
1313626a879aSdrh 
1314626a879aSdrh /*
1315cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1316967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1317aacc543eSdrh ** index to the table in the table list and a column offset.  The
1318aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1319aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1320832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1321aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1322aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1323aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1324aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1325aacc543eSdrh ** alias for ROWID.
132619a775c2Sdrh **
1327626a879aSdrh ** Also resolve function names and check the functions for proper
1328626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1329626a879aSdrh ** have the correct number of arguments.  Leave an error message
1330626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1331626a879aSdrh **
133273b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
133373b211abSdrh ** property on the expression.
1334626a879aSdrh */
1335626a879aSdrh int sqlite3ExprResolveNames(
1336b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1337b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1338626a879aSdrh ){
133913449892Sdrh   int savedHasAgg;
134073b211abSdrh   if( pExpr==0 ) return 0;
134113449892Sdrh   savedHasAgg = pNC->hasAgg;
134213449892Sdrh   pNC->hasAgg = 0;
1343b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1344b3bce662Sdanielk1977   if( pNC->nErr>0 ){
134573b211abSdrh     ExprSetProperty(pExpr, EP_Error);
134673b211abSdrh   }
134713449892Sdrh   if( pNC->hasAgg ){
134813449892Sdrh     ExprSetProperty(pExpr, EP_Agg);
134913449892Sdrh   }else if( savedHasAgg ){
135013449892Sdrh     pNC->hasAgg = 1;
135113449892Sdrh   }
135273b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1353626a879aSdrh }
1354626a879aSdrh 
13551398ad36Sdrh /*
13561398ad36Sdrh ** A pointer instance of this structure is used to pass information
13571398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
13581398ad36Sdrh */
13591398ad36Sdrh typedef struct QueryCoder QueryCoder;
13601398ad36Sdrh struct QueryCoder {
13611398ad36Sdrh   Parse *pParse;       /* The parsing context */
13621398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
13631398ad36Sdrh };
13641398ad36Sdrh 
1365626a879aSdrh 
1366626a879aSdrh /*
13679cbe6352Sdrh ** Generate code for scalar subqueries used as an expression
13689cbe6352Sdrh ** and IN operators.  Examples:
1369626a879aSdrh **
13709cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
13719cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
13729cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
13739cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1374fef5208cSdrh **
13759cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
13769cbe6352Sdrh ** operator or subquery.
1377cce7d176Sdrh */
137851522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1379b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
138057dbd7b3Sdrh   int testAddr = 0;                       /* One-time test address */
1381b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1382b3bce662Sdanielk1977   if( v==0 ) return;
1383b3bce662Sdanielk1977 
138457dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
138557dbd7b3Sdrh   ** if any of the following is true:
138657dbd7b3Sdrh   **
138757dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
138857dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
138957dbd7b3Sdrh   **    *  We are inside a trigger
139057dbd7b3Sdrh   **
139157dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
139257dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1393b3bce662Sdanielk1977   */
1394b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1395b3bce662Sdanielk1977     int mem = pParse->nMem++;
1396b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
139757dbd7b3Sdrh     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
13989e12800dSdanielk1977     assert( testAddr>0 || sqlite3MallocFailed() );
1399d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1400b3bce662Sdanielk1977   }
1401b3bce662Sdanielk1977 
1402cce7d176Sdrh   switch( pExpr->op ){
1403fef5208cSdrh     case TK_IN: {
1404e014a838Sdanielk1977       char affinity;
1405d3d39e93Sdrh       KeyInfo keyInfo;
1406b9bb7c18Sdrh       int addr;        /* Address of OP_OpenEphemeral instruction */
1407d3d39e93Sdrh 
1408bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1409e014a838Sdanielk1977 
1410e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
141157dbd7b3Sdrh       ** expression it is handled the same way. A virtual table is
1412e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1413e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1414fef5208cSdrh       **
1415e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1416e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1417e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1418e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1419e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1420e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1421e014a838Sdanielk1977       ** is used.
1422fef5208cSdrh       */
1423832508b7Sdrh       pExpr->iTable = pParse->nTab++;
1424b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
1425d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1426d3d39e93Sdrh       keyInfo.nField = 1;
1427f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1428e014a838Sdanielk1977 
1429e014a838Sdanielk1977       if( pExpr->pSelect ){
1430e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1431e014a838Sdanielk1977         **
1432e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1433e014a838Sdanielk1977         ** table allocated and opened above.
1434e014a838Sdanielk1977         */
1435e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1436be5c89acSdrh         ExprList *pEList;
1437e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
143894ccde58Sdrh         if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
143994ccde58Sdrh           return;
144094ccde58Sdrh         }
1441be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1442be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
14437cedc8d4Sdanielk1977           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
1444be5c89acSdrh               pEList->a[0].pExpr);
14450202b29eSdanielk1977         }
1446fef5208cSdrh       }else if( pExpr->pList ){
1447fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1448fef5208cSdrh         **
1449e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
1450e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1451e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1452e014a838Sdanielk1977         ** a column, use numeric affinity.
1453fef5208cSdrh         */
1454e014a838Sdanielk1977         int i;
145557dbd7b3Sdrh         ExprList *pList = pExpr->pList;
145657dbd7b3Sdrh         struct ExprList_item *pItem;
145757dbd7b3Sdrh 
1458e014a838Sdanielk1977         if( !affinity ){
14598159a35fSdrh           affinity = SQLITE_AFF_NONE;
1460e014a838Sdanielk1977         }
14610202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1462e014a838Sdanielk1977 
1463e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
146457dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
146557dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1466e014a838Sdanielk1977 
146757dbd7b3Sdrh           /* If the expression is not constant then we will need to
146857dbd7b3Sdrh           ** disable the test that was generated above that makes sure
146957dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
147057dbd7b3Sdrh           ** expression we need to rerun this code each time.
147157dbd7b3Sdrh           */
14726c30be8eSdrh           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
1473f8875400Sdrh             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
147457dbd7b3Sdrh             testAddr = 0;
14754794b980Sdrh           }
1476e014a838Sdanielk1977 
1477e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
14784adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
147994a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1480f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1481fef5208cSdrh         }
1482fef5208cSdrh       }
14830202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1484b3bce662Sdanielk1977       break;
1485fef5208cSdrh     }
1486fef5208cSdrh 
148751522cd3Sdrh     case TK_EXISTS:
148819a775c2Sdrh     case TK_SELECT: {
1489fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1490fef5208cSdrh       ** value of this select in a memory cell and record the number
1491967e8b73Sdrh       ** of the memory cell in iColumn.
1492fef5208cSdrh       */
14932646da7eSdrh       static const Token one = { (u8*)"1", 0, 1 };
149451522cd3Sdrh       Select *pSel;
1495ec7429aeSdrh       int iMem;
1496ec7429aeSdrh       int sop;
14971398ad36Sdrh 
1498ec7429aeSdrh       pExpr->iColumn = iMem = pParse->nMem++;
149951522cd3Sdrh       pSel = pExpr->pSelect;
150051522cd3Sdrh       if( pExpr->op==TK_SELECT ){
150151522cd3Sdrh         sop = SRT_Mem;
1502ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1503ec7429aeSdrh         VdbeComment((v, "# Init subquery result"));
150451522cd3Sdrh       }else{
150551522cd3Sdrh         sop = SRT_Exists;
1506ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1507ec7429aeSdrh         VdbeComment((v, "# Init EXISTS result"));
150851522cd3Sdrh       }
1509ec7429aeSdrh       sqlite3ExprDelete(pSel->pLimit);
1510ec7429aeSdrh       pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
151194ccde58Sdrh       if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
151294ccde58Sdrh         return;
151394ccde58Sdrh       }
1514b3bce662Sdanielk1977       break;
151519a775c2Sdrh     }
1516cce7d176Sdrh   }
1517b3bce662Sdanielk1977 
151857dbd7b3Sdrh   if( testAddr ){
1519d654be80Sdrh     sqlite3VdbeJumpHere(v, testAddr);
1520b3bce662Sdanielk1977   }
1521b3bce662Sdanielk1977   return;
1522cce7d176Sdrh }
152351522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1524cce7d176Sdrh 
1525cce7d176Sdrh /*
1526fec19aadSdrh ** Generate an instruction that will put the integer describe by
1527fec19aadSdrh ** text z[0..n-1] on the stack.
1528fec19aadSdrh */
1529fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1530fec19aadSdrh   int i;
15316fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
15326fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
15336fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
153429dda4aeSdrh     sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1535fec19aadSdrh   }else{
1536fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1537fec19aadSdrh   }
1538fec19aadSdrh }
1539fec19aadSdrh 
1540945498f3Sdrh 
1541945498f3Sdrh /*
1542945498f3Sdrh ** Generate code that will extract the iColumn-th column from
1543945498f3Sdrh ** table pTab and push that column value on the stack.  There
1544945498f3Sdrh ** is an open cursor to pTab in iTable.  If iColumn<0 then
1545945498f3Sdrh ** code is generated that extracts the rowid.
1546945498f3Sdrh */
1547945498f3Sdrh void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
1548945498f3Sdrh   if( iColumn<0 ){
1549945498f3Sdrh     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
1550945498f3Sdrh     sqlite3VdbeAddOp(v, op, iTable, 0);
1551945498f3Sdrh   }else if( pTab==0 ){
1552945498f3Sdrh     sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
1553945498f3Sdrh   }else{
1554945498f3Sdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
1555945498f3Sdrh     sqlite3VdbeAddOp(v, op, iTable, iColumn);
1556945498f3Sdrh     sqlite3ColumnDefault(v, pTab, iColumn);
1557945498f3Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
1558945498f3Sdrh     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
1559945498f3Sdrh       sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
1560945498f3Sdrh     }
1561945498f3Sdrh #endif
1562945498f3Sdrh   }
1563945498f3Sdrh }
1564945498f3Sdrh 
1565fec19aadSdrh /*
1566cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
15671ccde15dSdrh ** expression and leave the result on the top of stack.
1568f2bc013cSdrh **
1569f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1570f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1571f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1572f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1573f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1574cce7d176Sdrh */
15754adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1576cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1577cce7d176Sdrh   int op;
1578ffe07b2dSdrh   int stackChng = 1;    /* Amount of change to stack depth */
1579ffe07b2dSdrh 
15807977a17fSdanielk1977   if( v==0 ) return;
15817977a17fSdanielk1977   if( pExpr==0 ){
1582f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
15837977a17fSdanielk1977     return;
15847977a17fSdanielk1977   }
1585f2bc013cSdrh   op = pExpr->op;
1586f2bc013cSdrh   switch( op ){
158713449892Sdrh     case TK_AGG_COLUMN: {
158813449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
158913449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
159013449892Sdrh       if( !pAggInfo->directMode ){
159113449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
159213449892Sdrh         break;
159313449892Sdrh       }else if( pAggInfo->useSortingIdx ){
159413449892Sdrh         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
159513449892Sdrh                               pCol->iSorterColumn);
159613449892Sdrh         break;
159713449892Sdrh       }
159813449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
159913449892Sdrh     }
1600967e8b73Sdrh     case TK_COLUMN: {
1601ffe07b2dSdrh       if( pExpr->iTable<0 ){
1602ffe07b2dSdrh         /* This only happens when coding check constraints */
1603ffe07b2dSdrh         assert( pParse->ckOffset>0 );
1604ffe07b2dSdrh         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1605c4a3c779Sdrh       }else{
1606945498f3Sdrh         sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
16072282792aSdrh       }
1608cce7d176Sdrh       break;
1609cce7d176Sdrh     }
1610cce7d176Sdrh     case TK_INTEGER: {
16112646da7eSdrh       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1612fec19aadSdrh       break;
161351e9a445Sdrh     }
1614fec19aadSdrh     case TK_FLOAT:
1615fec19aadSdrh     case TK_STRING: {
1616f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1617f2bc013cSdrh       assert( TK_STRING==OP_String8 );
1618d2687b77Sdrh       sqlite3DequoteExpr(pExpr);
16192646da7eSdrh       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1620cce7d176Sdrh       break;
1621cce7d176Sdrh     }
1622f0863fe5Sdrh     case TK_NULL: {
1623f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1624f0863fe5Sdrh       break;
1625f0863fe5Sdrh     }
16265338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1627c572ef7fSdanielk1977     case TK_BLOB: {
16286c8c6cecSdrh       int n;
16296c8c6cecSdrh       const char *z;
1630f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
16316c8c6cecSdrh       n = pExpr->token.n - 3;
16322646da7eSdrh       z = (char*)pExpr->token.z + 2;
16336c8c6cecSdrh       assert( n>=0 );
16346c8c6cecSdrh       if( n==0 ){
16356c8c6cecSdrh         z = "";
16366c8c6cecSdrh       }
16376c8c6cecSdrh       sqlite3VdbeOp3(v, op, 0, 0, z, n);
1638c572ef7fSdanielk1977       break;
1639c572ef7fSdanielk1977     }
16405338a5f7Sdanielk1977 #endif
164150457896Sdrh     case TK_VARIABLE: {
16424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1643895d7472Sdrh       if( pExpr->token.n>1 ){
16442646da7eSdrh         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1645895d7472Sdrh       }
164650457896Sdrh       break;
164750457896Sdrh     }
16484e0cff60Sdrh     case TK_REGISTER: {
16494e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
16504e0cff60Sdrh       break;
16514e0cff60Sdrh     }
1652487e262fSdrh #ifndef SQLITE_OMIT_CAST
1653487e262fSdrh     case TK_CAST: {
1654487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
1655f0113000Sdanielk1977       int aff, to_op;
1656487e262fSdrh       sqlite3ExprCode(pParse, pExpr->pLeft);
16578a51256cSdrh       aff = sqlite3AffinityType(&pExpr->token);
1658f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1659f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
1660f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
1661f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1662f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
1663f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
1664f0113000Sdanielk1977       sqlite3VdbeAddOp(v, to_op, 0, 0);
1665ffe07b2dSdrh       stackChng = 0;
1666487e262fSdrh       break;
1667487e262fSdrh     }
1668487e262fSdrh #endif /* SQLITE_OMIT_CAST */
1669c9b84a1fSdrh     case TK_LT:
1670c9b84a1fSdrh     case TK_LE:
1671c9b84a1fSdrh     case TK_GT:
1672c9b84a1fSdrh     case TK_GE:
1673c9b84a1fSdrh     case TK_NE:
1674c9b84a1fSdrh     case TK_EQ: {
1675f2bc013cSdrh       assert( TK_LT==OP_Lt );
1676f2bc013cSdrh       assert( TK_LE==OP_Le );
1677f2bc013cSdrh       assert( TK_GT==OP_Gt );
1678f2bc013cSdrh       assert( TK_GE==OP_Ge );
1679f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1680f2bc013cSdrh       assert( TK_NE==OP_Ne );
1681a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1682a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1683be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1684ffe07b2dSdrh       stackChng = -1;
1685a37cdde0Sdanielk1977       break;
1686c9b84a1fSdrh     }
1687cce7d176Sdrh     case TK_AND:
1688cce7d176Sdrh     case TK_OR:
1689cce7d176Sdrh     case TK_PLUS:
1690cce7d176Sdrh     case TK_STAR:
1691cce7d176Sdrh     case TK_MINUS:
1692bf4133cbSdrh     case TK_REM:
1693bf4133cbSdrh     case TK_BITAND:
1694bf4133cbSdrh     case TK_BITOR:
169517c40294Sdrh     case TK_SLASH:
1696bf4133cbSdrh     case TK_LSHIFT:
1697855eb1cfSdrh     case TK_RSHIFT:
16980040077dSdrh     case TK_CONCAT: {
1699f2bc013cSdrh       assert( TK_AND==OP_And );
1700f2bc013cSdrh       assert( TK_OR==OP_Or );
1701f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1702f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1703f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1704f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1705f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1706f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1707f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1708f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1709f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
17104adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17114adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1712855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
1713ffe07b2dSdrh       stackChng = -1;
17140040077dSdrh       break;
17150040077dSdrh     }
1716cce7d176Sdrh     case TK_UMINUS: {
1717fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1718fec19aadSdrh       assert( pLeft );
1719fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1720fec19aadSdrh         Token *p = &pLeft->token;
17219267bdceSdrh         char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
1722fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1723fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1724e6840900Sdrh         }else{
1725fec19aadSdrh           codeInteger(v, z, p->n+1);
1726e6840900Sdrh         }
17276e142f54Sdrh         sqliteFree(z);
17286e142f54Sdrh         break;
17296e142f54Sdrh       }
17301ccde15dSdrh       /* Fall through into TK_NOT */
17316e142f54Sdrh     }
1732bf4133cbSdrh     case TK_BITNOT:
17336e142f54Sdrh     case TK_NOT: {
1734f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1735f2bc013cSdrh       assert( TK_NOT==OP_Not );
17364adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17374adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1738ffe07b2dSdrh       stackChng = 0;
1739cce7d176Sdrh       break;
1740cce7d176Sdrh     }
1741cce7d176Sdrh     case TK_ISNULL:
1742cce7d176Sdrh     case TK_NOTNULL: {
1743cce7d176Sdrh       int dest;
1744f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1745f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
17464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
17474adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17484adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
17494adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
17504adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1751ffe07b2dSdrh       stackChng = 0;
1752a37cdde0Sdanielk1977       break;
1753f2bc013cSdrh     }
17542282792aSdrh     case TK_AGG_FUNCTION: {
175513449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
17567e56e711Sdrh       if( pInfo==0 ){
17577e56e711Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
17587e56e711Sdrh             &pExpr->span);
17597e56e711Sdrh       }else{
176013449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
17617e56e711Sdrh       }
17622282792aSdrh       break;
17632282792aSdrh     }
1764b71090fdSdrh     case TK_CONST_FUNC:
1765cce7d176Sdrh     case TK_FUNCTION: {
1766cce7d176Sdrh       ExprList *pList = pExpr->pList;
176789425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
17680bce8354Sdrh       FuncDef *pDef;
17694b59ab5eSdrh       int nId;
17704b59ab5eSdrh       const char *zId;
177113449892Sdrh       int constMask = 0;
1772682f68b0Sdanielk1977       int i;
177314db2665Sdanielk1977       u8 enc = ENC(pParse->db);
1774dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
17752646da7eSdrh       zId = (char*)pExpr->token.z;
1776b71090fdSdrh       nId = pExpr->token.n;
1777d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
17780bce8354Sdrh       assert( pDef!=0 );
1779f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1780b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1781a43fa227Sdrh       /* Possibly overload the function if the first argument is
1782a43fa227Sdrh       ** a virtual table column.
1783a43fa227Sdrh       **
1784a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1785a43fa227Sdrh       ** second argument, not the first, as the argument to test to
1786a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
1787a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
1788a43fa227Sdrh       ** control overloading) ends up as the second argument to the
1789a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
1790a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
1791a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
1792a43fa227Sdrh       */
17936a03a1c5Sdrh       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
17946a03a1c5Sdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[1].pExpr);
17956a03a1c5Sdrh       }else if( nExpr>0 ){
1796b7f6f68fSdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[0].pExpr);
1797b7f6f68fSdrh       }
1798b7f6f68fSdrh #endif
1799682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1800d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
180113449892Sdrh           constMask |= (1<<i);
1802d02eb1fdSdanielk1977         }
1803dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1804dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1805dc1bdc4fSdanielk1977         }
1806dc1bdc4fSdanielk1977       }
1807dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1808dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1809d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1810682f68b0Sdanielk1977       }
181113449892Sdrh       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1812ffe07b2dSdrh       stackChng = 1-nExpr;
18136ec2733bSdrh       break;
18146ec2733bSdrh     }
1815fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1816fe2093d7Sdrh     case TK_EXISTS:
181719a775c2Sdrh     case TK_SELECT: {
181841714d6fSdrh       if( pExpr->iColumn==0 ){
1819b3bce662Sdanielk1977         sqlite3CodeSubselect(pParse, pExpr);
182041714d6fSdrh       }
18214adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1822ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
182319a775c2Sdrh       break;
182419a775c2Sdrh     }
1825fef5208cSdrh     case TK_IN: {
1826fef5208cSdrh       int addr;
182794a11211Sdrh       char affinity;
1828afa5f680Sdrh       int ckOffset = pParse->ckOffset;
1829b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
1830e014a838Sdanielk1977 
1831e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1832e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1833ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1834e014a838Sdanielk1977       */
183594a11211Sdrh       affinity = comparisonAffinity(pExpr);
1836e014a838Sdanielk1977 
18374adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1838afa5f680Sdrh       pParse->ckOffset = ckOffset+1;
1839e014a838Sdanielk1977 
1840e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1841e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1842e014a838Sdanielk1977       */
18434adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18444adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1845e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
18464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
1847f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1848e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
184994a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
1850e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1851e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1852e014a838Sdanielk1977 
1853fef5208cSdrh       break;
1854fef5208cSdrh     }
185593758c8dSdanielk1977 #endif
1856fef5208cSdrh     case TK_BETWEEN: {
1857be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1858be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1859be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1860be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
18614adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1862be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1863be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
18644adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1865be5c89acSdrh       pLItem++;
1866be5c89acSdrh       pRight = pLItem->pExpr;
1867be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1868be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
18694adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1870fef5208cSdrh       break;
1871fef5208cSdrh     }
187251e9a445Sdrh     case TK_UPLUS:
1873a2e00042Sdrh     case TK_AS: {
18744adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1875ffe07b2dSdrh       stackChng = 0;
1876a2e00042Sdrh       break;
1877a2e00042Sdrh     }
187817a7f8ddSdrh     case TK_CASE: {
187917a7f8ddSdrh       int expr_end_label;
1880f5905aa7Sdrh       int jumpInst;
1881f5905aa7Sdrh       int nExpr;
188217a7f8ddSdrh       int i;
1883be5c89acSdrh       ExprList *pEList;
1884be5c89acSdrh       struct ExprList_item *aListelem;
188517a7f8ddSdrh 
188617a7f8ddSdrh       assert(pExpr->pList);
188717a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
188817a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1889be5c89acSdrh       pEList = pExpr->pList;
1890be5c89acSdrh       aListelem = pEList->a;
1891be5c89acSdrh       nExpr = pEList->nExpr;
18924adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
189317a7f8ddSdrh       if( pExpr->pLeft ){
18944adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1895cce7d176Sdrh       }
1896f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1897be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
189817a7f8ddSdrh         if( pExpr->pLeft ){
18994adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1900be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1901be5c89acSdrh                                  OP_Ne, 0, 1);
19024adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1903f5905aa7Sdrh         }else{
19044adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
190517a7f8ddSdrh         }
1906be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
19074adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
1908d654be80Sdrh         sqlite3VdbeJumpHere(v, jumpInst);
190917a7f8ddSdrh       }
1910f570f011Sdrh       if( pExpr->pLeft ){
19114adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1912f570f011Sdrh       }
191317a7f8ddSdrh       if( pExpr->pRight ){
19144adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
191517a7f8ddSdrh       }else{
1916f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
191717a7f8ddSdrh       }
19184adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
19196f34903eSdanielk1977       break;
19206f34903eSdanielk1977     }
19215338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
19226f34903eSdanielk1977     case TK_RAISE: {
19236f34903eSdanielk1977       if( !pParse->trigStack ){
19244adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1925da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
19266f34903eSdanielk1977 	return;
19276f34903eSdanielk1977       }
1928ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
1929ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
19306f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
1931ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
1932d2687b77Sdrh          sqlite3DequoteExpr(pExpr);
19334adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
19342646da7eSdrh                         (char*)pExpr->token.z, pExpr->token.n);
19356f34903eSdanielk1977       } else {
19366f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
1937344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
1938ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
1939ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
19406f34903eSdanielk1977       }
1941ffe07b2dSdrh       stackChng = 0;
1942ffe07b2dSdrh       break;
194317a7f8ddSdrh     }
19445338a5f7Sdanielk1977 #endif
1945ffe07b2dSdrh   }
1946ffe07b2dSdrh 
1947ffe07b2dSdrh   if( pParse->ckOffset ){
1948ffe07b2dSdrh     pParse->ckOffset += stackChng;
1949ffe07b2dSdrh     assert( pParse->ckOffset );
195017a7f8ddSdrh   }
1951cce7d176Sdrh }
1952cce7d176Sdrh 
195393758c8dSdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
1954cce7d176Sdrh /*
195525303780Sdrh ** Generate code that evalutes the given expression and leaves the result
195625303780Sdrh ** on the stack.  See also sqlite3ExprCode().
195725303780Sdrh **
195825303780Sdrh ** This routine might also cache the result and modify the pExpr tree
195925303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
196025303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
196125303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
196225303780Sdrh ** memory location.
196325303780Sdrh */
196425303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
196525303780Sdrh   Vdbe *v = pParse->pVdbe;
196625303780Sdrh   int iMem;
196725303780Sdrh   int addr1, addr2;
196825303780Sdrh   if( v==0 ) return;
196925303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
197025303780Sdrh   sqlite3ExprCode(pParse, pExpr);
197125303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
197225303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
197325303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
197425303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
197525303780Sdrh     pExpr->op = TK_REGISTER;
197625303780Sdrh   }
197725303780Sdrh }
197893758c8dSdanielk1977 #endif
197925303780Sdrh 
198025303780Sdrh /*
1981268380caSdrh ** Generate code that pushes the value of every element of the given
1982f9b596ebSdrh ** expression list onto the stack.
1983268380caSdrh **
1984268380caSdrh ** Return the number of elements pushed onto the stack.
1985268380caSdrh */
19864adee20fSdanielk1977 int sqlite3ExprCodeExprList(
1987268380caSdrh   Parse *pParse,     /* Parsing context */
1988f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
1989268380caSdrh ){
1990268380caSdrh   struct ExprList_item *pItem;
1991268380caSdrh   int i, n;
1992268380caSdrh   if( pList==0 ) return 0;
1993268380caSdrh   n = pList->nExpr;
1994c182d163Sdrh   for(pItem=pList->a, i=n; i>0; i--, pItem++){
19954adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
1996268380caSdrh   }
1997f9b596ebSdrh   return n;
1998268380caSdrh }
1999268380caSdrh 
2000268380caSdrh /*
2001cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
2002cce7d176Sdrh ** to the label "dest" if the expression is true but execution
2003cce7d176Sdrh ** continues straight thru if the expression is false.
2004f5905aa7Sdrh **
2005f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
2006f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
2007f2bc013cSdrh **
2008f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
2009f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2010f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
2011f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
2012f2bc013cSdrh ** below verify that the numbers are aligned correctly.
2013cce7d176Sdrh */
20144adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2015cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2016cce7d176Sdrh   int op = 0;
2017ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2018daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2019f2bc013cSdrh   op = pExpr->op;
2020f2bc013cSdrh   switch( op ){
2021cce7d176Sdrh     case TK_AND: {
20224adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
20234adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
20244adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
20254adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2026cce7d176Sdrh       break;
2027cce7d176Sdrh     }
2028cce7d176Sdrh     case TK_OR: {
20294adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
20304adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2031cce7d176Sdrh       break;
2032cce7d176Sdrh     }
2033cce7d176Sdrh     case TK_NOT: {
20344adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2035cce7d176Sdrh       break;
2036cce7d176Sdrh     }
2037cce7d176Sdrh     case TK_LT:
2038cce7d176Sdrh     case TK_LE:
2039cce7d176Sdrh     case TK_GT:
2040cce7d176Sdrh     case TK_GE:
2041cce7d176Sdrh     case TK_NE:
20420ac65892Sdrh     case TK_EQ: {
2043f2bc013cSdrh       assert( TK_LT==OP_Lt );
2044f2bc013cSdrh       assert( TK_LE==OP_Le );
2045f2bc013cSdrh       assert( TK_GT==OP_Gt );
2046f2bc013cSdrh       assert( TK_GE==OP_Ge );
2047f2bc013cSdrh       assert( TK_EQ==OP_Eq );
2048f2bc013cSdrh       assert( TK_NE==OP_Ne );
20494adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20504adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2051be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2052cce7d176Sdrh       break;
2053cce7d176Sdrh     }
2054cce7d176Sdrh     case TK_ISNULL:
2055cce7d176Sdrh     case TK_NOTNULL: {
2056f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
2057f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
20584adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20594adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2060cce7d176Sdrh       break;
2061cce7d176Sdrh     }
2062fef5208cSdrh     case TK_BETWEEN: {
20630202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
20640202b29eSdanielk1977       **
20650202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
20660202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
20670202b29eSdanielk1977       ** 3 ...
20680202b29eSdanielk1977       */
2069f5905aa7Sdrh       int addr;
2070be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2071be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2072be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
20734adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2074be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2075be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
20760202b29eSdanielk1977 
2077be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2078be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2079be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
20800202b29eSdanielk1977 
20814adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2082d654be80Sdrh       sqlite3VdbeJumpHere(v, addr);
20834adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2084fef5208cSdrh       break;
2085fef5208cSdrh     }
2086cce7d176Sdrh     default: {
20874adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
20884adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
2089cce7d176Sdrh       break;
2090cce7d176Sdrh     }
2091cce7d176Sdrh   }
2092ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2093cce7d176Sdrh }
2094cce7d176Sdrh 
2095cce7d176Sdrh /*
209666b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
2097cce7d176Sdrh ** to the label "dest" if the expression is false but execution
2098cce7d176Sdrh ** continues straight thru if the expression is true.
2099f5905aa7Sdrh **
2100f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
2101f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
2102cce7d176Sdrh */
21034adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2104cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2105cce7d176Sdrh   int op = 0;
2106ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2107daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2108f2bc013cSdrh 
2109f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
2110f2bc013cSdrh   **
2111f2bc013cSdrh   **       pExpr->op            op
2112f2bc013cSdrh   **       ---------          ----------
2113f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
2114f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
2115f2bc013cSdrh   **       TK_NE              OP_Eq
2116f2bc013cSdrh   **       TK_EQ              OP_Ne
2117f2bc013cSdrh   **       TK_GT              OP_Le
2118f2bc013cSdrh   **       TK_LE              OP_Gt
2119f2bc013cSdrh   **       TK_GE              OP_Lt
2120f2bc013cSdrh   **       TK_LT              OP_Ge
2121f2bc013cSdrh   **
2122f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
2123f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
2124f2bc013cSdrh   ** can compute the mapping above using the following expression.
2125f2bc013cSdrh   ** Assert()s verify that the computation is correct.
2126f2bc013cSdrh   */
2127f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2128f2bc013cSdrh 
2129f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
2130f2bc013cSdrh   */
2131f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2132f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2133f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
2134f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
2135f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
2136f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
2137f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
2138f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
2139f2bc013cSdrh 
2140cce7d176Sdrh   switch( pExpr->op ){
2141cce7d176Sdrh     case TK_AND: {
21424adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
21434adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2144cce7d176Sdrh       break;
2145cce7d176Sdrh     }
2146cce7d176Sdrh     case TK_OR: {
21474adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
21484adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
21494adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
21504adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2151cce7d176Sdrh       break;
2152cce7d176Sdrh     }
2153cce7d176Sdrh     case TK_NOT: {
21544adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2155cce7d176Sdrh       break;
2156cce7d176Sdrh     }
2157cce7d176Sdrh     case TK_LT:
2158cce7d176Sdrh     case TK_LE:
2159cce7d176Sdrh     case TK_GT:
2160cce7d176Sdrh     case TK_GE:
2161cce7d176Sdrh     case TK_NE:
2162cce7d176Sdrh     case TK_EQ: {
21634adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
21644adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2165be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2166cce7d176Sdrh       break;
2167cce7d176Sdrh     }
2168cce7d176Sdrh     case TK_ISNULL:
2169cce7d176Sdrh     case TK_NOTNULL: {
21704adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
21714adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2172cce7d176Sdrh       break;
2173cce7d176Sdrh     }
2174fef5208cSdrh     case TK_BETWEEN: {
21750202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
21760202b29eSdanielk1977       **
21770202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
21780202b29eSdanielk1977       ** 2 GOTO <dest>
21790202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
21800202b29eSdanielk1977       */
2181fef5208cSdrh       int addr;
2182be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2183be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2184be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
21854adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2186be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
21874adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
2188be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2189be5c89acSdrh 
21904adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
21914adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2192be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2193be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2194be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2195fef5208cSdrh       break;
2196fef5208cSdrh     }
2197cce7d176Sdrh     default: {
21984adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
21994adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2200cce7d176Sdrh       break;
2201cce7d176Sdrh     }
2202cce7d176Sdrh   }
2203ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2204cce7d176Sdrh }
22052282792aSdrh 
22062282792aSdrh /*
22072282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
22082282792aSdrh ** if they are identical and return FALSE if they differ in any way.
2209d40aab0eSdrh **
2210d40aab0eSdrh ** Sometimes this routine will return FALSE even if the two expressions
2211d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
2212d40aab0eSdrh ** identical, we return FALSE just to be safe.  So if this routine
2213d40aab0eSdrh ** returns false, then you do not really know for certain if the two
2214d40aab0eSdrh ** expressions are the same.  But if you get a TRUE return, then you
2215d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
2216d40aab0eSdrh ** this routine is used, it does not hurt to get an extra FALSE - that
2217d40aab0eSdrh ** just might result in some slightly slower code.  But returning
2218d40aab0eSdrh ** an incorrect TRUE could lead to a malfunction.
22192282792aSdrh */
22204adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
22212282792aSdrh   int i;
22224b202ae2Sdanielk1977   if( pA==0||pB==0 ){
22234b202ae2Sdanielk1977     return pB==pA;
22242282792aSdrh   }
22252282792aSdrh   if( pA->op!=pB->op ) return 0;
2226fd357974Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
22274adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
22284adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
22292282792aSdrh   if( pA->pList ){
22302282792aSdrh     if( pB->pList==0 ) return 0;
22312282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
22322282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
22334adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
22342282792aSdrh         return 0;
22352282792aSdrh       }
22362282792aSdrh     }
22372282792aSdrh   }else if( pB->pList ){
22382282792aSdrh     return 0;
22392282792aSdrh   }
22402282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
22412f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
2242dd73521bSdrh   if( pA->op!=TK_COLUMN && pA->token.z ){
22432282792aSdrh     if( pB->token.z==0 ) return 0;
22446977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
22452646da7eSdrh     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
22462646da7eSdrh       return 0;
22472646da7eSdrh     }
22482282792aSdrh   }
22492282792aSdrh   return 1;
22502282792aSdrh }
22512282792aSdrh 
225213449892Sdrh 
22532282792aSdrh /*
225413449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
225513449892Sdrh ** the new element.  Return a negative number if malloc fails.
22562282792aSdrh */
225713449892Sdrh static int addAggInfoColumn(AggInfo *pInfo){
225813449892Sdrh   int i;
2259cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
2260cf643729Sdrh        pInfo->aCol,
2261cf643729Sdrh        sizeof(pInfo->aCol[0]),
2262cf643729Sdrh        3,
2263cf643729Sdrh        &pInfo->nColumn,
2264cf643729Sdrh        &pInfo->nColumnAlloc,
2265cf643729Sdrh        &i
2266cf643729Sdrh   );
226713449892Sdrh   return i;
22682282792aSdrh }
226913449892Sdrh 
227013449892Sdrh /*
227113449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
227213449892Sdrh ** the new element.  Return a negative number if malloc fails.
227313449892Sdrh */
227413449892Sdrh static int addAggInfoFunc(AggInfo *pInfo){
227513449892Sdrh   int i;
2276cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
2277cf643729Sdrh        pInfo->aFunc,
2278cf643729Sdrh        sizeof(pInfo->aFunc[0]),
2279cf643729Sdrh        3,
2280cf643729Sdrh        &pInfo->nFunc,
2281cf643729Sdrh        &pInfo->nFuncAlloc,
2282cf643729Sdrh        &i
2283cf643729Sdrh   );
228413449892Sdrh   return i;
22852282792aSdrh }
22862282792aSdrh 
22872282792aSdrh /*
2288626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
2289626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2290626a879aSdrh ** for additional information.
22912282792aSdrh **
2292626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
22932282792aSdrh */
2294626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
22952282792aSdrh   int i;
2296a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
2297a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
2298a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
229913449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
230013449892Sdrh 
23012282792aSdrh 
23022282792aSdrh   switch( pExpr->op ){
230389c69d00Sdrh     case TK_AGG_COLUMN:
2304967e8b73Sdrh     case TK_COLUMN: {
230513449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
230613449892Sdrh       ** clause of the aggregate query */
230713449892Sdrh       if( pSrcList ){
230813449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
230913449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
231013449892Sdrh           struct AggInfo_col *pCol;
231113449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
231213449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
231313449892Sdrh             ** that is in the FROM clause of the aggregate query.
231413449892Sdrh             **
231513449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
231613449892Sdrh             ** is not an entry there already.
231713449892Sdrh             */
23187f906d63Sdrh             int k;
231913449892Sdrh             pCol = pAggInfo->aCol;
23207f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
232113449892Sdrh               if( pCol->iTable==pExpr->iTable &&
232213449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
23232282792aSdrh                 break;
23242282792aSdrh               }
23252282792aSdrh             }
23267f906d63Sdrh             if( k>=pAggInfo->nColumn && (k = addAggInfoColumn(pAggInfo))>=0 ){
23277f906d63Sdrh               pCol = &pAggInfo->aCol[k];
23280817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
232913449892Sdrh               pCol->iTable = pExpr->iTable;
233013449892Sdrh               pCol->iColumn = pExpr->iColumn;
233113449892Sdrh               pCol->iMem = pParse->nMem++;
233213449892Sdrh               pCol->iSorterColumn = -1;
23335774b806Sdrh               pCol->pExpr = pExpr;
233413449892Sdrh               if( pAggInfo->pGroupBy ){
233513449892Sdrh                 int j, n;
233613449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
233713449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
233813449892Sdrh                 n = pGB->nExpr;
233913449892Sdrh                 for(j=0; j<n; j++, pTerm++){
234013449892Sdrh                   Expr *pE = pTerm->pExpr;
234113449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
234213449892Sdrh                       pE->iColumn==pExpr->iColumn ){
234313449892Sdrh                     pCol->iSorterColumn = j;
234413449892Sdrh                     break;
23452282792aSdrh                   }
234613449892Sdrh                 }
234713449892Sdrh               }
234813449892Sdrh               if( pCol->iSorterColumn<0 ){
234913449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
235013449892Sdrh               }
235113449892Sdrh             }
235213449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
235313449892Sdrh             ** because it was there before or because we just created it).
235413449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
235513449892Sdrh             ** pAggInfo->aCol[] entry.
235613449892Sdrh             */
235713449892Sdrh             pExpr->pAggInfo = pAggInfo;
235813449892Sdrh             pExpr->op = TK_AGG_COLUMN;
23597f906d63Sdrh             pExpr->iAgg = k;
236013449892Sdrh             break;
236113449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
236213449892Sdrh         } /* end loop over pSrcList */
2363a58fdfb1Sdanielk1977       }
2364626a879aSdrh       return 1;
23652282792aSdrh     }
23662282792aSdrh     case TK_AGG_FUNCTION: {
236713449892Sdrh       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
236813449892Sdrh       ** to be ignored */
2369a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
237013449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
237113449892Sdrh         ** function that is already in the pAggInfo structure
237213449892Sdrh         */
237313449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
237413449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
237513449892Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
23762282792aSdrh             break;
23772282792aSdrh           }
23782282792aSdrh         }
237913449892Sdrh         if( i>=pAggInfo->nFunc ){
238013449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
238113449892Sdrh           */
238214db2665Sdanielk1977           u8 enc = ENC(pParse->db);
238313449892Sdrh           i = addAggInfoFunc(pAggInfo);
238413449892Sdrh           if( i>=0 ){
238513449892Sdrh             pItem = &pAggInfo->aFunc[i];
238613449892Sdrh             pItem->pExpr = pExpr;
238713449892Sdrh             pItem->iMem = pParse->nMem++;
238813449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
23892646da7eSdrh                    (char*)pExpr->token.z, pExpr->token.n,
2390d8123366Sdanielk1977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2391fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
2392fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
2393fd357974Sdrh             }else{
2394fd357974Sdrh               pItem->iDistinct = -1;
2395fd357974Sdrh             }
23962282792aSdrh           }
239713449892Sdrh         }
239813449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
239913449892Sdrh         */
24002282792aSdrh         pExpr->iAgg = i;
240113449892Sdrh         pExpr->pAggInfo = pAggInfo;
2402626a879aSdrh         return 1;
24032282792aSdrh       }
24042282792aSdrh     }
2405a58fdfb1Sdanielk1977   }
240613449892Sdrh 
240713449892Sdrh   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
240813449892Sdrh   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
240913449892Sdrh   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
241013449892Sdrh   */
2411a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
2412a58fdfb1Sdanielk1977     pNC->nDepth++;
2413a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2414a58fdfb1Sdanielk1977     pNC->nDepth--;
2415a58fdfb1Sdanielk1977   }
2416626a879aSdrh   return 0;
24172282792aSdrh }
2418626a879aSdrh 
2419626a879aSdrh /*
2420626a879aSdrh ** Analyze the given expression looking for aggregate functions and
2421626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
2422626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
2423626a879aSdrh **
2424626a879aSdrh ** This routine should only be called after the expression has been
2425626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
2426626a879aSdrh **
2427626a879aSdrh ** If errors are seen, leave an error message in zErrMsg and return
2428626a879aSdrh ** the number of errors.
2429626a879aSdrh */
2430a58fdfb1Sdanielk1977 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2431a58fdfb1Sdanielk1977   int nErr = pNC->pParse->nErr;
2432a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
2433a58fdfb1Sdanielk1977   return pNC->pParse->nErr - nErr;
24342282792aSdrh }
24355d9a4af9Sdrh 
24365d9a4af9Sdrh /*
24375d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
24385d9a4af9Sdrh ** expression list.  Return the number of errors.
24395d9a4af9Sdrh **
24405d9a4af9Sdrh ** If an error is found, the analysis is cut short.
24415d9a4af9Sdrh */
24425d9a4af9Sdrh int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
24435d9a4af9Sdrh   struct ExprList_item *pItem;
24445d9a4af9Sdrh   int i;
24455d9a4af9Sdrh   int nErr = 0;
24465d9a4af9Sdrh   if( pList ){
24475d9a4af9Sdrh     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
24485d9a4af9Sdrh       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
24495d9a4af9Sdrh     }
24505d9a4af9Sdrh   }
24515d9a4af9Sdrh   return nErr;
24525d9a4af9Sdrh }
2453