xref: /sqlite-3.40.0/src/expr.c (revision 2eaf93d3)
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*2eaf93d3Sdrh ** $Id: expr.c,v 1.370 2008/04/29 00:15:21 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
1804738cb9Sdrh #include <ctype.h>
19a2e00042Sdrh 
20e014a838Sdanielk1977 /*
21e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
22e014a838Sdanielk1977 **
23e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
24e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
25e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
26e014a838Sdanielk1977 ** indicating no affinity for the expression.
27e014a838Sdanielk1977 **
28e014a838Sdanielk1977 ** i.e. the WHERE clause expresssions in the following statements all
29e014a838Sdanielk1977 ** have an affinity:
30e014a838Sdanielk1977 **
31e014a838Sdanielk1977 ** CREATE TABLE t1(a);
32e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
33e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
34e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
35e014a838Sdanielk1977 */
36bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
37487e262fSdrh   int op = pExpr->op;
38487e262fSdrh   if( op==TK_SELECT ){
39bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
40a37cdde0Sdanielk1977   }
41487e262fSdrh #ifndef SQLITE_OMIT_CAST
42487e262fSdrh   if( op==TK_CAST ){
438a51256cSdrh     return sqlite3AffinityType(&pExpr->token);
44487e262fSdrh   }
45487e262fSdrh #endif
46a37cdde0Sdanielk1977   return pExpr->affinity;
47a37cdde0Sdanielk1977 }
48a37cdde0Sdanielk1977 
4953db1458Sdrh /*
508b4c40d8Sdrh ** Set the collating sequence for expression pExpr to be the collating
518b4c40d8Sdrh ** sequence named by pToken.   Return a pointer to the revised expression.
52a34001c9Sdrh ** The collating sequence is marked as "explicit" using the EP_ExpCollate
53a34001c9Sdrh ** flag.  An explicit collating sequence will override implicit
54a34001c9Sdrh ** collating sequences.
558b4c40d8Sdrh */
568b4c40d8Sdrh Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
5739002505Sdanielk1977   char *zColl = 0;            /* Dequoted name of collation sequence */
588b4c40d8Sdrh   CollSeq *pColl;
5939002505Sdanielk1977   zColl = sqlite3NameFromToken(pParse->db, pName);
6039002505Sdanielk1977   if( pExpr && zColl ){
6139002505Sdanielk1977     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
628b4c40d8Sdrh     if( pColl ){
638b4c40d8Sdrh       pExpr->pColl = pColl;
648b4c40d8Sdrh       pExpr->flags |= EP_ExpCollate;
658b4c40d8Sdrh     }
6639002505Sdanielk1977   }
6739002505Sdanielk1977   sqlite3_free(zColl);
688b4c40d8Sdrh   return pExpr;
698b4c40d8Sdrh }
708b4c40d8Sdrh 
718b4c40d8Sdrh /*
720202b29eSdanielk1977 ** Return the default collation sequence for the expression pExpr. If
730202b29eSdanielk1977 ** there is no default collation type, return 0.
740202b29eSdanielk1977 */
757cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
767cedc8d4Sdanielk1977   CollSeq *pColl = 0;
770202b29eSdanielk1977   if( pExpr ){
787e09fe0bSdrh     int op;
797cedc8d4Sdanielk1977     pColl = pExpr->pColl;
807e09fe0bSdrh     op = pExpr->op;
817e09fe0bSdrh     if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
827cedc8d4Sdanielk1977       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
830202b29eSdanielk1977     }
840202b29eSdanielk1977   }
857cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
867cedc8d4Sdanielk1977     pColl = 0;
877cedc8d4Sdanielk1977   }
887cedc8d4Sdanielk1977   return pColl;
890202b29eSdanielk1977 }
900202b29eSdanielk1977 
910202b29eSdanielk1977 /*
92626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
93626a879aSdrh ** type affinity of the other operand.  This routine returns the
9453db1458Sdrh ** type affinity that should be used for the comparison operator.
9553db1458Sdrh */
96e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
97bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
98e014a838Sdanielk1977   if( aff1 && aff2 ){
998df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
1008df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
101e014a838Sdanielk1977     */
1028a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
103e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
104e014a838Sdanielk1977     }else{
105e014a838Sdanielk1977       return SQLITE_AFF_NONE;
106e014a838Sdanielk1977     }
107e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
1085f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
1095f6a87b3Sdrh     ** results directly.
110e014a838Sdanielk1977     */
1115f6a87b3Sdrh     return SQLITE_AFF_NONE;
112e014a838Sdanielk1977   }else{
113e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
114fe05af87Sdrh     assert( aff1==0 || aff2==0 );
115e014a838Sdanielk1977     return (aff1 + aff2);
116e014a838Sdanielk1977   }
117e014a838Sdanielk1977 }
118e014a838Sdanielk1977 
11953db1458Sdrh /*
12053db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
12153db1458Sdrh ** be applied to both operands prior to doing the comparison.
12253db1458Sdrh */
123e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
124e014a838Sdanielk1977   char aff;
125e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
126e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
127e014a838Sdanielk1977           pExpr->op==TK_NE );
128e014a838Sdanielk1977   assert( pExpr->pLeft );
129bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
130e014a838Sdanielk1977   if( pExpr->pRight ){
131e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
132e014a838Sdanielk1977   }
133e014a838Sdanielk1977   else if( pExpr->pSelect ){
134e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
135e014a838Sdanielk1977   }
136e014a838Sdanielk1977   else if( !aff ){
137de087bd5Sdrh     aff = SQLITE_AFF_NONE;
138e014a838Sdanielk1977   }
139e014a838Sdanielk1977   return aff;
140e014a838Sdanielk1977 }
141e014a838Sdanielk1977 
142e014a838Sdanielk1977 /*
143e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
144e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
145e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
146e014a838Sdanielk1977 ** the comparison in pExpr.
147e014a838Sdanielk1977 */
148e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
149e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
1508a51256cSdrh   switch( aff ){
1518a51256cSdrh     case SQLITE_AFF_NONE:
1528a51256cSdrh       return 1;
1538a51256cSdrh     case SQLITE_AFF_TEXT:
1548a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
1558a51256cSdrh     default:
1568a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
1578a51256cSdrh   }
158e014a838Sdanielk1977 }
159e014a838Sdanielk1977 
160a37cdde0Sdanielk1977 /*
16135573356Sdrh ** Return the P5 value that should be used for a binary comparison
162a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
163a37cdde0Sdanielk1977 */
16435573356Sdrh static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
16535573356Sdrh   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
16635573356Sdrh   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
16735573356Sdrh   return aff;
168a37cdde0Sdanielk1977 }
169a37cdde0Sdanielk1977 
170a2e00042Sdrh /*
1710202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
1720202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
1730202b29eSdanielk1977 **
1740202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
1750202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
1760202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
1770202b29eSdanielk1977 ** type.
178bcbb04e5Sdanielk1977 **
179bcbb04e5Sdanielk1977 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
180bcbb04e5Sdanielk1977 ** it is not considered.
1810202b29eSdanielk1977 */
182bcbb04e5Sdanielk1977 CollSeq *sqlite3BinaryCompareCollSeq(
183bcbb04e5Sdanielk1977   Parse *pParse,
184bcbb04e5Sdanielk1977   Expr *pLeft,
185bcbb04e5Sdanielk1977   Expr *pRight
186bcbb04e5Sdanielk1977 ){
187ec41ddacSdrh   CollSeq *pColl;
188ec41ddacSdrh   assert( pLeft );
189ec41ddacSdrh   if( pLeft->flags & EP_ExpCollate ){
190ec41ddacSdrh     assert( pLeft->pColl );
191ec41ddacSdrh     pColl = pLeft->pColl;
192bcbb04e5Sdanielk1977   }else if( pRight && pRight->flags & EP_ExpCollate ){
193ec41ddacSdrh     assert( pRight->pColl );
194ec41ddacSdrh     pColl = pRight->pColl;
195ec41ddacSdrh   }else{
196ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
1970202b29eSdanielk1977     if( !pColl ){
1987cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
1990202b29eSdanielk1977     }
200ec41ddacSdrh   }
2010202b29eSdanielk1977   return pColl;
2020202b29eSdanielk1977 }
2030202b29eSdanielk1977 
2040202b29eSdanielk1977 /*
205da250ea5Sdrh ** Generate the operands for a comparison operation.  Before
206da250ea5Sdrh ** generating the code for each operand, set the EP_AnyAff
207da250ea5Sdrh ** flag on the expression so that it will be able to used a
208da250ea5Sdrh ** cached column value that has previously undergone an
209da250ea5Sdrh ** affinity change.
210da250ea5Sdrh */
211da250ea5Sdrh static void codeCompareOperands(
212da250ea5Sdrh   Parse *pParse,    /* Parsing and code generating context */
213da250ea5Sdrh   Expr *pLeft,      /* The left operand */
214da250ea5Sdrh   int *pRegLeft,    /* Register where left operand is stored */
215da250ea5Sdrh   int *pFreeLeft,   /* Free this register when done */
216da250ea5Sdrh   Expr *pRight,     /* The right operand */
217da250ea5Sdrh   int *pRegRight,   /* Register where right operand is stored */
218da250ea5Sdrh   int *pFreeRight   /* Write temp register for right operand there */
219da250ea5Sdrh ){
220da250ea5Sdrh   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
221da250ea5Sdrh   pLeft->flags |= EP_AnyAff;
222da250ea5Sdrh   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
223da250ea5Sdrh   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
224da250ea5Sdrh   pRight->flags |= EP_AnyAff;
225da250ea5Sdrh   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
226da250ea5Sdrh }
227da250ea5Sdrh 
228da250ea5Sdrh /*
229be5c89acSdrh ** Generate code for a comparison operator.
230be5c89acSdrh */
231be5c89acSdrh static int codeCompare(
232be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
233be5c89acSdrh   Expr *pLeft,      /* The left operand */
234be5c89acSdrh   Expr *pRight,     /* The right operand */
235be5c89acSdrh   int opcode,       /* The comparison opcode */
23635573356Sdrh   int in1, int in2, /* Register holding operands */
237be5c89acSdrh   int dest,         /* Jump here if true.  */
238be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
239be5c89acSdrh ){
24035573356Sdrh   int p5;
24135573356Sdrh   int addr;
24235573356Sdrh   CollSeq *p4;
24335573356Sdrh 
24435573356Sdrh   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
24535573356Sdrh   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
24635573356Sdrh   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
24735573356Sdrh                            (void*)p4, P4_COLLSEQ);
24835573356Sdrh   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
2492f7794c1Sdrh   if( p5 & SQLITE_AFF_MASK ){
250da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
251da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
2522f7794c1Sdrh   }
25335573356Sdrh   return addr;
254be5c89acSdrh }
255be5c89acSdrh 
256be5c89acSdrh /*
257a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
25817435752Sdrh ** for this node is obtained from sqlite3_malloc().  The calling function
259a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
260a76b5dfcSdrh */
26117435752Sdrh Expr *sqlite3Expr(
262a1644fd8Sdanielk1977   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
26317435752Sdrh   int op,                 /* Expression opcode */
26417435752Sdrh   Expr *pLeft,            /* Left operand */
26517435752Sdrh   Expr *pRight,           /* Right operand */
26617435752Sdrh   const Token *pToken     /* Argument token */
26717435752Sdrh ){
268a76b5dfcSdrh   Expr *pNew;
2695c070538Sdrh   static const Expr zeroExpr;
2705c070538Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(Expr));
271a76b5dfcSdrh   if( pNew==0 ){
272d5d56523Sdanielk1977     /* When malloc fails, delete pLeft and pRight. Expressions passed to
273d5d56523Sdanielk1977     ** this function must always be allocated with sqlite3Expr() for this
274d5d56523Sdanielk1977     ** reason.
275d5d56523Sdanielk1977     */
276d5d56523Sdanielk1977     sqlite3ExprDelete(pLeft);
277d5d56523Sdanielk1977     sqlite3ExprDelete(pRight);
278a76b5dfcSdrh     return 0;
279a76b5dfcSdrh   }
2805c070538Sdrh   *pNew = zeroExpr;
281a76b5dfcSdrh   pNew->op = op;
282a76b5dfcSdrh   pNew->pLeft = pLeft;
283a76b5dfcSdrh   pNew->pRight = pRight;
284a58fdfb1Sdanielk1977   pNew->iAgg = -1;
285a76b5dfcSdrh   if( pToken ){
2864b59ab5eSdrh     assert( pToken->dyn==0 );
287145716b3Sdrh     pNew->span = pNew->token = *pToken;
288a34001c9Sdrh   }else if( pLeft ){
289a34001c9Sdrh     if( pRight ){
2904adee20fSdanielk1977       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
2915ffb3ac8Sdrh       if( pRight->flags & EP_ExpCollate ){
292a34001c9Sdrh         pNew->flags |= EP_ExpCollate;
293a34001c9Sdrh         pNew->pColl = pRight->pColl;
294a34001c9Sdrh       }
295a34001c9Sdrh     }
2965ffb3ac8Sdrh     if( pLeft->flags & EP_ExpCollate ){
297a34001c9Sdrh       pNew->flags |= EP_ExpCollate;
298a34001c9Sdrh       pNew->pColl = pLeft->pColl;
299a34001c9Sdrh     }
300a76b5dfcSdrh   }
301fc976065Sdanielk1977 
302fc976065Sdanielk1977   sqlite3ExprSetHeight(pNew);
303a76b5dfcSdrh   return pNew;
304a76b5dfcSdrh }
305a76b5dfcSdrh 
306a76b5dfcSdrh /*
30717435752Sdrh ** Works like sqlite3Expr() except that it takes an extra Parse*
30817435752Sdrh ** argument and notifies the associated connection object if malloc fails.
309206f3d96Sdrh */
31017435752Sdrh Expr *sqlite3PExpr(
31117435752Sdrh   Parse *pParse,          /* Parsing context */
31217435752Sdrh   int op,                 /* Expression opcode */
31317435752Sdrh   Expr *pLeft,            /* Left operand */
31417435752Sdrh   Expr *pRight,           /* Right operand */
31517435752Sdrh   const Token *pToken     /* Argument token */
31617435752Sdrh ){
317a1644fd8Sdanielk1977   return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
318206f3d96Sdrh }
319206f3d96Sdrh 
320206f3d96Sdrh /*
3214e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
322b7654111Sdrh ** that look like this:   #1 #2 ...  These terms refer to registers
323b7654111Sdrh ** in the virtual machine.  #N is the N-th register.
3244e0cff60Sdrh **
3254e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
3264e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
3274e0cff60Sdrh ** The returns an expression that will code to extract the value from
3284e0cff60Sdrh ** that memory location as needed.
3294e0cff60Sdrh */
3304e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
3314e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
3324e0cff60Sdrh   Expr *p;
3334e0cff60Sdrh   if( pParse->nested==0 ){
3344e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
335a1644fd8Sdanielk1977     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
3364e0cff60Sdrh   }
337bb7ac00bSdrh   if( v==0 ) return 0;
338a1644fd8Sdanielk1977   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
33973c42a13Sdrh   if( p==0 ){
34073c42a13Sdrh     return 0;  /* Malloc failed */
34173c42a13Sdrh   }
342b7654111Sdrh   p->iTable = atoi((char*)&pToken->z[1]);
3434e0cff60Sdrh   return p;
3444e0cff60Sdrh }
3454e0cff60Sdrh 
3464e0cff60Sdrh /*
34791bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
34891bb0eedSdrh ** NULL, then just return the other expression.
34991bb0eedSdrh */
3501e536953Sdanielk1977 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
35191bb0eedSdrh   if( pLeft==0 ){
35291bb0eedSdrh     return pRight;
35391bb0eedSdrh   }else if( pRight==0 ){
35491bb0eedSdrh     return pLeft;
35591bb0eedSdrh   }else{
356880c15beSdanielk1977     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
35791bb0eedSdrh   }
35891bb0eedSdrh }
35991bb0eedSdrh 
36091bb0eedSdrh /*
3616977fea8Sdrh ** Set the Expr.span field of the given expression to span all
362a76b5dfcSdrh ** text between the two given tokens.
363a76b5dfcSdrh */
3644adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
3654efc4754Sdrh   assert( pRight!=0 );
3664efc4754Sdrh   assert( pLeft!=0 );
367f3a65f7eSdrh   if( pExpr && pRight->z && pLeft->z ){
368ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
369145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
3706977fea8Sdrh       pExpr->span.z = pLeft->z;
37197903fefSdrh       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
3724b59ab5eSdrh     }else{
3736977fea8Sdrh       pExpr->span.z = 0;
3744b59ab5eSdrh     }
375a76b5dfcSdrh   }
376a76b5dfcSdrh }
377a76b5dfcSdrh 
378a76b5dfcSdrh /*
379a76b5dfcSdrh ** Construct a new expression node for a function with multiple
380a76b5dfcSdrh ** arguments.
381a76b5dfcSdrh */
38217435752Sdrh Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
383a76b5dfcSdrh   Expr *pNew;
3844b202ae2Sdanielk1977   assert( pToken );
38517435752Sdrh   pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) );
386a76b5dfcSdrh   if( pNew==0 ){
387d5d56523Sdanielk1977     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
388a76b5dfcSdrh     return 0;
389a76b5dfcSdrh   }
390a76b5dfcSdrh   pNew->op = TK_FUNCTION;
391a76b5dfcSdrh   pNew->pList = pList;
3924b59ab5eSdrh   assert( pToken->dyn==0 );
393a76b5dfcSdrh   pNew->token = *pToken;
3946977fea8Sdrh   pNew->span = pNew->token;
395fc976065Sdanielk1977 
396fc976065Sdanielk1977   sqlite3ExprSetHeight(pNew);
397a76b5dfcSdrh   return pNew;
398a76b5dfcSdrh }
399a76b5dfcSdrh 
400a76b5dfcSdrh /*
401fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
402fa6bc000Sdrh ** in the original SQL statement.
403fa6bc000Sdrh **
404fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
405fa6bc000Sdrh ** variable number.
406fa6bc000Sdrh **
407fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
408fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
409fa6bc000Sdrh ** the SQL statement comes from an external source.
410fa6bc000Sdrh **
411fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
412fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
413fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
414fa6bc000Sdrh ** assigned.
415fa6bc000Sdrh */
416fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
417fa6bc000Sdrh   Token *pToken;
41817435752Sdrh   sqlite3 *db = pParse->db;
41917435752Sdrh 
420fa6bc000Sdrh   if( pExpr==0 ) return;
421fa6bc000Sdrh   pToken = &pExpr->token;
422fa6bc000Sdrh   assert( pToken->n>=1 );
423fa6bc000Sdrh   assert( pToken->z!=0 );
424fa6bc000Sdrh   assert( pToken->z[0]!=0 );
425fa6bc000Sdrh   if( pToken->n==1 ){
426fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
427fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
428fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
429fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
430fa6bc000Sdrh     ** use it as the variable number */
431fa6bc000Sdrh     int i;
4322646da7eSdrh     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
433c5499befSdrh     testcase( i==0 );
434c5499befSdrh     testcase( i==1 );
435c5499befSdrh     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
436c5499befSdrh     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
437bb4957f8Sdrh     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
438fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
439bb4957f8Sdrh           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
440fa6bc000Sdrh     }
441fa6bc000Sdrh     if( i>pParse->nVar ){
442fa6bc000Sdrh       pParse->nVar = i;
443fa6bc000Sdrh     }
444fa6bc000Sdrh   }else{
445fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
446fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
447fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
448fa6bc000Sdrh     */
449fa6bc000Sdrh     int i, n;
450fa6bc000Sdrh     n = pToken->n;
451fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
452fa6bc000Sdrh       Expr *pE;
453fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
454fa6bc000Sdrh           && pE->token.n==n
455fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
456fa6bc000Sdrh         pExpr->iTable = pE->iTable;
457fa6bc000Sdrh         break;
458fa6bc000Sdrh       }
459fa6bc000Sdrh     }
460fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
461fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
462fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
463fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
46417435752Sdrh         pParse->apVarExpr =
46517435752Sdrh             sqlite3DbReallocOrFree(
46617435752Sdrh               db,
46717435752Sdrh               pParse->apVarExpr,
46817435752Sdrh               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
46917435752Sdrh             );
470fa6bc000Sdrh       }
47117435752Sdrh       if( !db->mallocFailed ){
472fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
473fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
474fa6bc000Sdrh       }
475fa6bc000Sdrh     }
476fa6bc000Sdrh   }
477bb4957f8Sdrh   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
478832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
479832b2664Sdanielk1977   }
480fa6bc000Sdrh }
481fa6bc000Sdrh 
482fa6bc000Sdrh /*
483a2e00042Sdrh ** Recursively delete an expression tree.
484a2e00042Sdrh */
4854adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
486a2e00042Sdrh   if( p==0 ) return;
48717435752Sdrh   if( p->span.dyn ) sqlite3_free((char*)p->span.z);
48817435752Sdrh   if( p->token.dyn ) sqlite3_free((char*)p->token.z);
4894adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
4904adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
4914adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
4924adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
49317435752Sdrh   sqlite3_free(p);
494a2e00042Sdrh }
495a2e00042Sdrh 
496d2687b77Sdrh /*
497d2687b77Sdrh ** The Expr.token field might be a string literal that is quoted.
498d2687b77Sdrh ** If so, remove the quotation marks.
499d2687b77Sdrh */
50017435752Sdrh void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
501d2687b77Sdrh   if( ExprHasAnyProperty(p, EP_Dequoted) ){
502d2687b77Sdrh     return;
503d2687b77Sdrh   }
504d2687b77Sdrh   ExprSetProperty(p, EP_Dequoted);
505d2687b77Sdrh   if( p->token.dyn==0 ){
50617435752Sdrh     sqlite3TokenCopy(db, &p->token, &p->token);
507d2687b77Sdrh   }
508d2687b77Sdrh   sqlite3Dequote((char*)p->token.z);
509d2687b77Sdrh }
510d2687b77Sdrh 
511a76b5dfcSdrh 
512a76b5dfcSdrh /*
513ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
514ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
515ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
516ff78bd2fSdrh ** without effecting the originals.
517ff78bd2fSdrh **
5184adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
5194adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
520ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
521ff78bd2fSdrh **
522ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
523ff78bd2fSdrh */
5241e536953Sdanielk1977 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
525ff78bd2fSdrh   Expr *pNew;
526ff78bd2fSdrh   if( p==0 ) return 0;
52717435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
528ff78bd2fSdrh   if( pNew==0 ) return 0;
5293b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
5306977fea8Sdrh   if( p->token.z!=0 ){
53117435752Sdrh     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
5324b59ab5eSdrh     pNew->token.dyn = 1;
5334b59ab5eSdrh   }else{
5344efc4754Sdrh     assert( pNew->token.z==0 );
5354b59ab5eSdrh   }
5366977fea8Sdrh   pNew->span.z = 0;
53717435752Sdrh   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
53817435752Sdrh   pNew->pRight = sqlite3ExprDup(db, p->pRight);
53917435752Sdrh   pNew->pList = sqlite3ExprListDup(db, p->pList);
54017435752Sdrh   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
541ff78bd2fSdrh   return pNew;
542ff78bd2fSdrh }
54317435752Sdrh void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
54417435752Sdrh   if( pTo->dyn ) sqlite3_free((char*)pTo->z);
5454b59ab5eSdrh   if( pFrom->z ){
5464b59ab5eSdrh     pTo->n = pFrom->n;
54717435752Sdrh     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
5484b59ab5eSdrh     pTo->dyn = 1;
5494b59ab5eSdrh   }else{
5504b59ab5eSdrh     pTo->z = 0;
5514b59ab5eSdrh   }
5524b59ab5eSdrh }
55317435752Sdrh ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
554ff78bd2fSdrh   ExprList *pNew;
555145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
556ff78bd2fSdrh   int i;
557ff78bd2fSdrh   if( p==0 ) return 0;
55817435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
559ff78bd2fSdrh   if( pNew==0 ) return 0;
56031dad9daSdanielk1977   pNew->iECursor = 0;
5614305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
56217435752Sdrh   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
563e0048400Sdanielk1977   if( pItem==0 ){
56417435752Sdrh     sqlite3_free(pNew);
565e0048400Sdanielk1977     return 0;
566e0048400Sdanielk1977   }
567145716b3Sdrh   pOldItem = p->a;
568145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
5694b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
57017435752Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
5716977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
5726977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
5734b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
5744b59ab5eSdrh       ** the names of columns in the result set needs this information */
57517435752Sdrh       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
5764b59ab5eSdrh     }
5771f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
5786f7adc8aSdrh             || pOldExpr->span.z==0
57917435752Sdrh             || db->mallocFailed );
58017435752Sdrh     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
581145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
582145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
5833e7bc9caSdrh     pItem->done = 0;
584ff78bd2fSdrh   }
585ff78bd2fSdrh   return pNew;
586ff78bd2fSdrh }
58793758c8dSdanielk1977 
58893758c8dSdanielk1977 /*
58993758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
59093758c8dSdanielk1977 ** the build, then none of the following routines, except for
59193758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
59293758c8dSdanielk1977 ** called with a NULL argument.
59393758c8dSdanielk1977 */
5946a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
5956a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
59617435752Sdrh SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
597ad3cab52Sdrh   SrcList *pNew;
598ad3cab52Sdrh   int i;
599113088ecSdrh   int nByte;
600ad3cab52Sdrh   if( p==0 ) return 0;
601113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
60217435752Sdrh   pNew = sqlite3DbMallocRaw(db, nByte );
603ad3cab52Sdrh   if( pNew==0 ) return 0;
6044305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
605ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
6064efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
6074efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
608ed8a3bb1Sdrh     Table *pTab;
60917435752Sdrh     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
61017435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61117435752Sdrh     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
6124efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
6134efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
6141787ccabSdanielk1977     pNewItem->isPopulated = pOldItem->isPopulated;
615ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
616ed8a3bb1Sdrh     if( pTab ){
617ed8a3bb1Sdrh       pTab->nRef++;
618a1cb183dSdanielk1977     }
61917435752Sdrh     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
62017435752Sdrh     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
62117435752Sdrh     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
6226c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
623ad3cab52Sdrh   }
624ad3cab52Sdrh   return pNew;
625ad3cab52Sdrh }
62617435752Sdrh IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
627ff78bd2fSdrh   IdList *pNew;
628ff78bd2fSdrh   int i;
629ff78bd2fSdrh   if( p==0 ) return 0;
63017435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
631ff78bd2fSdrh   if( pNew==0 ) return 0;
6324305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
63317435752Sdrh   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
634d5d56523Sdanielk1977   if( pNew->a==0 ){
63517435752Sdrh     sqlite3_free(pNew);
636d5d56523Sdanielk1977     return 0;
637d5d56523Sdanielk1977   }
638ff78bd2fSdrh   for(i=0; i<p->nId; i++){
6394efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
6404efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
64117435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
6424efc4754Sdrh     pNewItem->idx = pOldItem->idx;
643ff78bd2fSdrh   }
644ff78bd2fSdrh   return pNew;
645ff78bd2fSdrh }
64617435752Sdrh Select *sqlite3SelectDup(sqlite3 *db, Select *p){
647ff78bd2fSdrh   Select *pNew;
648ff78bd2fSdrh   if( p==0 ) return 0;
64917435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
650ff78bd2fSdrh   if( pNew==0 ) return 0;
651ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
65217435752Sdrh   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
65317435752Sdrh   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
65417435752Sdrh   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
65517435752Sdrh   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
65617435752Sdrh   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
65717435752Sdrh   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
658ff78bd2fSdrh   pNew->op = p->op;
65917435752Sdrh   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
66017435752Sdrh   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
66117435752Sdrh   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
6627b58daeaSdrh   pNew->iLimit = -1;
6637b58daeaSdrh   pNew->iOffset = -1;
664a1cb183dSdanielk1977   pNew->isResolved = p->isResolved;
665a1cb183dSdanielk1977   pNew->isAgg = p->isAgg;
666b9bb7c18Sdrh   pNew->usesEphm = 0;
6678e647b81Sdrh   pNew->disallowOrderBy = 0;
6680342b1f5Sdrh   pNew->pRightmost = 0;
669b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
670b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
671b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
672ff78bd2fSdrh   return pNew;
673ff78bd2fSdrh }
67493758c8dSdanielk1977 #else
67517435752Sdrh Select *sqlite3SelectDup(sqlite3 *db, Select *p){
67693758c8dSdanielk1977   assert( p==0 );
67793758c8dSdanielk1977   return 0;
67893758c8dSdanielk1977 }
67993758c8dSdanielk1977 #endif
680ff78bd2fSdrh 
681ff78bd2fSdrh 
682ff78bd2fSdrh /*
683a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
684a76b5dfcSdrh ** initially NULL, then create a new expression list.
685a76b5dfcSdrh */
68617435752Sdrh ExprList *sqlite3ExprListAppend(
68717435752Sdrh   Parse *pParse,          /* Parsing context */
68817435752Sdrh   ExprList *pList,        /* List to which to append. Might be NULL */
68917435752Sdrh   Expr *pExpr,            /* Expression to be appended */
69017435752Sdrh   Token *pName            /* AS keyword for the expression */
69117435752Sdrh ){
69217435752Sdrh   sqlite3 *db = pParse->db;
693a76b5dfcSdrh   if( pList==0 ){
69417435752Sdrh     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
695a76b5dfcSdrh     if( pList==0 ){
696d5d56523Sdanielk1977       goto no_mem;
697a76b5dfcSdrh     }
6984efc4754Sdrh     assert( pList->nAlloc==0 );
699a76b5dfcSdrh   }
7004305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
701d5d56523Sdanielk1977     struct ExprList_item *a;
702d5d56523Sdanielk1977     int n = pList->nAlloc*2 + 4;
70326783a58Sdanielk1977     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
704d5d56523Sdanielk1977     if( a==0 ){
705d5d56523Sdanielk1977       goto no_mem;
706a76b5dfcSdrh     }
707d5d56523Sdanielk1977     pList->a = a;
708d5d56523Sdanielk1977     pList->nAlloc = n;
709a76b5dfcSdrh   }
7104efc4754Sdrh   assert( pList->a!=0 );
7114efc4754Sdrh   if( pExpr || pName ){
7124efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
7134efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
71417435752Sdrh     pItem->zName = sqlite3NameFromToken(db, pName);
715e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
716a76b5dfcSdrh   }
717a76b5dfcSdrh   return pList;
718d5d56523Sdanielk1977 
719d5d56523Sdanielk1977 no_mem:
720d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
721d5d56523Sdanielk1977   sqlite3ExprDelete(pExpr);
722d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
723d5d56523Sdanielk1977   return 0;
724a76b5dfcSdrh }
725a76b5dfcSdrh 
726a76b5dfcSdrh /*
7277a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
7287a15a4beSdanielk1977 ** leave an error message in pParse.
7297a15a4beSdanielk1977 */
7307a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
7317a15a4beSdanielk1977   Parse *pParse,
7327a15a4beSdanielk1977   ExprList *pEList,
7337a15a4beSdanielk1977   const char *zObject
7347a15a4beSdanielk1977 ){
735b1a6c3c1Sdrh   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
736c5499befSdrh   testcase( pEList && pEList->nExpr==mx );
737c5499befSdrh   testcase( pEList && pEList->nExpr==mx+1 );
738b1a6c3c1Sdrh   if( pEList && pEList->nExpr>mx ){
7397a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
7407a15a4beSdanielk1977   }
7417a15a4beSdanielk1977 }
7427a15a4beSdanielk1977 
743fc976065Sdanielk1977 
744fc976065Sdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
745fc976065Sdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
746fc976065Sdanielk1977 ** of any expression tree referenced by the structure passed as the
747fc976065Sdanielk1977 ** first argument.
748fc976065Sdanielk1977 **
749fc976065Sdanielk1977 ** If this maximum height is greater than the current value pointed
750fc976065Sdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
751fc976065Sdanielk1977 ** value.
752fc976065Sdanielk1977 */
753fc976065Sdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
754fc976065Sdanielk1977   if( p ){
755fc976065Sdanielk1977     if( p->nHeight>*pnHeight ){
756fc976065Sdanielk1977       *pnHeight = p->nHeight;
757fc976065Sdanielk1977     }
758fc976065Sdanielk1977   }
759fc976065Sdanielk1977 }
760fc976065Sdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
761fc976065Sdanielk1977   if( p ){
762fc976065Sdanielk1977     int i;
763fc976065Sdanielk1977     for(i=0; i<p->nExpr; i++){
764fc976065Sdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
765fc976065Sdanielk1977     }
766fc976065Sdanielk1977   }
767fc976065Sdanielk1977 }
768fc976065Sdanielk1977 static void heightOfSelect(Select *p, int *pnHeight){
769fc976065Sdanielk1977   if( p ){
770fc976065Sdanielk1977     heightOfExpr(p->pWhere, pnHeight);
771fc976065Sdanielk1977     heightOfExpr(p->pHaving, pnHeight);
772fc976065Sdanielk1977     heightOfExpr(p->pLimit, pnHeight);
773fc976065Sdanielk1977     heightOfExpr(p->pOffset, pnHeight);
774fc976065Sdanielk1977     heightOfExprList(p->pEList, pnHeight);
775fc976065Sdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
776fc976065Sdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
777fc976065Sdanielk1977     heightOfSelect(p->pPrior, pnHeight);
778fc976065Sdanielk1977   }
779fc976065Sdanielk1977 }
780fc976065Sdanielk1977 
781fc976065Sdanielk1977 /*
782fc976065Sdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
783fc976065Sdanielk1977 ** argument. An expression with no children, Expr.pList or
784fc976065Sdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
785fc976065Sdanielk1977 ** has a height equal to the maximum height of any other
786fc976065Sdanielk1977 ** referenced Expr plus one.
787fc976065Sdanielk1977 */
788fc976065Sdanielk1977 void sqlite3ExprSetHeight(Expr *p){
789fc976065Sdanielk1977   int nHeight = 0;
790fc976065Sdanielk1977   heightOfExpr(p->pLeft, &nHeight);
791fc976065Sdanielk1977   heightOfExpr(p->pRight, &nHeight);
792fc976065Sdanielk1977   heightOfExprList(p->pList, &nHeight);
793fc976065Sdanielk1977   heightOfSelect(p->pSelect, &nHeight);
794fc976065Sdanielk1977   p->nHeight = nHeight + 1;
795fc976065Sdanielk1977 }
796fc976065Sdanielk1977 
797fc976065Sdanielk1977 /*
798fc976065Sdanielk1977 ** Return the maximum height of any expression tree referenced
799fc976065Sdanielk1977 ** by the select statement passed as an argument.
800fc976065Sdanielk1977 */
801fc976065Sdanielk1977 int sqlite3SelectExprHeight(Select *p){
802fc976065Sdanielk1977   int nHeight = 0;
803fc976065Sdanielk1977   heightOfSelect(p, &nHeight);
804fc976065Sdanielk1977   return nHeight;
805fc976065Sdanielk1977 }
806fc976065Sdanielk1977 
8077a15a4beSdanielk1977 /*
808a76b5dfcSdrh ** Delete an entire expression list.
809a76b5dfcSdrh */
8104adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
811a76b5dfcSdrh   int i;
812be5c89acSdrh   struct ExprList_item *pItem;
813a76b5dfcSdrh   if( pList==0 ) return;
8141bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
8151bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
816be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
817be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
81817435752Sdrh     sqlite3_free(pItem->zName);
819a76b5dfcSdrh   }
82017435752Sdrh   sqlite3_free(pList->a);
82117435752Sdrh   sqlite3_free(pList);
822a76b5dfcSdrh }
823a76b5dfcSdrh 
824a76b5dfcSdrh /*
825678ccce8Sdrh ** Walk an expression tree.  Call xFunc for each node visited.  xFunc
826678ccce8Sdrh ** is called on the node before xFunc is called on the nodes children.
82773b211abSdrh **
828626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
829626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
830626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
831626a879aSdrh ** the tree walk completely.
832626a879aSdrh **
833626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
834626a879aSdrh ** and 0 to continue.
83587abf5c0Sdrh **
83687abf5c0Sdrh ** NOTICE:  This routine does *not* descend into subqueries.
837626a879aSdrh */
838a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
839626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
840626a879aSdrh   int rc;
841626a879aSdrh   if( pExpr==0 ) return 0;
842626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
843626a879aSdrh   if( rc==0 ){
844626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
845626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
846a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
847626a879aSdrh   }
848626a879aSdrh   return rc>1;
849626a879aSdrh }
850626a879aSdrh 
851626a879aSdrh /*
852a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
853a58fdfb1Sdanielk1977 */
854a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
855a58fdfb1Sdanielk1977   int i;
856a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
857a58fdfb1Sdanielk1977   if( !p ) return 0;
858a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
859a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
860a58fdfb1Sdanielk1977   }
861a58fdfb1Sdanielk1977   return 0;
862a58fdfb1Sdanielk1977 }
863a58fdfb1Sdanielk1977 
864a58fdfb1Sdanielk1977 /*
865a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
866a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
867a58fdfb1Sdanielk1977 ** or OFFSET expressions..
868a58fdfb1Sdanielk1977 */
869a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
870a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
871a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
872a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
873a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
874a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
87515d7982aSdanielk1977   if( p->pPrior ){
87615d7982aSdanielk1977     walkSelectExpr(p->pPrior, xFunc, pArg);
87715d7982aSdanielk1977   }
878a58fdfb1Sdanielk1977   return 0;
879a58fdfb1Sdanielk1977 }
880a58fdfb1Sdanielk1977 
881a58fdfb1Sdanielk1977 
882a58fdfb1Sdanielk1977 /*
883626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
884626a879aSdrh **
885626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
88673b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
88773b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
88873b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
88973b211abSdrh ** then do nothing.
89073b211abSdrh **
89173b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
89273b211abSdrh ** the expression as constant, then we assume the whole expression
89373b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
894626a879aSdrh */
895626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
8960a168377Sdrh   int *pN = (int*)pArg;
8970a168377Sdrh 
8980a168377Sdrh   /* If *pArg is 3 then any term of the expression that comes from
8990a168377Sdrh   ** the ON or USING clauses of a join disqualifies the expression
9000a168377Sdrh   ** from being considered constant. */
9010a168377Sdrh   if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
9020a168377Sdrh     *pN = 0;
9030a168377Sdrh     return 2;
9040a168377Sdrh   }
9050a168377Sdrh 
906626a879aSdrh   switch( pExpr->op ){
907eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
908eb55bd2fSdrh     ** and *pArg==2 */
909eb55bd2fSdrh     case TK_FUNCTION:
9100a168377Sdrh       if( (*pN)==2 ) return 0;
911eb55bd2fSdrh       /* Fall through */
912626a879aSdrh     case TK_ID:
913626a879aSdrh     case TK_COLUMN:
914626a879aSdrh     case TK_DOT:
915626a879aSdrh     case TK_AGG_FUNCTION:
91613449892Sdrh     case TK_AGG_COLUMN:
917fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
918fe2093d7Sdrh     case TK_SELECT:
919fe2093d7Sdrh     case TK_EXISTS:
920c5499befSdrh       testcase( pExpr->op==TK_SELECT );
921c5499befSdrh       testcase( pExpr->op==TK_EXISTS );
922fe2093d7Sdrh #endif
923c5499befSdrh       testcase( pExpr->op==TK_ID );
924c5499befSdrh       testcase( pExpr->op==TK_COLUMN );
925c5499befSdrh       testcase( pExpr->op==TK_DOT );
926c5499befSdrh       testcase( pExpr->op==TK_AGG_FUNCTION );
927c5499befSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
9280a168377Sdrh       *pN = 0;
929626a879aSdrh       return 2;
93087abf5c0Sdrh     case TK_IN:
93187abf5c0Sdrh       if( pExpr->pSelect ){
9320a168377Sdrh         *pN = 0;
93387abf5c0Sdrh         return 2;
93487abf5c0Sdrh       }
935626a879aSdrh     default:
936626a879aSdrh       return 0;
937626a879aSdrh   }
938626a879aSdrh }
939626a879aSdrh 
940626a879aSdrh /*
941fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
942eb55bd2fSdrh ** and 0 if it involves variables or function calls.
9432398937bSdrh **
9442398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
9452398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
9462398937bSdrh ** a constant.
947fef5208cSdrh */
9484adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
949626a879aSdrh   int isConst = 1;
950626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
951626a879aSdrh   return isConst;
952fef5208cSdrh }
953fef5208cSdrh 
954fef5208cSdrh /*
955eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
9560a168377Sdrh ** that does no originate from the ON or USING clauses of a join.
9570a168377Sdrh ** Return 0 if it involves variables or function calls or terms from
9580a168377Sdrh ** an ON or USING clause.
9590a168377Sdrh */
9600a168377Sdrh int sqlite3ExprIsConstantNotJoin(Expr *p){
9610a168377Sdrh   int isConst = 3;
9620a168377Sdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
9630a168377Sdrh   return isConst!=0;
9640a168377Sdrh }
9650a168377Sdrh 
9660a168377Sdrh /*
9670a168377Sdrh ** Walk an expression tree.  Return 1 if the expression is constant
968eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
969eb55bd2fSdrh ** are any variables.
970eb55bd2fSdrh **
971eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
972eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
973eb55bd2fSdrh ** a constant.
974eb55bd2fSdrh */
975eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
976eb55bd2fSdrh   int isConst = 2;
977eb55bd2fSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
978eb55bd2fSdrh   return isConst!=0;
979eb55bd2fSdrh }
980eb55bd2fSdrh 
981eb55bd2fSdrh /*
98273b211abSdrh ** If the expression p codes a constant integer that is small enough
983202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
984202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
985202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
986e4de1febSdrh */
9874adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
988e4de1febSdrh   switch( p->op ){
989e4de1febSdrh     case TK_INTEGER: {
9902646da7eSdrh       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
991e4de1febSdrh         return 1;
992e4de1febSdrh       }
993202b2df7Sdrh       break;
994202b2df7Sdrh     }
9954b59ab5eSdrh     case TK_UPLUS: {
9964adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
9974b59ab5eSdrh     }
998e4de1febSdrh     case TK_UMINUS: {
999e4de1febSdrh       int v;
10004adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1001e4de1febSdrh         *pValue = -v;
1002e4de1febSdrh         return 1;
1003e4de1febSdrh       }
1004e4de1febSdrh       break;
1005e4de1febSdrh     }
1006e4de1febSdrh     default: break;
1007e4de1febSdrh   }
1008e4de1febSdrh   return 0;
1009e4de1febSdrh }
1010e4de1febSdrh 
1011e4de1febSdrh /*
1012c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
1013c4a3c779Sdrh */
10144adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
10154adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
10164adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
10174adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1018c4a3c779Sdrh   return 0;
1019c4a3c779Sdrh }
1020c4a3c779Sdrh 
1021c4a3c779Sdrh /*
10228141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
10238141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
10248141f61eSdrh ** expression node refer back to that source column.  The following changes
10258141f61eSdrh ** are made to pExpr:
10268141f61eSdrh **
10278141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
10288141f61eSdrh **                         the table.
10298141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
10308141f61eSdrh **                         from pSrcList.
10318141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
10328141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
10338141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
10348141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
10358141f61eSdrh **
10368141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
10378141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
10388141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
10398141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
10408141f61eSdrh ** means that the form of the name is Z and that columns from any table
10418141f61eSdrh ** can be used.
10428141f61eSdrh **
10438141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
10448141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
10458141f61eSdrh */
10468141f61eSdrh static int lookupName(
10478141f61eSdrh   Parse *pParse,       /* The parsing context */
10488141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
10498141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
10508141f61eSdrh   Token *pColumnToken, /* Name of the column. */
1051626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
10528141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
10538141f61eSdrh ){
10548141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
10558141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
10568141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
10578141f61eSdrh   int i, j;            /* Loop counters */
10588141f61eSdrh   int cnt = 0;         /* Number of matching column names */
10598141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
10609bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
106151669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
106251669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
106373b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
1064728b5779Sdrh   Schema *pSchema = 0;              /* Schema of the expression */
10658141f61eSdrh 
10668141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
106717435752Sdrh   zDb = sqlite3NameFromToken(db, pDbToken);
106817435752Sdrh   zTab = sqlite3NameFromToken(db, pTableToken);
106917435752Sdrh   zCol = sqlite3NameFromToken(db, pColumnToken);
107017435752Sdrh   if( db->mallocFailed ){
1071d5d56523Sdanielk1977     goto lookupname_end;
10728141f61eSdrh   }
10738141f61eSdrh 
10748141f61eSdrh   pExpr->iTable = -1;
1075626a879aSdrh   while( pNC && cnt==0 ){
1076ffe07b2dSdrh     ExprList *pEList;
1077626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
1078626a879aSdrh 
1079b3bce662Sdanielk1977     if( pSrcList ){
108051669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
108143617e9aSdrh         Table *pTab;
108243617e9aSdrh         int iDb;
10838141f61eSdrh         Column *pCol;
10848141f61eSdrh 
108543617e9aSdrh         pTab = pItem->pTab;
108643617e9aSdrh         assert( pTab!=0 );
108743617e9aSdrh         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
10888141f61eSdrh         assert( pTab->nCol>0 );
10898141f61eSdrh         if( zTab ){
10908141f61eSdrh           if( pItem->zAlias ){
10918141f61eSdrh             char *zTabName = pItem->zAlias;
10924adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
10938141f61eSdrh           }else{
10948141f61eSdrh             char *zTabName = pTab->zName;
10954adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1096da184236Sdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
10978141f61eSdrh               continue;
10988141f61eSdrh             }
10998141f61eSdrh           }
11008141f61eSdrh         }
11018141f61eSdrh         if( 0==(cntTab++) ){
11028141f61eSdrh           pExpr->iTable = pItem->iCursor;
1103728b5779Sdrh           pSchema = pTab->pSchema;
110451669863Sdrh           pMatch = pItem;
11058141f61eSdrh         }
11068141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
11074adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1108b3bf556eSdanielk1977             const char *zColl = pTab->aCol[j].zColl;
1109873fac0cSdrh             IdList *pUsing;
11108141f61eSdrh             cnt++;
11118141f61eSdrh             pExpr->iTable = pItem->iCursor;
111251669863Sdrh             pMatch = pItem;
1113728b5779Sdrh             pSchema = pTab->pSchema;
11148141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
11158141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
1116a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
11178b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1118b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
11198b4c40d8Sdrh             }
112061dfc31dSdrh             if( i<pSrcList->nSrc-1 ){
112161dfc31dSdrh               if( pItem[1].jointype & JT_NATURAL ){
1122355ef361Sdrh                 /* If this match occurred in the left table of a natural join,
1123355ef361Sdrh                 ** then skip the right table to avoid a duplicate match */
1124355ef361Sdrh                 pItem++;
1125355ef361Sdrh                 i++;
112661dfc31dSdrh               }else if( (pUsing = pItem[1].pUsing)!=0 ){
1127873fac0cSdrh                 /* If this match occurs on a column that is in the USING clause
1128873fac0cSdrh                 ** of a join, skip the search of the right table of the join
1129873fac0cSdrh                 ** to avoid a duplicate match there. */
1130873fac0cSdrh                 int k;
1131873fac0cSdrh                 for(k=0; k<pUsing->nId; k++){
1132873fac0cSdrh                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
1133873fac0cSdrh                     pItem++;
1134873fac0cSdrh                     i++;
1135873fac0cSdrh                     break;
1136873fac0cSdrh                   }
1137873fac0cSdrh                 }
1138873fac0cSdrh               }
113961dfc31dSdrh             }
11408141f61eSdrh             break;
11418141f61eSdrh           }
11428141f61eSdrh         }
11438141f61eSdrh       }
1144b3bce662Sdanielk1977     }
11458141f61eSdrh 
1146b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
11478141f61eSdrh     /* If we have not already resolved the name, then maybe
11488141f61eSdrh     ** it is a new.* or old.* trigger argument reference
11498141f61eSdrh     */
11508141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
11518141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
11528141f61eSdrh       Table *pTab = 0;
11538f2c54e6Sdanielk1977       u32 *piColMask;
11544adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
11558141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
11568141f61eSdrh         assert( pTriggerStack->pTab );
11578141f61eSdrh         pTab = pTriggerStack->pTab;
11588f2c54e6Sdanielk1977         piColMask = &(pTriggerStack->newColMask);
11594adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
11608141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
11618141f61eSdrh         assert( pTriggerStack->pTab );
11628141f61eSdrh         pTab = pTriggerStack->pTab;
11638f2c54e6Sdanielk1977         piColMask = &(pTriggerStack->oldColMask);
11648141f61eSdrh       }
11658141f61eSdrh 
11668141f61eSdrh       if( pTab ){
1167f0113000Sdanielk1977         int iCol;
11688141f61eSdrh         Column *pCol = pTab->aCol;
11698141f61eSdrh 
1170728b5779Sdrh         pSchema = pTab->pSchema;
11718141f61eSdrh         cntTab++;
1172f0113000Sdanielk1977         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
11734adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1174f0113000Sdanielk1977             const char *zColl = pTab->aCol[iCol].zColl;
11758141f61eSdrh             cnt++;
1176f0113000Sdanielk1977             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1177f0113000Sdanielk1977             pExpr->affinity = pTab->aCol[iCol].affinity;
11788b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1179b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
11808b4c40d8Sdrh             }
1181aee18ef8Sdanielk1977             pExpr->pTab = pTab;
11828f2c54e6Sdanielk1977             if( iCol>=0 ){
1183c5499befSdrh               testcase( iCol==31 );
1184c5499befSdrh               testcase( iCol==32 );
11858f2c54e6Sdanielk1977               *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
11868f2c54e6Sdanielk1977             }
11878141f61eSdrh             break;
11888141f61eSdrh           }
11898141f61eSdrh         }
11908141f61eSdrh       }
11918141f61eSdrh     }
1192b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
11938141f61eSdrh 
11948141f61eSdrh     /*
11958141f61eSdrh     ** Perhaps the name is a reference to the ROWID
11968141f61eSdrh     */
11974adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
11988141f61eSdrh       cnt = 1;
11998141f61eSdrh       pExpr->iColumn = -1;
12008a51256cSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
12018141f61eSdrh     }
12028141f61eSdrh 
12038141f61eSdrh     /*
12048141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
12058141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
12068141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
12078141f61eSdrh     **
12088141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
12098141f61eSdrh     **
12108141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
12118141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
12128141f61eSdrh     ** Note that the expression in the result set should have already been
12138141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
12148141f61eSdrh     */
1215ffe07b2dSdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
12168141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
12178141f61eSdrh         char *zAs = pEList->a[j].zName;
12184adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
121936379e97Sdrh           Expr *pDup, *pOrig;
12208141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
12214f07e5fbSdrh           assert( pExpr->pList==0 );
12224f07e5fbSdrh           assert( pExpr->pSelect==0 );
122336379e97Sdrh           pOrig = pEList->a[j].pExpr;
122436379e97Sdrh           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
122536379e97Sdrh             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
122617435752Sdrh             sqlite3_free(zCol);
122736379e97Sdrh             return 2;
122836379e97Sdrh           }
12291e536953Sdanielk1977           pDup = sqlite3ExprDup(db, pOrig);
12304f07e5fbSdrh           if( pExpr->flags & EP_ExpCollate ){
12314f07e5fbSdrh             pDup->pColl = pExpr->pColl;
12324f07e5fbSdrh             pDup->flags |= EP_ExpCollate;
12334f07e5fbSdrh           }
123417435752Sdrh           if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z);
123517435752Sdrh           if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z);
12364f07e5fbSdrh           memcpy(pExpr, pDup, sizeof(*pExpr));
123717435752Sdrh           sqlite3_free(pDup);
123815ccce1cSdrh           cnt = 1;
1239c9cf6e3dSdanielk1977           pMatch = 0;
12408141f61eSdrh           assert( zTab==0 && zDb==0 );
124115ccce1cSdrh           goto lookupname_end_2;
12428141f61eSdrh         }
12438141f61eSdrh       }
12448141f61eSdrh     }
12458141f61eSdrh 
1246626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
1247626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
1248626a879aSdrh     */
1249626a879aSdrh     if( cnt==0 ){
1250626a879aSdrh       pNC = pNC->pNext;
1251626a879aSdrh     }
1252626a879aSdrh   }
1253626a879aSdrh 
12548141f61eSdrh   /*
12558141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
12568141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
12578141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
12588141f61eSdrh   ** case, we need to return right away and not make any changes to
12598141f61eSdrh   ** pExpr.
126015ccce1cSdrh   **
126115ccce1cSdrh   ** Because no reference was made to outer contexts, the pNC->nRef
126215ccce1cSdrh   ** fields are not changed in any context.
12638141f61eSdrh   */
12648141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
126517435752Sdrh     sqlite3_free(zCol);
12668141f61eSdrh     return 0;
12678141f61eSdrh   }
12688141f61eSdrh 
12698141f61eSdrh   /*
12708141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
12718141f61eSdrh   ** more matches.  Either way, we have an error.
12728141f61eSdrh   */
12738141f61eSdrh   if( cnt!=1 ){
1274de4fcfddSdrh     const char *zErr;
1275de4fcfddSdrh     zErr = cnt==0 ? "no such column" : "ambiguous column name";
12768141f61eSdrh     if( zDb ){
1277de4fcfddSdrh       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
12788141f61eSdrh     }else if( zTab ){
1279de4fcfddSdrh       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
12808141f61eSdrh     }else{
1281de4fcfddSdrh       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
12828141f61eSdrh     }
128373b211abSdrh     pTopNC->nErr++;
12848141f61eSdrh   }
12858141f61eSdrh 
128651669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
128751669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
128851669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
128951669863Sdrh   ** column number is greater than the number of bits in the bitmask
129051669863Sdrh   ** then set the high-order bit of the bitmask.
129151669863Sdrh   */
129251669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
129351669863Sdrh     int n = pExpr->iColumn;
1294c5499befSdrh     testcase( n==sizeof(Bitmask)*8-1 );
129551669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
129651669863Sdrh       n = sizeof(Bitmask)*8-1;
129751669863Sdrh     }
129851669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
1299ca83ac51Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
130051669863Sdrh   }
130151669863Sdrh 
1302d5d56523Sdanielk1977 lookupname_end:
13038141f61eSdrh   /* Clean up and return
13048141f61eSdrh   */
130517435752Sdrh   sqlite3_free(zDb);
130617435752Sdrh   sqlite3_free(zTab);
13074adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
13088141f61eSdrh   pExpr->pLeft = 0;
13094adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
13108141f61eSdrh   pExpr->pRight = 0;
13118141f61eSdrh   pExpr->op = TK_COLUMN;
131215ccce1cSdrh lookupname_end_2:
131317435752Sdrh   sqlite3_free(zCol);
1314626a879aSdrh   if( cnt==1 ){
1315b3bce662Sdanielk1977     assert( pNC!=0 );
1316728b5779Sdrh     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
1317aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
1318aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
1319aee18ef8Sdanielk1977     }
132015ccce1cSdrh     /* Increment the nRef value on all name contexts from TopNC up to
132115ccce1cSdrh     ** the point where the name matched. */
132215ccce1cSdrh     for(;;){
132315ccce1cSdrh       assert( pTopNC!=0 );
132415ccce1cSdrh       pTopNC->nRef++;
132515ccce1cSdrh       if( pTopNC==pNC ) break;
132615ccce1cSdrh       pTopNC = pTopNC->pNext;
1327626a879aSdrh     }
132815ccce1cSdrh     return 0;
132915ccce1cSdrh   } else {
133015ccce1cSdrh     return 1;
133115ccce1cSdrh   }
13328141f61eSdrh }
13338141f61eSdrh 
13348141f61eSdrh /*
1335626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1336626a879aSdrh **
133773b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1338626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
133973b211abSdrh ** the tree or 2 to abort the tree walk.
134073b211abSdrh **
134173b211abSdrh ** This routine also does error checking and name resolution for
134273b211abSdrh ** function names.  The operator for aggregate functions is changed
134373b211abSdrh ** to TK_AGG_FUNCTION.
1344626a879aSdrh */
1345626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1346626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1347626a879aSdrh   Parse *pParse;
1348626a879aSdrh 
1349b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1350626a879aSdrh   assert( pNC!=0 );
1351626a879aSdrh   pParse = pNC->pParse;
1352b3bce662Sdanielk1977 
1353626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1354626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1355626a879aSdrh #ifndef NDEBUG
1356f0113000Sdanielk1977   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1357f0113000Sdanielk1977     SrcList *pSrcList = pNC->pSrcList;
1358940fac9dSdanielk1977     int i;
1359f0113000Sdanielk1977     for(i=0; i<pNC->pSrcList->nSrc; i++){
1360626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1361626a879aSdrh     }
1362626a879aSdrh   }
1363626a879aSdrh #endif
1364626a879aSdrh   switch( pExpr->op ){
1365626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1366626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1367626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1368626a879aSdrh     */
1369626a879aSdrh     case TK_STRING: {
1370626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1371626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1372626a879aSdrh     }
1373626a879aSdrh     /* A lone identifier is the name of a column.
1374626a879aSdrh     */
1375626a879aSdrh     case TK_ID: {
1376626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1377626a879aSdrh       return 1;
1378626a879aSdrh     }
1379626a879aSdrh 
1380626a879aSdrh     /* A table name and column name:     ID.ID
1381626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1382626a879aSdrh     */
1383626a879aSdrh     case TK_DOT: {
1384626a879aSdrh       Token *pColumn;
1385626a879aSdrh       Token *pTable;
1386626a879aSdrh       Token *pDb;
1387626a879aSdrh       Expr *pRight;
1388626a879aSdrh 
1389b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1390626a879aSdrh       pRight = pExpr->pRight;
1391626a879aSdrh       if( pRight->op==TK_ID ){
1392626a879aSdrh         pDb = 0;
1393626a879aSdrh         pTable = &pExpr->pLeft->token;
1394626a879aSdrh         pColumn = &pRight->token;
1395626a879aSdrh       }else{
1396626a879aSdrh         assert( pRight->op==TK_DOT );
1397626a879aSdrh         pDb = &pExpr->pLeft->token;
1398626a879aSdrh         pTable = &pRight->pLeft->token;
1399626a879aSdrh         pColumn = &pRight->pRight->token;
1400626a879aSdrh       }
1401626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1402626a879aSdrh       return 1;
1403626a879aSdrh     }
1404626a879aSdrh 
1405626a879aSdrh     /* Resolve function names
1406626a879aSdrh     */
1407b71090fdSdrh     case TK_CONST_FUNC:
1408626a879aSdrh     case TK_FUNCTION: {
1409626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1410626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1411626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1412626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1413626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1414626a879aSdrh       int i;
14155169bbc6Sdrh       int auth;                   /* Authorization to use the function */
1416626a879aSdrh       int nId;                    /* Number of characters in function name */
1417626a879aSdrh       const char *zId;            /* The function name. */
141873b211abSdrh       FuncDef *pDef;              /* Information about the function */
141914db2665Sdanielk1977       int enc = ENC(pParse->db);  /* The database encoding */
1420626a879aSdrh 
14212646da7eSdrh       zId = (char*)pExpr->token.z;
1422b71090fdSdrh       nId = pExpr->token.n;
1423626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1424626a879aSdrh       if( pDef==0 ){
1425626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1426626a879aSdrh         if( pDef==0 ){
1427626a879aSdrh           no_such_func = 1;
1428626a879aSdrh         }else{
1429626a879aSdrh           wrong_num_args = 1;
1430626a879aSdrh         }
1431626a879aSdrh       }else{
1432626a879aSdrh         is_agg = pDef->xFunc==0;
1433626a879aSdrh       }
14342fca7fefSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
14355169bbc6Sdrh       if( pDef ){
14365169bbc6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
14375169bbc6Sdrh         if( auth!=SQLITE_OK ){
14385169bbc6Sdrh           if( auth==SQLITE_DENY ){
14395169bbc6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
14405169bbc6Sdrh                                     pDef->zName);
14415169bbc6Sdrh             pNC->nErr++;
14425169bbc6Sdrh           }
14435169bbc6Sdrh           pExpr->op = TK_NULL;
14445169bbc6Sdrh           return 1;
14455169bbc6Sdrh         }
14465169bbc6Sdrh       }
1447b8b14219Sdrh #endif
1448626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1449626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1450626a879aSdrh         pNC->nErr++;
1451626a879aSdrh         is_agg = 0;
1452626a879aSdrh       }else if( no_such_func ){
1453626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1454626a879aSdrh         pNC->nErr++;
1455626a879aSdrh       }else if( wrong_num_args ){
1456626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1457626a879aSdrh              nId, zId);
1458626a879aSdrh         pNC->nErr++;
1459626a879aSdrh       }
1460626a879aSdrh       if( is_agg ){
1461626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1462626a879aSdrh         pNC->hasAgg = 1;
1463626a879aSdrh       }
146473b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1465626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
146673b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1467626a879aSdrh       }
146873b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1469626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1470626a879aSdrh       ** type of the function
1471626a879aSdrh       */
1472626a879aSdrh       return is_agg;
1473626a879aSdrh     }
1474b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1475b3bce662Sdanielk1977     case TK_SELECT:
1476b3bce662Sdanielk1977     case TK_EXISTS:
1477b3bce662Sdanielk1977 #endif
1478b3bce662Sdanielk1977     case TK_IN: {
1479b3bce662Sdanielk1977       if( pExpr->pSelect ){
14808a9f38feSdrh         int nRef = pNC->nRef;
148106f6541eSdrh #ifndef SQLITE_OMIT_CHECK
148206f6541eSdrh         if( pNC->isCheck ){
148306f6541eSdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
148406f6541eSdrh         }
148506f6541eSdrh #endif
1486b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1487b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1488b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1489b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1490b3bce662Sdanielk1977         }
1491b3bce662Sdanielk1977       }
14924284fb07Sdrh       break;
1493b3bce662Sdanielk1977     }
14944284fb07Sdrh #ifndef SQLITE_OMIT_CHECK
14954284fb07Sdrh     case TK_VARIABLE: {
14964284fb07Sdrh       if( pNC->isCheck ){
14974284fb07Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
14984284fb07Sdrh       }
14994284fb07Sdrh       break;
15004284fb07Sdrh     }
15014284fb07Sdrh #endif
1502626a879aSdrh   }
1503626a879aSdrh   return 0;
1504626a879aSdrh }
1505626a879aSdrh 
1506626a879aSdrh /*
1507cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1508967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1509aacc543eSdrh ** index to the table in the table list and a column offset.  The
1510aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1511aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1512832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1513aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1514aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1515aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1516aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1517aacc543eSdrh ** alias for ROWID.
151819a775c2Sdrh **
1519626a879aSdrh ** Also resolve function names and check the functions for proper
1520626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1521626a879aSdrh ** have the correct number of arguments.  Leave an error message
1522626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1523626a879aSdrh **
152473b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
152573b211abSdrh ** property on the expression.
1526626a879aSdrh */
1527626a879aSdrh int sqlite3ExprResolveNames(
1528b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1529b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1530626a879aSdrh ){
153113449892Sdrh   int savedHasAgg;
1532bb4957f8Sdrh 
153373b211abSdrh   if( pExpr==0 ) return 0;
1534bb4957f8Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
1535bb4957f8Sdrh   {
1536bb4957f8Sdrh     int mxDepth = pNC->pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
1537bb4957f8Sdrh     if( (pExpr->nHeight+pNC->pParse->nHeight)>mxDepth ){
1538fc976065Sdanielk1977       sqlite3ErrorMsg(pNC->pParse,
1539bb4957f8Sdrh          "Expression tree is too large (maximum depth %d)", mxDepth
1540fc976065Sdanielk1977       );
1541fc976065Sdanielk1977       return 1;
1542fc976065Sdanielk1977     }
1543fc976065Sdanielk1977     pNC->pParse->nHeight += pExpr->nHeight;
1544bb4957f8Sdrh   }
1545fc976065Sdanielk1977 #endif
154613449892Sdrh   savedHasAgg = pNC->hasAgg;
154713449892Sdrh   pNC->hasAgg = 0;
1548b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1549bb4957f8Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
1550fc976065Sdanielk1977   pNC->pParse->nHeight -= pExpr->nHeight;
1551fc976065Sdanielk1977 #endif
1552b3bce662Sdanielk1977   if( pNC->nErr>0 ){
155373b211abSdrh     ExprSetProperty(pExpr, EP_Error);
155473b211abSdrh   }
155513449892Sdrh   if( pNC->hasAgg ){
155613449892Sdrh     ExprSetProperty(pExpr, EP_Agg);
155713449892Sdrh   }else if( savedHasAgg ){
155813449892Sdrh     pNC->hasAgg = 1;
155913449892Sdrh   }
156073b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1561626a879aSdrh }
1562626a879aSdrh 
15631398ad36Sdrh /*
15641398ad36Sdrh ** A pointer instance of this structure is used to pass information
15651398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
15661398ad36Sdrh */
15671398ad36Sdrh typedef struct QueryCoder QueryCoder;
15681398ad36Sdrh struct QueryCoder {
15691398ad36Sdrh   Parse *pParse;       /* The parsing context */
15701398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
15711398ad36Sdrh };
15721398ad36Sdrh 
15739a96b668Sdanielk1977 #ifdef SQLITE_TEST
15749a96b668Sdanielk1977   int sqlite3_enable_in_opt = 1;
15759a96b668Sdanielk1977 #else
15769a96b668Sdanielk1977   #define sqlite3_enable_in_opt 1
15779a96b668Sdanielk1977 #endif
15789a96b668Sdanielk1977 
15799a96b668Sdanielk1977 /*
1580b287f4b6Sdrh ** Return true if the IN operator optimization is enabled and
1581b287f4b6Sdrh ** the SELECT statement p exists and is of the
1582b287f4b6Sdrh ** simple form:
1583b287f4b6Sdrh **
1584b287f4b6Sdrh **     SELECT <column> FROM <table>
1585b287f4b6Sdrh **
1586b287f4b6Sdrh ** If this is the case, it may be possible to use an existing table
1587b287f4b6Sdrh ** or index instead of generating an epheremal table.
1588b287f4b6Sdrh */
1589b287f4b6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1590b287f4b6Sdrh static int isCandidateForInOpt(Select *p){
1591b287f4b6Sdrh   SrcList *pSrc;
1592b287f4b6Sdrh   ExprList *pEList;
1593b287f4b6Sdrh   Table *pTab;
1594b287f4b6Sdrh   if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
1595b287f4b6Sdrh   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
1596b287f4b6Sdrh   if( p->pPrior ) return 0;              /* Not a compound SELECT */
1597b287f4b6Sdrh   if( p->isDistinct ) return 0;          /* No DISTINCT keyword */
1598b287f4b6Sdrh   if( p->isAgg ) return 0;               /* Contains no aggregate functions */
1599b287f4b6Sdrh   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
1600b287f4b6Sdrh   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
1601b287f4b6Sdrh   if( p->pOffset ) return 0;
1602b287f4b6Sdrh   if( p->pWhere ) return 0;              /* Has no WHERE clause */
1603b287f4b6Sdrh   pSrc = p->pSrc;
1604b287f4b6Sdrh   if( pSrc==0 ) return 0;                /* A single table in the FROM clause */
1605b287f4b6Sdrh   if( pSrc->nSrc!=1 ) return 0;
1606b287f4b6Sdrh   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
1607b287f4b6Sdrh   pTab = pSrc->a[0].pTab;
1608b287f4b6Sdrh   if( pTab==0 ) return 0;
1609b287f4b6Sdrh   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
1610b287f4b6Sdrh   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
1611b287f4b6Sdrh   pEList = p->pEList;
1612b287f4b6Sdrh   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
1613b287f4b6Sdrh   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1614b287f4b6Sdrh   return 1;
1615b287f4b6Sdrh }
1616b287f4b6Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1617b287f4b6Sdrh 
1618b287f4b6Sdrh /*
16199a96b668Sdanielk1977 ** This function is used by the implementation of the IN (...) operator.
16209a96b668Sdanielk1977 ** It's job is to find or create a b-tree structure that may be used
16219a96b668Sdanielk1977 ** either to test for membership of the (...) set or to iterate through
162285b623f2Sdrh ** its members, skipping duplicates.
16239a96b668Sdanielk1977 **
16249a96b668Sdanielk1977 ** The cursor opened on the structure (database table, database index
16259a96b668Sdanielk1977 ** or ephermal table) is stored in pX->iTable before this function returns.
16269a96b668Sdanielk1977 ** The returned value indicates the structure type, as follows:
16279a96b668Sdanielk1977 **
16289a96b668Sdanielk1977 **   IN_INDEX_ROWID - The cursor was opened on a database table.
16292d401ab8Sdrh **   IN_INDEX_INDEX - The cursor was opened on a database index.
16309a96b668Sdanielk1977 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
16319a96b668Sdanielk1977 **                    populated epheremal table.
16329a96b668Sdanielk1977 **
16339a96b668Sdanielk1977 ** An existing structure may only be used if the SELECT is of the simple
16349a96b668Sdanielk1977 ** form:
16359a96b668Sdanielk1977 **
16369a96b668Sdanielk1977 **     SELECT <column> FROM <table>
16379a96b668Sdanielk1977 **
16389a96b668Sdanielk1977 ** If the mustBeUnique parameter is false, the structure will be used
16399a96b668Sdanielk1977 ** for fast set membership tests. In this case an epheremal table must
16409a96b668Sdanielk1977 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
164185b623f2Sdrh ** be found with <column> as its left-most column.
16429a96b668Sdanielk1977 **
16439a96b668Sdanielk1977 ** If mustBeUnique is true, then the structure will be used to iterate
16449a96b668Sdanielk1977 ** through the set members, skipping any duplicates. In this case an
16459a96b668Sdanielk1977 ** epheremal table must be used unless the selected <column> is guaranteed
16469a96b668Sdanielk1977 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
16479a96b668Sdanielk1977 ** is unique by virtue of a constraint or implicit index.
16489a96b668Sdanielk1977 */
1649284f4acaSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
16509a96b668Sdanielk1977 int sqlite3FindInIndex(Parse *pParse, Expr *pX, int mustBeUnique){
16519a96b668Sdanielk1977   Select *p;
16529a96b668Sdanielk1977   int eType = 0;
16539a96b668Sdanielk1977   int iTab = pParse->nTab++;
16549a96b668Sdanielk1977 
16559a96b668Sdanielk1977   /* The follwing if(...) expression is true if the SELECT is of the
16569a96b668Sdanielk1977   ** simple form:
16579a96b668Sdanielk1977   **
16589a96b668Sdanielk1977   **     SELECT <column> FROM <table>
16599a96b668Sdanielk1977   **
16609a96b668Sdanielk1977   ** If this is the case, it may be possible to use an existing table
16619a96b668Sdanielk1977   ** or index instead of generating an epheremal table.
16629a96b668Sdanielk1977   */
1663b287f4b6Sdrh   p = pX->pSelect;
1664b287f4b6Sdrh   if( isCandidateForInOpt(p) ){
16659a96b668Sdanielk1977     sqlite3 *db = pParse->db;
16669a96b668Sdanielk1977     Index *pIdx;
16679a96b668Sdanielk1977     Expr *pExpr = p->pEList->a[0].pExpr;
16689a96b668Sdanielk1977     int iCol = pExpr->iColumn;
16699a96b668Sdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
16709a96b668Sdanielk1977 
16719a96b668Sdanielk1977     /* This function is only called from two places. In both cases the vdbe
16729a96b668Sdanielk1977     ** has already been allocated. So assume sqlite3GetVdbe() is always
16739a96b668Sdanielk1977     ** successful here.
16749a96b668Sdanielk1977     */
16759a96b668Sdanielk1977     assert(v);
16769a96b668Sdanielk1977     if( iCol<0 ){
16770a07c107Sdrh       int iMem = ++pParse->nMem;
16789a96b668Sdanielk1977       int iAddr;
16799a96b668Sdanielk1977       Table *pTab = p->pSrc->a[0].pTab;
16809a96b668Sdanielk1977       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
16819a96b668Sdanielk1977       sqlite3VdbeUsesBtree(v, iDb);
16829a96b668Sdanielk1977 
1683892d3179Sdrh       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
16844c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
16859a96b668Sdanielk1977 
16869a96b668Sdanielk1977       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
16879a96b668Sdanielk1977       eType = IN_INDEX_ROWID;
16889a96b668Sdanielk1977 
16899a96b668Sdanielk1977       sqlite3VdbeJumpHere(v, iAddr);
16909a96b668Sdanielk1977     }else{
16919a96b668Sdanielk1977       /* The collation sequence used by the comparison. If an index is to
16929a96b668Sdanielk1977       ** be used in place of a temp-table, it must be ordered according
16939a96b668Sdanielk1977       ** to this collation sequence.
16949a96b668Sdanielk1977       */
16959a96b668Sdanielk1977       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
16969a96b668Sdanielk1977 
16979a96b668Sdanielk1977       /* Check that the affinity that will be used to perform the
16989a96b668Sdanielk1977       ** comparison is the same as the affinity of the column. If
16999a96b668Sdanielk1977       ** it is not, it is not possible to use any index.
17009a96b668Sdanielk1977       */
17019a96b668Sdanielk1977       Table *pTab = p->pSrc->a[0].pTab;
17029a96b668Sdanielk1977       char aff = comparisonAffinity(pX);
17039a96b668Sdanielk1977       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
17049a96b668Sdanielk1977 
17059a96b668Sdanielk1977       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
17069a96b668Sdanielk1977         if( (pIdx->aiColumn[0]==iCol)
17079a96b668Sdanielk1977          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
17089a96b668Sdanielk1977          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
17099a96b668Sdanielk1977         ){
17109a96b668Sdanielk1977           int iDb;
17110a07c107Sdrh           int iMem = ++pParse->nMem;
17129a96b668Sdanielk1977           int iAddr;
17139a96b668Sdanielk1977           char *pKey;
17149a96b668Sdanielk1977 
17159a96b668Sdanielk1977           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
17169a96b668Sdanielk1977           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
17179a96b668Sdanielk1977           sqlite3VdbeUsesBtree(v, iDb);
17189a96b668Sdanielk1977 
1719892d3179Sdrh           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
17204c583128Sdrh           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
17219a96b668Sdanielk1977 
1722cd3e8f7cSdanielk1977           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
1723207872a4Sdanielk1977           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
172466a5167bSdrh                                pKey,P4_KEYINFO_HANDOFF);
1725207872a4Sdanielk1977           VdbeComment((v, "%s", pIdx->zName));
17269a96b668Sdanielk1977           eType = IN_INDEX_INDEX;
17279a96b668Sdanielk1977 
17289a96b668Sdanielk1977           sqlite3VdbeJumpHere(v, iAddr);
17299a96b668Sdanielk1977         }
17309a96b668Sdanielk1977       }
17319a96b668Sdanielk1977     }
17329a96b668Sdanielk1977   }
17339a96b668Sdanielk1977 
17349a96b668Sdanielk1977   if( eType==0 ){
17359a96b668Sdanielk1977     sqlite3CodeSubselect(pParse, pX);
17369a96b668Sdanielk1977     eType = IN_INDEX_EPH;
17379a96b668Sdanielk1977   }else{
17389a96b668Sdanielk1977     pX->iTable = iTab;
17399a96b668Sdanielk1977   }
17409a96b668Sdanielk1977   return eType;
17419a96b668Sdanielk1977 }
1742284f4acaSdanielk1977 #endif
1743626a879aSdrh 
1744626a879aSdrh /*
17459cbe6352Sdrh ** Generate code for scalar subqueries used as an expression
17469cbe6352Sdrh ** and IN operators.  Examples:
1747626a879aSdrh **
17489cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
17499cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
17509cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
17519cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1752fef5208cSdrh **
17539cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
17549cbe6352Sdrh ** operator or subquery.
1755cce7d176Sdrh */
175651522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1757b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
175857dbd7b3Sdrh   int testAddr = 0;                       /* One-time test address */
1759b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1760b3bce662Sdanielk1977   if( v==0 ) return;
1761b3bce662Sdanielk1977 
1762fc976065Sdanielk1977 
176357dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
176457dbd7b3Sdrh   ** if any of the following is true:
176557dbd7b3Sdrh   **
176657dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
176757dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
176857dbd7b3Sdrh   **    *  We are inside a trigger
176957dbd7b3Sdrh   **
177057dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
177157dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1772b3bce662Sdanielk1977   */
1773b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
17740a07c107Sdrh     int mem = ++pParse->nMem;
1775892d3179Sdrh     sqlite3VdbeAddOp1(v, OP_If, mem);
1776892d3179Sdrh     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
177717435752Sdrh     assert( testAddr>0 || pParse->db->mallocFailed );
1778b3bce662Sdanielk1977   }
1779b3bce662Sdanielk1977 
1780cce7d176Sdrh   switch( pExpr->op ){
1781fef5208cSdrh     case TK_IN: {
1782e014a838Sdanielk1977       char affinity;
1783d3d39e93Sdrh       KeyInfo keyInfo;
1784b9bb7c18Sdrh       int addr;        /* Address of OP_OpenEphemeral instruction */
1785d3d39e93Sdrh 
1786bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1787e014a838Sdanielk1977 
1788e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
178957dbd7b3Sdrh       ** expression it is handled the same way. A virtual table is
1790e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1791e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1792fef5208cSdrh       **
1793e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1794e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1795e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1796e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1797e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1798e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1799e014a838Sdanielk1977       ** is used.
1800fef5208cSdrh       */
1801832508b7Sdrh       pExpr->iTable = pParse->nTab++;
1802cd3e8f7cSdanielk1977       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, 1);
1803d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1804d3d39e93Sdrh       keyInfo.nField = 1;
1805e014a838Sdanielk1977 
1806e014a838Sdanielk1977       if( pExpr->pSelect ){
1807e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1808e014a838Sdanielk1977         **
1809e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1810e014a838Sdanielk1977         ** table allocated and opened above.
1811e014a838Sdanielk1977         */
18121013c932Sdrh         SelectDest dest;
1813be5c89acSdrh         ExprList *pEList;
18141013c932Sdrh 
18151013c932Sdrh         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
18161013c932Sdrh         dest.affinity = (int)affinity;
1817e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
18186c8c8ce0Sdanielk1977         if( sqlite3Select(pParse, pExpr->pSelect, &dest, 0, 0, 0, 0) ){
181994ccde58Sdrh           return;
182094ccde58Sdrh         }
1821be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1822be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
1823bcbb04e5Sdanielk1977           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1824be5c89acSdrh               pEList->a[0].pExpr);
18250202b29eSdanielk1977         }
1826fef5208cSdrh       }else if( pExpr->pList ){
1827fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1828fef5208cSdrh         **
1829e014a838Sdanielk1977         ** For each expression, build an index key from the evaluation and
1830e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1831e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1832e014a838Sdanielk1977         ** a column, use numeric affinity.
1833fef5208cSdrh         */
1834e014a838Sdanielk1977         int i;
183557dbd7b3Sdrh         ExprList *pList = pExpr->pList;
183657dbd7b3Sdrh         struct ExprList_item *pItem;
18372d401ab8Sdrh         int r1, r2;
183857dbd7b3Sdrh 
1839e014a838Sdanielk1977         if( !affinity ){
18408159a35fSdrh           affinity = SQLITE_AFF_NONE;
1841e014a838Sdanielk1977         }
18420202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1843e014a838Sdanielk1977 
1844e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
18452d401ab8Sdrh         r1 = sqlite3GetTempReg(pParse);
18462d401ab8Sdrh         r2 = sqlite3GetTempReg(pParse);
184757dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
184857dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1849e014a838Sdanielk1977 
185057dbd7b3Sdrh           /* If the expression is not constant then we will need to
185157dbd7b3Sdrh           ** disable the test that was generated above that makes sure
185257dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
185357dbd7b3Sdrh           ** expression we need to rerun this code each time.
185457dbd7b3Sdrh           */
1855892d3179Sdrh           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
1856892d3179Sdrh             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
185757dbd7b3Sdrh             testAddr = 0;
18584794b980Sdrh           }
1859e014a838Sdanielk1977 
1860e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
1861e55cbd72Sdrh           pParse->disableColCache++;
18622d401ab8Sdrh           sqlite3ExprCode(pParse, pE2, r1);
1863c5499befSdrh           assert( pParse->disableColCache>0 );
1864e55cbd72Sdrh           pParse->disableColCache--;
18651db639ceSdrh           sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
1866da250ea5Sdrh           sqlite3ExprCacheAffinityChange(pParse, r1, 1);
18672d401ab8Sdrh           sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
1868fef5208cSdrh         }
18692d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r1);
18702d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r2);
1871fef5208cSdrh       }
187266a5167bSdrh       sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
1873b3bce662Sdanielk1977       break;
1874fef5208cSdrh     }
1875fef5208cSdrh 
187651522cd3Sdrh     case TK_EXISTS:
187719a775c2Sdrh     case TK_SELECT: {
1878fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1879fef5208cSdrh       ** value of this select in a memory cell and record the number
1880967e8b73Sdrh       ** of the memory cell in iColumn.
1881fef5208cSdrh       */
18822646da7eSdrh       static const Token one = { (u8*)"1", 0, 1 };
188351522cd3Sdrh       Select *pSel;
18846c8c8ce0Sdanielk1977       SelectDest dest;
18851398ad36Sdrh 
188651522cd3Sdrh       pSel = pExpr->pSelect;
18871013c932Sdrh       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
188851522cd3Sdrh       if( pExpr->op==TK_SELECT ){
18896c8c8ce0Sdanielk1977         dest.eDest = SRT_Mem;
18904c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
1891d4e70ebdSdrh         VdbeComment((v, "Init subquery result"));
189251522cd3Sdrh       }else{
18936c8c8ce0Sdanielk1977         dest.eDest = SRT_Exists;
18944c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
1895d4e70ebdSdrh         VdbeComment((v, "Init EXISTS result"));
189651522cd3Sdrh       }
1897ec7429aeSdrh       sqlite3ExprDelete(pSel->pLimit);
1898a1644fd8Sdanielk1977       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
18996c8c8ce0Sdanielk1977       if( sqlite3Select(pParse, pSel, &dest, 0, 0, 0, 0) ){
190094ccde58Sdrh         return;
190194ccde58Sdrh       }
19026c8c8ce0Sdanielk1977       pExpr->iColumn = dest.iParm;
1903b3bce662Sdanielk1977       break;
190419a775c2Sdrh     }
1905cce7d176Sdrh   }
1906b3bce662Sdanielk1977 
190757dbd7b3Sdrh   if( testAddr ){
1908892d3179Sdrh     sqlite3VdbeJumpHere(v, testAddr-1);
1909b3bce662Sdanielk1977   }
1910fc976065Sdanielk1977 
1911b3bce662Sdanielk1977   return;
1912cce7d176Sdrh }
191351522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1914cce7d176Sdrh 
1915cce7d176Sdrh /*
1916598f1340Sdrh ** Duplicate an 8-byte value
1917598f1340Sdrh */
1918598f1340Sdrh static char *dup8bytes(Vdbe *v, const char *in){
1919598f1340Sdrh   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
1920598f1340Sdrh   if( out ){
1921598f1340Sdrh     memcpy(out, in, 8);
1922598f1340Sdrh   }
1923598f1340Sdrh   return out;
1924598f1340Sdrh }
1925598f1340Sdrh 
1926598f1340Sdrh /*
1927598f1340Sdrh ** Generate an instruction that will put the floating point
19289cbf3425Sdrh ** value described by z[0..n-1] into register iMem.
19290cf19ed8Sdrh **
19300cf19ed8Sdrh ** The z[] string will probably not be zero-terminated.  But the
19310cf19ed8Sdrh ** z[n] character is guaranteed to be something that does not look
19320cf19ed8Sdrh ** like the continuation of the number.
1933598f1340Sdrh */
19349de221dfSdrh static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
1935598f1340Sdrh   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
1936598f1340Sdrh   if( z ){
1937598f1340Sdrh     double value;
1938598f1340Sdrh     char *zV;
19390cf19ed8Sdrh     assert( !isdigit(z[n]) );
1940598f1340Sdrh     sqlite3AtoF(z, &value);
1941*2eaf93d3Sdrh     if( sqlite3IsNaN(value) ){
1942*2eaf93d3Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
1943*2eaf93d3Sdrh     }else{
1944598f1340Sdrh       if( negateFlag ) value = -value;
1945598f1340Sdrh       zV = dup8bytes(v, (char*)&value);
19469de221dfSdrh       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
1947598f1340Sdrh     }
1948598f1340Sdrh   }
1949*2eaf93d3Sdrh }
1950598f1340Sdrh 
1951598f1340Sdrh 
1952598f1340Sdrh /*
1953fec19aadSdrh ** Generate an instruction that will put the integer describe by
19549cbf3425Sdrh ** text z[0..n-1] into register iMem.
19550cf19ed8Sdrh **
19560cf19ed8Sdrh ** The z[] string will probably not be zero-terminated.  But the
19570cf19ed8Sdrh ** z[n] character is guaranteed to be something that does not look
19580cf19ed8Sdrh ** like the continuation of the number.
1959fec19aadSdrh */
19609de221dfSdrh static void codeInteger(Vdbe *v, const char *z, int n, int negFlag, int iMem){
1961abb6fcabSdrh   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
1962c9cf901dSdanielk1977   if( z ){
1963fec19aadSdrh     int i;
19640cf19ed8Sdrh     assert( !isdigit(z[n]) );
19656fec0762Sdrh     if( sqlite3GetInt32(z, &i) ){
19669de221dfSdrh       if( negFlag ) i = -i;
19679de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
19689de221dfSdrh     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
1969598f1340Sdrh       i64 value;
1970598f1340Sdrh       char *zV;
1971598f1340Sdrh       sqlite3Atoi64(z, &value);
19729de221dfSdrh       if( negFlag ) value = -value;
1973598f1340Sdrh       zV = dup8bytes(v, (char*)&value);
19749de221dfSdrh       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
1975fec19aadSdrh     }else{
19769de221dfSdrh       codeReal(v, z, n, negFlag, iMem);
1977fec19aadSdrh     }
1978fec19aadSdrh   }
1979c9cf901dSdanielk1977 }
1980fec19aadSdrh 
1981945498f3Sdrh 
1982945498f3Sdrh /*
1983945498f3Sdrh ** Generate code that will extract the iColumn-th column from
1984e55cbd72Sdrh ** table pTab and store the column value in a register.  An effort
1985e55cbd72Sdrh ** is made to store the column value in register iReg, but this is
1986e55cbd72Sdrh ** not guaranteed.  The location of the column value is returned.
1987e55cbd72Sdrh **
1988e55cbd72Sdrh ** There must be an open cursor to pTab in iTable when this routine
1989e55cbd72Sdrh ** is called.  If iColumn<0 then code is generated that extracts the rowid.
1990da250ea5Sdrh **
1991da250ea5Sdrh ** This routine might attempt to reuse the value of the column that
1992da250ea5Sdrh ** has already been loaded into a register.  The value will always
1993da250ea5Sdrh ** be used if it has not undergone any affinity changes.  But if
1994da250ea5Sdrh ** an affinity change has occurred, then the cached value will only be
1995da250ea5Sdrh ** used if allowAffChng is true.
1996945498f3Sdrh */
1997e55cbd72Sdrh int sqlite3ExprCodeGetColumn(
1998e55cbd72Sdrh   Parse *pParse,   /* Parsing and code generating context */
19992133d822Sdrh   Table *pTab,     /* Description of the table we are reading from */
20002133d822Sdrh   int iColumn,     /* Index of the table column */
20012133d822Sdrh   int iTable,      /* The cursor pointing to the table */
2002da250ea5Sdrh   int iReg,        /* Store results here */
2003da250ea5Sdrh   int allowAffChng /* True if prior affinity changes are OK */
20042133d822Sdrh ){
2005e55cbd72Sdrh   Vdbe *v = pParse->pVdbe;
2006e55cbd72Sdrh   int i;
2007da250ea5Sdrh   struct yColCache *p;
2008e55cbd72Sdrh 
2009da250ea5Sdrh   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
2010da250ea5Sdrh     if( p->iTable==iTable && p->iColumn==iColumn
2011da250ea5Sdrh            && (!p->affChange || allowAffChng) ){
2012e55cbd72Sdrh #if 0
2013e55cbd72Sdrh       sqlite3VdbeAddOp0(v, OP_Noop);
2014da250ea5Sdrh       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
2015e55cbd72Sdrh #endif
2016da250ea5Sdrh       return p->iReg;
2017e55cbd72Sdrh     }
2018e55cbd72Sdrh   }
2019e55cbd72Sdrh   assert( v!=0 );
2020945498f3Sdrh   if( iColumn<0 ){
2021945498f3Sdrh     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
20222133d822Sdrh     sqlite3VdbeAddOp2(v, op, iTable, iReg);
2023945498f3Sdrh   }else if( pTab==0 ){
20242133d822Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
2025945498f3Sdrh   }else{
2026945498f3Sdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
20272133d822Sdrh     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
2028945498f3Sdrh     sqlite3ColumnDefault(v, pTab, iColumn);
2029945498f3Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2030945498f3Sdrh     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
20312133d822Sdrh       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
2032945498f3Sdrh     }
2033945498f3Sdrh #endif
2034945498f3Sdrh   }
2035e55cbd72Sdrh   if( pParse->disableColCache==0 ){
2036e55cbd72Sdrh     i = pParse->iColCache;
2037da250ea5Sdrh     p = &pParse->aColCache[i];
2038da250ea5Sdrh     p->iTable = iTable;
2039da250ea5Sdrh     p->iColumn = iColumn;
2040da250ea5Sdrh     p->iReg = iReg;
2041c5499befSdrh     p->affChange = 0;
2042e55cbd72Sdrh     i++;
20432f7794c1Sdrh     if( i>=ArraySize(pParse->aColCache) ) i = 0;
2044e55cbd72Sdrh     if( i>pParse->nColCache ) pParse->nColCache = i;
20452f7794c1Sdrh     pParse->iColCache = i;
2046e55cbd72Sdrh   }
2047e55cbd72Sdrh   return iReg;
2048e55cbd72Sdrh }
2049e55cbd72Sdrh 
2050e55cbd72Sdrh /*
2051e55cbd72Sdrh ** Clear all column cache entries associated with the vdbe
2052e55cbd72Sdrh ** cursor with cursor number iTable.
2053e55cbd72Sdrh */
2054e55cbd72Sdrh void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
2055e55cbd72Sdrh   if( iTable<0 ){
2056e55cbd72Sdrh     pParse->nColCache = 0;
2057e55cbd72Sdrh     pParse->iColCache = 0;
2058e55cbd72Sdrh   }else{
2059e55cbd72Sdrh     int i;
2060e55cbd72Sdrh     for(i=0; i<pParse->nColCache; i++){
2061e55cbd72Sdrh       if( pParse->aColCache[i].iTable==iTable ){
2062c5499befSdrh         testcase( i==pParse->nColCache-1 );
2063e55cbd72Sdrh         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
2064e55cbd72Sdrh         pParse->iColCache = pParse->nColCache;
2065e55cbd72Sdrh       }
2066e55cbd72Sdrh     }
2067da250ea5Sdrh   }
2068da250ea5Sdrh }
2069e55cbd72Sdrh 
2070e55cbd72Sdrh /*
2071da250ea5Sdrh ** Record the fact that an affinity change has occurred on iCount
2072da250ea5Sdrh ** registers starting with iStart.
2073e55cbd72Sdrh */
2074da250ea5Sdrh void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2075da250ea5Sdrh   int iEnd = iStart + iCount - 1;
2076e55cbd72Sdrh   int i;
2077e55cbd72Sdrh   for(i=0; i<pParse->nColCache; i++){
2078e55cbd72Sdrh     int r = pParse->aColCache[i].iReg;
2079da250ea5Sdrh     if( r>=iStart && r<=iEnd ){
2080da250ea5Sdrh       pParse->aColCache[i].affChange = 1;
2081e55cbd72Sdrh     }
2082e55cbd72Sdrh   }
2083e55cbd72Sdrh }
2084e55cbd72Sdrh 
2085e55cbd72Sdrh /*
2086e55cbd72Sdrh ** Generate code to moves content from one register to another.
2087e55cbd72Sdrh ** Keep the column cache up-to-date.
2088e55cbd72Sdrh */
2089e55cbd72Sdrh void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo){
2090e55cbd72Sdrh   int i;
2091e55cbd72Sdrh   if( iFrom==iTo ) return;
2092e55cbd72Sdrh   sqlite3VdbeAddOp2(pParse->pVdbe, OP_Move, iFrom, iTo);
2093e55cbd72Sdrh   for(i=0; i<pParse->nColCache; i++){
2094e55cbd72Sdrh     if( pParse->aColCache[i].iReg==iFrom ){
2095e55cbd72Sdrh       pParse->aColCache[i].iReg = iTo;
2096e55cbd72Sdrh     }
2097e55cbd72Sdrh   }
2098945498f3Sdrh }
2099945498f3Sdrh 
2100fec19aadSdrh /*
2101652fbf55Sdrh ** Return true if any register in the range iFrom..iTo (inclusive)
2102652fbf55Sdrh ** is used as part of the column cache.
2103652fbf55Sdrh */
2104652fbf55Sdrh static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2105652fbf55Sdrh   int i;
2106652fbf55Sdrh   for(i=0; i<pParse->nColCache; i++){
2107652fbf55Sdrh     int r = pParse->aColCache[i].iReg;
2108652fbf55Sdrh     if( r>=iFrom && r<=iTo ) return 1;
2109652fbf55Sdrh   }
2110652fbf55Sdrh   return 0;
2111652fbf55Sdrh }
2112652fbf55Sdrh 
2113652fbf55Sdrh /*
2114652fbf55Sdrh ** Theres is a value in register iCurrent.  We ultimately want
2115652fbf55Sdrh ** the value to be in register iTarget.  It might be that
2116652fbf55Sdrh ** iCurrent and iTarget are the same register.
2117652fbf55Sdrh **
2118652fbf55Sdrh ** We are going to modify the value, so we need to make sure it
2119652fbf55Sdrh ** is not a cached register.  If iCurrent is a cached register,
2120652fbf55Sdrh ** then try to move the value over to iTarget.  If iTarget is a
2121652fbf55Sdrh ** cached register, then clear the corresponding cache line.
2122652fbf55Sdrh **
2123652fbf55Sdrh ** Return the register that the value ends up in.
2124652fbf55Sdrh */
2125652fbf55Sdrh int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
2126da250ea5Sdrh   int i;
2127652fbf55Sdrh   assert( pParse->pVdbe!=0 );
2128652fbf55Sdrh   if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
2129652fbf55Sdrh     return iCurrent;
2130652fbf55Sdrh   }
21312f7794c1Sdrh   if( iCurrent!=iTarget ){
2132652fbf55Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
21332f7794c1Sdrh   }
2134da250ea5Sdrh   for(i=0; i<pParse->nColCache; i++){
2135da250ea5Sdrh     if( pParse->aColCache[i].iReg==iTarget ){
2136da250ea5Sdrh       pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
2137da250ea5Sdrh       pParse->iColCache = pParse->nColCache;
2138da250ea5Sdrh     }
2139da250ea5Sdrh   }
2140652fbf55Sdrh   return iTarget;
2141652fbf55Sdrh }
2142652fbf55Sdrh 
2143652fbf55Sdrh /*
2144191b54cbSdrh ** If the last instruction coded is an ephemeral copy of any of
2145191b54cbSdrh ** the registers in the nReg registers beginning with iReg, then
2146191b54cbSdrh ** convert the last instruction from OP_SCopy to OP_Copy.
2147191b54cbSdrh */
2148191b54cbSdrh void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
2149191b54cbSdrh   int addr;
2150191b54cbSdrh   VdbeOp *pOp;
2151191b54cbSdrh   Vdbe *v;
2152191b54cbSdrh 
2153191b54cbSdrh   v = pParse->pVdbe;
2154191b54cbSdrh   addr = sqlite3VdbeCurrentAddr(v);
2155191b54cbSdrh   pOp = sqlite3VdbeGetOp(v, addr-1);
2156d7eb2ed5Sdanielk1977   assert( pOp || pParse->db->mallocFailed );
2157d7eb2ed5Sdanielk1977   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
2158191b54cbSdrh     pOp->opcode = OP_Copy;
2159191b54cbSdrh   }
2160191b54cbSdrh }
2161191b54cbSdrh 
2162191b54cbSdrh /*
2163cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
21642dcef11bSdrh ** expression.  Attempt to store the results in register "target".
21652dcef11bSdrh ** Return the register where results are stored.
2166389a1adbSdrh **
21672dcef11bSdrh ** With this routine, there is no guaranteed that results will
21682dcef11bSdrh ** be stored in target.  The result might be stored in some other
21692dcef11bSdrh ** register if it is convenient to do so.  The calling function
21702dcef11bSdrh ** must check the return code and move the results to the desired
21712dcef11bSdrh ** register.
2172cce7d176Sdrh */
2173678ccce8Sdrh int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
21742dcef11bSdrh   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
21752dcef11bSdrh   int op;                   /* The opcode being coded */
21762dcef11bSdrh   int inReg = target;       /* Results stored in register inReg */
21772dcef11bSdrh   int regFree1 = 0;         /* If non-zero free this temporary register */
21782dcef11bSdrh   int regFree2 = 0;         /* If non-zero free this temporary register */
2179678ccce8Sdrh   int r1, r2, r3, r4;       /* Various register numbers */
2180ffe07b2dSdrh 
2181389a1adbSdrh   assert( v!=0 || pParse->db->mallocFailed );
21829cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
2183389a1adbSdrh   if( v==0 ) return 0;
2184389a1adbSdrh 
2185389a1adbSdrh   if( pExpr==0 ){
2186389a1adbSdrh     op = TK_NULL;
2187389a1adbSdrh   }else{
2188f2bc013cSdrh     op = pExpr->op;
2189389a1adbSdrh   }
2190f2bc013cSdrh   switch( op ){
219113449892Sdrh     case TK_AGG_COLUMN: {
219213449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
219313449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
219413449892Sdrh       if( !pAggInfo->directMode ){
21959de221dfSdrh         assert( pCol->iMem>0 );
21969de221dfSdrh         inReg = pCol->iMem;
219713449892Sdrh         break;
219813449892Sdrh       }else if( pAggInfo->useSortingIdx ){
2199389a1adbSdrh         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
2200389a1adbSdrh                               pCol->iSorterColumn, target);
220113449892Sdrh         break;
220213449892Sdrh       }
220313449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
220413449892Sdrh     }
2205967e8b73Sdrh     case TK_COLUMN: {
2206ffe07b2dSdrh       if( pExpr->iTable<0 ){
2207ffe07b2dSdrh         /* This only happens when coding check constraints */
2208aa9b8963Sdrh         assert( pParse->ckBase>0 );
2209aa9b8963Sdrh         inReg = pExpr->iColumn + pParse->ckBase;
2210c4a3c779Sdrh       }else{
2211c5499befSdrh         testcase( (pExpr->flags & EP_AnyAff)!=0 );
2212e55cbd72Sdrh         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2213da250ea5Sdrh                                  pExpr->iColumn, pExpr->iTable, target,
2214da250ea5Sdrh                                  pExpr->flags & EP_AnyAff);
22152282792aSdrh       }
2216cce7d176Sdrh       break;
2217cce7d176Sdrh     }
2218cce7d176Sdrh     case TK_INTEGER: {
22199de221dfSdrh       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
2220fec19aadSdrh       break;
222151e9a445Sdrh     }
2222598f1340Sdrh     case TK_FLOAT: {
22239de221dfSdrh       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
2224598f1340Sdrh       break;
2225598f1340Sdrh     }
2226fec19aadSdrh     case TK_STRING: {
22271e536953Sdanielk1977       sqlite3DequoteExpr(pParse->db, pExpr);
22289de221dfSdrh       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
222966a5167bSdrh                         (char*)pExpr->token.z, pExpr->token.n);
2230cce7d176Sdrh       break;
2231cce7d176Sdrh     }
2232f0863fe5Sdrh     case TK_NULL: {
22339de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2234f0863fe5Sdrh       break;
2235f0863fe5Sdrh     }
22365338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
2237c572ef7fSdanielk1977     case TK_BLOB: {
22386c8c6cecSdrh       int n;
22396c8c6cecSdrh       const char *z;
2240ca48c90fSdrh       char *zBlob;
2241ca48c90fSdrh       assert( pExpr->token.n>=3 );
2242ca48c90fSdrh       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
2243ca48c90fSdrh       assert( pExpr->token.z[1]=='\'' );
2244ca48c90fSdrh       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
22456c8c6cecSdrh       n = pExpr->token.n - 3;
22462646da7eSdrh       z = (char*)pExpr->token.z + 2;
2247ca48c90fSdrh       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2248ca48c90fSdrh       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2249c572ef7fSdanielk1977       break;
2250c572ef7fSdanielk1977     }
22515338a5f7Sdanielk1977 #endif
225250457896Sdrh     case TK_VARIABLE: {
22539de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
2254895d7472Sdrh       if( pExpr->token.n>1 ){
225566a5167bSdrh         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
2256895d7472Sdrh       }
225750457896Sdrh       break;
225850457896Sdrh     }
22594e0cff60Sdrh     case TK_REGISTER: {
22609de221dfSdrh       inReg = pExpr->iTable;
22614e0cff60Sdrh       break;
22624e0cff60Sdrh     }
2263487e262fSdrh #ifndef SQLITE_OMIT_CAST
2264487e262fSdrh     case TK_CAST: {
2265487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
2266f0113000Sdanielk1977       int aff, to_op;
22672dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
22688a51256cSdrh       aff = sqlite3AffinityType(&pExpr->token);
2269f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
2270f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
2271f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
2272f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
2273f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
2274f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
2275c5499befSdrh       testcase( to_op==OP_ToText );
2276c5499befSdrh       testcase( to_op==OP_ToBlob );
2277c5499befSdrh       testcase( to_op==OP_ToNumeric );
2278c5499befSdrh       testcase( to_op==OP_ToInt );
2279c5499befSdrh       testcase( to_op==OP_ToReal );
22802dcef11bSdrh       sqlite3VdbeAddOp1(v, to_op, inReg);
2281c5499befSdrh       testcase( usedAsColumnCache(pParse, inReg, inReg) );
2282b3843a82Sdrh       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
2283487e262fSdrh       break;
2284487e262fSdrh     }
2285487e262fSdrh #endif /* SQLITE_OMIT_CAST */
2286c9b84a1fSdrh     case TK_LT:
2287c9b84a1fSdrh     case TK_LE:
2288c9b84a1fSdrh     case TK_GT:
2289c9b84a1fSdrh     case TK_GE:
2290c9b84a1fSdrh     case TK_NE:
2291c9b84a1fSdrh     case TK_EQ: {
2292f2bc013cSdrh       assert( TK_LT==OP_Lt );
2293f2bc013cSdrh       assert( TK_LE==OP_Le );
2294f2bc013cSdrh       assert( TK_GT==OP_Gt );
2295f2bc013cSdrh       assert( TK_GE==OP_Ge );
2296f2bc013cSdrh       assert( TK_EQ==OP_Eq );
2297f2bc013cSdrh       assert( TK_NE==OP_Ne );
2298c5499befSdrh       testcase( op==TK_LT );
2299c5499befSdrh       testcase( op==TK_LE );
2300c5499befSdrh       testcase( op==TK_GT );
2301c5499befSdrh       testcase( op==TK_GE );
2302c5499befSdrh       testcase( op==TK_EQ );
2303c5499befSdrh       testcase( op==TK_NE );
2304da250ea5Sdrh       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
2305da250ea5Sdrh                                   pExpr->pRight, &r2, &regFree2);
230635573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
230735573356Sdrh                   r1, r2, inReg, SQLITE_STOREP2);
2308c5499befSdrh       testcase( regFree1==0 );
2309c5499befSdrh       testcase( regFree2==0 );
2310a37cdde0Sdanielk1977       break;
2311c9b84a1fSdrh     }
2312cce7d176Sdrh     case TK_AND:
2313cce7d176Sdrh     case TK_OR:
2314cce7d176Sdrh     case TK_PLUS:
2315cce7d176Sdrh     case TK_STAR:
2316cce7d176Sdrh     case TK_MINUS:
2317bf4133cbSdrh     case TK_REM:
2318bf4133cbSdrh     case TK_BITAND:
2319bf4133cbSdrh     case TK_BITOR:
232017c40294Sdrh     case TK_SLASH:
2321bf4133cbSdrh     case TK_LSHIFT:
2322855eb1cfSdrh     case TK_RSHIFT:
23230040077dSdrh     case TK_CONCAT: {
2324f2bc013cSdrh       assert( TK_AND==OP_And );
2325f2bc013cSdrh       assert( TK_OR==OP_Or );
2326f2bc013cSdrh       assert( TK_PLUS==OP_Add );
2327f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
2328f2bc013cSdrh       assert( TK_REM==OP_Remainder );
2329f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
2330f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
2331f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
2332f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
2333f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
2334f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
2335c5499befSdrh       testcase( op==TK_AND );
2336c5499befSdrh       testcase( op==TK_OR );
2337c5499befSdrh       testcase( op==TK_PLUS );
2338c5499befSdrh       testcase( op==TK_MINUS );
2339c5499befSdrh       testcase( op==TK_REM );
2340c5499befSdrh       testcase( op==TK_BITAND );
2341c5499befSdrh       testcase( op==TK_BITOR );
2342c5499befSdrh       testcase( op==TK_SLASH );
2343c5499befSdrh       testcase( op==TK_LSHIFT );
2344c5499befSdrh       testcase( op==TK_RSHIFT );
2345c5499befSdrh       testcase( op==TK_CONCAT );
23462dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
23472dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
23485b6afba9Sdrh       sqlite3VdbeAddOp3(v, op, r2, r1, target);
2349c5499befSdrh       testcase( regFree1==0 );
2350c5499befSdrh       testcase( regFree2==0 );
23510040077dSdrh       break;
23520040077dSdrh     }
2353cce7d176Sdrh     case TK_UMINUS: {
2354fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
2355fec19aadSdrh       assert( pLeft );
2356fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
2357fec19aadSdrh         Token *p = &pLeft->token;
2358fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
23599de221dfSdrh           codeReal(v, (char*)p->z, p->n, 1, target);
2360e6840900Sdrh         }else{
23619de221dfSdrh           codeInteger(v, (char*)p->z, p->n, 1, target);
2362e6840900Sdrh         }
23633c84ddffSdrh       }else{
23642dcef11bSdrh         regFree1 = r1 = sqlite3GetTempReg(pParse);
23653c84ddffSdrh         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
2366e55cbd72Sdrh         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
23672dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
2368c5499befSdrh         testcase( regFree2==0 );
23693c84ddffSdrh       }
23709de221dfSdrh       inReg = target;
23716e142f54Sdrh       break;
23726e142f54Sdrh     }
2373bf4133cbSdrh     case TK_BITNOT:
23746e142f54Sdrh     case TK_NOT: {
2375f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
2376f2bc013cSdrh       assert( TK_NOT==OP_Not );
2377c5499befSdrh       testcase( op==TK_BITNOT );
2378c5499befSdrh       testcase( op==TK_NOT );
23792dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2380c5499befSdrh       testcase( inReg==target );
2381c5499befSdrh       testcase( usedAsColumnCache(pParse, inReg, inReg) );
2382652fbf55Sdrh       inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
23832dcef11bSdrh       sqlite3VdbeAddOp1(v, op, inReg);
2384cce7d176Sdrh       break;
2385cce7d176Sdrh     }
2386cce7d176Sdrh     case TK_ISNULL:
2387cce7d176Sdrh     case TK_NOTNULL: {
23886a288a33Sdrh       int addr;
2389f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
2390f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
2391c5499befSdrh       testcase( op==TK_ISNULL );
2392c5499befSdrh       testcase( op==TK_NOTNULL );
23939de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
23942dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2395c5499befSdrh       testcase( regFree1==0 );
23962dcef11bSdrh       addr = sqlite3VdbeAddOp1(v, op, r1);
23979de221dfSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
23986a288a33Sdrh       sqlite3VdbeJumpHere(v, addr);
2399a37cdde0Sdanielk1977       break;
2400f2bc013cSdrh     }
24012282792aSdrh     case TK_AGG_FUNCTION: {
240213449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
24037e56e711Sdrh       if( pInfo==0 ){
24047e56e711Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
24057e56e711Sdrh             &pExpr->span);
24067e56e711Sdrh       }else{
24079de221dfSdrh         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
24087e56e711Sdrh       }
24092282792aSdrh       break;
24102282792aSdrh     }
2411b71090fdSdrh     case TK_CONST_FUNC:
2412cce7d176Sdrh     case TK_FUNCTION: {
2413cce7d176Sdrh       ExprList *pList = pExpr->pList;
241489425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
24150bce8354Sdrh       FuncDef *pDef;
24164b59ab5eSdrh       int nId;
24174b59ab5eSdrh       const char *zId;
241813449892Sdrh       int constMask = 0;
2419682f68b0Sdanielk1977       int i;
242017435752Sdrh       sqlite3 *db = pParse->db;
242117435752Sdrh       u8 enc = ENC(db);
2422dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
242317435752Sdrh 
2424c5499befSdrh       testcase( op==TK_CONST_FUNC );
2425c5499befSdrh       testcase( op==TK_FUNCTION );
24262646da7eSdrh       zId = (char*)pExpr->token.z;
2427b71090fdSdrh       nId = pExpr->token.n;
2428d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
24290bce8354Sdrh       assert( pDef!=0 );
2430892d3179Sdrh       if( pList ){
2431892d3179Sdrh         nExpr = pList->nExpr;
24322dcef11bSdrh         r1 = sqlite3GetTempRange(pParse, nExpr);
2433191b54cbSdrh         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
2434892d3179Sdrh       }else{
2435d847eaadSdrh         nExpr = r1 = 0;
2436892d3179Sdrh       }
2437b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
2438a43fa227Sdrh       /* Possibly overload the function if the first argument is
2439a43fa227Sdrh       ** a virtual table column.
2440a43fa227Sdrh       **
2441a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2442a43fa227Sdrh       ** second argument, not the first, as the argument to test to
2443a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
2444a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
2445a43fa227Sdrh       ** control overloading) ends up as the second argument to the
2446a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
2447a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
2448a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
2449a43fa227Sdrh       */
24506a03a1c5Sdrh       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
245117435752Sdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
24526a03a1c5Sdrh       }else if( nExpr>0 ){
245317435752Sdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
2454b7f6f68fSdrh       }
2455b7f6f68fSdrh #endif
2456682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
2457d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
245813449892Sdrh           constMask |= (1<<i);
2459d02eb1fdSdanielk1977         }
2460dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
2461dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
2462dc1bdc4fSdanielk1977         }
2463dc1bdc4fSdanielk1977       }
2464dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
2465dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
246666a5167bSdrh         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
2467682f68b0Sdanielk1977       }
24682dcef11bSdrh       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
246966a5167bSdrh                         (char*)pDef, P4_FUNCDEF);
247098757157Sdrh       sqlite3VdbeChangeP5(v, nExpr);
24712dcef11bSdrh       if( nExpr ){
24722dcef11bSdrh         sqlite3ReleaseTempRange(pParse, r1, nExpr);
24732dcef11bSdrh       }
2474da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
24756ec2733bSdrh       break;
24766ec2733bSdrh     }
2477fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
2478fe2093d7Sdrh     case TK_EXISTS:
247919a775c2Sdrh     case TK_SELECT: {
2480c5499befSdrh       testcase( op==TK_EXISTS );
2481c5499befSdrh       testcase( op==TK_SELECT );
248241714d6fSdrh       if( pExpr->iColumn==0 ){
2483b3bce662Sdanielk1977         sqlite3CodeSubselect(pParse, pExpr);
248441714d6fSdrh       }
24859de221dfSdrh       inReg = pExpr->iColumn;
248619a775c2Sdrh       break;
248719a775c2Sdrh     }
2488fef5208cSdrh     case TK_IN: {
24896a288a33Sdrh       int j1, j2, j3, j4, j5;
249094a11211Sdrh       char affinity;
24919a96b668Sdanielk1977       int eType;
24929a96b668Sdanielk1977 
24939a96b668Sdanielk1977       eType = sqlite3FindInIndex(pParse, pExpr, 0);
2494e014a838Sdanielk1977 
2495e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
2496e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
249766a5167bSdrh       ** P4 of OP_MakeRecord.
2498e014a838Sdanielk1977       */
249994a11211Sdrh       affinity = comparisonAffinity(pExpr);
2500e014a838Sdanielk1977 
25012dcef11bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2502e014a838Sdanielk1977 
2503e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
2504e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
2505e014a838Sdanielk1977       */
25062dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2507c5499befSdrh       testcase( regFree1==0 );
25082dcef11bSdrh       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
25092dcef11bSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
25106a288a33Sdrh       j2  = sqlite3VdbeAddOp0(v, OP_Goto);
25116a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
25129a96b668Sdanielk1977       if( eType==IN_INDEX_ROWID ){
2513678ccce8Sdrh         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, r1);
25142dcef11bSdrh         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, r1);
25156a288a33Sdrh         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
25166a288a33Sdrh         sqlite3VdbeJumpHere(v, j3);
25176a288a33Sdrh         sqlite3VdbeJumpHere(v, j4);
25189a96b668Sdanielk1977       }else{
25192dcef11bSdrh         r2 = regFree2 = sqlite3GetTempReg(pParse);
25201db639ceSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
2521da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, r1, 1);
25222dcef11bSdrh         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
25239a96b668Sdanielk1977       }
25242dcef11bSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
25256a288a33Sdrh       sqlite3VdbeJumpHere(v, j2);
25266a288a33Sdrh       sqlite3VdbeJumpHere(v, j5);
2527fef5208cSdrh       break;
2528fef5208cSdrh     }
252993758c8dSdanielk1977 #endif
25302dcef11bSdrh     /*
25312dcef11bSdrh     **    x BETWEEN y AND z
25322dcef11bSdrh     **
25332dcef11bSdrh     ** This is equivalent to
25342dcef11bSdrh     **
25352dcef11bSdrh     **    x>=y AND x<=z
25362dcef11bSdrh     **
25372dcef11bSdrh     ** X is stored in pExpr->pLeft.
25382dcef11bSdrh     ** Y is stored in pExpr->pList->a[0].pExpr.
25392dcef11bSdrh     ** Z is stored in pExpr->pList->a[1].pExpr.
25402dcef11bSdrh     */
2541fef5208cSdrh     case TK_BETWEEN: {
2542be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2543be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
2544be5c89acSdrh       Expr *pRight = pLItem->pExpr;
254535573356Sdrh 
2546da250ea5Sdrh       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
2547da250ea5Sdrh                                   pRight, &r2, &regFree2);
2548c5499befSdrh       testcase( regFree1==0 );
2549c5499befSdrh       testcase( regFree2==0 );
25502dcef11bSdrh       r3 = sqlite3GetTempReg(pParse);
2551678ccce8Sdrh       r4 = sqlite3GetTempReg(pParse);
255235573356Sdrh       codeCompare(pParse, pLeft, pRight, OP_Ge,
255335573356Sdrh                   r1, r2, r3, SQLITE_STOREP2);
2554be5c89acSdrh       pLItem++;
2555be5c89acSdrh       pRight = pLItem->pExpr;
25562dcef11bSdrh       sqlite3ReleaseTempReg(pParse, regFree2);
25572dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
2558c5499befSdrh       testcase( regFree2==0 );
2559678ccce8Sdrh       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
2560678ccce8Sdrh       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
25612dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r3);
2562678ccce8Sdrh       sqlite3ReleaseTempReg(pParse, r4);
2563fef5208cSdrh       break;
2564fef5208cSdrh     }
25654f07e5fbSdrh     case TK_UPLUS: {
25662dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2567a2e00042Sdrh       break;
2568a2e00042Sdrh     }
25692dcef11bSdrh 
25702dcef11bSdrh     /*
25712dcef11bSdrh     ** Form A:
25722dcef11bSdrh     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
25732dcef11bSdrh     **
25742dcef11bSdrh     ** Form B:
25752dcef11bSdrh     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
25762dcef11bSdrh     **
25772dcef11bSdrh     ** Form A is can be transformed into the equivalent form B as follows:
25782dcef11bSdrh     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
25792dcef11bSdrh     **        WHEN x=eN THEN rN ELSE y END
25802dcef11bSdrh     **
25812dcef11bSdrh     ** X (if it exists) is in pExpr->pLeft.
25822dcef11bSdrh     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
25832dcef11bSdrh     ** ELSE clause and no other term matches, then the result of the
25842dcef11bSdrh     ** exprssion is NULL.
25852dcef11bSdrh     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
25862dcef11bSdrh     **
25872dcef11bSdrh     ** The result of the expression is the Ri for the first matching Ei,
25882dcef11bSdrh     ** or if there is no matching Ei, the ELSE term Y, or if there is
25892dcef11bSdrh     ** no ELSE term, NULL.
25902dcef11bSdrh     */
259117a7f8ddSdrh     case TK_CASE: {
25922dcef11bSdrh       int endLabel;                     /* GOTO label for end of CASE stmt */
25932dcef11bSdrh       int nextCase;                     /* GOTO label for next WHEN clause */
25942dcef11bSdrh       int nExpr;                        /* 2x number of WHEN terms */
25952dcef11bSdrh       int i;                            /* Loop counter */
25962dcef11bSdrh       ExprList *pEList;                 /* List of WHEN terms */
25972dcef11bSdrh       struct ExprList_item *aListelem;  /* Array of WHEN terms */
25982dcef11bSdrh       Expr opCompare;                   /* The X==Ei expression */
25992dcef11bSdrh       Expr cacheX;                      /* Cached expression X */
26002dcef11bSdrh       Expr *pX;                         /* The X expression */
26012dcef11bSdrh       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
260217a7f8ddSdrh 
260317a7f8ddSdrh       assert(pExpr->pList);
260417a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
260517a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
2606be5c89acSdrh       pEList = pExpr->pList;
2607be5c89acSdrh       aListelem = pEList->a;
2608be5c89acSdrh       nExpr = pEList->nExpr;
26092dcef11bSdrh       endLabel = sqlite3VdbeMakeLabel(v);
26102dcef11bSdrh       if( (pX = pExpr->pLeft)!=0 ){
26112dcef11bSdrh         cacheX = *pX;
2612c5499befSdrh         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
26132dcef11bSdrh         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
2614c5499befSdrh         testcase( regFree1==0 );
26152dcef11bSdrh         cacheX.op = TK_REGISTER;
2616678ccce8Sdrh         cacheX.iColumn = 0;
26172dcef11bSdrh         opCompare.op = TK_EQ;
26182dcef11bSdrh         opCompare.pLeft = &cacheX;
26192dcef11bSdrh         pTest = &opCompare;
2620cce7d176Sdrh       }
2621c5499befSdrh       pParse->disableColCache++;
2622f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
26232dcef11bSdrh         if( pX ){
26242dcef11bSdrh           opCompare.pRight = aListelem[i].pExpr;
2625f5905aa7Sdrh         }else{
26262dcef11bSdrh           pTest = aListelem[i].pExpr;
262717a7f8ddSdrh         }
26282dcef11bSdrh         nextCase = sqlite3VdbeMakeLabel(v);
2629c5499befSdrh         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
26302dcef11bSdrh         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
2631c5499befSdrh         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
2632c5499befSdrh         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
26339de221dfSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
26342dcef11bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
26352dcef11bSdrh         sqlite3VdbeResolveLabel(v, nextCase);
2636f570f011Sdrh       }
263717a7f8ddSdrh       if( pExpr->pRight ){
26389de221dfSdrh         sqlite3ExprCode(pParse, pExpr->pRight, target);
263917a7f8ddSdrh       }else{
26409de221dfSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
264117a7f8ddSdrh       }
26422dcef11bSdrh       sqlite3VdbeResolveLabel(v, endLabel);
2643c5499befSdrh       assert( pParse->disableColCache>0 );
2644c5499befSdrh       pParse->disableColCache--;
26456f34903eSdanielk1977       break;
26466f34903eSdanielk1977     }
26475338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
26486f34903eSdanielk1977     case TK_RAISE: {
26496f34903eSdanielk1977       if( !pParse->trigStack ){
26504adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
2651da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
2652389a1adbSdrh         return 0;
26536f34903eSdanielk1977       }
2654ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
2655ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
26566f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
2657ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
26581e536953Sdanielk1977          sqlite3DequoteExpr(pParse->db, pExpr);
265966a5167bSdrh          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
26602646da7eSdrh                         (char*)pExpr->token.z, pExpr->token.n);
26616f34903eSdanielk1977       } else {
26626f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
266366a5167bSdrh          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
266466a5167bSdrh          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
2665d4e70ebdSdrh          VdbeComment((v, "raise(IGNORE)"));
26666f34903eSdanielk1977       }
2667ffe07b2dSdrh       break;
266817a7f8ddSdrh     }
26695338a5f7Sdanielk1977 #endif
2670ffe07b2dSdrh   }
26712dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
26722dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
26732dcef11bSdrh   return inReg;
26745b6afba9Sdrh }
26752dcef11bSdrh 
26762dcef11bSdrh /*
26772dcef11bSdrh ** Generate code to evaluate an expression and store the results
26782dcef11bSdrh ** into a register.  Return the register number where the results
26792dcef11bSdrh ** are stored.
26802dcef11bSdrh **
26812dcef11bSdrh ** If the register is a temporary register that can be deallocated,
2682678ccce8Sdrh ** then write its number into *pReg.  If the result register is not
26832dcef11bSdrh ** a temporary, then set *pReg to zero.
26842dcef11bSdrh */
26852dcef11bSdrh int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
26862dcef11bSdrh   int r1 = sqlite3GetTempReg(pParse);
26872dcef11bSdrh   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
26882dcef11bSdrh   if( r2==r1 ){
26892dcef11bSdrh     *pReg = r1;
26902dcef11bSdrh   }else{
26912dcef11bSdrh     sqlite3ReleaseTempReg(pParse, r1);
26922dcef11bSdrh     *pReg = 0;
26932dcef11bSdrh   }
26942dcef11bSdrh   return r2;
26952dcef11bSdrh }
26962dcef11bSdrh 
26972dcef11bSdrh /*
26982dcef11bSdrh ** Generate code that will evaluate expression pExpr and store the
26992dcef11bSdrh ** results in register target.  The results are guaranteed to appear
27002dcef11bSdrh ** in register target.
27012dcef11bSdrh */
27022dcef11bSdrh int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
27039cbf3425Sdrh   int inReg;
27049cbf3425Sdrh 
27059cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
27069cbf3425Sdrh   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
27070e359b30Sdrh   assert( pParse->pVdbe || pParse->db->mallocFailed );
27080e359b30Sdrh   if( inReg!=target && pParse->pVdbe ){
27099cbf3425Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
271017a7f8ddSdrh   }
2711389a1adbSdrh   return target;
2712cce7d176Sdrh }
2713cce7d176Sdrh 
2714cce7d176Sdrh /*
27152dcef11bSdrh ** Generate code that evalutes the given expression and puts the result
2716de4fcfddSdrh ** in register target.
271725303780Sdrh **
27182dcef11bSdrh ** Also make a copy of the expression results into another "cache" register
27192dcef11bSdrh ** and modify the expression so that the next time it is evaluated,
27202dcef11bSdrh ** the result is a copy of the cache register.
27212dcef11bSdrh **
27222dcef11bSdrh ** This routine is used for expressions that are used multiple
27232dcef11bSdrh ** times.  They are evaluated once and the results of the expression
27242dcef11bSdrh ** are reused.
272525303780Sdrh */
27262dcef11bSdrh int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
272725303780Sdrh   Vdbe *v = pParse->pVdbe;
27282dcef11bSdrh   int inReg;
27292dcef11bSdrh   inReg = sqlite3ExprCode(pParse, pExpr, target);
2730de4fcfddSdrh   assert( target>0 );
27312dcef11bSdrh   if( pExpr->op!=TK_REGISTER ){
273225303780Sdrh     int iMem;
27332dcef11bSdrh     iMem = ++pParse->nMem;
27342dcef11bSdrh     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
27352dcef11bSdrh     pExpr->iTable = iMem;
2736678ccce8Sdrh     pExpr->iColumn = pExpr->op;
273725303780Sdrh     pExpr->op = TK_REGISTER;
273825303780Sdrh   }
27392dcef11bSdrh   return inReg;
274025303780Sdrh }
27412dcef11bSdrh 
2742678ccce8Sdrh /*
274347de955eSdrh ** Return TRUE if pExpr is an constant expression that is appropriate
274447de955eSdrh ** for factoring out of a loop.  Appropriate expressions are:
274547de955eSdrh **
274647de955eSdrh **    *  Any expression that evaluates to two or more opcodes.
274747de955eSdrh **
274847de955eSdrh **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
274947de955eSdrh **       or OP_Variable that does not need to be placed in a
275047de955eSdrh **       specific register.
275147de955eSdrh **
275247de955eSdrh ** There is no point in factoring out single-instruction constant
275347de955eSdrh ** expressions that need to be placed in a particular register.
275447de955eSdrh ** We could factor them out, but then we would end up adding an
275547de955eSdrh ** OP_SCopy instruction to move the value into the correct register
275647de955eSdrh ** later.  We might as well just use the original instruction and
275747de955eSdrh ** avoid the OP_SCopy.
275847de955eSdrh */
275947de955eSdrh static int isAppropriateForFactoring(Expr *p){
276047de955eSdrh   if( !sqlite3ExprIsConstantNotJoin(p) ){
276147de955eSdrh     return 0;  /* Only constant expressions are appropriate for factoring */
276247de955eSdrh   }
276347de955eSdrh   if( (p->flags & EP_FixedDest)==0 ){
276447de955eSdrh     return 1;  /* Any constant without a fixed destination is appropriate */
276547de955eSdrh   }
276647de955eSdrh   while( p->op==TK_UPLUS ) p = p->pLeft;
276747de955eSdrh   switch( p->op ){
276847de955eSdrh #ifndef SQLITE_OMIT_BLOB_LITERAL
276947de955eSdrh     case TK_BLOB:
277047de955eSdrh #endif
277147de955eSdrh     case TK_VARIABLE:
277247de955eSdrh     case TK_INTEGER:
277347de955eSdrh     case TK_FLOAT:
277447de955eSdrh     case TK_NULL:
277547de955eSdrh     case TK_STRING: {
277647de955eSdrh       testcase( p->op==TK_BLOB );
277747de955eSdrh       testcase( p->op==TK_VARIABLE );
277847de955eSdrh       testcase( p->op==TK_INTEGER );
277947de955eSdrh       testcase( p->op==TK_FLOAT );
278047de955eSdrh       testcase( p->op==TK_NULL );
278147de955eSdrh       testcase( p->op==TK_STRING );
278247de955eSdrh       /* Single-instruction constants with a fixed destination are
278347de955eSdrh       ** better done in-line.  If we factor them, they will just end
278447de955eSdrh       ** up generating an OP_SCopy to move the value to the destination
278547de955eSdrh       ** register. */
278647de955eSdrh       return 0;
278747de955eSdrh     }
278847de955eSdrh     case TK_UMINUS: {
278947de955eSdrh        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
279047de955eSdrh          return 0;
279147de955eSdrh        }
279247de955eSdrh        break;
279347de955eSdrh     }
279447de955eSdrh     default: {
279547de955eSdrh       break;
279647de955eSdrh     }
279747de955eSdrh   }
279847de955eSdrh   return 1;
279947de955eSdrh }
280047de955eSdrh 
280147de955eSdrh /*
280247de955eSdrh ** If pExpr is a constant expression that is appropriate for
280347de955eSdrh ** factoring out of a loop, then evaluate the expression
2804678ccce8Sdrh ** into a register and convert the expression into a TK_REGISTER
2805678ccce8Sdrh ** expression.
2806678ccce8Sdrh */
2807678ccce8Sdrh static int evalConstExpr(void *pArg, Expr *pExpr){
2808678ccce8Sdrh   Parse *pParse = (Parse*)pArg;
280947de955eSdrh   switch( pExpr->op ){
281047de955eSdrh     case TK_REGISTER: {
2811678ccce8Sdrh       return 1;
2812678ccce8Sdrh     }
281347de955eSdrh     case TK_FUNCTION:
281447de955eSdrh     case TK_AGG_FUNCTION:
281547de955eSdrh     case TK_CONST_FUNC: {
281647de955eSdrh       /* The arguments to a function have a fixed destination.
281747de955eSdrh       ** Mark them this way to avoid generated unneeded OP_SCopy
281847de955eSdrh       ** instructions.
281947de955eSdrh       */
282047de955eSdrh       ExprList *pList = pExpr->pList;
282147de955eSdrh       if( pList ){
282247de955eSdrh         int i = pList->nExpr;
282347de955eSdrh         struct ExprList_item *pItem = pList->a;
282447de955eSdrh         for(; i>0; i--, pItem++){
282547de955eSdrh           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
282647de955eSdrh         }
282747de955eSdrh       }
282847de955eSdrh       break;
282947de955eSdrh     }
283047de955eSdrh   }
283147de955eSdrh   if( isAppropriateForFactoring(pExpr) ){
2832678ccce8Sdrh     int r1 = ++pParse->nMem;
2833678ccce8Sdrh     int r2;
2834678ccce8Sdrh     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
2835c5499befSdrh     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
2836678ccce8Sdrh     pExpr->iColumn = pExpr->op;
2837678ccce8Sdrh     pExpr->op = TK_REGISTER;
2838678ccce8Sdrh     pExpr->iTable = r2;
2839678ccce8Sdrh     return 1;
2840678ccce8Sdrh   }
2841678ccce8Sdrh   return 0;
2842678ccce8Sdrh }
2843678ccce8Sdrh 
2844678ccce8Sdrh /*
2845678ccce8Sdrh ** Preevaluate constant subexpressions within pExpr and store the
2846678ccce8Sdrh ** results in registers.  Modify pExpr so that the constant subexpresions
2847678ccce8Sdrh ** are TK_REGISTER opcodes that refer to the precomputed values.
2848678ccce8Sdrh */
2849678ccce8Sdrh void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
2850678ccce8Sdrh    walkExprTree(pExpr, evalConstExpr, pParse);
2851678ccce8Sdrh }
2852678ccce8Sdrh 
285325303780Sdrh 
285425303780Sdrh /*
2855268380caSdrh ** Generate code that pushes the value of every element of the given
28569cbf3425Sdrh ** expression list into a sequence of registers beginning at target.
2857268380caSdrh **
2858892d3179Sdrh ** Return the number of elements evaluated.
2859268380caSdrh */
28604adee20fSdanielk1977 int sqlite3ExprCodeExprList(
2861268380caSdrh   Parse *pParse,     /* Parsing context */
2862389a1adbSdrh   ExprList *pList,   /* The expression list to be coded */
2863191b54cbSdrh   int target,        /* Where to write results */
2864191b54cbSdrh   int doHardCopy     /* Call sqlite3ExprHardCopy on each element if true */
2865268380caSdrh ){
2866268380caSdrh   struct ExprList_item *pItem;
28679cbf3425Sdrh   int i, n;
2868892d3179Sdrh   assert( pList!=0 || pParse->db->mallocFailed );
2869892d3179Sdrh   if( pList==0 ){
2870892d3179Sdrh     return 0;
2871892d3179Sdrh   }
28729cbf3425Sdrh   assert( target>0 );
2873268380caSdrh   n = pList->nExpr;
2874191b54cbSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
2875191b54cbSdrh     sqlite3ExprCode(pParse, pItem->pExpr, target+i);
2876191b54cbSdrh     if( doHardCopy ) sqlite3ExprHardCopy(pParse, target, n);
2877268380caSdrh   }
2878f9b596ebSdrh   return n;
2879268380caSdrh }
2880268380caSdrh 
2881268380caSdrh /*
2882cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
2883cce7d176Sdrh ** to the label "dest" if the expression is true but execution
2884cce7d176Sdrh ** continues straight thru if the expression is false.
2885f5905aa7Sdrh **
2886f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
288735573356Sdrh ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
2888f2bc013cSdrh **
2889f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
2890f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2891f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
2892f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
2893f2bc013cSdrh ** below verify that the numbers are aligned correctly.
2894cce7d176Sdrh */
28954adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2896cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2897cce7d176Sdrh   int op = 0;
28982dcef11bSdrh   int regFree1 = 0;
28992dcef11bSdrh   int regFree2 = 0;
29002dcef11bSdrh   int r1, r2;
29012dcef11bSdrh 
290235573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
2903daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2904f2bc013cSdrh   op = pExpr->op;
2905f2bc013cSdrh   switch( op ){
2906cce7d176Sdrh     case TK_AND: {
29074adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
2908c5499befSdrh       testcase( jumpIfNull==0 );
2909c5499befSdrh       testcase( pParse->disableColCache==0 );
291035573356Sdrh       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
2911e55cbd72Sdrh       pParse->disableColCache++;
29124adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2913c5499befSdrh       assert( pParse->disableColCache>0 );
2914e55cbd72Sdrh       pParse->disableColCache--;
29154adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2916cce7d176Sdrh       break;
2917cce7d176Sdrh     }
2918cce7d176Sdrh     case TK_OR: {
2919c5499befSdrh       testcase( jumpIfNull==0 );
2920c5499befSdrh       testcase( pParse->disableColCache==0 );
29214adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2922e55cbd72Sdrh       pParse->disableColCache++;
29234adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2924c5499befSdrh       assert( pParse->disableColCache>0 );
2925e55cbd72Sdrh       pParse->disableColCache--;
2926cce7d176Sdrh       break;
2927cce7d176Sdrh     }
2928cce7d176Sdrh     case TK_NOT: {
2929c5499befSdrh       testcase( jumpIfNull==0 );
29304adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2931cce7d176Sdrh       break;
2932cce7d176Sdrh     }
2933cce7d176Sdrh     case TK_LT:
2934cce7d176Sdrh     case TK_LE:
2935cce7d176Sdrh     case TK_GT:
2936cce7d176Sdrh     case TK_GE:
2937cce7d176Sdrh     case TK_NE:
29380ac65892Sdrh     case TK_EQ: {
2939f2bc013cSdrh       assert( TK_LT==OP_Lt );
2940f2bc013cSdrh       assert( TK_LE==OP_Le );
2941f2bc013cSdrh       assert( TK_GT==OP_Gt );
2942f2bc013cSdrh       assert( TK_GE==OP_Ge );
2943f2bc013cSdrh       assert( TK_EQ==OP_Eq );
2944f2bc013cSdrh       assert( TK_NE==OP_Ne );
2945c5499befSdrh       testcase( op==TK_LT );
2946c5499befSdrh       testcase( op==TK_LE );
2947c5499befSdrh       testcase( op==TK_GT );
2948c5499befSdrh       testcase( op==TK_GE );
2949c5499befSdrh       testcase( op==TK_EQ );
2950c5499befSdrh       testcase( op==TK_NE );
2951c5499befSdrh       testcase( jumpIfNull==0 );
2952da250ea5Sdrh       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
2953da250ea5Sdrh                                   pExpr->pRight, &r2, &regFree2);
295435573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
29552dcef11bSdrh                   r1, r2, dest, jumpIfNull);
2956c5499befSdrh       testcase( regFree1==0 );
2957c5499befSdrh       testcase( regFree2==0 );
2958cce7d176Sdrh       break;
2959cce7d176Sdrh     }
2960cce7d176Sdrh     case TK_ISNULL:
2961cce7d176Sdrh     case TK_NOTNULL: {
2962f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
2963f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
2964c5499befSdrh       testcase( op==TK_ISNULL );
2965c5499befSdrh       testcase( op==TK_NOTNULL );
29662dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
29672dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
2968c5499befSdrh       testcase( regFree1==0 );
2969cce7d176Sdrh       break;
2970cce7d176Sdrh     }
2971fef5208cSdrh     case TK_BETWEEN: {
29722dcef11bSdrh       /*    x BETWEEN y AND z
29730202b29eSdanielk1977       **
29742dcef11bSdrh       ** Is equivalent to
29752dcef11bSdrh       **
29762dcef11bSdrh       **    x>=y AND x<=z
29772dcef11bSdrh       **
29782dcef11bSdrh       ** Code it as such, taking care to do the common subexpression
29792dcef11bSdrh       ** elementation of x.
29800202b29eSdanielk1977       */
29812dcef11bSdrh       Expr exprAnd;
29822dcef11bSdrh       Expr compLeft;
29832dcef11bSdrh       Expr compRight;
29842dcef11bSdrh       Expr exprX;
29850202b29eSdanielk1977 
29862dcef11bSdrh       exprX = *pExpr->pLeft;
29872dcef11bSdrh       exprAnd.op = TK_AND;
29882dcef11bSdrh       exprAnd.pLeft = &compLeft;
29892dcef11bSdrh       exprAnd.pRight = &compRight;
29902dcef11bSdrh       compLeft.op = TK_GE;
29912dcef11bSdrh       compLeft.pLeft = &exprX;
29922dcef11bSdrh       compLeft.pRight = pExpr->pList->a[0].pExpr;
29932dcef11bSdrh       compRight.op = TK_LE;
29942dcef11bSdrh       compRight.pLeft = &exprX;
29952dcef11bSdrh       compRight.pRight = pExpr->pList->a[1].pExpr;
29962dcef11bSdrh       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
2997c5499befSdrh       testcase( regFree1==0 );
29982dcef11bSdrh       exprX.op = TK_REGISTER;
2999c5499befSdrh       testcase( jumpIfNull==0 );
30002dcef11bSdrh       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
3001fef5208cSdrh       break;
3002fef5208cSdrh     }
3003cce7d176Sdrh     default: {
30042dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
30052dcef11bSdrh       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
3006c5499befSdrh       testcase( regFree1==0 );
3007c5499befSdrh       testcase( jumpIfNull==0 );
3008cce7d176Sdrh       break;
3009cce7d176Sdrh     }
3010cce7d176Sdrh   }
30112dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
30122dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3013cce7d176Sdrh }
3014cce7d176Sdrh 
3015cce7d176Sdrh /*
301666b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
3017cce7d176Sdrh ** to the label "dest" if the expression is false but execution
3018cce7d176Sdrh ** continues straight thru if the expression is true.
3019f5905aa7Sdrh **
3020f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
302135573356Sdrh ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
302235573356Sdrh ** is 0.
3023cce7d176Sdrh */
30244adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3025cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3026cce7d176Sdrh   int op = 0;
30272dcef11bSdrh   int regFree1 = 0;
30282dcef11bSdrh   int regFree2 = 0;
30292dcef11bSdrh   int r1, r2;
30302dcef11bSdrh 
303135573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
3032daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
3033f2bc013cSdrh 
3034f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
3035f2bc013cSdrh   **
3036f2bc013cSdrh   **       pExpr->op            op
3037f2bc013cSdrh   **       ---------          ----------
3038f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
3039f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
3040f2bc013cSdrh   **       TK_NE              OP_Eq
3041f2bc013cSdrh   **       TK_EQ              OP_Ne
3042f2bc013cSdrh   **       TK_GT              OP_Le
3043f2bc013cSdrh   **       TK_LE              OP_Gt
3044f2bc013cSdrh   **       TK_GE              OP_Lt
3045f2bc013cSdrh   **       TK_LT              OP_Ge
3046f2bc013cSdrh   **
3047f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
3048f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
3049f2bc013cSdrh   ** can compute the mapping above using the following expression.
3050f2bc013cSdrh   ** Assert()s verify that the computation is correct.
3051f2bc013cSdrh   */
3052f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3053f2bc013cSdrh 
3054f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
3055f2bc013cSdrh   */
3056f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3057f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3058f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
3059f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
3060f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
3061f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
3062f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
3063f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
3064f2bc013cSdrh 
3065cce7d176Sdrh   switch( pExpr->op ){
3066cce7d176Sdrh     case TK_AND: {
3067c5499befSdrh       testcase( jumpIfNull==0 );
3068c5499befSdrh       testcase( pParse->disableColCache==0 );
30694adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3070e55cbd72Sdrh       pParse->disableColCache++;
30714adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3072c5499befSdrh       assert( pParse->disableColCache>0 );
3073e55cbd72Sdrh       pParse->disableColCache--;
3074cce7d176Sdrh       break;
3075cce7d176Sdrh     }
3076cce7d176Sdrh     case TK_OR: {
30774adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3078c5499befSdrh       testcase( jumpIfNull==0 );
3079c5499befSdrh       testcase( pParse->disableColCache==0 );
308035573356Sdrh       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
3081e55cbd72Sdrh       pParse->disableColCache++;
30824adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3083c5499befSdrh       assert( pParse->disableColCache>0 );
3084e55cbd72Sdrh       pParse->disableColCache--;
30854adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3086cce7d176Sdrh       break;
3087cce7d176Sdrh     }
3088cce7d176Sdrh     case TK_NOT: {
30894adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3090cce7d176Sdrh       break;
3091cce7d176Sdrh     }
3092cce7d176Sdrh     case TK_LT:
3093cce7d176Sdrh     case TK_LE:
3094cce7d176Sdrh     case TK_GT:
3095cce7d176Sdrh     case TK_GE:
3096cce7d176Sdrh     case TK_NE:
3097cce7d176Sdrh     case TK_EQ: {
3098c5499befSdrh       testcase( op==TK_LT );
3099c5499befSdrh       testcase( op==TK_LE );
3100c5499befSdrh       testcase( op==TK_GT );
3101c5499befSdrh       testcase( op==TK_GE );
3102c5499befSdrh       testcase( op==TK_EQ );
3103c5499befSdrh       testcase( op==TK_NE );
3104c5499befSdrh       testcase( jumpIfNull==0 );
3105da250ea5Sdrh       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
3106da250ea5Sdrh                                   pExpr->pRight, &r2, &regFree2);
310735573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
31082dcef11bSdrh                   r1, r2, dest, jumpIfNull);
3109c5499befSdrh       testcase( regFree1==0 );
3110c5499befSdrh       testcase( regFree2==0 );
3111cce7d176Sdrh       break;
3112cce7d176Sdrh     }
3113cce7d176Sdrh     case TK_ISNULL:
3114cce7d176Sdrh     case TK_NOTNULL: {
3115c5499befSdrh       testcase( op==TK_ISNULL );
3116c5499befSdrh       testcase( op==TK_NOTNULL );
31172dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
31182dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
3119c5499befSdrh       testcase( regFree1==0 );
3120cce7d176Sdrh       break;
3121cce7d176Sdrh     }
3122fef5208cSdrh     case TK_BETWEEN: {
31232dcef11bSdrh       /*    x BETWEEN y AND z
31240202b29eSdanielk1977       **
31252dcef11bSdrh       ** Is equivalent to
31262dcef11bSdrh       **
31272dcef11bSdrh       **    x>=y AND x<=z
31282dcef11bSdrh       **
31292dcef11bSdrh       ** Code it as such, taking care to do the common subexpression
31302dcef11bSdrh       ** elementation of x.
31310202b29eSdanielk1977       */
31322dcef11bSdrh       Expr exprAnd;
31332dcef11bSdrh       Expr compLeft;
31342dcef11bSdrh       Expr compRight;
31352dcef11bSdrh       Expr exprX;
3136be5c89acSdrh 
31372dcef11bSdrh       exprX = *pExpr->pLeft;
31382dcef11bSdrh       exprAnd.op = TK_AND;
31392dcef11bSdrh       exprAnd.pLeft = &compLeft;
31402dcef11bSdrh       exprAnd.pRight = &compRight;
31412dcef11bSdrh       compLeft.op = TK_GE;
31422dcef11bSdrh       compLeft.pLeft = &exprX;
31432dcef11bSdrh       compLeft.pRight = pExpr->pList->a[0].pExpr;
31442dcef11bSdrh       compRight.op = TK_LE;
31452dcef11bSdrh       compRight.pLeft = &exprX;
31462dcef11bSdrh       compRight.pRight = pExpr->pList->a[1].pExpr;
31472dcef11bSdrh       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
3148c5499befSdrh       testcase( regFree1==0 );
31492dcef11bSdrh       exprX.op = TK_REGISTER;
3150c5499befSdrh       testcase( jumpIfNull==0 );
31512dcef11bSdrh       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
3152fef5208cSdrh       break;
3153fef5208cSdrh     }
3154cce7d176Sdrh     default: {
31552dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
31562dcef11bSdrh       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
3157c5499befSdrh       testcase( regFree1==0 );
3158c5499befSdrh       testcase( jumpIfNull==0 );
3159cce7d176Sdrh       break;
3160cce7d176Sdrh     }
3161cce7d176Sdrh   }
31622dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
31632dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3164cce7d176Sdrh }
31652282792aSdrh 
31662282792aSdrh /*
31672282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
31682282792aSdrh ** if they are identical and return FALSE if they differ in any way.
3169d40aab0eSdrh **
3170d40aab0eSdrh ** Sometimes this routine will return FALSE even if the two expressions
3171d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
3172d40aab0eSdrh ** identical, we return FALSE just to be safe.  So if this routine
3173d40aab0eSdrh ** returns false, then you do not really know for certain if the two
3174d40aab0eSdrh ** expressions are the same.  But if you get a TRUE return, then you
3175d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
3176d40aab0eSdrh ** this routine is used, it does not hurt to get an extra FALSE - that
3177d40aab0eSdrh ** just might result in some slightly slower code.  But returning
3178d40aab0eSdrh ** an incorrect TRUE could lead to a malfunction.
31792282792aSdrh */
31804adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
31812282792aSdrh   int i;
31824b202ae2Sdanielk1977   if( pA==0||pB==0 ){
31834b202ae2Sdanielk1977     return pB==pA;
31842282792aSdrh   }
31852282792aSdrh   if( pA->op!=pB->op ) return 0;
3186fd357974Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
31874adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
31884adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
31892282792aSdrh   if( pA->pList ){
31902282792aSdrh     if( pB->pList==0 ) return 0;
31912282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
31922282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
31934adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
31942282792aSdrh         return 0;
31952282792aSdrh       }
31962282792aSdrh     }
31972282792aSdrh   }else if( pB->pList ){
31982282792aSdrh     return 0;
31992282792aSdrh   }
32002282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
32012f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
3202dd73521bSdrh   if( pA->op!=TK_COLUMN && pA->token.z ){
32032282792aSdrh     if( pB->token.z==0 ) return 0;
32046977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
32052646da7eSdrh     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
32062646da7eSdrh       return 0;
32072646da7eSdrh     }
32082282792aSdrh   }
32092282792aSdrh   return 1;
32102282792aSdrh }
32112282792aSdrh 
321213449892Sdrh 
32132282792aSdrh /*
321413449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
321513449892Sdrh ** the new element.  Return a negative number if malloc fails.
32162282792aSdrh */
321717435752Sdrh static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
321813449892Sdrh   int i;
3219cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
322017435752Sdrh        db,
3221cf643729Sdrh        pInfo->aCol,
3222cf643729Sdrh        sizeof(pInfo->aCol[0]),
3223cf643729Sdrh        3,
3224cf643729Sdrh        &pInfo->nColumn,
3225cf643729Sdrh        &pInfo->nColumnAlloc,
3226cf643729Sdrh        &i
3227cf643729Sdrh   );
322813449892Sdrh   return i;
32292282792aSdrh }
323013449892Sdrh 
323113449892Sdrh /*
323213449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
323313449892Sdrh ** the new element.  Return a negative number if malloc fails.
323413449892Sdrh */
323517435752Sdrh static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
323613449892Sdrh   int i;
3237cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
323817435752Sdrh        db,
3239cf643729Sdrh        pInfo->aFunc,
3240cf643729Sdrh        sizeof(pInfo->aFunc[0]),
3241cf643729Sdrh        3,
3242cf643729Sdrh        &pInfo->nFunc,
3243cf643729Sdrh        &pInfo->nFuncAlloc,
3244cf643729Sdrh        &i
3245cf643729Sdrh   );
324613449892Sdrh   return i;
32472282792aSdrh }
32482282792aSdrh 
32492282792aSdrh /*
3250626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
3251626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
3252626a879aSdrh ** for additional information.
32532282792aSdrh **
3254626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
32552282792aSdrh */
3256626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
32572282792aSdrh   int i;
3258a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
3259a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
3260a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
326113449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
326213449892Sdrh 
32632282792aSdrh   switch( pExpr->op ){
326489c69d00Sdrh     case TK_AGG_COLUMN:
3265967e8b73Sdrh     case TK_COLUMN: {
326613449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
326713449892Sdrh       ** clause of the aggregate query */
326813449892Sdrh       if( pSrcList ){
326913449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
327013449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
327113449892Sdrh           struct AggInfo_col *pCol;
327213449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
327313449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
327413449892Sdrh             ** that is in the FROM clause of the aggregate query.
327513449892Sdrh             **
327613449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
327713449892Sdrh             ** is not an entry there already.
327813449892Sdrh             */
32797f906d63Sdrh             int k;
328013449892Sdrh             pCol = pAggInfo->aCol;
32817f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
328213449892Sdrh               if( pCol->iTable==pExpr->iTable &&
328313449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
32842282792aSdrh                 break;
32852282792aSdrh               }
32862282792aSdrh             }
32871e536953Sdanielk1977             if( (k>=pAggInfo->nColumn)
32881e536953Sdanielk1977              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
32891e536953Sdanielk1977             ){
32907f906d63Sdrh               pCol = &pAggInfo->aCol[k];
32910817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
329213449892Sdrh               pCol->iTable = pExpr->iTable;
329313449892Sdrh               pCol->iColumn = pExpr->iColumn;
32940a07c107Sdrh               pCol->iMem = ++pParse->nMem;
329513449892Sdrh               pCol->iSorterColumn = -1;
32965774b806Sdrh               pCol->pExpr = pExpr;
329713449892Sdrh               if( pAggInfo->pGroupBy ){
329813449892Sdrh                 int j, n;
329913449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
330013449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
330113449892Sdrh                 n = pGB->nExpr;
330213449892Sdrh                 for(j=0; j<n; j++, pTerm++){
330313449892Sdrh                   Expr *pE = pTerm->pExpr;
330413449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
330513449892Sdrh                       pE->iColumn==pExpr->iColumn ){
330613449892Sdrh                     pCol->iSorterColumn = j;
330713449892Sdrh                     break;
33082282792aSdrh                   }
330913449892Sdrh                 }
331013449892Sdrh               }
331113449892Sdrh               if( pCol->iSorterColumn<0 ){
331213449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
331313449892Sdrh               }
331413449892Sdrh             }
331513449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
331613449892Sdrh             ** because it was there before or because we just created it).
331713449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
331813449892Sdrh             ** pAggInfo->aCol[] entry.
331913449892Sdrh             */
332013449892Sdrh             pExpr->pAggInfo = pAggInfo;
332113449892Sdrh             pExpr->op = TK_AGG_COLUMN;
33227f906d63Sdrh             pExpr->iAgg = k;
332313449892Sdrh             break;
332413449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
332513449892Sdrh         } /* end loop over pSrcList */
3326a58fdfb1Sdanielk1977       }
3327626a879aSdrh       return 1;
33282282792aSdrh     }
33292282792aSdrh     case TK_AGG_FUNCTION: {
333013449892Sdrh       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
333113449892Sdrh       ** to be ignored */
3332a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
333313449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
333413449892Sdrh         ** function that is already in the pAggInfo structure
333513449892Sdrh         */
333613449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
333713449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
333813449892Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
33392282792aSdrh             break;
33402282792aSdrh           }
33412282792aSdrh         }
334213449892Sdrh         if( i>=pAggInfo->nFunc ){
334313449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
334413449892Sdrh           */
334514db2665Sdanielk1977           u8 enc = ENC(pParse->db);
33461e536953Sdanielk1977           i = addAggInfoFunc(pParse->db, pAggInfo);
334713449892Sdrh           if( i>=0 ){
334813449892Sdrh             pItem = &pAggInfo->aFunc[i];
334913449892Sdrh             pItem->pExpr = pExpr;
33500a07c107Sdrh             pItem->iMem = ++pParse->nMem;
335113449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
33522646da7eSdrh                    (char*)pExpr->token.z, pExpr->token.n,
3353d8123366Sdanielk1977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
3354fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
3355fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
3356fd357974Sdrh             }else{
3357fd357974Sdrh               pItem->iDistinct = -1;
3358fd357974Sdrh             }
33592282792aSdrh           }
336013449892Sdrh         }
336113449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
336213449892Sdrh         */
33632282792aSdrh         pExpr->iAgg = i;
336413449892Sdrh         pExpr->pAggInfo = pAggInfo;
3365626a879aSdrh         return 1;
33662282792aSdrh       }
33672282792aSdrh     }
3368a58fdfb1Sdanielk1977   }
336913449892Sdrh 
337013449892Sdrh   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
337113449892Sdrh   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
337213449892Sdrh   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
337313449892Sdrh   */
3374a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
3375a58fdfb1Sdanielk1977     pNC->nDepth++;
3376a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
3377a58fdfb1Sdanielk1977     pNC->nDepth--;
3378a58fdfb1Sdanielk1977   }
3379626a879aSdrh   return 0;
33802282792aSdrh }
3381626a879aSdrh 
3382626a879aSdrh /*
3383626a879aSdrh ** Analyze the given expression looking for aggregate functions and
3384626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
3385626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
3386626a879aSdrh **
3387626a879aSdrh ** This routine should only be called after the expression has been
3388626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
3389626a879aSdrh */
3390d2b3e23bSdrh void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
3391a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
33922282792aSdrh }
33935d9a4af9Sdrh 
33945d9a4af9Sdrh /*
33955d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
33965d9a4af9Sdrh ** expression list.  Return the number of errors.
33975d9a4af9Sdrh **
33985d9a4af9Sdrh ** If an error is found, the analysis is cut short.
33995d9a4af9Sdrh */
3400d2b3e23bSdrh void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
34015d9a4af9Sdrh   struct ExprList_item *pItem;
34025d9a4af9Sdrh   int i;
34035d9a4af9Sdrh   if( pList ){
3404d2b3e23bSdrh     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
3405d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
34065d9a4af9Sdrh     }
34075d9a4af9Sdrh   }
34085d9a4af9Sdrh }
3409892d3179Sdrh 
3410892d3179Sdrh /*
3411892d3179Sdrh ** Allocate or deallocate temporary use registers during code generation.
3412892d3179Sdrh */
3413892d3179Sdrh int sqlite3GetTempReg(Parse *pParse){
3414e55cbd72Sdrh   int i, r;
3415e55cbd72Sdrh   if( pParse->nTempReg==0 ){
3416892d3179Sdrh     return ++pParse->nMem;
3417892d3179Sdrh   }
3418e55cbd72Sdrh   for(i=0; i<pParse->nTempReg; i++){
3419e55cbd72Sdrh     r = pParse->aTempReg[i];
3420e55cbd72Sdrh     if( usedAsColumnCache(pParse, r, r) ) continue;
3421e55cbd72Sdrh   }
3422e55cbd72Sdrh   if( i>=pParse->nTempReg ){
3423e55cbd72Sdrh     return ++pParse->nMem;
3424e55cbd72Sdrh   }
3425e55cbd72Sdrh   while( i<pParse->nTempReg-1 ){
3426e55cbd72Sdrh     pParse->aTempReg[i] = pParse->aTempReg[i+1];
3427e55cbd72Sdrh   }
3428e55cbd72Sdrh   pParse->nTempReg--;
3429e55cbd72Sdrh   return r;
3430892d3179Sdrh }
3431892d3179Sdrh void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
34322dcef11bSdrh   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
3433892d3179Sdrh     pParse->aTempReg[pParse->nTempReg++] = iReg;
3434892d3179Sdrh   }
3435892d3179Sdrh }
3436892d3179Sdrh 
3437892d3179Sdrh /*
3438892d3179Sdrh ** Allocate or deallocate a block of nReg consecutive registers
3439892d3179Sdrh */
3440892d3179Sdrh int sqlite3GetTempRange(Parse *pParse, int nReg){
3441e55cbd72Sdrh   int i, n;
3442892d3179Sdrh   i = pParse->iRangeReg;
3443e55cbd72Sdrh   n = pParse->nRangeReg;
3444e55cbd72Sdrh   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
3445892d3179Sdrh     pParse->iRangeReg += nReg;
3446892d3179Sdrh     pParse->nRangeReg -= nReg;
3447892d3179Sdrh   }else{
3448892d3179Sdrh     i = pParse->nMem+1;
3449892d3179Sdrh     pParse->nMem += nReg;
3450892d3179Sdrh   }
3451892d3179Sdrh   return i;
3452892d3179Sdrh }
3453892d3179Sdrh void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
3454892d3179Sdrh   if( nReg>pParse->nRangeReg ){
3455892d3179Sdrh     pParse->nRangeReg = nReg;
3456892d3179Sdrh     pParse->iRangeReg = iReg;
3457892d3179Sdrh   }
3458892d3179Sdrh }
3459