xref: /sqlite-3.40.0/src/expr.c (revision cdbd8eff)
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*cdbd8effSdanielk1977 ** $Id: expr.c,v 1.292 2007/05/12 06:11:12 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   }
250fc976065Sdanielk1977 
251fc976065Sdanielk1977   sqlite3ExprSetHeight(pNew);
252a76b5dfcSdrh   return pNew;
253a76b5dfcSdrh }
254a76b5dfcSdrh 
255a76b5dfcSdrh /*
256206f3d96Sdrh ** Works like sqlite3Expr() but frees its pLeft and pRight arguments
257206f3d96Sdrh ** if it fails due to a malloc problem.
258206f3d96Sdrh */
259206f3d96Sdrh Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
260206f3d96Sdrh   Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
261206f3d96Sdrh   if( pNew==0 ){
262206f3d96Sdrh     sqlite3ExprDelete(pLeft);
263206f3d96Sdrh     sqlite3ExprDelete(pRight);
264206f3d96Sdrh   }
265206f3d96Sdrh   return pNew;
266206f3d96Sdrh }
267206f3d96Sdrh 
268206f3d96Sdrh /*
2694e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
2704e0cff60Sdrh ** that look like this:   #0 #1 #2 ...  These terms refer to elements
271288d37f1Sdrh ** on the stack.  "#0" means the top of the stack.
272288d37f1Sdrh ** "#1" means the next down on the stack.  And so forth.
2734e0cff60Sdrh **
2744e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
2754e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
2764e0cff60Sdrh ** The returns an expression that will code to extract the value from
2774e0cff60Sdrh ** that memory location as needed.
2784e0cff60Sdrh */
2794e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
2804e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
2814e0cff60Sdrh   Expr *p;
2824e0cff60Sdrh   int depth;
2834e0cff60Sdrh   if( pParse->nested==0 ){
2844e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
2854e05c83bSdrh     return sqlite3Expr(TK_NULL, 0, 0, 0);
2864e0cff60Sdrh   }
287bb7ac00bSdrh   if( v==0 ) return 0;
2884e0cff60Sdrh   p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
28973c42a13Sdrh   if( p==0 ){
29073c42a13Sdrh     return 0;  /* Malloc failed */
29173c42a13Sdrh   }
2922646da7eSdrh   depth = atoi((char*)&pToken->z[1]);
2934e0cff60Sdrh   p->iTable = pParse->nMem++;
2944e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
2954e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
2964e0cff60Sdrh   return p;
2974e0cff60Sdrh }
2984e0cff60Sdrh 
2994e0cff60Sdrh /*
30091bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
30191bb0eedSdrh ** NULL, then just return the other expression.
30291bb0eedSdrh */
30391bb0eedSdrh Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
30491bb0eedSdrh   if( pLeft==0 ){
30591bb0eedSdrh     return pRight;
30691bb0eedSdrh   }else if( pRight==0 ){
30791bb0eedSdrh     return pLeft;
30891bb0eedSdrh   }else{
30991bb0eedSdrh     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
31091bb0eedSdrh   }
31191bb0eedSdrh }
31291bb0eedSdrh 
31391bb0eedSdrh /*
3146977fea8Sdrh ** Set the Expr.span field of the given expression to span all
315a76b5dfcSdrh ** text between the two given tokens.
316a76b5dfcSdrh */
3174adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
3184efc4754Sdrh   assert( pRight!=0 );
3194efc4754Sdrh   assert( pLeft!=0 );
3209e12800dSdanielk1977   if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
321ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
322145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
3236977fea8Sdrh       pExpr->span.z = pLeft->z;
32497903fefSdrh       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
3254b59ab5eSdrh     }else{
3266977fea8Sdrh       pExpr->span.z = 0;
3274b59ab5eSdrh     }
328a76b5dfcSdrh   }
329a76b5dfcSdrh }
330a76b5dfcSdrh 
331a76b5dfcSdrh /*
332a76b5dfcSdrh ** Construct a new expression node for a function with multiple
333a76b5dfcSdrh ** arguments.
334a76b5dfcSdrh */
3354adee20fSdanielk1977 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
336a76b5dfcSdrh   Expr *pNew;
3374b202ae2Sdanielk1977   assert( pToken );
338a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
339a76b5dfcSdrh   if( pNew==0 ){
340d5d56523Sdanielk1977     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
341a76b5dfcSdrh     return 0;
342a76b5dfcSdrh   }
343a76b5dfcSdrh   pNew->op = TK_FUNCTION;
344a76b5dfcSdrh   pNew->pList = pList;
3454b59ab5eSdrh   assert( pToken->dyn==0 );
346a76b5dfcSdrh   pNew->token = *pToken;
3476977fea8Sdrh   pNew->span = pNew->token;
348fc976065Sdanielk1977 
349fc976065Sdanielk1977   sqlite3ExprSetHeight(pNew);
350a76b5dfcSdrh   return pNew;
351a76b5dfcSdrh }
352a76b5dfcSdrh 
353a76b5dfcSdrh /*
354fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
355fa6bc000Sdrh ** in the original SQL statement.
356fa6bc000Sdrh **
357fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
358fa6bc000Sdrh ** variable number.
359fa6bc000Sdrh **
360fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
361fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
362fa6bc000Sdrh ** the SQL statement comes from an external source.
363fa6bc000Sdrh **
364fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
365fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
366fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
367fa6bc000Sdrh ** assigned.
368fa6bc000Sdrh */
369fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
370fa6bc000Sdrh   Token *pToken;
371fa6bc000Sdrh   if( pExpr==0 ) return;
372fa6bc000Sdrh   pToken = &pExpr->token;
373fa6bc000Sdrh   assert( pToken->n>=1 );
374fa6bc000Sdrh   assert( pToken->z!=0 );
375fa6bc000Sdrh   assert( pToken->z[0]!=0 );
376fa6bc000Sdrh   if( pToken->n==1 ){
377fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
378fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
379fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
380fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
381fa6bc000Sdrh     ** use it as the variable number */
382fa6bc000Sdrh     int i;
3832646da7eSdrh     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
384fa6bc000Sdrh     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
385fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
386fa6bc000Sdrh           SQLITE_MAX_VARIABLE_NUMBER);
387fa6bc000Sdrh     }
388fa6bc000Sdrh     if( i>pParse->nVar ){
389fa6bc000Sdrh       pParse->nVar = i;
390fa6bc000Sdrh     }
391fa6bc000Sdrh   }else{
392fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
393fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
394fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
395fa6bc000Sdrh     */
396fa6bc000Sdrh     int i, n;
397fa6bc000Sdrh     n = pToken->n;
398fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
399fa6bc000Sdrh       Expr *pE;
400fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
401fa6bc000Sdrh           && pE->token.n==n
402fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
403fa6bc000Sdrh         pExpr->iTable = pE->iTable;
404fa6bc000Sdrh         break;
405fa6bc000Sdrh       }
406fa6bc000Sdrh     }
407fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
408fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
409fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
410fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
411cf643729Sdrh         pParse->apVarExpr = sqliteReallocOrFree(pParse->apVarExpr,
412fa6bc000Sdrh                        pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
413fa6bc000Sdrh       }
4149e12800dSdanielk1977       if( !sqlite3MallocFailed() ){
415fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
416fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
417fa6bc000Sdrh       }
418fa6bc000Sdrh     }
419fa6bc000Sdrh   }
420832b2664Sdanielk1977   if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
421832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
422832b2664Sdanielk1977   }
423fa6bc000Sdrh }
424fa6bc000Sdrh 
425fa6bc000Sdrh /*
426a2e00042Sdrh ** Recursively delete an expression tree.
427a2e00042Sdrh */
4284adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
429a2e00042Sdrh   if( p==0 ) return;
4304efc4754Sdrh   if( p->span.dyn ) sqliteFree((char*)p->span.z);
4314efc4754Sdrh   if( p->token.dyn ) sqliteFree((char*)p->token.z);
4324adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
4334adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
4344adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
4354adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
436a2e00042Sdrh   sqliteFree(p);
437a2e00042Sdrh }
438a2e00042Sdrh 
439d2687b77Sdrh /*
440d2687b77Sdrh ** The Expr.token field might be a string literal that is quoted.
441d2687b77Sdrh ** If so, remove the quotation marks.
442d2687b77Sdrh */
443d2687b77Sdrh void sqlite3DequoteExpr(Expr *p){
444d2687b77Sdrh   if( ExprHasAnyProperty(p, EP_Dequoted) ){
445d2687b77Sdrh     return;
446d2687b77Sdrh   }
447d2687b77Sdrh   ExprSetProperty(p, EP_Dequoted);
448d2687b77Sdrh   if( p->token.dyn==0 ){
449d2687b77Sdrh     sqlite3TokenCopy(&p->token, &p->token);
450d2687b77Sdrh   }
451d2687b77Sdrh   sqlite3Dequote((char*)p->token.z);
452d2687b77Sdrh }
453d2687b77Sdrh 
454a76b5dfcSdrh 
455a76b5dfcSdrh /*
456ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
457ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
458ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
459ff78bd2fSdrh ** without effecting the originals.
460ff78bd2fSdrh **
4614adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
4624adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
463ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
464ff78bd2fSdrh **
465ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
466ff78bd2fSdrh */
4674adee20fSdanielk1977 Expr *sqlite3ExprDup(Expr *p){
468ff78bd2fSdrh   Expr *pNew;
469ff78bd2fSdrh   if( p==0 ) return 0;
470fcb78a49Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
471ff78bd2fSdrh   if( pNew==0 ) return 0;
4723b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
4736977fea8Sdrh   if( p->token.z!=0 ){
4742646da7eSdrh     pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
4754b59ab5eSdrh     pNew->token.dyn = 1;
4764b59ab5eSdrh   }else{
4774efc4754Sdrh     assert( pNew->token.z==0 );
4784b59ab5eSdrh   }
4796977fea8Sdrh   pNew->span.z = 0;
4804adee20fSdanielk1977   pNew->pLeft = sqlite3ExprDup(p->pLeft);
4814adee20fSdanielk1977   pNew->pRight = sqlite3ExprDup(p->pRight);
4824adee20fSdanielk1977   pNew->pList = sqlite3ExprListDup(p->pList);
4834adee20fSdanielk1977   pNew->pSelect = sqlite3SelectDup(p->pSelect);
484aee18ef8Sdanielk1977   pNew->pTab = p->pTab;
485fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
486fc976065Sdanielk1977   pNew->nHeight = p->nHeight;
487fc976065Sdanielk1977 #endif
488ff78bd2fSdrh   return pNew;
489ff78bd2fSdrh }
4904adee20fSdanielk1977 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
4914b59ab5eSdrh   if( pTo->dyn ) sqliteFree((char*)pTo->z);
4924b59ab5eSdrh   if( pFrom->z ){
4934b59ab5eSdrh     pTo->n = pFrom->n;
4942646da7eSdrh     pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
4954b59ab5eSdrh     pTo->dyn = 1;
4964b59ab5eSdrh   }else{
4974b59ab5eSdrh     pTo->z = 0;
4984b59ab5eSdrh   }
4994b59ab5eSdrh }
5004adee20fSdanielk1977 ExprList *sqlite3ExprListDup(ExprList *p){
501ff78bd2fSdrh   ExprList *pNew;
502145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
503ff78bd2fSdrh   int i;
504ff78bd2fSdrh   if( p==0 ) return 0;
505ff78bd2fSdrh   pNew = sqliteMalloc( sizeof(*pNew) );
506ff78bd2fSdrh   if( pNew==0 ) return 0;
5074305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
5083e7bc9caSdrh   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
509e0048400Sdanielk1977   if( pItem==0 ){
510e0048400Sdanielk1977     sqliteFree(pNew);
511e0048400Sdanielk1977     return 0;
512e0048400Sdanielk1977   }
513145716b3Sdrh   pOldItem = p->a;
514145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
5154b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
516145716b3Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
5176977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
5186977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
5194b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
5204b59ab5eSdrh       ** the names of columns in the result set needs this information */
5214adee20fSdanielk1977       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
5224b59ab5eSdrh     }
5231f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
5246f7adc8aSdrh             || pOldExpr->span.z==0
5259e12800dSdanielk1977             || sqlite3MallocFailed() );
526145716b3Sdrh     pItem->zName = sqliteStrDup(pOldItem->zName);
527145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
528145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
5293e7bc9caSdrh     pItem->done = 0;
530ff78bd2fSdrh   }
531ff78bd2fSdrh   return pNew;
532ff78bd2fSdrh }
53393758c8dSdanielk1977 
53493758c8dSdanielk1977 /*
53593758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
53693758c8dSdanielk1977 ** the build, then none of the following routines, except for
53793758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
53893758c8dSdanielk1977 ** called with a NULL argument.
53993758c8dSdanielk1977 */
5406a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
5416a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
5424adee20fSdanielk1977 SrcList *sqlite3SrcListDup(SrcList *p){
543ad3cab52Sdrh   SrcList *pNew;
544ad3cab52Sdrh   int i;
545113088ecSdrh   int nByte;
546ad3cab52Sdrh   if( p==0 ) return 0;
547113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
5484efc4754Sdrh   pNew = sqliteMallocRaw( nByte );
549ad3cab52Sdrh   if( pNew==0 ) return 0;
5504305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
551ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
5524efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
5534efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
554ed8a3bb1Sdrh     Table *pTab;
5554efc4754Sdrh     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
5564efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5574efc4754Sdrh     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
5584efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
5594efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
5601787ccabSdanielk1977     pNewItem->isPopulated = pOldItem->isPopulated;
561ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
562ed8a3bb1Sdrh     if( pTab ){
563ed8a3bb1Sdrh       pTab->nRef++;
564a1cb183dSdanielk1977     }
5654adee20fSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
5664adee20fSdanielk1977     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
5674adee20fSdanielk1977     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
5686c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
569ad3cab52Sdrh   }
570ad3cab52Sdrh   return pNew;
571ad3cab52Sdrh }
5724adee20fSdanielk1977 IdList *sqlite3IdListDup(IdList *p){
573ff78bd2fSdrh   IdList *pNew;
574ff78bd2fSdrh   int i;
575ff78bd2fSdrh   if( p==0 ) return 0;
5764efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*pNew) );
577ff78bd2fSdrh   if( pNew==0 ) return 0;
5784305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
5794efc4754Sdrh   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
580d5d56523Sdanielk1977   if( pNew->a==0 ){
581d5d56523Sdanielk1977     sqliteFree(pNew);
582d5d56523Sdanielk1977     return 0;
583d5d56523Sdanielk1977   }
584ff78bd2fSdrh   for(i=0; i<p->nId; i++){
5854efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
5864efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
5874efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5884efc4754Sdrh     pNewItem->idx = pOldItem->idx;
589ff78bd2fSdrh   }
590ff78bd2fSdrh   return pNew;
591ff78bd2fSdrh }
5924adee20fSdanielk1977 Select *sqlite3SelectDup(Select *p){
593ff78bd2fSdrh   Select *pNew;
594ff78bd2fSdrh   if( p==0 ) return 0;
5954efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
596ff78bd2fSdrh   if( pNew==0 ) return 0;
597ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
5984adee20fSdanielk1977   pNew->pEList = sqlite3ExprListDup(p->pEList);
5994adee20fSdanielk1977   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
6004adee20fSdanielk1977   pNew->pWhere = sqlite3ExprDup(p->pWhere);
6014adee20fSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
6024adee20fSdanielk1977   pNew->pHaving = sqlite3ExprDup(p->pHaving);
6034adee20fSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
604ff78bd2fSdrh   pNew->op = p->op;
6054adee20fSdanielk1977   pNew->pPrior = sqlite3SelectDup(p->pPrior);
606a2dc3b1aSdanielk1977   pNew->pLimit = sqlite3ExprDup(p->pLimit);
607a2dc3b1aSdanielk1977   pNew->pOffset = sqlite3ExprDup(p->pOffset);
6087b58daeaSdrh   pNew->iLimit = -1;
6097b58daeaSdrh   pNew->iOffset = -1;
610a1cb183dSdanielk1977   pNew->isResolved = p->isResolved;
611a1cb183dSdanielk1977   pNew->isAgg = p->isAgg;
612b9bb7c18Sdrh   pNew->usesEphm = 0;
6138e647b81Sdrh   pNew->disallowOrderBy = 0;
6140342b1f5Sdrh   pNew->pRightmost = 0;
615b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
616b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
617b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
618ff78bd2fSdrh   return pNew;
619ff78bd2fSdrh }
62093758c8dSdanielk1977 #else
62193758c8dSdanielk1977 Select *sqlite3SelectDup(Select *p){
62293758c8dSdanielk1977   assert( p==0 );
62393758c8dSdanielk1977   return 0;
62493758c8dSdanielk1977 }
62593758c8dSdanielk1977 #endif
626ff78bd2fSdrh 
627ff78bd2fSdrh 
628ff78bd2fSdrh /*
629a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
630a76b5dfcSdrh ** initially NULL, then create a new expression list.
631a76b5dfcSdrh */
6324adee20fSdanielk1977 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
633a76b5dfcSdrh   if( pList==0 ){
634a76b5dfcSdrh     pList = sqliteMalloc( sizeof(ExprList) );
635a76b5dfcSdrh     if( pList==0 ){
636d5d56523Sdanielk1977       goto no_mem;
637a76b5dfcSdrh     }
6384efc4754Sdrh     assert( pList->nAlloc==0 );
639a76b5dfcSdrh   }
6404305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
641d5d56523Sdanielk1977     struct ExprList_item *a;
642d5d56523Sdanielk1977     int n = pList->nAlloc*2 + 4;
643d5d56523Sdanielk1977     a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
644d5d56523Sdanielk1977     if( a==0 ){
645d5d56523Sdanielk1977       goto no_mem;
646a76b5dfcSdrh     }
647d5d56523Sdanielk1977     pList->a = a;
648d5d56523Sdanielk1977     pList->nAlloc = n;
649a76b5dfcSdrh   }
6504efc4754Sdrh   assert( pList->a!=0 );
6514efc4754Sdrh   if( pExpr || pName ){
6524efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
6534efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
654a99db3b6Sdrh     pItem->zName = sqlite3NameFromToken(pName);
655e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
656a76b5dfcSdrh   }
657a76b5dfcSdrh   return pList;
658d5d56523Sdanielk1977 
659d5d56523Sdanielk1977 no_mem:
660d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
661d5d56523Sdanielk1977   sqlite3ExprDelete(pExpr);
662d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
663d5d56523Sdanielk1977   return 0;
664a76b5dfcSdrh }
665a76b5dfcSdrh 
666a76b5dfcSdrh /*
6677a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
6687a15a4beSdanielk1977 ** leave an error message in pParse.
6697a15a4beSdanielk1977 */
6707a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
6717a15a4beSdanielk1977   Parse *pParse,
6727a15a4beSdanielk1977   ExprList *pEList,
6737a15a4beSdanielk1977   int iLimit,
6747a15a4beSdanielk1977   const char *zObject
6757a15a4beSdanielk1977 ){
676b4fc6794Sdanielk1977   if( pEList && pEList->nExpr>iLimit ){
6777a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
6787a15a4beSdanielk1977   }
6797a15a4beSdanielk1977 }
6807a15a4beSdanielk1977 
681fc976065Sdanielk1977 
682fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
683fc976065Sdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
684fc976065Sdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
685fc976065Sdanielk1977 ** of any expression tree referenced by the structure passed as the
686fc976065Sdanielk1977 ** first argument.
687fc976065Sdanielk1977 **
688fc976065Sdanielk1977 ** If this maximum height is greater than the current value pointed
689fc976065Sdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
690fc976065Sdanielk1977 ** value.
691fc976065Sdanielk1977 */
692fc976065Sdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
693fc976065Sdanielk1977   if( p ){
694fc976065Sdanielk1977     if( p->nHeight>*pnHeight ){
695fc976065Sdanielk1977       *pnHeight = p->nHeight;
696fc976065Sdanielk1977     }
697fc976065Sdanielk1977   }
698fc976065Sdanielk1977 }
699fc976065Sdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
700fc976065Sdanielk1977   if( p ){
701fc976065Sdanielk1977     int i;
702fc976065Sdanielk1977     for(i=0; i<p->nExpr; i++){
703fc976065Sdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
704fc976065Sdanielk1977     }
705fc976065Sdanielk1977   }
706fc976065Sdanielk1977 }
707fc976065Sdanielk1977 static void heightOfSelect(Select *p, int *pnHeight){
708fc976065Sdanielk1977   if( p ){
709fc976065Sdanielk1977     heightOfExpr(p->pWhere, pnHeight);
710fc976065Sdanielk1977     heightOfExpr(p->pHaving, pnHeight);
711fc976065Sdanielk1977     heightOfExpr(p->pLimit, pnHeight);
712fc976065Sdanielk1977     heightOfExpr(p->pOffset, pnHeight);
713fc976065Sdanielk1977     heightOfExprList(p->pEList, pnHeight);
714fc976065Sdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
715fc976065Sdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
716fc976065Sdanielk1977     heightOfSelect(p->pPrior, pnHeight);
717fc976065Sdanielk1977   }
718fc976065Sdanielk1977 }
719fc976065Sdanielk1977 
720fc976065Sdanielk1977 /*
721fc976065Sdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
722fc976065Sdanielk1977 ** argument. An expression with no children, Expr.pList or
723fc976065Sdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
724fc976065Sdanielk1977 ** has a height equal to the maximum height of any other
725fc976065Sdanielk1977 ** referenced Expr plus one.
726fc976065Sdanielk1977 */
727fc976065Sdanielk1977 void sqlite3ExprSetHeight(Expr *p){
728fc976065Sdanielk1977   int nHeight = 0;
729fc976065Sdanielk1977   heightOfExpr(p->pLeft, &nHeight);
730fc976065Sdanielk1977   heightOfExpr(p->pRight, &nHeight);
731fc976065Sdanielk1977   heightOfExprList(p->pList, &nHeight);
732fc976065Sdanielk1977   heightOfSelect(p->pSelect, &nHeight);
733fc976065Sdanielk1977   p->nHeight = nHeight + 1;
734fc976065Sdanielk1977 }
735fc976065Sdanielk1977 
736fc976065Sdanielk1977 /*
737fc976065Sdanielk1977 ** Return the maximum height of any expression tree referenced
738fc976065Sdanielk1977 ** by the select statement passed as an argument.
739fc976065Sdanielk1977 */
740fc976065Sdanielk1977 int sqlite3SelectExprHeight(Select *p){
741fc976065Sdanielk1977   int nHeight = 0;
742fc976065Sdanielk1977   heightOfSelect(p, &nHeight);
743fc976065Sdanielk1977   return nHeight;
744fc976065Sdanielk1977 }
745fc976065Sdanielk1977 #endif
746fc976065Sdanielk1977 
7477a15a4beSdanielk1977 /*
748a76b5dfcSdrh ** Delete an entire expression list.
749a76b5dfcSdrh */
7504adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
751a76b5dfcSdrh   int i;
752be5c89acSdrh   struct ExprList_item *pItem;
753a76b5dfcSdrh   if( pList==0 ) return;
7541bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
7551bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
756be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
757be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
758be5c89acSdrh     sqliteFree(pItem->zName);
759a76b5dfcSdrh   }
760a76b5dfcSdrh   sqliteFree(pList->a);
761a76b5dfcSdrh   sqliteFree(pList);
762a76b5dfcSdrh }
763a76b5dfcSdrh 
764a76b5dfcSdrh /*
765626a879aSdrh ** Walk an expression tree.  Call xFunc for each node visited.
76673b211abSdrh **
767626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
768626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
769626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
770626a879aSdrh ** the tree walk completely.
771626a879aSdrh **
772626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
773626a879aSdrh ** and 0 to continue.
77487abf5c0Sdrh **
77587abf5c0Sdrh ** NOTICE:  This routine does *not* descend into subqueries.
776626a879aSdrh */
777a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
778626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
779626a879aSdrh   int rc;
780626a879aSdrh   if( pExpr==0 ) return 0;
781626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
782626a879aSdrh   if( rc==0 ){
783626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
784626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
785a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
786626a879aSdrh   }
787626a879aSdrh   return rc>1;
788626a879aSdrh }
789626a879aSdrh 
790626a879aSdrh /*
791a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
792a58fdfb1Sdanielk1977 */
793a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
794a58fdfb1Sdanielk1977   int i;
795a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
796a58fdfb1Sdanielk1977   if( !p ) return 0;
797a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
798a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
799a58fdfb1Sdanielk1977   }
800a58fdfb1Sdanielk1977   return 0;
801a58fdfb1Sdanielk1977 }
802a58fdfb1Sdanielk1977 
803a58fdfb1Sdanielk1977 /*
804a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
805a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
806a58fdfb1Sdanielk1977 ** or OFFSET expressions..
807a58fdfb1Sdanielk1977 */
808a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
809a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
810a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
811a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
812a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
813a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
814a58fdfb1Sdanielk1977   return 0;
815a58fdfb1Sdanielk1977 }
816a58fdfb1Sdanielk1977 
817a58fdfb1Sdanielk1977 
818a58fdfb1Sdanielk1977 /*
819626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
820626a879aSdrh **
821626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
82273b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
82373b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
82473b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
82573b211abSdrh ** then do nothing.
82673b211abSdrh **
82773b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
82873b211abSdrh ** the expression as constant, then we assume the whole expression
82973b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
830626a879aSdrh */
831626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
832626a879aSdrh   switch( pExpr->op ){
833eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
834eb55bd2fSdrh     ** and *pArg==2 */
835eb55bd2fSdrh     case TK_FUNCTION:
836eb55bd2fSdrh       if( *((int*)pArg)==2 ) return 0;
837eb55bd2fSdrh       /* Fall through */
838626a879aSdrh     case TK_ID:
839626a879aSdrh     case TK_COLUMN:
840626a879aSdrh     case TK_DOT:
841626a879aSdrh     case TK_AGG_FUNCTION:
84213449892Sdrh     case TK_AGG_COLUMN:
843fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
844fe2093d7Sdrh     case TK_SELECT:
845fe2093d7Sdrh     case TK_EXISTS:
846fe2093d7Sdrh #endif
847626a879aSdrh       *((int*)pArg) = 0;
848626a879aSdrh       return 2;
84987abf5c0Sdrh     case TK_IN:
85087abf5c0Sdrh       if( pExpr->pSelect ){
85187abf5c0Sdrh         *((int*)pArg) = 0;
85287abf5c0Sdrh         return 2;
85387abf5c0Sdrh       }
854626a879aSdrh     default:
855626a879aSdrh       return 0;
856626a879aSdrh   }
857626a879aSdrh }
858626a879aSdrh 
859626a879aSdrh /*
860fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
861eb55bd2fSdrh ** and 0 if it involves variables or function calls.
8622398937bSdrh **
8632398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
8642398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
8652398937bSdrh ** a constant.
866fef5208cSdrh */
8674adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
868626a879aSdrh   int isConst = 1;
869626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
870626a879aSdrh   return isConst;
871fef5208cSdrh }
872fef5208cSdrh 
873fef5208cSdrh /*
874eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
875eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
876eb55bd2fSdrh ** are any variables.
877eb55bd2fSdrh **
878eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
879eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
880eb55bd2fSdrh ** a constant.
881eb55bd2fSdrh */
882eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
883eb55bd2fSdrh   int isConst = 2;
884eb55bd2fSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
885eb55bd2fSdrh   return isConst!=0;
886eb55bd2fSdrh }
887eb55bd2fSdrh 
888eb55bd2fSdrh /*
88973b211abSdrh ** If the expression p codes a constant integer that is small enough
890202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
891202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
892202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
893e4de1febSdrh */
8944adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
895e4de1febSdrh   switch( p->op ){
896e4de1febSdrh     case TK_INTEGER: {
8972646da7eSdrh       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
898e4de1febSdrh         return 1;
899e4de1febSdrh       }
900202b2df7Sdrh       break;
901202b2df7Sdrh     }
9024b59ab5eSdrh     case TK_UPLUS: {
9034adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
9044b59ab5eSdrh     }
905e4de1febSdrh     case TK_UMINUS: {
906e4de1febSdrh       int v;
9074adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
908e4de1febSdrh         *pValue = -v;
909e4de1febSdrh         return 1;
910e4de1febSdrh       }
911e4de1febSdrh       break;
912e4de1febSdrh     }
913e4de1febSdrh     default: break;
914e4de1febSdrh   }
915e4de1febSdrh   return 0;
916e4de1febSdrh }
917e4de1febSdrh 
918e4de1febSdrh /*
919c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
920c4a3c779Sdrh */
9214adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
9224adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
9234adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
9244adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
925c4a3c779Sdrh   return 0;
926c4a3c779Sdrh }
927c4a3c779Sdrh 
928c4a3c779Sdrh /*
9298141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
9308141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
9318141f61eSdrh ** expression node refer back to that source column.  The following changes
9328141f61eSdrh ** are made to pExpr:
9338141f61eSdrh **
9348141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
9358141f61eSdrh **                         the table.
9368141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
9378141f61eSdrh **                         from pSrcList.
9388141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
9398141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
9408141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
9418141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
9428141f61eSdrh **
9438141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
9448141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
9458141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
9468141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
9478141f61eSdrh ** means that the form of the name is Z and that columns from any table
9488141f61eSdrh ** can be used.
9498141f61eSdrh **
9508141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
9518141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
9528141f61eSdrh */
9538141f61eSdrh static int lookupName(
9548141f61eSdrh   Parse *pParse,       /* The parsing context */
9558141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
9568141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
9578141f61eSdrh   Token *pColumnToken, /* Name of the column. */
958626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
9598141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
9608141f61eSdrh ){
9618141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
9628141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
9638141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
9648141f61eSdrh   int i, j;            /* Loop counters */
9658141f61eSdrh   int cnt = 0;         /* Number of matching column names */
9668141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
9679bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
96851669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
96951669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
97073b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
9718141f61eSdrh 
9728141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
973a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
974a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
975a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
9769e12800dSdanielk1977   if( sqlite3MallocFailed() ){
977d5d56523Sdanielk1977     goto lookupname_end;
9788141f61eSdrh   }
9798141f61eSdrh 
9808141f61eSdrh   pExpr->iTable = -1;
981626a879aSdrh   while( pNC && cnt==0 ){
982ffe07b2dSdrh     ExprList *pEList;
983626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
984626a879aSdrh 
985b3bce662Sdanielk1977     if( pSrcList ){
98651669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
98743617e9aSdrh         Table *pTab;
98843617e9aSdrh         int iDb;
9898141f61eSdrh         Column *pCol;
9908141f61eSdrh 
99143617e9aSdrh         pTab = pItem->pTab;
99243617e9aSdrh         assert( pTab!=0 );
99343617e9aSdrh         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
9948141f61eSdrh         assert( pTab->nCol>0 );
9958141f61eSdrh         if( zTab ){
9968141f61eSdrh           if( pItem->zAlias ){
9978141f61eSdrh             char *zTabName = pItem->zAlias;
9984adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
9998141f61eSdrh           }else{
10008141f61eSdrh             char *zTabName = pTab->zName;
10014adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1002da184236Sdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
10038141f61eSdrh               continue;
10048141f61eSdrh             }
10058141f61eSdrh           }
10068141f61eSdrh         }
10078141f61eSdrh         if( 0==(cntTab++) ){
10088141f61eSdrh           pExpr->iTable = pItem->iCursor;
1009da184236Sdanielk1977           pExpr->pSchema = pTab->pSchema;
101051669863Sdrh           pMatch = pItem;
10118141f61eSdrh         }
10128141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
10134adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1014b3bf556eSdanielk1977             const char *zColl = pTab->aCol[j].zColl;
1015873fac0cSdrh             IdList *pUsing;
10168141f61eSdrh             cnt++;
10178141f61eSdrh             pExpr->iTable = pItem->iCursor;
101851669863Sdrh             pMatch = pItem;
1019da184236Sdanielk1977             pExpr->pSchema = pTab->pSchema;
10208141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
10218141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
1022a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
10238b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1024b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
10258b4c40d8Sdrh             }
102661dfc31dSdrh             if( i<pSrcList->nSrc-1 ){
102761dfc31dSdrh               if( pItem[1].jointype & JT_NATURAL ){
1028355ef361Sdrh                 /* If this match occurred in the left table of a natural join,
1029355ef361Sdrh                 ** then skip the right table to avoid a duplicate match */
1030355ef361Sdrh                 pItem++;
1031355ef361Sdrh                 i++;
103261dfc31dSdrh               }else if( (pUsing = pItem[1].pUsing)!=0 ){
1033873fac0cSdrh                 /* If this match occurs on a column that is in the USING clause
1034873fac0cSdrh                 ** of a join, skip the search of the right table of the join
1035873fac0cSdrh                 ** to avoid a duplicate match there. */
1036873fac0cSdrh                 int k;
1037873fac0cSdrh                 for(k=0; k<pUsing->nId; k++){
1038873fac0cSdrh                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
1039873fac0cSdrh                     pItem++;
1040873fac0cSdrh                     i++;
1041873fac0cSdrh                     break;
1042873fac0cSdrh                   }
1043873fac0cSdrh                 }
1044873fac0cSdrh               }
104561dfc31dSdrh             }
10468141f61eSdrh             break;
10478141f61eSdrh           }
10488141f61eSdrh         }
10498141f61eSdrh       }
1050b3bce662Sdanielk1977     }
10518141f61eSdrh 
1052b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
10538141f61eSdrh     /* If we have not already resolved the name, then maybe
10548141f61eSdrh     ** it is a new.* or old.* trigger argument reference
10558141f61eSdrh     */
10568141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
10578141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
10588141f61eSdrh       Table *pTab = 0;
10594adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
10608141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
10618141f61eSdrh         assert( pTriggerStack->pTab );
10628141f61eSdrh         pTab = pTriggerStack->pTab;
10634adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
10648141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
10658141f61eSdrh         assert( pTriggerStack->pTab );
10668141f61eSdrh         pTab = pTriggerStack->pTab;
10678141f61eSdrh       }
10688141f61eSdrh 
10698141f61eSdrh       if( pTab ){
1070f0113000Sdanielk1977         int iCol;
10718141f61eSdrh         Column *pCol = pTab->aCol;
10728141f61eSdrh 
1073da184236Sdanielk1977         pExpr->pSchema = pTab->pSchema;
10748141f61eSdrh         cntTab++;
1075f0113000Sdanielk1977         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
10764adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1077f0113000Sdanielk1977             const char *zColl = pTab->aCol[iCol].zColl;
10788141f61eSdrh             cnt++;
1079f0113000Sdanielk1977             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1080f0113000Sdanielk1977             pExpr->affinity = pTab->aCol[iCol].affinity;
10818b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1082b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
10838b4c40d8Sdrh             }
1084aee18ef8Sdanielk1977             pExpr->pTab = pTab;
10858141f61eSdrh             break;
10868141f61eSdrh           }
10878141f61eSdrh         }
10888141f61eSdrh       }
10898141f61eSdrh     }
1090b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
10918141f61eSdrh 
10928141f61eSdrh     /*
10938141f61eSdrh     ** Perhaps the name is a reference to the ROWID
10948141f61eSdrh     */
10954adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
10968141f61eSdrh       cnt = 1;
10978141f61eSdrh       pExpr->iColumn = -1;
10988a51256cSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
10998141f61eSdrh     }
11008141f61eSdrh 
11018141f61eSdrh     /*
11028141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
11038141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
11048141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
11058141f61eSdrh     **
11068141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
11078141f61eSdrh     **
11088141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
11098141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
11108141f61eSdrh     ** Note that the expression in the result set should have already been
11118141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
11128141f61eSdrh     */
1113ffe07b2dSdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
11148141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
11158141f61eSdrh         char *zAs = pEList->a[j].zName;
11164adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
11178141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
11188141f61eSdrh           pExpr->op = TK_AS;
11198141f61eSdrh           pExpr->iColumn = j;
11204adee20fSdanielk1977           pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
112115ccce1cSdrh           cnt = 1;
11228141f61eSdrh           assert( zTab==0 && zDb==0 );
112315ccce1cSdrh           goto lookupname_end_2;
11248141f61eSdrh         }
11258141f61eSdrh       }
11268141f61eSdrh     }
11278141f61eSdrh 
1128626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
1129626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
1130626a879aSdrh     */
1131626a879aSdrh     if( cnt==0 ){
1132626a879aSdrh       pNC = pNC->pNext;
1133626a879aSdrh     }
1134626a879aSdrh   }
1135626a879aSdrh 
11368141f61eSdrh   /*
11378141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
11388141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
11398141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
11408141f61eSdrh   ** case, we need to return right away and not make any changes to
11418141f61eSdrh   ** pExpr.
114215ccce1cSdrh   **
114315ccce1cSdrh   ** Because no reference was made to outer contexts, the pNC->nRef
114415ccce1cSdrh   ** fields are not changed in any context.
11458141f61eSdrh   */
11468141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
11478141f61eSdrh     sqliteFree(zCol);
11488141f61eSdrh     return 0;
11498141f61eSdrh   }
11508141f61eSdrh 
11518141f61eSdrh   /*
11528141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
11538141f61eSdrh   ** more matches.  Either way, we have an error.
11548141f61eSdrh   */
11558141f61eSdrh   if( cnt!=1 ){
11568141f61eSdrh     char *z = 0;
11578141f61eSdrh     char *zErr;
11588141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
11598141f61eSdrh     if( zDb ){
1160f93339deSdrh       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
11618141f61eSdrh     }else if( zTab ){
1162f93339deSdrh       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
11638141f61eSdrh     }else{
11648141f61eSdrh       z = sqliteStrDup(zCol);
11658141f61eSdrh     }
11664adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
11678141f61eSdrh     sqliteFree(z);
116873b211abSdrh     pTopNC->nErr++;
11698141f61eSdrh   }
11708141f61eSdrh 
117151669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
117251669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
117351669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
117451669863Sdrh   ** column number is greater than the number of bits in the bitmask
117551669863Sdrh   ** then set the high-order bit of the bitmask.
117651669863Sdrh   */
117751669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
117851669863Sdrh     int n = pExpr->iColumn;
117951669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
118051669863Sdrh       n = sizeof(Bitmask)*8-1;
118151669863Sdrh     }
118251669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
1183ca83ac51Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
118451669863Sdrh   }
118551669863Sdrh 
1186d5d56523Sdanielk1977 lookupname_end:
11878141f61eSdrh   /* Clean up and return
11888141f61eSdrh   */
11898141f61eSdrh   sqliteFree(zDb);
11908141f61eSdrh   sqliteFree(zTab);
11914adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
11928141f61eSdrh   pExpr->pLeft = 0;
11934adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
11948141f61eSdrh   pExpr->pRight = 0;
11958141f61eSdrh   pExpr->op = TK_COLUMN;
119615ccce1cSdrh lookupname_end_2:
119715ccce1cSdrh   sqliteFree(zCol);
1198626a879aSdrh   if( cnt==1 ){
1199b3bce662Sdanielk1977     assert( pNC!=0 );
1200626a879aSdrh     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1201aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
1202aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
1203aee18ef8Sdanielk1977     }
120415ccce1cSdrh     /* Increment the nRef value on all name contexts from TopNC up to
120515ccce1cSdrh     ** the point where the name matched. */
120615ccce1cSdrh     for(;;){
120715ccce1cSdrh       assert( pTopNC!=0 );
120815ccce1cSdrh       pTopNC->nRef++;
120915ccce1cSdrh       if( pTopNC==pNC ) break;
121015ccce1cSdrh       pTopNC = pTopNC->pNext;
1211626a879aSdrh     }
121215ccce1cSdrh     return 0;
121315ccce1cSdrh   } else {
121415ccce1cSdrh     return 1;
121515ccce1cSdrh   }
12168141f61eSdrh }
12178141f61eSdrh 
12188141f61eSdrh /*
1219626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1220626a879aSdrh **
122173b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1222626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
122373b211abSdrh ** the tree or 2 to abort the tree walk.
122473b211abSdrh **
122573b211abSdrh ** This routine also does error checking and name resolution for
122673b211abSdrh ** function names.  The operator for aggregate functions is changed
122773b211abSdrh ** to TK_AGG_FUNCTION.
1228626a879aSdrh */
1229626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1230626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1231626a879aSdrh   Parse *pParse;
1232626a879aSdrh 
1233b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1234626a879aSdrh   assert( pNC!=0 );
1235626a879aSdrh   pParse = pNC->pParse;
1236b3bce662Sdanielk1977 
1237626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1238626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1239626a879aSdrh #ifndef NDEBUG
1240f0113000Sdanielk1977   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1241f0113000Sdanielk1977     SrcList *pSrcList = pNC->pSrcList;
1242940fac9dSdanielk1977     int i;
1243f0113000Sdanielk1977     for(i=0; i<pNC->pSrcList->nSrc; i++){
1244626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1245626a879aSdrh     }
1246626a879aSdrh   }
1247626a879aSdrh #endif
1248626a879aSdrh   switch( pExpr->op ){
1249626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1250626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1251626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1252626a879aSdrh     */
1253626a879aSdrh     case TK_STRING: {
1254626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1255626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1256626a879aSdrh     }
1257626a879aSdrh     /* A lone identifier is the name of a column.
1258626a879aSdrh     */
1259626a879aSdrh     case TK_ID: {
1260626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1261626a879aSdrh       return 1;
1262626a879aSdrh     }
1263626a879aSdrh 
1264626a879aSdrh     /* A table name and column name:     ID.ID
1265626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1266626a879aSdrh     */
1267626a879aSdrh     case TK_DOT: {
1268626a879aSdrh       Token *pColumn;
1269626a879aSdrh       Token *pTable;
1270626a879aSdrh       Token *pDb;
1271626a879aSdrh       Expr *pRight;
1272626a879aSdrh 
1273b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1274626a879aSdrh       pRight = pExpr->pRight;
1275626a879aSdrh       if( pRight->op==TK_ID ){
1276626a879aSdrh         pDb = 0;
1277626a879aSdrh         pTable = &pExpr->pLeft->token;
1278626a879aSdrh         pColumn = &pRight->token;
1279626a879aSdrh       }else{
1280626a879aSdrh         assert( pRight->op==TK_DOT );
1281626a879aSdrh         pDb = &pExpr->pLeft->token;
1282626a879aSdrh         pTable = &pRight->pLeft->token;
1283626a879aSdrh         pColumn = &pRight->pRight->token;
1284626a879aSdrh       }
1285626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1286626a879aSdrh       return 1;
1287626a879aSdrh     }
1288626a879aSdrh 
1289626a879aSdrh     /* Resolve function names
1290626a879aSdrh     */
1291b71090fdSdrh     case TK_CONST_FUNC:
1292626a879aSdrh     case TK_FUNCTION: {
1293626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1294626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1295626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1296626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1297626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1298626a879aSdrh       int i;
12995169bbc6Sdrh       int auth;                   /* Authorization to use the function */
1300626a879aSdrh       int nId;                    /* Number of characters in function name */
1301626a879aSdrh       const char *zId;            /* The function name. */
130273b211abSdrh       FuncDef *pDef;              /* Information about the function */
130314db2665Sdanielk1977       int enc = ENC(pParse->db);  /* The database encoding */
1304626a879aSdrh 
13052646da7eSdrh       zId = (char*)pExpr->token.z;
1306b71090fdSdrh       nId = pExpr->token.n;
1307626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1308626a879aSdrh       if( pDef==0 ){
1309626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1310626a879aSdrh         if( pDef==0 ){
1311626a879aSdrh           no_such_func = 1;
1312626a879aSdrh         }else{
1313626a879aSdrh           wrong_num_args = 1;
1314626a879aSdrh         }
1315626a879aSdrh       }else{
1316626a879aSdrh         is_agg = pDef->xFunc==0;
1317626a879aSdrh       }
13182fca7fefSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
13195169bbc6Sdrh       if( pDef ){
13205169bbc6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
13215169bbc6Sdrh         if( auth!=SQLITE_OK ){
13225169bbc6Sdrh           if( auth==SQLITE_DENY ){
13235169bbc6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
13245169bbc6Sdrh                                     pDef->zName);
13255169bbc6Sdrh             pNC->nErr++;
13265169bbc6Sdrh           }
13275169bbc6Sdrh           pExpr->op = TK_NULL;
13285169bbc6Sdrh           return 1;
13295169bbc6Sdrh         }
13305169bbc6Sdrh       }
1331b8b14219Sdrh #endif
1332626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1333626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1334626a879aSdrh         pNC->nErr++;
1335626a879aSdrh         is_agg = 0;
1336626a879aSdrh       }else if( no_such_func ){
1337626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1338626a879aSdrh         pNC->nErr++;
1339626a879aSdrh       }else if( wrong_num_args ){
1340626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1341626a879aSdrh              nId, zId);
1342626a879aSdrh         pNC->nErr++;
1343626a879aSdrh       }
1344626a879aSdrh       if( is_agg ){
1345626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1346626a879aSdrh         pNC->hasAgg = 1;
1347626a879aSdrh       }
134873b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1349626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
135073b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1351626a879aSdrh       }
135273b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1353626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1354626a879aSdrh       ** type of the function
1355626a879aSdrh       */
1356626a879aSdrh       return is_agg;
1357626a879aSdrh     }
1358b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1359b3bce662Sdanielk1977     case TK_SELECT:
1360b3bce662Sdanielk1977     case TK_EXISTS:
1361b3bce662Sdanielk1977 #endif
1362b3bce662Sdanielk1977     case TK_IN: {
1363b3bce662Sdanielk1977       if( pExpr->pSelect ){
13648a9f38feSdrh         int nRef = pNC->nRef;
136506f6541eSdrh #ifndef SQLITE_OMIT_CHECK
136606f6541eSdrh         if( pNC->isCheck ){
136706f6541eSdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
136806f6541eSdrh         }
136906f6541eSdrh #endif
1370b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1371b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1372b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1373b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1374b3bce662Sdanielk1977         }
1375b3bce662Sdanielk1977       }
13764284fb07Sdrh       break;
1377b3bce662Sdanielk1977     }
13784284fb07Sdrh #ifndef SQLITE_OMIT_CHECK
13794284fb07Sdrh     case TK_VARIABLE: {
13804284fb07Sdrh       if( pNC->isCheck ){
13814284fb07Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
13824284fb07Sdrh       }
13834284fb07Sdrh       break;
13844284fb07Sdrh     }
13854284fb07Sdrh #endif
1386626a879aSdrh   }
1387626a879aSdrh   return 0;
1388626a879aSdrh }
1389626a879aSdrh 
1390626a879aSdrh /*
1391cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1392967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1393aacc543eSdrh ** index to the table in the table list and a column offset.  The
1394aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1395aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1396832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1397aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1398aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1399aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1400aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1401aacc543eSdrh ** alias for ROWID.
140219a775c2Sdrh **
1403626a879aSdrh ** Also resolve function names and check the functions for proper
1404626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1405626a879aSdrh ** have the correct number of arguments.  Leave an error message
1406626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1407626a879aSdrh **
140873b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
140973b211abSdrh ** property on the expression.
1410626a879aSdrh */
1411626a879aSdrh int sqlite3ExprResolveNames(
1412b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1413b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1414626a879aSdrh ){
141513449892Sdrh   int savedHasAgg;
141673b211abSdrh   if( pExpr==0 ) return 0;
1417fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
1418fc976065Sdanielk1977   if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
1419fc976065Sdanielk1977     sqlite3ErrorMsg(pNC->pParse,
1420fc976065Sdanielk1977        "Expression tree is too large (maximum depth %d)",
1421fc976065Sdanielk1977        SQLITE_MAX_EXPR_DEPTH
1422fc976065Sdanielk1977     );
1423fc976065Sdanielk1977     return 1;
1424fc976065Sdanielk1977   }
1425fc976065Sdanielk1977   pNC->pParse->nHeight += pExpr->nHeight;
1426fc976065Sdanielk1977 #endif
142713449892Sdrh   savedHasAgg = pNC->hasAgg;
142813449892Sdrh   pNC->hasAgg = 0;
1429b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1430fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
1431fc976065Sdanielk1977   pNC->pParse->nHeight -= pExpr->nHeight;
1432fc976065Sdanielk1977 #endif
1433b3bce662Sdanielk1977   if( pNC->nErr>0 ){
143473b211abSdrh     ExprSetProperty(pExpr, EP_Error);
143573b211abSdrh   }
143613449892Sdrh   if( pNC->hasAgg ){
143713449892Sdrh     ExprSetProperty(pExpr, EP_Agg);
143813449892Sdrh   }else if( savedHasAgg ){
143913449892Sdrh     pNC->hasAgg = 1;
144013449892Sdrh   }
144173b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1442626a879aSdrh }
1443626a879aSdrh 
14441398ad36Sdrh /*
14451398ad36Sdrh ** A pointer instance of this structure is used to pass information
14461398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
14471398ad36Sdrh */
14481398ad36Sdrh typedef struct QueryCoder QueryCoder;
14491398ad36Sdrh struct QueryCoder {
14501398ad36Sdrh   Parse *pParse;       /* The parsing context */
14511398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
14521398ad36Sdrh };
14531398ad36Sdrh 
1454626a879aSdrh 
1455626a879aSdrh /*
14569cbe6352Sdrh ** Generate code for scalar subqueries used as an expression
14579cbe6352Sdrh ** and IN operators.  Examples:
1458626a879aSdrh **
14599cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
14609cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
14619cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
14629cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1463fef5208cSdrh **
14649cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
14659cbe6352Sdrh ** operator or subquery.
1466cce7d176Sdrh */
146751522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1468b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
146957dbd7b3Sdrh   int testAddr = 0;                       /* One-time test address */
1470b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1471b3bce662Sdanielk1977   if( v==0 ) return;
1472b3bce662Sdanielk1977 
1473fc976065Sdanielk1977 
147457dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
147557dbd7b3Sdrh   ** if any of the following is true:
147657dbd7b3Sdrh   **
147757dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
147857dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
147957dbd7b3Sdrh   **    *  We are inside a trigger
148057dbd7b3Sdrh   **
148157dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
148257dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1483b3bce662Sdanielk1977   */
1484b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1485b3bce662Sdanielk1977     int mem = pParse->nMem++;
1486b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
148757dbd7b3Sdrh     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
14889e12800dSdanielk1977     assert( testAddr>0 || sqlite3MallocFailed() );
1489d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1490b3bce662Sdanielk1977   }
1491b3bce662Sdanielk1977 
1492cce7d176Sdrh   switch( pExpr->op ){
1493fef5208cSdrh     case TK_IN: {
1494e014a838Sdanielk1977       char affinity;
1495d3d39e93Sdrh       KeyInfo keyInfo;
1496b9bb7c18Sdrh       int addr;        /* Address of OP_OpenEphemeral instruction */
1497d3d39e93Sdrh 
1498bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1499e014a838Sdanielk1977 
1500e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
150157dbd7b3Sdrh       ** expression it is handled the same way. A virtual table is
1502e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1503e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1504fef5208cSdrh       **
1505e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1506e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1507e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1508e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1509e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1510e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1511e014a838Sdanielk1977       ** is used.
1512fef5208cSdrh       */
1513832508b7Sdrh       pExpr->iTable = pParse->nTab++;
1514b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
1515d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1516d3d39e93Sdrh       keyInfo.nField = 1;
1517f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1518e014a838Sdanielk1977 
1519e014a838Sdanielk1977       if( pExpr->pSelect ){
1520e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1521e014a838Sdanielk1977         **
1522e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1523e014a838Sdanielk1977         ** table allocated and opened above.
1524e014a838Sdanielk1977         */
1525e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1526be5c89acSdrh         ExprList *pEList;
1527e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
152894ccde58Sdrh         if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
152994ccde58Sdrh           return;
153094ccde58Sdrh         }
1531be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1532be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
15337cedc8d4Sdanielk1977           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
1534be5c89acSdrh               pEList->a[0].pExpr);
15350202b29eSdanielk1977         }
1536fef5208cSdrh       }else if( pExpr->pList ){
1537fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1538fef5208cSdrh         **
1539e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
1540e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1541e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1542e014a838Sdanielk1977         ** a column, use numeric affinity.
1543fef5208cSdrh         */
1544e014a838Sdanielk1977         int i;
154557dbd7b3Sdrh         ExprList *pList = pExpr->pList;
154657dbd7b3Sdrh         struct ExprList_item *pItem;
154757dbd7b3Sdrh 
1548e014a838Sdanielk1977         if( !affinity ){
15498159a35fSdrh           affinity = SQLITE_AFF_NONE;
1550e014a838Sdanielk1977         }
15510202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1552e014a838Sdanielk1977 
1553e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
155457dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
155557dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1556e014a838Sdanielk1977 
155757dbd7b3Sdrh           /* If the expression is not constant then we will need to
155857dbd7b3Sdrh           ** disable the test that was generated above that makes sure
155957dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
156057dbd7b3Sdrh           ** expression we need to rerun this code each time.
156157dbd7b3Sdrh           */
15626c30be8eSdrh           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
1563f8875400Sdrh             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
156457dbd7b3Sdrh             testAddr = 0;
15654794b980Sdrh           }
1566e014a838Sdanielk1977 
1567e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
15684adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
156994a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1570f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1571fef5208cSdrh         }
1572fef5208cSdrh       }
15730202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1574b3bce662Sdanielk1977       break;
1575fef5208cSdrh     }
1576fef5208cSdrh 
157751522cd3Sdrh     case TK_EXISTS:
157819a775c2Sdrh     case TK_SELECT: {
1579fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1580fef5208cSdrh       ** value of this select in a memory cell and record the number
1581967e8b73Sdrh       ** of the memory cell in iColumn.
1582fef5208cSdrh       */
15832646da7eSdrh       static const Token one = { (u8*)"1", 0, 1 };
158451522cd3Sdrh       Select *pSel;
1585ec7429aeSdrh       int iMem;
1586ec7429aeSdrh       int sop;
15871398ad36Sdrh 
1588ec7429aeSdrh       pExpr->iColumn = iMem = pParse->nMem++;
158951522cd3Sdrh       pSel = pExpr->pSelect;
159051522cd3Sdrh       if( pExpr->op==TK_SELECT ){
159151522cd3Sdrh         sop = SRT_Mem;
1592ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1593ec7429aeSdrh         VdbeComment((v, "# Init subquery result"));
159451522cd3Sdrh       }else{
159551522cd3Sdrh         sop = SRT_Exists;
1596ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1597ec7429aeSdrh         VdbeComment((v, "# Init EXISTS result"));
159851522cd3Sdrh       }
1599ec7429aeSdrh       sqlite3ExprDelete(pSel->pLimit);
1600ec7429aeSdrh       pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
160194ccde58Sdrh       if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
160294ccde58Sdrh         return;
160394ccde58Sdrh       }
1604b3bce662Sdanielk1977       break;
160519a775c2Sdrh     }
1606cce7d176Sdrh   }
1607b3bce662Sdanielk1977 
160857dbd7b3Sdrh   if( testAddr ){
1609d654be80Sdrh     sqlite3VdbeJumpHere(v, testAddr);
1610b3bce662Sdanielk1977   }
1611fc976065Sdanielk1977 
1612b3bce662Sdanielk1977   return;
1613cce7d176Sdrh }
161451522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1615cce7d176Sdrh 
1616cce7d176Sdrh /*
1617fec19aadSdrh ** Generate an instruction that will put the integer describe by
1618fec19aadSdrh ** text z[0..n-1] on the stack.
1619fec19aadSdrh */
1620fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1621fec19aadSdrh   int i;
16226fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
16236fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
16246fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
162529dda4aeSdrh     sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1626fec19aadSdrh   }else{
1627fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1628fec19aadSdrh   }
1629fec19aadSdrh }
1630fec19aadSdrh 
1631945498f3Sdrh 
1632945498f3Sdrh /*
1633945498f3Sdrh ** Generate code that will extract the iColumn-th column from
1634945498f3Sdrh ** table pTab and push that column value on the stack.  There
1635945498f3Sdrh ** is an open cursor to pTab in iTable.  If iColumn<0 then
1636945498f3Sdrh ** code is generated that extracts the rowid.
1637945498f3Sdrh */
1638945498f3Sdrh void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
1639945498f3Sdrh   if( iColumn<0 ){
1640945498f3Sdrh     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
1641945498f3Sdrh     sqlite3VdbeAddOp(v, op, iTable, 0);
1642945498f3Sdrh   }else if( pTab==0 ){
1643945498f3Sdrh     sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
1644945498f3Sdrh   }else{
1645945498f3Sdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
1646945498f3Sdrh     sqlite3VdbeAddOp(v, op, iTable, iColumn);
1647945498f3Sdrh     sqlite3ColumnDefault(v, pTab, iColumn);
1648945498f3Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
1649945498f3Sdrh     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
1650945498f3Sdrh       sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
1651945498f3Sdrh     }
1652945498f3Sdrh #endif
1653945498f3Sdrh   }
1654945498f3Sdrh }
1655945498f3Sdrh 
1656fec19aadSdrh /*
1657cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
16581ccde15dSdrh ** expression and leave the result on the top of stack.
1659f2bc013cSdrh **
1660f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1661f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1662f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1663f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1664f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1665cce7d176Sdrh */
16664adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1667cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1668cce7d176Sdrh   int op;
1669ffe07b2dSdrh   int stackChng = 1;    /* Amount of change to stack depth */
1670ffe07b2dSdrh 
16717977a17fSdanielk1977   if( v==0 ) return;
16727977a17fSdanielk1977   if( pExpr==0 ){
1673f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
16747977a17fSdanielk1977     return;
16757977a17fSdanielk1977   }
1676f2bc013cSdrh   op = pExpr->op;
1677f2bc013cSdrh   switch( op ){
167813449892Sdrh     case TK_AGG_COLUMN: {
167913449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
168013449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
168113449892Sdrh       if( !pAggInfo->directMode ){
168213449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
168313449892Sdrh         break;
168413449892Sdrh       }else if( pAggInfo->useSortingIdx ){
168513449892Sdrh         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
168613449892Sdrh                               pCol->iSorterColumn);
168713449892Sdrh         break;
168813449892Sdrh       }
168913449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
169013449892Sdrh     }
1691967e8b73Sdrh     case TK_COLUMN: {
1692ffe07b2dSdrh       if( pExpr->iTable<0 ){
1693ffe07b2dSdrh         /* This only happens when coding check constraints */
1694ffe07b2dSdrh         assert( pParse->ckOffset>0 );
1695ffe07b2dSdrh         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1696c4a3c779Sdrh       }else{
1697945498f3Sdrh         sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
16982282792aSdrh       }
1699cce7d176Sdrh       break;
1700cce7d176Sdrh     }
1701cce7d176Sdrh     case TK_INTEGER: {
17022646da7eSdrh       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1703fec19aadSdrh       break;
170451e9a445Sdrh     }
1705fec19aadSdrh     case TK_FLOAT:
1706fec19aadSdrh     case TK_STRING: {
1707f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1708f2bc013cSdrh       assert( TK_STRING==OP_String8 );
1709d2687b77Sdrh       sqlite3DequoteExpr(pExpr);
17102646da7eSdrh       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1711cce7d176Sdrh       break;
1712cce7d176Sdrh     }
1713f0863fe5Sdrh     case TK_NULL: {
1714f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1715f0863fe5Sdrh       break;
1716f0863fe5Sdrh     }
17175338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1718c572ef7fSdanielk1977     case TK_BLOB: {
17196c8c6cecSdrh       int n;
17206c8c6cecSdrh       const char *z;
1721f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
17226c8c6cecSdrh       n = pExpr->token.n - 3;
17232646da7eSdrh       z = (char*)pExpr->token.z + 2;
17246c8c6cecSdrh       assert( n>=0 );
17256c8c6cecSdrh       if( n==0 ){
17266c8c6cecSdrh         z = "";
17276c8c6cecSdrh       }
17286c8c6cecSdrh       sqlite3VdbeOp3(v, op, 0, 0, z, n);
1729c572ef7fSdanielk1977       break;
1730c572ef7fSdanielk1977     }
17315338a5f7Sdanielk1977 #endif
173250457896Sdrh     case TK_VARIABLE: {
17334adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1734895d7472Sdrh       if( pExpr->token.n>1 ){
17352646da7eSdrh         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1736895d7472Sdrh       }
173750457896Sdrh       break;
173850457896Sdrh     }
17394e0cff60Sdrh     case TK_REGISTER: {
17404e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
17414e0cff60Sdrh       break;
17424e0cff60Sdrh     }
1743487e262fSdrh #ifndef SQLITE_OMIT_CAST
1744487e262fSdrh     case TK_CAST: {
1745487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
1746f0113000Sdanielk1977       int aff, to_op;
1747487e262fSdrh       sqlite3ExprCode(pParse, pExpr->pLeft);
17488a51256cSdrh       aff = sqlite3AffinityType(&pExpr->token);
1749f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1750f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
1751f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
1752f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1753f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
1754f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
1755f0113000Sdanielk1977       sqlite3VdbeAddOp(v, to_op, 0, 0);
1756ffe07b2dSdrh       stackChng = 0;
1757487e262fSdrh       break;
1758487e262fSdrh     }
1759487e262fSdrh #endif /* SQLITE_OMIT_CAST */
1760c9b84a1fSdrh     case TK_LT:
1761c9b84a1fSdrh     case TK_LE:
1762c9b84a1fSdrh     case TK_GT:
1763c9b84a1fSdrh     case TK_GE:
1764c9b84a1fSdrh     case TK_NE:
1765c9b84a1fSdrh     case TK_EQ: {
1766f2bc013cSdrh       assert( TK_LT==OP_Lt );
1767f2bc013cSdrh       assert( TK_LE==OP_Le );
1768f2bc013cSdrh       assert( TK_GT==OP_Gt );
1769f2bc013cSdrh       assert( TK_GE==OP_Ge );
1770f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1771f2bc013cSdrh       assert( TK_NE==OP_Ne );
1772a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1773a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1774be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1775ffe07b2dSdrh       stackChng = -1;
1776a37cdde0Sdanielk1977       break;
1777c9b84a1fSdrh     }
1778cce7d176Sdrh     case TK_AND:
1779cce7d176Sdrh     case TK_OR:
1780cce7d176Sdrh     case TK_PLUS:
1781cce7d176Sdrh     case TK_STAR:
1782cce7d176Sdrh     case TK_MINUS:
1783bf4133cbSdrh     case TK_REM:
1784bf4133cbSdrh     case TK_BITAND:
1785bf4133cbSdrh     case TK_BITOR:
178617c40294Sdrh     case TK_SLASH:
1787bf4133cbSdrh     case TK_LSHIFT:
1788855eb1cfSdrh     case TK_RSHIFT:
17890040077dSdrh     case TK_CONCAT: {
1790f2bc013cSdrh       assert( TK_AND==OP_And );
1791f2bc013cSdrh       assert( TK_OR==OP_Or );
1792f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1793f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1794f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1795f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1796f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1797f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1798f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1799f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1800f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
18014adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18024adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1803855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
1804ffe07b2dSdrh       stackChng = -1;
18050040077dSdrh       break;
18060040077dSdrh     }
1807cce7d176Sdrh     case TK_UMINUS: {
1808fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1809fec19aadSdrh       assert( pLeft );
1810fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1811fec19aadSdrh         Token *p = &pLeft->token;
18129267bdceSdrh         char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
1813fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1814fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1815e6840900Sdrh         }else{
1816fec19aadSdrh           codeInteger(v, z, p->n+1);
1817e6840900Sdrh         }
18186e142f54Sdrh         sqliteFree(z);
18196e142f54Sdrh         break;
18206e142f54Sdrh       }
18211ccde15dSdrh       /* Fall through into TK_NOT */
18226e142f54Sdrh     }
1823bf4133cbSdrh     case TK_BITNOT:
18246e142f54Sdrh     case TK_NOT: {
1825f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1826f2bc013cSdrh       assert( TK_NOT==OP_Not );
18274adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18284adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1829ffe07b2dSdrh       stackChng = 0;
1830cce7d176Sdrh       break;
1831cce7d176Sdrh     }
1832cce7d176Sdrh     case TK_ISNULL:
1833cce7d176Sdrh     case TK_NOTNULL: {
1834cce7d176Sdrh       int dest;
1835f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1836f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
18374adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
18384adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18394adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
18404adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
18414adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1842ffe07b2dSdrh       stackChng = 0;
1843a37cdde0Sdanielk1977       break;
1844f2bc013cSdrh     }
18452282792aSdrh     case TK_AGG_FUNCTION: {
184613449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
18477e56e711Sdrh       if( pInfo==0 ){
18487e56e711Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
18497e56e711Sdrh             &pExpr->span);
18507e56e711Sdrh       }else{
185113449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
18527e56e711Sdrh       }
18532282792aSdrh       break;
18542282792aSdrh     }
1855b71090fdSdrh     case TK_CONST_FUNC:
1856cce7d176Sdrh     case TK_FUNCTION: {
1857cce7d176Sdrh       ExprList *pList = pExpr->pList;
185889425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
18590bce8354Sdrh       FuncDef *pDef;
18604b59ab5eSdrh       int nId;
18614b59ab5eSdrh       const char *zId;
186213449892Sdrh       int constMask = 0;
1863682f68b0Sdanielk1977       int i;
186414db2665Sdanielk1977       u8 enc = ENC(pParse->db);
1865dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
18662646da7eSdrh       zId = (char*)pExpr->token.z;
1867b71090fdSdrh       nId = pExpr->token.n;
1868d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
18690bce8354Sdrh       assert( pDef!=0 );
1870f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1871b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1872a43fa227Sdrh       /* Possibly overload the function if the first argument is
1873a43fa227Sdrh       ** a virtual table column.
1874a43fa227Sdrh       **
1875a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1876a43fa227Sdrh       ** second argument, not the first, as the argument to test to
1877a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
1878a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
1879a43fa227Sdrh       ** control overloading) ends up as the second argument to the
1880a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
1881a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
1882a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
1883a43fa227Sdrh       */
18846a03a1c5Sdrh       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
18856a03a1c5Sdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[1].pExpr);
18866a03a1c5Sdrh       }else if( nExpr>0 ){
1887b7f6f68fSdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[0].pExpr);
1888b7f6f68fSdrh       }
1889b7f6f68fSdrh #endif
1890682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1891d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
189213449892Sdrh           constMask |= (1<<i);
1893d02eb1fdSdanielk1977         }
1894dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1895dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1896dc1bdc4fSdanielk1977         }
1897dc1bdc4fSdanielk1977       }
1898dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1899dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1900d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1901682f68b0Sdanielk1977       }
190213449892Sdrh       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1903ffe07b2dSdrh       stackChng = 1-nExpr;
19046ec2733bSdrh       break;
19056ec2733bSdrh     }
1906fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1907fe2093d7Sdrh     case TK_EXISTS:
190819a775c2Sdrh     case TK_SELECT: {
190941714d6fSdrh       if( pExpr->iColumn==0 ){
1910b3bce662Sdanielk1977         sqlite3CodeSubselect(pParse, pExpr);
191141714d6fSdrh       }
19124adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1913ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
191419a775c2Sdrh       break;
191519a775c2Sdrh     }
1916fef5208cSdrh     case TK_IN: {
1917fef5208cSdrh       int addr;
191894a11211Sdrh       char affinity;
1919afa5f680Sdrh       int ckOffset = pParse->ckOffset;
1920b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
1921e014a838Sdanielk1977 
1922e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1923e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1924ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1925e014a838Sdanielk1977       */
192694a11211Sdrh       affinity = comparisonAffinity(pExpr);
1927e014a838Sdanielk1977 
19284adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1929*cdbd8effSdanielk1977       pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
1930e014a838Sdanielk1977 
1931e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1932e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1933e014a838Sdanielk1977       */
19344adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19354adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1936e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
19374adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
1938f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1939e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
194094a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
1941e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1942e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1943e014a838Sdanielk1977 
1944fef5208cSdrh       break;
1945fef5208cSdrh     }
194693758c8dSdanielk1977 #endif
1947fef5208cSdrh     case TK_BETWEEN: {
1948be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1949be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1950be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1951be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
19524adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1953be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1954be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
19554adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1956be5c89acSdrh       pLItem++;
1957be5c89acSdrh       pRight = pLItem->pExpr;
1958be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1959be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
19604adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1961fef5208cSdrh       break;
1962fef5208cSdrh     }
196351e9a445Sdrh     case TK_UPLUS:
1964a2e00042Sdrh     case TK_AS: {
19654adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1966ffe07b2dSdrh       stackChng = 0;
1967a2e00042Sdrh       break;
1968a2e00042Sdrh     }
196917a7f8ddSdrh     case TK_CASE: {
197017a7f8ddSdrh       int expr_end_label;
1971f5905aa7Sdrh       int jumpInst;
1972f5905aa7Sdrh       int nExpr;
197317a7f8ddSdrh       int i;
1974be5c89acSdrh       ExprList *pEList;
1975be5c89acSdrh       struct ExprList_item *aListelem;
197617a7f8ddSdrh 
197717a7f8ddSdrh       assert(pExpr->pList);
197817a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
197917a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1980be5c89acSdrh       pEList = pExpr->pList;
1981be5c89acSdrh       aListelem = pEList->a;
1982be5c89acSdrh       nExpr = pEList->nExpr;
19834adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
198417a7f8ddSdrh       if( pExpr->pLeft ){
19854adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1986cce7d176Sdrh       }
1987f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1988be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
198917a7f8ddSdrh         if( pExpr->pLeft ){
19904adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1991be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1992be5c89acSdrh                                  OP_Ne, 0, 1);
19934adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1994f5905aa7Sdrh         }else{
19954adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
199617a7f8ddSdrh         }
1997be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
19984adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
1999d654be80Sdrh         sqlite3VdbeJumpHere(v, jumpInst);
200017a7f8ddSdrh       }
2001f570f011Sdrh       if( pExpr->pLeft ){
20024adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2003f570f011Sdrh       }
200417a7f8ddSdrh       if( pExpr->pRight ){
20054adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
200617a7f8ddSdrh       }else{
2007f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
200817a7f8ddSdrh       }
20094adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
20106f34903eSdanielk1977       break;
20116f34903eSdanielk1977     }
20125338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
20136f34903eSdanielk1977     case TK_RAISE: {
20146f34903eSdanielk1977       if( !pParse->trigStack ){
20154adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
2016da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
20176f34903eSdanielk1977 	return;
20186f34903eSdanielk1977       }
2019ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
2020ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
20216f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
2022ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
2023d2687b77Sdrh          sqlite3DequoteExpr(pExpr);
20244adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
20252646da7eSdrh                         (char*)pExpr->token.z, pExpr->token.n);
20266f34903eSdanielk1977       } else {
20276f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
2028344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
2029ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
2030ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
20316f34903eSdanielk1977       }
2032ffe07b2dSdrh       stackChng = 0;
2033ffe07b2dSdrh       break;
203417a7f8ddSdrh     }
20355338a5f7Sdanielk1977 #endif
2036ffe07b2dSdrh   }
2037ffe07b2dSdrh 
2038ffe07b2dSdrh   if( pParse->ckOffset ){
2039ffe07b2dSdrh     pParse->ckOffset += stackChng;
2040ffe07b2dSdrh     assert( pParse->ckOffset );
204117a7f8ddSdrh   }
2042cce7d176Sdrh }
2043cce7d176Sdrh 
204493758c8dSdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
2045cce7d176Sdrh /*
204625303780Sdrh ** Generate code that evalutes the given expression and leaves the result
204725303780Sdrh ** on the stack.  See also sqlite3ExprCode().
204825303780Sdrh **
204925303780Sdrh ** This routine might also cache the result and modify the pExpr tree
205025303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
205125303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
205225303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
205325303780Sdrh ** memory location.
205425303780Sdrh */
205525303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
205625303780Sdrh   Vdbe *v = pParse->pVdbe;
205725303780Sdrh   int iMem;
205825303780Sdrh   int addr1, addr2;
205925303780Sdrh   if( v==0 ) return;
206025303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
206125303780Sdrh   sqlite3ExprCode(pParse, pExpr);
206225303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
206325303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
206425303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
206525303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
206625303780Sdrh     pExpr->op = TK_REGISTER;
206725303780Sdrh   }
206825303780Sdrh }
206993758c8dSdanielk1977 #endif
207025303780Sdrh 
207125303780Sdrh /*
2072268380caSdrh ** Generate code that pushes the value of every element of the given
2073f9b596ebSdrh ** expression list onto the stack.
2074268380caSdrh **
2075268380caSdrh ** Return the number of elements pushed onto the stack.
2076268380caSdrh */
20774adee20fSdanielk1977 int sqlite3ExprCodeExprList(
2078268380caSdrh   Parse *pParse,     /* Parsing context */
2079f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
2080268380caSdrh ){
2081268380caSdrh   struct ExprList_item *pItem;
2082268380caSdrh   int i, n;
2083268380caSdrh   if( pList==0 ) return 0;
2084268380caSdrh   n = pList->nExpr;
2085c182d163Sdrh   for(pItem=pList->a, i=n; i>0; i--, pItem++){
20864adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
2087268380caSdrh   }
2088f9b596ebSdrh   return n;
2089268380caSdrh }
2090268380caSdrh 
2091268380caSdrh /*
2092cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
2093cce7d176Sdrh ** to the label "dest" if the expression is true but execution
2094cce7d176Sdrh ** continues straight thru if the expression is false.
2095f5905aa7Sdrh **
2096f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
2097f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
2098f2bc013cSdrh **
2099f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
2100f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2101f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
2102f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
2103f2bc013cSdrh ** below verify that the numbers are aligned correctly.
2104cce7d176Sdrh */
21054adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2106cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2107cce7d176Sdrh   int op = 0;
2108ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2109daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2110f2bc013cSdrh   op = pExpr->op;
2111f2bc013cSdrh   switch( op ){
2112cce7d176Sdrh     case TK_AND: {
21134adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
21144adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
21154adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
21164adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2117cce7d176Sdrh       break;
2118cce7d176Sdrh     }
2119cce7d176Sdrh     case TK_OR: {
21204adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
21214adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2122cce7d176Sdrh       break;
2123cce7d176Sdrh     }
2124cce7d176Sdrh     case TK_NOT: {
21254adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2126cce7d176Sdrh       break;
2127cce7d176Sdrh     }
2128cce7d176Sdrh     case TK_LT:
2129cce7d176Sdrh     case TK_LE:
2130cce7d176Sdrh     case TK_GT:
2131cce7d176Sdrh     case TK_GE:
2132cce7d176Sdrh     case TK_NE:
21330ac65892Sdrh     case TK_EQ: {
2134f2bc013cSdrh       assert( TK_LT==OP_Lt );
2135f2bc013cSdrh       assert( TK_LE==OP_Le );
2136f2bc013cSdrh       assert( TK_GT==OP_Gt );
2137f2bc013cSdrh       assert( TK_GE==OP_Ge );
2138f2bc013cSdrh       assert( TK_EQ==OP_Eq );
2139f2bc013cSdrh       assert( TK_NE==OP_Ne );
21404adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
21414adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2142be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2143cce7d176Sdrh       break;
2144cce7d176Sdrh     }
2145cce7d176Sdrh     case TK_ISNULL:
2146cce7d176Sdrh     case TK_NOTNULL: {
2147f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
2148f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
21494adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
21504adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2151cce7d176Sdrh       break;
2152cce7d176Sdrh     }
2153fef5208cSdrh     case TK_BETWEEN: {
21540202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
21550202b29eSdanielk1977       **
21560202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
21570202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
21580202b29eSdanielk1977       ** 3 ...
21590202b29eSdanielk1977       */
2160f5905aa7Sdrh       int addr;
2161be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2162be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2163be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
21644adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2165be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2166be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
21670202b29eSdanielk1977 
2168be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2169be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2170be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
21710202b29eSdanielk1977 
21724adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2173d654be80Sdrh       sqlite3VdbeJumpHere(v, addr);
21744adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2175fef5208cSdrh       break;
2176fef5208cSdrh     }
2177cce7d176Sdrh     default: {
21784adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
21794adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
2180cce7d176Sdrh       break;
2181cce7d176Sdrh     }
2182cce7d176Sdrh   }
2183ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2184cce7d176Sdrh }
2185cce7d176Sdrh 
2186cce7d176Sdrh /*
218766b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
2188cce7d176Sdrh ** to the label "dest" if the expression is false but execution
2189cce7d176Sdrh ** continues straight thru if the expression is true.
2190f5905aa7Sdrh **
2191f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
2192f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
2193cce7d176Sdrh */
21944adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2195cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2196cce7d176Sdrh   int op = 0;
2197ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2198daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2199f2bc013cSdrh 
2200f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
2201f2bc013cSdrh   **
2202f2bc013cSdrh   **       pExpr->op            op
2203f2bc013cSdrh   **       ---------          ----------
2204f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
2205f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
2206f2bc013cSdrh   **       TK_NE              OP_Eq
2207f2bc013cSdrh   **       TK_EQ              OP_Ne
2208f2bc013cSdrh   **       TK_GT              OP_Le
2209f2bc013cSdrh   **       TK_LE              OP_Gt
2210f2bc013cSdrh   **       TK_GE              OP_Lt
2211f2bc013cSdrh   **       TK_LT              OP_Ge
2212f2bc013cSdrh   **
2213f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
2214f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
2215f2bc013cSdrh   ** can compute the mapping above using the following expression.
2216f2bc013cSdrh   ** Assert()s verify that the computation is correct.
2217f2bc013cSdrh   */
2218f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2219f2bc013cSdrh 
2220f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
2221f2bc013cSdrh   */
2222f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2223f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2224f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
2225f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
2226f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
2227f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
2228f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
2229f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
2230f2bc013cSdrh 
2231cce7d176Sdrh   switch( pExpr->op ){
2232cce7d176Sdrh     case TK_AND: {
22334adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
22344adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2235cce7d176Sdrh       break;
2236cce7d176Sdrh     }
2237cce7d176Sdrh     case TK_OR: {
22384adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
22394adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
22404adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
22414adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2242cce7d176Sdrh       break;
2243cce7d176Sdrh     }
2244cce7d176Sdrh     case TK_NOT: {
22454adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2246cce7d176Sdrh       break;
2247cce7d176Sdrh     }
2248cce7d176Sdrh     case TK_LT:
2249cce7d176Sdrh     case TK_LE:
2250cce7d176Sdrh     case TK_GT:
2251cce7d176Sdrh     case TK_GE:
2252cce7d176Sdrh     case TK_NE:
2253cce7d176Sdrh     case TK_EQ: {
22544adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
22554adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2256be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2257cce7d176Sdrh       break;
2258cce7d176Sdrh     }
2259cce7d176Sdrh     case TK_ISNULL:
2260cce7d176Sdrh     case TK_NOTNULL: {
22614adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
22624adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2263cce7d176Sdrh       break;
2264cce7d176Sdrh     }
2265fef5208cSdrh     case TK_BETWEEN: {
22660202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
22670202b29eSdanielk1977       **
22680202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
22690202b29eSdanielk1977       ** 2 GOTO <dest>
22700202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
22710202b29eSdanielk1977       */
2272fef5208cSdrh       int addr;
2273be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2274be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2275be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
22764adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2277be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
22784adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
2279be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2280be5c89acSdrh 
22814adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
22824adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2283be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2284be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2285be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2286fef5208cSdrh       break;
2287fef5208cSdrh     }
2288cce7d176Sdrh     default: {
22894adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
22904adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2291cce7d176Sdrh       break;
2292cce7d176Sdrh     }
2293cce7d176Sdrh   }
2294ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2295cce7d176Sdrh }
22962282792aSdrh 
22972282792aSdrh /*
22982282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
22992282792aSdrh ** if they are identical and return FALSE if they differ in any way.
2300d40aab0eSdrh **
2301d40aab0eSdrh ** Sometimes this routine will return FALSE even if the two expressions
2302d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
2303d40aab0eSdrh ** identical, we return FALSE just to be safe.  So if this routine
2304d40aab0eSdrh ** returns false, then you do not really know for certain if the two
2305d40aab0eSdrh ** expressions are the same.  But if you get a TRUE return, then you
2306d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
2307d40aab0eSdrh ** this routine is used, it does not hurt to get an extra FALSE - that
2308d40aab0eSdrh ** just might result in some slightly slower code.  But returning
2309d40aab0eSdrh ** an incorrect TRUE could lead to a malfunction.
23102282792aSdrh */
23114adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
23122282792aSdrh   int i;
23134b202ae2Sdanielk1977   if( pA==0||pB==0 ){
23144b202ae2Sdanielk1977     return pB==pA;
23152282792aSdrh   }
23162282792aSdrh   if( pA->op!=pB->op ) return 0;
2317fd357974Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
23184adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
23194adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
23202282792aSdrh   if( pA->pList ){
23212282792aSdrh     if( pB->pList==0 ) return 0;
23222282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
23232282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
23244adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
23252282792aSdrh         return 0;
23262282792aSdrh       }
23272282792aSdrh     }
23282282792aSdrh   }else if( pB->pList ){
23292282792aSdrh     return 0;
23302282792aSdrh   }
23312282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
23322f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
2333dd73521bSdrh   if( pA->op!=TK_COLUMN && pA->token.z ){
23342282792aSdrh     if( pB->token.z==0 ) return 0;
23356977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
23362646da7eSdrh     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
23372646da7eSdrh       return 0;
23382646da7eSdrh     }
23392282792aSdrh   }
23402282792aSdrh   return 1;
23412282792aSdrh }
23422282792aSdrh 
234313449892Sdrh 
23442282792aSdrh /*
234513449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
234613449892Sdrh ** the new element.  Return a negative number if malloc fails.
23472282792aSdrh */
234813449892Sdrh static int addAggInfoColumn(AggInfo *pInfo){
234913449892Sdrh   int i;
2350cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
2351cf643729Sdrh        pInfo->aCol,
2352cf643729Sdrh        sizeof(pInfo->aCol[0]),
2353cf643729Sdrh        3,
2354cf643729Sdrh        &pInfo->nColumn,
2355cf643729Sdrh        &pInfo->nColumnAlloc,
2356cf643729Sdrh        &i
2357cf643729Sdrh   );
235813449892Sdrh   return i;
23592282792aSdrh }
236013449892Sdrh 
236113449892Sdrh /*
236213449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
236313449892Sdrh ** the new element.  Return a negative number if malloc fails.
236413449892Sdrh */
236513449892Sdrh static int addAggInfoFunc(AggInfo *pInfo){
236613449892Sdrh   int i;
2367cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
2368cf643729Sdrh        pInfo->aFunc,
2369cf643729Sdrh        sizeof(pInfo->aFunc[0]),
2370cf643729Sdrh        3,
2371cf643729Sdrh        &pInfo->nFunc,
2372cf643729Sdrh        &pInfo->nFuncAlloc,
2373cf643729Sdrh        &i
2374cf643729Sdrh   );
237513449892Sdrh   return i;
23762282792aSdrh }
23772282792aSdrh 
23782282792aSdrh /*
2379626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
2380626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2381626a879aSdrh ** for additional information.
23822282792aSdrh **
2383626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
23842282792aSdrh */
2385626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
23862282792aSdrh   int i;
2387a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
2388a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
2389a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
239013449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
239113449892Sdrh 
23922282792aSdrh 
23932282792aSdrh   switch( pExpr->op ){
239489c69d00Sdrh     case TK_AGG_COLUMN:
2395967e8b73Sdrh     case TK_COLUMN: {
239613449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
239713449892Sdrh       ** clause of the aggregate query */
239813449892Sdrh       if( pSrcList ){
239913449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
240013449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
240113449892Sdrh           struct AggInfo_col *pCol;
240213449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
240313449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
240413449892Sdrh             ** that is in the FROM clause of the aggregate query.
240513449892Sdrh             **
240613449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
240713449892Sdrh             ** is not an entry there already.
240813449892Sdrh             */
24097f906d63Sdrh             int k;
241013449892Sdrh             pCol = pAggInfo->aCol;
24117f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
241213449892Sdrh               if( pCol->iTable==pExpr->iTable &&
241313449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
24142282792aSdrh                 break;
24152282792aSdrh               }
24162282792aSdrh             }
24177f906d63Sdrh             if( k>=pAggInfo->nColumn && (k = addAggInfoColumn(pAggInfo))>=0 ){
24187f906d63Sdrh               pCol = &pAggInfo->aCol[k];
24190817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
242013449892Sdrh               pCol->iTable = pExpr->iTable;
242113449892Sdrh               pCol->iColumn = pExpr->iColumn;
242213449892Sdrh               pCol->iMem = pParse->nMem++;
242313449892Sdrh               pCol->iSorterColumn = -1;
24245774b806Sdrh               pCol->pExpr = pExpr;
242513449892Sdrh               if( pAggInfo->pGroupBy ){
242613449892Sdrh                 int j, n;
242713449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
242813449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
242913449892Sdrh                 n = pGB->nExpr;
243013449892Sdrh                 for(j=0; j<n; j++, pTerm++){
243113449892Sdrh                   Expr *pE = pTerm->pExpr;
243213449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
243313449892Sdrh                       pE->iColumn==pExpr->iColumn ){
243413449892Sdrh                     pCol->iSorterColumn = j;
243513449892Sdrh                     break;
24362282792aSdrh                   }
243713449892Sdrh                 }
243813449892Sdrh               }
243913449892Sdrh               if( pCol->iSorterColumn<0 ){
244013449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
244113449892Sdrh               }
244213449892Sdrh             }
244313449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
244413449892Sdrh             ** because it was there before or because we just created it).
244513449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
244613449892Sdrh             ** pAggInfo->aCol[] entry.
244713449892Sdrh             */
244813449892Sdrh             pExpr->pAggInfo = pAggInfo;
244913449892Sdrh             pExpr->op = TK_AGG_COLUMN;
24507f906d63Sdrh             pExpr->iAgg = k;
245113449892Sdrh             break;
245213449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
245313449892Sdrh         } /* end loop over pSrcList */
2454a58fdfb1Sdanielk1977       }
2455626a879aSdrh       return 1;
24562282792aSdrh     }
24572282792aSdrh     case TK_AGG_FUNCTION: {
245813449892Sdrh       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
245913449892Sdrh       ** to be ignored */
2460a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
246113449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
246213449892Sdrh         ** function that is already in the pAggInfo structure
246313449892Sdrh         */
246413449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
246513449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
246613449892Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
24672282792aSdrh             break;
24682282792aSdrh           }
24692282792aSdrh         }
247013449892Sdrh         if( i>=pAggInfo->nFunc ){
247113449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
247213449892Sdrh           */
247314db2665Sdanielk1977           u8 enc = ENC(pParse->db);
247413449892Sdrh           i = addAggInfoFunc(pAggInfo);
247513449892Sdrh           if( i>=0 ){
247613449892Sdrh             pItem = &pAggInfo->aFunc[i];
247713449892Sdrh             pItem->pExpr = pExpr;
247813449892Sdrh             pItem->iMem = pParse->nMem++;
247913449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
24802646da7eSdrh                    (char*)pExpr->token.z, pExpr->token.n,
2481d8123366Sdanielk1977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2482fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
2483fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
2484fd357974Sdrh             }else{
2485fd357974Sdrh               pItem->iDistinct = -1;
2486fd357974Sdrh             }
24872282792aSdrh           }
248813449892Sdrh         }
248913449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
249013449892Sdrh         */
24912282792aSdrh         pExpr->iAgg = i;
249213449892Sdrh         pExpr->pAggInfo = pAggInfo;
2493626a879aSdrh         return 1;
24942282792aSdrh       }
24952282792aSdrh     }
2496a58fdfb1Sdanielk1977   }
249713449892Sdrh 
249813449892Sdrh   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
249913449892Sdrh   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
250013449892Sdrh   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
250113449892Sdrh   */
2502a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
2503a58fdfb1Sdanielk1977     pNC->nDepth++;
2504a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2505a58fdfb1Sdanielk1977     pNC->nDepth--;
2506a58fdfb1Sdanielk1977   }
2507626a879aSdrh   return 0;
25082282792aSdrh }
2509626a879aSdrh 
2510626a879aSdrh /*
2511626a879aSdrh ** Analyze the given expression looking for aggregate functions and
2512626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
2513626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
2514626a879aSdrh **
2515626a879aSdrh ** This routine should only be called after the expression has been
2516626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
2517626a879aSdrh **
2518626a879aSdrh ** If errors are seen, leave an error message in zErrMsg and return
2519626a879aSdrh ** the number of errors.
2520626a879aSdrh */
2521a58fdfb1Sdanielk1977 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2522a58fdfb1Sdanielk1977   int nErr = pNC->pParse->nErr;
2523a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
2524a58fdfb1Sdanielk1977   return pNC->pParse->nErr - nErr;
25252282792aSdrh }
25265d9a4af9Sdrh 
25275d9a4af9Sdrh /*
25285d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
25295d9a4af9Sdrh ** expression list.  Return the number of errors.
25305d9a4af9Sdrh **
25315d9a4af9Sdrh ** If an error is found, the analysis is cut short.
25325d9a4af9Sdrh */
25335d9a4af9Sdrh int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
25345d9a4af9Sdrh   struct ExprList_item *pItem;
25355d9a4af9Sdrh   int i;
25365d9a4af9Sdrh   int nErr = 0;
25375d9a4af9Sdrh   if( pList ){
25385d9a4af9Sdrh     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
25395d9a4af9Sdrh       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
25405d9a4af9Sdrh     }
25415d9a4af9Sdrh   }
25425d9a4af9Sdrh   return nErr;
25435d9a4af9Sdrh }
2544