xref: /sqlite-3.40.0/src/expr.c (revision bcbb04e5)
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*bcbb04e5Sdanielk1977 ** $Id: expr.c,v 1.295 2007/05/29 12:11:30 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
1804738cb9Sdrh #include <ctype.h>
19a2e00042Sdrh 
20e014a838Sdanielk1977 /*
21e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
22e014a838Sdanielk1977 **
23e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
24e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
25e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
26e014a838Sdanielk1977 ** indicating no affinity for the expression.
27e014a838Sdanielk1977 **
28e014a838Sdanielk1977 ** i.e. the WHERE clause expresssions in the following statements all
29e014a838Sdanielk1977 ** have an affinity:
30e014a838Sdanielk1977 **
31e014a838Sdanielk1977 ** CREATE TABLE t1(a);
32e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
33e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
34e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
35e014a838Sdanielk1977 */
36bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
37487e262fSdrh   int op = pExpr->op;
38487e262fSdrh   if( op==TK_SELECT ){
39bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
40a37cdde0Sdanielk1977   }
41487e262fSdrh #ifndef SQLITE_OMIT_CAST
42487e262fSdrh   if( op==TK_CAST ){
438a51256cSdrh     return sqlite3AffinityType(&pExpr->token);
44487e262fSdrh   }
45487e262fSdrh #endif
46a37cdde0Sdanielk1977   return pExpr->affinity;
47a37cdde0Sdanielk1977 }
48a37cdde0Sdanielk1977 
4953db1458Sdrh /*
508b4c40d8Sdrh ** Set the collating sequence for expression pExpr to be the collating
518b4c40d8Sdrh ** sequence named by pToken.   Return a pointer to the revised expression.
52a34001c9Sdrh ** The collating sequence is marked as "explicit" using the EP_ExpCollate
53a34001c9Sdrh ** flag.  An explicit collating sequence will override implicit
54a34001c9Sdrh ** collating sequences.
558b4c40d8Sdrh */
568b4c40d8Sdrh Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
578b4c40d8Sdrh   CollSeq *pColl;
588b4c40d8Sdrh   if( pExpr==0 ) return 0;
598b4c40d8Sdrh   pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
608b4c40d8Sdrh   if( pColl ){
618b4c40d8Sdrh     pExpr->pColl = pColl;
628b4c40d8Sdrh     pExpr->flags |= EP_ExpCollate;
638b4c40d8Sdrh   }
648b4c40d8Sdrh   return pExpr;
658b4c40d8Sdrh }
668b4c40d8Sdrh 
678b4c40d8Sdrh /*
680202b29eSdanielk1977 ** Return the default collation sequence for the expression pExpr. If
690202b29eSdanielk1977 ** there is no default collation type, return 0.
700202b29eSdanielk1977 */
717cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
727cedc8d4Sdanielk1977   CollSeq *pColl = 0;
730202b29eSdanielk1977   if( pExpr ){
747cedc8d4Sdanielk1977     pColl = pExpr->pColl;
754f07e5fbSdrh     if( pExpr->op==TK_CAST && !pColl ){
767cedc8d4Sdanielk1977       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
770202b29eSdanielk1977     }
780202b29eSdanielk1977   }
797cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
807cedc8d4Sdanielk1977     pColl = 0;
817cedc8d4Sdanielk1977   }
827cedc8d4Sdanielk1977   return pColl;
830202b29eSdanielk1977 }
840202b29eSdanielk1977 
850202b29eSdanielk1977 /*
86626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
87626a879aSdrh ** type affinity of the other operand.  This routine returns the
8853db1458Sdrh ** type affinity that should be used for the comparison operator.
8953db1458Sdrh */
90e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
91bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
92e014a838Sdanielk1977   if( aff1 && aff2 ){
938df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
948df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
95e014a838Sdanielk1977     */
968a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
97e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
98e014a838Sdanielk1977     }else{
99e014a838Sdanielk1977       return SQLITE_AFF_NONE;
100e014a838Sdanielk1977     }
101e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
1025f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
1035f6a87b3Sdrh     ** results directly.
104e014a838Sdanielk1977     */
1055f6a87b3Sdrh     return SQLITE_AFF_NONE;
106e014a838Sdanielk1977   }else{
107e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
108fe05af87Sdrh     assert( aff1==0 || aff2==0 );
109e014a838Sdanielk1977     return (aff1 + aff2);
110e014a838Sdanielk1977   }
111e014a838Sdanielk1977 }
112e014a838Sdanielk1977 
11353db1458Sdrh /*
11453db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
11553db1458Sdrh ** be applied to both operands prior to doing the comparison.
11653db1458Sdrh */
117e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
118e014a838Sdanielk1977   char aff;
119e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
120e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
121e014a838Sdanielk1977           pExpr->op==TK_NE );
122e014a838Sdanielk1977   assert( pExpr->pLeft );
123bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
124e014a838Sdanielk1977   if( pExpr->pRight ){
125e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
126e014a838Sdanielk1977   }
127e014a838Sdanielk1977   else if( pExpr->pSelect ){
128e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
129e014a838Sdanielk1977   }
130e014a838Sdanielk1977   else if( !aff ){
131de087bd5Sdrh     aff = SQLITE_AFF_NONE;
132e014a838Sdanielk1977   }
133e014a838Sdanielk1977   return aff;
134e014a838Sdanielk1977 }
135e014a838Sdanielk1977 
136e014a838Sdanielk1977 /*
137e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
138e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
139e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
140e014a838Sdanielk1977 ** the comparison in pExpr.
141e014a838Sdanielk1977 */
142e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
143e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
1448a51256cSdrh   switch( aff ){
1458a51256cSdrh     case SQLITE_AFF_NONE:
1468a51256cSdrh       return 1;
1478a51256cSdrh     case SQLITE_AFF_TEXT:
1488a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
1498a51256cSdrh     default:
1508a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
1518a51256cSdrh   }
152e014a838Sdanielk1977 }
153e014a838Sdanielk1977 
154a37cdde0Sdanielk1977 /*
155a37cdde0Sdanielk1977 ** Return the P1 value that should be used for a binary comparison
156a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
157a37cdde0Sdanielk1977 ** If jumpIfNull is true, then set the low byte of the returned
158a37cdde0Sdanielk1977 ** P1 value to tell the opcode to jump if either expression
159a37cdde0Sdanielk1977 ** evaluates to NULL.
160a37cdde0Sdanielk1977 */
161e014a838Sdanielk1977 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
162bf3b721fSdanielk1977   char aff = sqlite3ExprAffinity(pExpr2);
163f0863fe5Sdrh   return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
164a37cdde0Sdanielk1977 }
165a37cdde0Sdanielk1977 
166a2e00042Sdrh /*
1670202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
1680202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
1690202b29eSdanielk1977 **
1700202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
1710202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
1720202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
1730202b29eSdanielk1977 ** type.
174*bcbb04e5Sdanielk1977 **
175*bcbb04e5Sdanielk1977 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
176*bcbb04e5Sdanielk1977 ** it is not considered.
1770202b29eSdanielk1977 */
178*bcbb04e5Sdanielk1977 CollSeq* sqlite3BinaryCompareCollSeq(
179*bcbb04e5Sdanielk1977   Parse *pParse,
180*bcbb04e5Sdanielk1977   Expr *pLeft,
181*bcbb04e5Sdanielk1977   Expr *pRight
182*bcbb04e5Sdanielk1977 ){
183ec41ddacSdrh   CollSeq *pColl;
184ec41ddacSdrh   assert( pLeft );
185ec41ddacSdrh   if( pLeft->flags & EP_ExpCollate ){
186ec41ddacSdrh     assert( pLeft->pColl );
187ec41ddacSdrh     pColl = pLeft->pColl;
188*bcbb04e5Sdanielk1977   }else if( pRight && pRight->flags & EP_ExpCollate ){
189ec41ddacSdrh     assert( pRight->pColl );
190ec41ddacSdrh     pColl = pRight->pColl;
191ec41ddacSdrh   }else{
192ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
1930202b29eSdanielk1977     if( !pColl ){
1947cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
1950202b29eSdanielk1977     }
196ec41ddacSdrh   }
1970202b29eSdanielk1977   return pColl;
1980202b29eSdanielk1977 }
1990202b29eSdanielk1977 
2000202b29eSdanielk1977 /*
201be5c89acSdrh ** Generate code for a comparison operator.
202be5c89acSdrh */
203be5c89acSdrh static int codeCompare(
204be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
205be5c89acSdrh   Expr *pLeft,      /* The left operand */
206be5c89acSdrh   Expr *pRight,     /* The right operand */
207be5c89acSdrh   int opcode,       /* The comparison opcode */
208be5c89acSdrh   int dest,         /* Jump here if true.  */
209be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
210be5c89acSdrh ){
211be5c89acSdrh   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
212*bcbb04e5Sdanielk1977   CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
213be5c89acSdrh   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
214be5c89acSdrh }
215be5c89acSdrh 
216be5c89acSdrh /*
217a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
218a76b5dfcSdrh ** for this node is obtained from sqliteMalloc().  The calling function
219a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
220a76b5dfcSdrh */
221e4e72072Sdrh Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
222a76b5dfcSdrh   Expr *pNew;
223a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
224a76b5dfcSdrh   if( pNew==0 ){
225d5d56523Sdanielk1977     /* When malloc fails, delete pLeft and pRight. Expressions passed to
226d5d56523Sdanielk1977     ** this function must always be allocated with sqlite3Expr() for this
227d5d56523Sdanielk1977     ** reason.
228d5d56523Sdanielk1977     */
229d5d56523Sdanielk1977     sqlite3ExprDelete(pLeft);
230d5d56523Sdanielk1977     sqlite3ExprDelete(pRight);
231a76b5dfcSdrh     return 0;
232a76b5dfcSdrh   }
233a76b5dfcSdrh   pNew->op = op;
234a76b5dfcSdrh   pNew->pLeft = pLeft;
235a76b5dfcSdrh   pNew->pRight = pRight;
236a58fdfb1Sdanielk1977   pNew->iAgg = -1;
237a76b5dfcSdrh   if( pToken ){
2384b59ab5eSdrh     assert( pToken->dyn==0 );
239145716b3Sdrh     pNew->span = pNew->token = *pToken;
240a34001c9Sdrh   }else if( pLeft ){
241a34001c9Sdrh     if( pRight ){
2424adee20fSdanielk1977       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
2435ffb3ac8Sdrh       if( pRight->flags & EP_ExpCollate ){
244a34001c9Sdrh         pNew->flags |= EP_ExpCollate;
245a34001c9Sdrh         pNew->pColl = pRight->pColl;
246a34001c9Sdrh       }
247a34001c9Sdrh     }
2485ffb3ac8Sdrh     if( pLeft->flags & EP_ExpCollate ){
249a34001c9Sdrh       pNew->flags |= EP_ExpCollate;
250a34001c9Sdrh       pNew->pColl = pLeft->pColl;
251a34001c9Sdrh     }
252a76b5dfcSdrh   }
253fc976065Sdanielk1977 
254fc976065Sdanielk1977   sqlite3ExprSetHeight(pNew);
255a76b5dfcSdrh   return pNew;
256a76b5dfcSdrh }
257a76b5dfcSdrh 
258a76b5dfcSdrh /*
259206f3d96Sdrh ** Works like sqlite3Expr() but frees its pLeft and pRight arguments
260206f3d96Sdrh ** if it fails due to a malloc problem.
261206f3d96Sdrh */
262206f3d96Sdrh Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
263206f3d96Sdrh   Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
264206f3d96Sdrh   if( pNew==0 ){
265206f3d96Sdrh     sqlite3ExprDelete(pLeft);
266206f3d96Sdrh     sqlite3ExprDelete(pRight);
267206f3d96Sdrh   }
268206f3d96Sdrh   return pNew;
269206f3d96Sdrh }
270206f3d96Sdrh 
271206f3d96Sdrh /*
2724e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
2734e0cff60Sdrh ** that look like this:   #0 #1 #2 ...  These terms refer to elements
274288d37f1Sdrh ** on the stack.  "#0" means the top of the stack.
275288d37f1Sdrh ** "#1" means the next down on the stack.  And so forth.
2764e0cff60Sdrh **
2774e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
2784e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
2794e0cff60Sdrh ** The returns an expression that will code to extract the value from
2804e0cff60Sdrh ** that memory location as needed.
2814e0cff60Sdrh */
2824e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
2834e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
2844e0cff60Sdrh   Expr *p;
2854e0cff60Sdrh   int depth;
2864e0cff60Sdrh   if( pParse->nested==0 ){
2874e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
2884e05c83bSdrh     return sqlite3Expr(TK_NULL, 0, 0, 0);
2894e0cff60Sdrh   }
290bb7ac00bSdrh   if( v==0 ) return 0;
2914e0cff60Sdrh   p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
29273c42a13Sdrh   if( p==0 ){
29373c42a13Sdrh     return 0;  /* Malloc failed */
29473c42a13Sdrh   }
2952646da7eSdrh   depth = atoi((char*)&pToken->z[1]);
2964e0cff60Sdrh   p->iTable = pParse->nMem++;
2974e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
2984e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
2994e0cff60Sdrh   return p;
3004e0cff60Sdrh }
3014e0cff60Sdrh 
3024e0cff60Sdrh /*
30391bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
30491bb0eedSdrh ** NULL, then just return the other expression.
30591bb0eedSdrh */
30691bb0eedSdrh Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
30791bb0eedSdrh   if( pLeft==0 ){
30891bb0eedSdrh     return pRight;
30991bb0eedSdrh   }else if( pRight==0 ){
31091bb0eedSdrh     return pLeft;
31191bb0eedSdrh   }else{
31291bb0eedSdrh     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
31391bb0eedSdrh   }
31491bb0eedSdrh }
31591bb0eedSdrh 
31691bb0eedSdrh /*
3176977fea8Sdrh ** Set the Expr.span field of the given expression to span all
318a76b5dfcSdrh ** text between the two given tokens.
319a76b5dfcSdrh */
3204adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
3214efc4754Sdrh   assert( pRight!=0 );
3224efc4754Sdrh   assert( pLeft!=0 );
3239e12800dSdanielk1977   if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
324ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
325145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
3266977fea8Sdrh       pExpr->span.z = pLeft->z;
32797903fefSdrh       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
3284b59ab5eSdrh     }else{
3296977fea8Sdrh       pExpr->span.z = 0;
3304b59ab5eSdrh     }
331a76b5dfcSdrh   }
332a76b5dfcSdrh }
333a76b5dfcSdrh 
334a76b5dfcSdrh /*
335a76b5dfcSdrh ** Construct a new expression node for a function with multiple
336a76b5dfcSdrh ** arguments.
337a76b5dfcSdrh */
3384adee20fSdanielk1977 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
339a76b5dfcSdrh   Expr *pNew;
3404b202ae2Sdanielk1977   assert( pToken );
341a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
342a76b5dfcSdrh   if( pNew==0 ){
343d5d56523Sdanielk1977     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
344a76b5dfcSdrh     return 0;
345a76b5dfcSdrh   }
346a76b5dfcSdrh   pNew->op = TK_FUNCTION;
347a76b5dfcSdrh   pNew->pList = pList;
3484b59ab5eSdrh   assert( pToken->dyn==0 );
349a76b5dfcSdrh   pNew->token = *pToken;
3506977fea8Sdrh   pNew->span = pNew->token;
351fc976065Sdanielk1977 
352fc976065Sdanielk1977   sqlite3ExprSetHeight(pNew);
353a76b5dfcSdrh   return pNew;
354a76b5dfcSdrh }
355a76b5dfcSdrh 
356a76b5dfcSdrh /*
357fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
358fa6bc000Sdrh ** in the original SQL statement.
359fa6bc000Sdrh **
360fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
361fa6bc000Sdrh ** variable number.
362fa6bc000Sdrh **
363fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
364fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
365fa6bc000Sdrh ** the SQL statement comes from an external source.
366fa6bc000Sdrh **
367fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
368fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
369fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
370fa6bc000Sdrh ** assigned.
371fa6bc000Sdrh */
372fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
373fa6bc000Sdrh   Token *pToken;
374fa6bc000Sdrh   if( pExpr==0 ) return;
375fa6bc000Sdrh   pToken = &pExpr->token;
376fa6bc000Sdrh   assert( pToken->n>=1 );
377fa6bc000Sdrh   assert( pToken->z!=0 );
378fa6bc000Sdrh   assert( pToken->z[0]!=0 );
379fa6bc000Sdrh   if( pToken->n==1 ){
380fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
381fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
382fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
383fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
384fa6bc000Sdrh     ** use it as the variable number */
385fa6bc000Sdrh     int i;
3862646da7eSdrh     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
387fa6bc000Sdrh     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
388fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
389fa6bc000Sdrh           SQLITE_MAX_VARIABLE_NUMBER);
390fa6bc000Sdrh     }
391fa6bc000Sdrh     if( i>pParse->nVar ){
392fa6bc000Sdrh       pParse->nVar = i;
393fa6bc000Sdrh     }
394fa6bc000Sdrh   }else{
395fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
396fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
397fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
398fa6bc000Sdrh     */
399fa6bc000Sdrh     int i, n;
400fa6bc000Sdrh     n = pToken->n;
401fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
402fa6bc000Sdrh       Expr *pE;
403fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
404fa6bc000Sdrh           && pE->token.n==n
405fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
406fa6bc000Sdrh         pExpr->iTable = pE->iTable;
407fa6bc000Sdrh         break;
408fa6bc000Sdrh       }
409fa6bc000Sdrh     }
410fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
411fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
412fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
413fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
414cf643729Sdrh         pParse->apVarExpr = sqliteReallocOrFree(pParse->apVarExpr,
415fa6bc000Sdrh                        pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
416fa6bc000Sdrh       }
4179e12800dSdanielk1977       if( !sqlite3MallocFailed() ){
418fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
419fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
420fa6bc000Sdrh       }
421fa6bc000Sdrh     }
422fa6bc000Sdrh   }
423832b2664Sdanielk1977   if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
424832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
425832b2664Sdanielk1977   }
426fa6bc000Sdrh }
427fa6bc000Sdrh 
428fa6bc000Sdrh /*
429a2e00042Sdrh ** Recursively delete an expression tree.
430a2e00042Sdrh */
4314adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
432a2e00042Sdrh   if( p==0 ) return;
4334efc4754Sdrh   if( p->span.dyn ) sqliteFree((char*)p->span.z);
4344efc4754Sdrh   if( p->token.dyn ) sqliteFree((char*)p->token.z);
4354adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
4364adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
4374adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
4384adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
439a2e00042Sdrh   sqliteFree(p);
440a2e00042Sdrh }
441a2e00042Sdrh 
442d2687b77Sdrh /*
443d2687b77Sdrh ** The Expr.token field might be a string literal that is quoted.
444d2687b77Sdrh ** If so, remove the quotation marks.
445d2687b77Sdrh */
446d2687b77Sdrh void sqlite3DequoteExpr(Expr *p){
447d2687b77Sdrh   if( ExprHasAnyProperty(p, EP_Dequoted) ){
448d2687b77Sdrh     return;
449d2687b77Sdrh   }
450d2687b77Sdrh   ExprSetProperty(p, EP_Dequoted);
451d2687b77Sdrh   if( p->token.dyn==0 ){
452d2687b77Sdrh     sqlite3TokenCopy(&p->token, &p->token);
453d2687b77Sdrh   }
454d2687b77Sdrh   sqlite3Dequote((char*)p->token.z);
455d2687b77Sdrh }
456d2687b77Sdrh 
457a76b5dfcSdrh 
458a76b5dfcSdrh /*
459ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
460ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
461ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
462ff78bd2fSdrh ** without effecting the originals.
463ff78bd2fSdrh **
4644adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
4654adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
466ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
467ff78bd2fSdrh **
468ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
469ff78bd2fSdrh */
4704adee20fSdanielk1977 Expr *sqlite3ExprDup(Expr *p){
471ff78bd2fSdrh   Expr *pNew;
472ff78bd2fSdrh   if( p==0 ) return 0;
473fcb78a49Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
474ff78bd2fSdrh   if( pNew==0 ) return 0;
4753b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
4766977fea8Sdrh   if( p->token.z!=0 ){
4772646da7eSdrh     pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
4784b59ab5eSdrh     pNew->token.dyn = 1;
4794b59ab5eSdrh   }else{
4804efc4754Sdrh     assert( pNew->token.z==0 );
4814b59ab5eSdrh   }
4826977fea8Sdrh   pNew->span.z = 0;
4834adee20fSdanielk1977   pNew->pLeft = sqlite3ExprDup(p->pLeft);
4844adee20fSdanielk1977   pNew->pRight = sqlite3ExprDup(p->pRight);
4854adee20fSdanielk1977   pNew->pList = sqlite3ExprListDup(p->pList);
4864adee20fSdanielk1977   pNew->pSelect = sqlite3SelectDup(p->pSelect);
487ff78bd2fSdrh   return pNew;
488ff78bd2fSdrh }
4894adee20fSdanielk1977 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
4904b59ab5eSdrh   if( pTo->dyn ) sqliteFree((char*)pTo->z);
4914b59ab5eSdrh   if( pFrom->z ){
4924b59ab5eSdrh     pTo->n = pFrom->n;
4932646da7eSdrh     pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
4944b59ab5eSdrh     pTo->dyn = 1;
4954b59ab5eSdrh   }else{
4964b59ab5eSdrh     pTo->z = 0;
4974b59ab5eSdrh   }
4984b59ab5eSdrh }
4994adee20fSdanielk1977 ExprList *sqlite3ExprListDup(ExprList *p){
500ff78bd2fSdrh   ExprList *pNew;
501145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
502ff78bd2fSdrh   int i;
503ff78bd2fSdrh   if( p==0 ) return 0;
504ff78bd2fSdrh   pNew = sqliteMalloc( sizeof(*pNew) );
505ff78bd2fSdrh   if( pNew==0 ) return 0;
5064305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
5073e7bc9caSdrh   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
508e0048400Sdanielk1977   if( pItem==0 ){
509e0048400Sdanielk1977     sqliteFree(pNew);
510e0048400Sdanielk1977     return 0;
511e0048400Sdanielk1977   }
512145716b3Sdrh   pOldItem = p->a;
513145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
5144b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
515145716b3Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
5166977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
5176977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
5184b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
5194b59ab5eSdrh       ** the names of columns in the result set needs this information */
5204adee20fSdanielk1977       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
5214b59ab5eSdrh     }
5221f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
5236f7adc8aSdrh             || pOldExpr->span.z==0
5249e12800dSdanielk1977             || sqlite3MallocFailed() );
525145716b3Sdrh     pItem->zName = sqliteStrDup(pOldItem->zName);
526145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
527145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
5283e7bc9caSdrh     pItem->done = 0;
529ff78bd2fSdrh   }
530ff78bd2fSdrh   return pNew;
531ff78bd2fSdrh }
53293758c8dSdanielk1977 
53393758c8dSdanielk1977 /*
53493758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
53593758c8dSdanielk1977 ** the build, then none of the following routines, except for
53693758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
53793758c8dSdanielk1977 ** called with a NULL argument.
53893758c8dSdanielk1977 */
5396a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
5406a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
5414adee20fSdanielk1977 SrcList *sqlite3SrcListDup(SrcList *p){
542ad3cab52Sdrh   SrcList *pNew;
543ad3cab52Sdrh   int i;
544113088ecSdrh   int nByte;
545ad3cab52Sdrh   if( p==0 ) return 0;
546113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
5474efc4754Sdrh   pNew = sqliteMallocRaw( nByte );
548ad3cab52Sdrh   if( pNew==0 ) return 0;
5494305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
550ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
5514efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
5524efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
553ed8a3bb1Sdrh     Table *pTab;
5544efc4754Sdrh     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
5554efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5564efc4754Sdrh     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
5574efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
5584efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
5591787ccabSdanielk1977     pNewItem->isPopulated = pOldItem->isPopulated;
560ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
561ed8a3bb1Sdrh     if( pTab ){
562ed8a3bb1Sdrh       pTab->nRef++;
563a1cb183dSdanielk1977     }
5644adee20fSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
5654adee20fSdanielk1977     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
5664adee20fSdanielk1977     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
5676c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
568ad3cab52Sdrh   }
569ad3cab52Sdrh   return pNew;
570ad3cab52Sdrh }
5714adee20fSdanielk1977 IdList *sqlite3IdListDup(IdList *p){
572ff78bd2fSdrh   IdList *pNew;
573ff78bd2fSdrh   int i;
574ff78bd2fSdrh   if( p==0 ) return 0;
5754efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*pNew) );
576ff78bd2fSdrh   if( pNew==0 ) return 0;
5774305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
5784efc4754Sdrh   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
579d5d56523Sdanielk1977   if( pNew->a==0 ){
580d5d56523Sdanielk1977     sqliteFree(pNew);
581d5d56523Sdanielk1977     return 0;
582d5d56523Sdanielk1977   }
583ff78bd2fSdrh   for(i=0; i<p->nId; i++){
5844efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
5854efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
5864efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5874efc4754Sdrh     pNewItem->idx = pOldItem->idx;
588ff78bd2fSdrh   }
589ff78bd2fSdrh   return pNew;
590ff78bd2fSdrh }
5914adee20fSdanielk1977 Select *sqlite3SelectDup(Select *p){
592ff78bd2fSdrh   Select *pNew;
593ff78bd2fSdrh   if( p==0 ) return 0;
5944efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
595ff78bd2fSdrh   if( pNew==0 ) return 0;
596ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
5974adee20fSdanielk1977   pNew->pEList = sqlite3ExprListDup(p->pEList);
5984adee20fSdanielk1977   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
5994adee20fSdanielk1977   pNew->pWhere = sqlite3ExprDup(p->pWhere);
6004adee20fSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
6014adee20fSdanielk1977   pNew->pHaving = sqlite3ExprDup(p->pHaving);
6024adee20fSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
603ff78bd2fSdrh   pNew->op = p->op;
6044adee20fSdanielk1977   pNew->pPrior = sqlite3SelectDup(p->pPrior);
605a2dc3b1aSdanielk1977   pNew->pLimit = sqlite3ExprDup(p->pLimit);
606a2dc3b1aSdanielk1977   pNew->pOffset = sqlite3ExprDup(p->pOffset);
6077b58daeaSdrh   pNew->iLimit = -1;
6087b58daeaSdrh   pNew->iOffset = -1;
609a1cb183dSdanielk1977   pNew->isResolved = p->isResolved;
610a1cb183dSdanielk1977   pNew->isAgg = p->isAgg;
611b9bb7c18Sdrh   pNew->usesEphm = 0;
6128e647b81Sdrh   pNew->disallowOrderBy = 0;
6130342b1f5Sdrh   pNew->pRightmost = 0;
614b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
615b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
616b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
617ff78bd2fSdrh   return pNew;
618ff78bd2fSdrh }
61993758c8dSdanielk1977 #else
62093758c8dSdanielk1977 Select *sqlite3SelectDup(Select *p){
62193758c8dSdanielk1977   assert( p==0 );
62293758c8dSdanielk1977   return 0;
62393758c8dSdanielk1977 }
62493758c8dSdanielk1977 #endif
625ff78bd2fSdrh 
626ff78bd2fSdrh 
627ff78bd2fSdrh /*
628a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
629a76b5dfcSdrh ** initially NULL, then create a new expression list.
630a76b5dfcSdrh */
6314adee20fSdanielk1977 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
632a76b5dfcSdrh   if( pList==0 ){
633a76b5dfcSdrh     pList = sqliteMalloc( sizeof(ExprList) );
634a76b5dfcSdrh     if( pList==0 ){
635d5d56523Sdanielk1977       goto no_mem;
636a76b5dfcSdrh     }
6374efc4754Sdrh     assert( pList->nAlloc==0 );
638a76b5dfcSdrh   }
6394305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
640d5d56523Sdanielk1977     struct ExprList_item *a;
641d5d56523Sdanielk1977     int n = pList->nAlloc*2 + 4;
642d5d56523Sdanielk1977     a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
643d5d56523Sdanielk1977     if( a==0 ){
644d5d56523Sdanielk1977       goto no_mem;
645a76b5dfcSdrh     }
646d5d56523Sdanielk1977     pList->a = a;
647d5d56523Sdanielk1977     pList->nAlloc = n;
648a76b5dfcSdrh   }
6494efc4754Sdrh   assert( pList->a!=0 );
6504efc4754Sdrh   if( pExpr || pName ){
6514efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
6524efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
653a99db3b6Sdrh     pItem->zName = sqlite3NameFromToken(pName);
654e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
655a76b5dfcSdrh   }
656a76b5dfcSdrh   return pList;
657d5d56523Sdanielk1977 
658d5d56523Sdanielk1977 no_mem:
659d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
660d5d56523Sdanielk1977   sqlite3ExprDelete(pExpr);
661d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
662d5d56523Sdanielk1977   return 0;
663a76b5dfcSdrh }
664a76b5dfcSdrh 
665a76b5dfcSdrh /*
6667a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
6677a15a4beSdanielk1977 ** leave an error message in pParse.
6687a15a4beSdanielk1977 */
6697a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
6707a15a4beSdanielk1977   Parse *pParse,
6717a15a4beSdanielk1977   ExprList *pEList,
6727a15a4beSdanielk1977   int iLimit,
6737a15a4beSdanielk1977   const char *zObject
6747a15a4beSdanielk1977 ){
675b4fc6794Sdanielk1977   if( pEList && pEList->nExpr>iLimit ){
6767a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
6777a15a4beSdanielk1977   }
6787a15a4beSdanielk1977 }
6797a15a4beSdanielk1977 
680fc976065Sdanielk1977 
681fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
682fc976065Sdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
683fc976065Sdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
684fc976065Sdanielk1977 ** of any expression tree referenced by the structure passed as the
685fc976065Sdanielk1977 ** first argument.
686fc976065Sdanielk1977 **
687fc976065Sdanielk1977 ** If this maximum height is greater than the current value pointed
688fc976065Sdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
689fc976065Sdanielk1977 ** value.
690fc976065Sdanielk1977 */
691fc976065Sdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
692fc976065Sdanielk1977   if( p ){
693fc976065Sdanielk1977     if( p->nHeight>*pnHeight ){
694fc976065Sdanielk1977       *pnHeight = p->nHeight;
695fc976065Sdanielk1977     }
696fc976065Sdanielk1977   }
697fc976065Sdanielk1977 }
698fc976065Sdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
699fc976065Sdanielk1977   if( p ){
700fc976065Sdanielk1977     int i;
701fc976065Sdanielk1977     for(i=0; i<p->nExpr; i++){
702fc976065Sdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
703fc976065Sdanielk1977     }
704fc976065Sdanielk1977   }
705fc976065Sdanielk1977 }
706fc976065Sdanielk1977 static void heightOfSelect(Select *p, int *pnHeight){
707fc976065Sdanielk1977   if( p ){
708fc976065Sdanielk1977     heightOfExpr(p->pWhere, pnHeight);
709fc976065Sdanielk1977     heightOfExpr(p->pHaving, pnHeight);
710fc976065Sdanielk1977     heightOfExpr(p->pLimit, pnHeight);
711fc976065Sdanielk1977     heightOfExpr(p->pOffset, pnHeight);
712fc976065Sdanielk1977     heightOfExprList(p->pEList, pnHeight);
713fc976065Sdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
714fc976065Sdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
715fc976065Sdanielk1977     heightOfSelect(p->pPrior, pnHeight);
716fc976065Sdanielk1977   }
717fc976065Sdanielk1977 }
718fc976065Sdanielk1977 
719fc976065Sdanielk1977 /*
720fc976065Sdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
721fc976065Sdanielk1977 ** argument. An expression with no children, Expr.pList or
722fc976065Sdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
723fc976065Sdanielk1977 ** has a height equal to the maximum height of any other
724fc976065Sdanielk1977 ** referenced Expr plus one.
725fc976065Sdanielk1977 */
726fc976065Sdanielk1977 void sqlite3ExprSetHeight(Expr *p){
727fc976065Sdanielk1977   int nHeight = 0;
728fc976065Sdanielk1977   heightOfExpr(p->pLeft, &nHeight);
729fc976065Sdanielk1977   heightOfExpr(p->pRight, &nHeight);
730fc976065Sdanielk1977   heightOfExprList(p->pList, &nHeight);
731fc976065Sdanielk1977   heightOfSelect(p->pSelect, &nHeight);
732fc976065Sdanielk1977   p->nHeight = nHeight + 1;
733fc976065Sdanielk1977 }
734fc976065Sdanielk1977 
735fc976065Sdanielk1977 /*
736fc976065Sdanielk1977 ** Return the maximum height of any expression tree referenced
737fc976065Sdanielk1977 ** by the select statement passed as an argument.
738fc976065Sdanielk1977 */
739fc976065Sdanielk1977 int sqlite3SelectExprHeight(Select *p){
740fc976065Sdanielk1977   int nHeight = 0;
741fc976065Sdanielk1977   heightOfSelect(p, &nHeight);
742fc976065Sdanielk1977   return nHeight;
743fc976065Sdanielk1977 }
744fc976065Sdanielk1977 #endif
745fc976065Sdanielk1977 
7467a15a4beSdanielk1977 /*
747a76b5dfcSdrh ** Delete an entire expression list.
748a76b5dfcSdrh */
7494adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
750a76b5dfcSdrh   int i;
751be5c89acSdrh   struct ExprList_item *pItem;
752a76b5dfcSdrh   if( pList==0 ) return;
7531bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
7541bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
755be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
756be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
757be5c89acSdrh     sqliteFree(pItem->zName);
758a76b5dfcSdrh   }
759a76b5dfcSdrh   sqliteFree(pList->a);
760a76b5dfcSdrh   sqliteFree(pList);
761a76b5dfcSdrh }
762a76b5dfcSdrh 
763a76b5dfcSdrh /*
764626a879aSdrh ** Walk an expression tree.  Call xFunc for each node visited.
76573b211abSdrh **
766626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
767626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
768626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
769626a879aSdrh ** the tree walk completely.
770626a879aSdrh **
771626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
772626a879aSdrh ** and 0 to continue.
77387abf5c0Sdrh **
77487abf5c0Sdrh ** NOTICE:  This routine does *not* descend into subqueries.
775626a879aSdrh */
776a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
777626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
778626a879aSdrh   int rc;
779626a879aSdrh   if( pExpr==0 ) return 0;
780626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
781626a879aSdrh   if( rc==0 ){
782626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
783626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
784a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
785626a879aSdrh   }
786626a879aSdrh   return rc>1;
787626a879aSdrh }
788626a879aSdrh 
789626a879aSdrh /*
790a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
791a58fdfb1Sdanielk1977 */
792a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
793a58fdfb1Sdanielk1977   int i;
794a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
795a58fdfb1Sdanielk1977   if( !p ) return 0;
796a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
797a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
798a58fdfb1Sdanielk1977   }
799a58fdfb1Sdanielk1977   return 0;
800a58fdfb1Sdanielk1977 }
801a58fdfb1Sdanielk1977 
802a58fdfb1Sdanielk1977 /*
803a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
804a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
805a58fdfb1Sdanielk1977 ** or OFFSET expressions..
806a58fdfb1Sdanielk1977 */
807a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
808a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
809a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
810a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
811a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
812a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
81315d7982aSdanielk1977   if( p->pPrior ){
81415d7982aSdanielk1977     walkSelectExpr(p->pPrior, xFunc, pArg);
81515d7982aSdanielk1977   }
816a58fdfb1Sdanielk1977   return 0;
817a58fdfb1Sdanielk1977 }
818a58fdfb1Sdanielk1977 
819a58fdfb1Sdanielk1977 
820a58fdfb1Sdanielk1977 /*
821626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
822626a879aSdrh **
823626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
82473b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
82573b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
82673b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
82773b211abSdrh ** then do nothing.
82873b211abSdrh **
82973b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
83073b211abSdrh ** the expression as constant, then we assume the whole expression
83173b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
832626a879aSdrh */
833626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
834626a879aSdrh   switch( pExpr->op ){
835eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
836eb55bd2fSdrh     ** and *pArg==2 */
837eb55bd2fSdrh     case TK_FUNCTION:
838eb55bd2fSdrh       if( *((int*)pArg)==2 ) return 0;
839eb55bd2fSdrh       /* Fall through */
840626a879aSdrh     case TK_ID:
841626a879aSdrh     case TK_COLUMN:
842626a879aSdrh     case TK_DOT:
843626a879aSdrh     case TK_AGG_FUNCTION:
84413449892Sdrh     case TK_AGG_COLUMN:
845fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
846fe2093d7Sdrh     case TK_SELECT:
847fe2093d7Sdrh     case TK_EXISTS:
848fe2093d7Sdrh #endif
849626a879aSdrh       *((int*)pArg) = 0;
850626a879aSdrh       return 2;
85187abf5c0Sdrh     case TK_IN:
85287abf5c0Sdrh       if( pExpr->pSelect ){
85387abf5c0Sdrh         *((int*)pArg) = 0;
85487abf5c0Sdrh         return 2;
85587abf5c0Sdrh       }
856626a879aSdrh     default:
857626a879aSdrh       return 0;
858626a879aSdrh   }
859626a879aSdrh }
860626a879aSdrh 
861626a879aSdrh /*
862fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
863eb55bd2fSdrh ** and 0 if it involves variables or function calls.
8642398937bSdrh **
8652398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
8662398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
8672398937bSdrh ** a constant.
868fef5208cSdrh */
8694adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
870626a879aSdrh   int isConst = 1;
871626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
872626a879aSdrh   return isConst;
873fef5208cSdrh }
874fef5208cSdrh 
875fef5208cSdrh /*
876eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
877eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
878eb55bd2fSdrh ** are any variables.
879eb55bd2fSdrh **
880eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
881eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
882eb55bd2fSdrh ** a constant.
883eb55bd2fSdrh */
884eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
885eb55bd2fSdrh   int isConst = 2;
886eb55bd2fSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
887eb55bd2fSdrh   return isConst!=0;
888eb55bd2fSdrh }
889eb55bd2fSdrh 
890eb55bd2fSdrh /*
89173b211abSdrh ** If the expression p codes a constant integer that is small enough
892202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
893202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
894202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
895e4de1febSdrh */
8964adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
897e4de1febSdrh   switch( p->op ){
898e4de1febSdrh     case TK_INTEGER: {
8992646da7eSdrh       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
900e4de1febSdrh         return 1;
901e4de1febSdrh       }
902202b2df7Sdrh       break;
903202b2df7Sdrh     }
9044b59ab5eSdrh     case TK_UPLUS: {
9054adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
9064b59ab5eSdrh     }
907e4de1febSdrh     case TK_UMINUS: {
908e4de1febSdrh       int v;
9094adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
910e4de1febSdrh         *pValue = -v;
911e4de1febSdrh         return 1;
912e4de1febSdrh       }
913e4de1febSdrh       break;
914e4de1febSdrh     }
915e4de1febSdrh     default: break;
916e4de1febSdrh   }
917e4de1febSdrh   return 0;
918e4de1febSdrh }
919e4de1febSdrh 
920e4de1febSdrh /*
921c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
922c4a3c779Sdrh */
9234adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
9244adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
9254adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
9264adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
927c4a3c779Sdrh   return 0;
928c4a3c779Sdrh }
929c4a3c779Sdrh 
930c4a3c779Sdrh /*
9318141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
9328141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
9338141f61eSdrh ** expression node refer back to that source column.  The following changes
9348141f61eSdrh ** are made to pExpr:
9358141f61eSdrh **
9368141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
9378141f61eSdrh **                         the table.
9388141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
9398141f61eSdrh **                         from pSrcList.
9408141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
9418141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
9428141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
9438141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
9448141f61eSdrh **
9458141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
9468141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
9478141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
9488141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
9498141f61eSdrh ** means that the form of the name is Z and that columns from any table
9508141f61eSdrh ** can be used.
9518141f61eSdrh **
9528141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
9538141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
9548141f61eSdrh */
9558141f61eSdrh static int lookupName(
9568141f61eSdrh   Parse *pParse,       /* The parsing context */
9578141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
9588141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
9598141f61eSdrh   Token *pColumnToken, /* Name of the column. */
960626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
9618141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
9628141f61eSdrh ){
9638141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
9648141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
9658141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
9668141f61eSdrh   int i, j;            /* Loop counters */
9678141f61eSdrh   int cnt = 0;         /* Number of matching column names */
9688141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
9699bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
97051669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
97151669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
97273b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
9738141f61eSdrh 
9748141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
975a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
976a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
977a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
9789e12800dSdanielk1977   if( sqlite3MallocFailed() ){
979d5d56523Sdanielk1977     goto lookupname_end;
9808141f61eSdrh   }
9818141f61eSdrh 
9828141f61eSdrh   pExpr->iTable = -1;
983626a879aSdrh   while( pNC && cnt==0 ){
984ffe07b2dSdrh     ExprList *pEList;
985626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
986626a879aSdrh 
987b3bce662Sdanielk1977     if( pSrcList ){
98851669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
98943617e9aSdrh         Table *pTab;
99043617e9aSdrh         int iDb;
9918141f61eSdrh         Column *pCol;
9928141f61eSdrh 
99343617e9aSdrh         pTab = pItem->pTab;
99443617e9aSdrh         assert( pTab!=0 );
99543617e9aSdrh         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
9968141f61eSdrh         assert( pTab->nCol>0 );
9978141f61eSdrh         if( zTab ){
9988141f61eSdrh           if( pItem->zAlias ){
9998141f61eSdrh             char *zTabName = pItem->zAlias;
10004adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
10018141f61eSdrh           }else{
10028141f61eSdrh             char *zTabName = pTab->zName;
10034adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1004da184236Sdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
10058141f61eSdrh               continue;
10068141f61eSdrh             }
10078141f61eSdrh           }
10088141f61eSdrh         }
10098141f61eSdrh         if( 0==(cntTab++) ){
10108141f61eSdrh           pExpr->iTable = pItem->iCursor;
1011da184236Sdanielk1977           pExpr->pSchema = pTab->pSchema;
101251669863Sdrh           pMatch = pItem;
10138141f61eSdrh         }
10148141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
10154adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1016b3bf556eSdanielk1977             const char *zColl = pTab->aCol[j].zColl;
1017873fac0cSdrh             IdList *pUsing;
10188141f61eSdrh             cnt++;
10198141f61eSdrh             pExpr->iTable = pItem->iCursor;
102051669863Sdrh             pMatch = pItem;
1021da184236Sdanielk1977             pExpr->pSchema = pTab->pSchema;
10228141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
10238141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
1024a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
10258b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1026b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
10278b4c40d8Sdrh             }
102861dfc31dSdrh             if( i<pSrcList->nSrc-1 ){
102961dfc31dSdrh               if( pItem[1].jointype & JT_NATURAL ){
1030355ef361Sdrh                 /* If this match occurred in the left table of a natural join,
1031355ef361Sdrh                 ** then skip the right table to avoid a duplicate match */
1032355ef361Sdrh                 pItem++;
1033355ef361Sdrh                 i++;
103461dfc31dSdrh               }else if( (pUsing = pItem[1].pUsing)!=0 ){
1035873fac0cSdrh                 /* If this match occurs on a column that is in the USING clause
1036873fac0cSdrh                 ** of a join, skip the search of the right table of the join
1037873fac0cSdrh                 ** to avoid a duplicate match there. */
1038873fac0cSdrh                 int k;
1039873fac0cSdrh                 for(k=0; k<pUsing->nId; k++){
1040873fac0cSdrh                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
1041873fac0cSdrh                     pItem++;
1042873fac0cSdrh                     i++;
1043873fac0cSdrh                     break;
1044873fac0cSdrh                   }
1045873fac0cSdrh                 }
1046873fac0cSdrh               }
104761dfc31dSdrh             }
10488141f61eSdrh             break;
10498141f61eSdrh           }
10508141f61eSdrh         }
10518141f61eSdrh       }
1052b3bce662Sdanielk1977     }
10538141f61eSdrh 
1054b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
10558141f61eSdrh     /* If we have not already resolved the name, then maybe
10568141f61eSdrh     ** it is a new.* or old.* trigger argument reference
10578141f61eSdrh     */
10588141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
10598141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
10608141f61eSdrh       Table *pTab = 0;
10614adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
10628141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
10638141f61eSdrh         assert( pTriggerStack->pTab );
10648141f61eSdrh         pTab = pTriggerStack->pTab;
10654adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
10668141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
10678141f61eSdrh         assert( pTriggerStack->pTab );
10688141f61eSdrh         pTab = pTriggerStack->pTab;
10698141f61eSdrh       }
10708141f61eSdrh 
10718141f61eSdrh       if( pTab ){
1072f0113000Sdanielk1977         int iCol;
10738141f61eSdrh         Column *pCol = pTab->aCol;
10748141f61eSdrh 
1075da184236Sdanielk1977         pExpr->pSchema = pTab->pSchema;
10768141f61eSdrh         cntTab++;
1077f0113000Sdanielk1977         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
10784adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1079f0113000Sdanielk1977             const char *zColl = pTab->aCol[iCol].zColl;
10808141f61eSdrh             cnt++;
1081f0113000Sdanielk1977             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1082f0113000Sdanielk1977             pExpr->affinity = pTab->aCol[iCol].affinity;
10838b4c40d8Sdrh             if( (pExpr->flags & EP_ExpCollate)==0 ){
1084b3bf556eSdanielk1977               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
10858b4c40d8Sdrh             }
1086aee18ef8Sdanielk1977             pExpr->pTab = pTab;
10878141f61eSdrh             break;
10888141f61eSdrh           }
10898141f61eSdrh         }
10908141f61eSdrh       }
10918141f61eSdrh     }
1092b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
10938141f61eSdrh 
10948141f61eSdrh     /*
10958141f61eSdrh     ** Perhaps the name is a reference to the ROWID
10968141f61eSdrh     */
10974adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
10988141f61eSdrh       cnt = 1;
10998141f61eSdrh       pExpr->iColumn = -1;
11008a51256cSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
11018141f61eSdrh     }
11028141f61eSdrh 
11038141f61eSdrh     /*
11048141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
11058141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
11068141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
11078141f61eSdrh     **
11088141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
11098141f61eSdrh     **
11108141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
11118141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
11128141f61eSdrh     ** Note that the expression in the result set should have already been
11138141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
11148141f61eSdrh     */
1115ffe07b2dSdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
11168141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
11178141f61eSdrh         char *zAs = pEList->a[j].zName;
11184adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
11194f07e5fbSdrh           Expr *pDup;
11208141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
11214f07e5fbSdrh           assert( pExpr->pList==0 );
11224f07e5fbSdrh           assert( pExpr->pSelect==0 );
11234f07e5fbSdrh           pDup = sqlite3ExprDup(pEList->a[j].pExpr);
11244f07e5fbSdrh           if( pExpr->flags & EP_ExpCollate ){
11254f07e5fbSdrh             pDup->pColl = pExpr->pColl;
11264f07e5fbSdrh             pDup->flags |= EP_ExpCollate;
11274f07e5fbSdrh           }
11284f07e5fbSdrh           memcpy(pExpr, pDup, sizeof(*pExpr));
11294f07e5fbSdrh           sqliteFree(pDup);
113015ccce1cSdrh           cnt = 1;
11318141f61eSdrh           assert( zTab==0 && zDb==0 );
113215ccce1cSdrh           goto lookupname_end_2;
11338141f61eSdrh         }
11348141f61eSdrh       }
11358141f61eSdrh     }
11368141f61eSdrh 
1137626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
1138626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
1139626a879aSdrh     */
1140626a879aSdrh     if( cnt==0 ){
1141626a879aSdrh       pNC = pNC->pNext;
1142626a879aSdrh     }
1143626a879aSdrh   }
1144626a879aSdrh 
11458141f61eSdrh   /*
11468141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
11478141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
11488141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
11498141f61eSdrh   ** case, we need to return right away and not make any changes to
11508141f61eSdrh   ** pExpr.
115115ccce1cSdrh   **
115215ccce1cSdrh   ** Because no reference was made to outer contexts, the pNC->nRef
115315ccce1cSdrh   ** fields are not changed in any context.
11548141f61eSdrh   */
11558141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
11568141f61eSdrh     sqliteFree(zCol);
11578141f61eSdrh     return 0;
11588141f61eSdrh   }
11598141f61eSdrh 
11608141f61eSdrh   /*
11618141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
11628141f61eSdrh   ** more matches.  Either way, we have an error.
11638141f61eSdrh   */
11648141f61eSdrh   if( cnt!=1 ){
11658141f61eSdrh     char *z = 0;
11668141f61eSdrh     char *zErr;
11678141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
11688141f61eSdrh     if( zDb ){
1169f93339deSdrh       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
11708141f61eSdrh     }else if( zTab ){
1171f93339deSdrh       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
11728141f61eSdrh     }else{
11738141f61eSdrh       z = sqliteStrDup(zCol);
11748141f61eSdrh     }
11754adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
11768141f61eSdrh     sqliteFree(z);
117773b211abSdrh     pTopNC->nErr++;
11788141f61eSdrh   }
11798141f61eSdrh 
118051669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
118151669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
118251669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
118351669863Sdrh   ** column number is greater than the number of bits in the bitmask
118451669863Sdrh   ** then set the high-order bit of the bitmask.
118551669863Sdrh   */
118651669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
118751669863Sdrh     int n = pExpr->iColumn;
118851669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
118951669863Sdrh       n = sizeof(Bitmask)*8-1;
119051669863Sdrh     }
119151669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
1192ca83ac51Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
119351669863Sdrh   }
119451669863Sdrh 
1195d5d56523Sdanielk1977 lookupname_end:
11968141f61eSdrh   /* Clean up and return
11978141f61eSdrh   */
11988141f61eSdrh   sqliteFree(zDb);
11998141f61eSdrh   sqliteFree(zTab);
12004adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
12018141f61eSdrh   pExpr->pLeft = 0;
12024adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
12038141f61eSdrh   pExpr->pRight = 0;
12048141f61eSdrh   pExpr->op = TK_COLUMN;
120515ccce1cSdrh lookupname_end_2:
120615ccce1cSdrh   sqliteFree(zCol);
1207626a879aSdrh   if( cnt==1 ){
1208b3bce662Sdanielk1977     assert( pNC!=0 );
1209626a879aSdrh     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1210aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
1211aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
1212aee18ef8Sdanielk1977     }
121315ccce1cSdrh     /* Increment the nRef value on all name contexts from TopNC up to
121415ccce1cSdrh     ** the point where the name matched. */
121515ccce1cSdrh     for(;;){
121615ccce1cSdrh       assert( pTopNC!=0 );
121715ccce1cSdrh       pTopNC->nRef++;
121815ccce1cSdrh       if( pTopNC==pNC ) break;
121915ccce1cSdrh       pTopNC = pTopNC->pNext;
1220626a879aSdrh     }
122115ccce1cSdrh     return 0;
122215ccce1cSdrh   } else {
122315ccce1cSdrh     return 1;
122415ccce1cSdrh   }
12258141f61eSdrh }
12268141f61eSdrh 
12278141f61eSdrh /*
1228626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1229626a879aSdrh **
123073b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1231626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
123273b211abSdrh ** the tree or 2 to abort the tree walk.
123373b211abSdrh **
123473b211abSdrh ** This routine also does error checking and name resolution for
123573b211abSdrh ** function names.  The operator for aggregate functions is changed
123673b211abSdrh ** to TK_AGG_FUNCTION.
1237626a879aSdrh */
1238626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1239626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1240626a879aSdrh   Parse *pParse;
1241626a879aSdrh 
1242b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1243626a879aSdrh   assert( pNC!=0 );
1244626a879aSdrh   pParse = pNC->pParse;
1245b3bce662Sdanielk1977 
1246626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1247626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1248626a879aSdrh #ifndef NDEBUG
1249f0113000Sdanielk1977   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1250f0113000Sdanielk1977     SrcList *pSrcList = pNC->pSrcList;
1251940fac9dSdanielk1977     int i;
1252f0113000Sdanielk1977     for(i=0; i<pNC->pSrcList->nSrc; i++){
1253626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1254626a879aSdrh     }
1255626a879aSdrh   }
1256626a879aSdrh #endif
1257626a879aSdrh   switch( pExpr->op ){
1258626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1259626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1260626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1261626a879aSdrh     */
1262626a879aSdrh     case TK_STRING: {
1263626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1264626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1265626a879aSdrh     }
1266626a879aSdrh     /* A lone identifier is the name of a column.
1267626a879aSdrh     */
1268626a879aSdrh     case TK_ID: {
1269626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1270626a879aSdrh       return 1;
1271626a879aSdrh     }
1272626a879aSdrh 
1273626a879aSdrh     /* A table name and column name:     ID.ID
1274626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1275626a879aSdrh     */
1276626a879aSdrh     case TK_DOT: {
1277626a879aSdrh       Token *pColumn;
1278626a879aSdrh       Token *pTable;
1279626a879aSdrh       Token *pDb;
1280626a879aSdrh       Expr *pRight;
1281626a879aSdrh 
1282b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1283626a879aSdrh       pRight = pExpr->pRight;
1284626a879aSdrh       if( pRight->op==TK_ID ){
1285626a879aSdrh         pDb = 0;
1286626a879aSdrh         pTable = &pExpr->pLeft->token;
1287626a879aSdrh         pColumn = &pRight->token;
1288626a879aSdrh       }else{
1289626a879aSdrh         assert( pRight->op==TK_DOT );
1290626a879aSdrh         pDb = &pExpr->pLeft->token;
1291626a879aSdrh         pTable = &pRight->pLeft->token;
1292626a879aSdrh         pColumn = &pRight->pRight->token;
1293626a879aSdrh       }
1294626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1295626a879aSdrh       return 1;
1296626a879aSdrh     }
1297626a879aSdrh 
1298626a879aSdrh     /* Resolve function names
1299626a879aSdrh     */
1300b71090fdSdrh     case TK_CONST_FUNC:
1301626a879aSdrh     case TK_FUNCTION: {
1302626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1303626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1304626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1305626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1306626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1307626a879aSdrh       int i;
13085169bbc6Sdrh       int auth;                   /* Authorization to use the function */
1309626a879aSdrh       int nId;                    /* Number of characters in function name */
1310626a879aSdrh       const char *zId;            /* The function name. */
131173b211abSdrh       FuncDef *pDef;              /* Information about the function */
131214db2665Sdanielk1977       int enc = ENC(pParse->db);  /* The database encoding */
1313626a879aSdrh 
13142646da7eSdrh       zId = (char*)pExpr->token.z;
1315b71090fdSdrh       nId = pExpr->token.n;
1316626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1317626a879aSdrh       if( pDef==0 ){
1318626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1319626a879aSdrh         if( pDef==0 ){
1320626a879aSdrh           no_such_func = 1;
1321626a879aSdrh         }else{
1322626a879aSdrh           wrong_num_args = 1;
1323626a879aSdrh         }
1324626a879aSdrh       }else{
1325626a879aSdrh         is_agg = pDef->xFunc==0;
1326626a879aSdrh       }
13272fca7fefSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
13285169bbc6Sdrh       if( pDef ){
13295169bbc6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
13305169bbc6Sdrh         if( auth!=SQLITE_OK ){
13315169bbc6Sdrh           if( auth==SQLITE_DENY ){
13325169bbc6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
13335169bbc6Sdrh                                     pDef->zName);
13345169bbc6Sdrh             pNC->nErr++;
13355169bbc6Sdrh           }
13365169bbc6Sdrh           pExpr->op = TK_NULL;
13375169bbc6Sdrh           return 1;
13385169bbc6Sdrh         }
13395169bbc6Sdrh       }
1340b8b14219Sdrh #endif
1341626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1342626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1343626a879aSdrh         pNC->nErr++;
1344626a879aSdrh         is_agg = 0;
1345626a879aSdrh       }else if( no_such_func ){
1346626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1347626a879aSdrh         pNC->nErr++;
1348626a879aSdrh       }else if( wrong_num_args ){
1349626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1350626a879aSdrh              nId, zId);
1351626a879aSdrh         pNC->nErr++;
1352626a879aSdrh       }
1353626a879aSdrh       if( is_agg ){
1354626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1355626a879aSdrh         pNC->hasAgg = 1;
1356626a879aSdrh       }
135773b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1358626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
135973b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1360626a879aSdrh       }
136173b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1362626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1363626a879aSdrh       ** type of the function
1364626a879aSdrh       */
1365626a879aSdrh       return is_agg;
1366626a879aSdrh     }
1367b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1368b3bce662Sdanielk1977     case TK_SELECT:
1369b3bce662Sdanielk1977     case TK_EXISTS:
1370b3bce662Sdanielk1977 #endif
1371b3bce662Sdanielk1977     case TK_IN: {
1372b3bce662Sdanielk1977       if( pExpr->pSelect ){
13738a9f38feSdrh         int nRef = pNC->nRef;
137406f6541eSdrh #ifndef SQLITE_OMIT_CHECK
137506f6541eSdrh         if( pNC->isCheck ){
137606f6541eSdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
137706f6541eSdrh         }
137806f6541eSdrh #endif
1379b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1380b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1381b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1382b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1383b3bce662Sdanielk1977         }
1384b3bce662Sdanielk1977       }
13854284fb07Sdrh       break;
1386b3bce662Sdanielk1977     }
13874284fb07Sdrh #ifndef SQLITE_OMIT_CHECK
13884284fb07Sdrh     case TK_VARIABLE: {
13894284fb07Sdrh       if( pNC->isCheck ){
13904284fb07Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
13914284fb07Sdrh       }
13924284fb07Sdrh       break;
13934284fb07Sdrh     }
13944284fb07Sdrh #endif
1395626a879aSdrh   }
1396626a879aSdrh   return 0;
1397626a879aSdrh }
1398626a879aSdrh 
1399626a879aSdrh /*
1400cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1401967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1402aacc543eSdrh ** index to the table in the table list and a column offset.  The
1403aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1404aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1405832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1406aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1407aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1408aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1409aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1410aacc543eSdrh ** alias for ROWID.
141119a775c2Sdrh **
1412626a879aSdrh ** Also resolve function names and check the functions for proper
1413626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1414626a879aSdrh ** have the correct number of arguments.  Leave an error message
1415626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1416626a879aSdrh **
141773b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
141873b211abSdrh ** property on the expression.
1419626a879aSdrh */
1420626a879aSdrh int sqlite3ExprResolveNames(
1421b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1422b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1423626a879aSdrh ){
142413449892Sdrh   int savedHasAgg;
142573b211abSdrh   if( pExpr==0 ) return 0;
1426fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
1427fc976065Sdanielk1977   if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
1428fc976065Sdanielk1977     sqlite3ErrorMsg(pNC->pParse,
1429fc976065Sdanielk1977        "Expression tree is too large (maximum depth %d)",
1430fc976065Sdanielk1977        SQLITE_MAX_EXPR_DEPTH
1431fc976065Sdanielk1977     );
1432fc976065Sdanielk1977     return 1;
1433fc976065Sdanielk1977   }
1434fc976065Sdanielk1977   pNC->pParse->nHeight += pExpr->nHeight;
1435fc976065Sdanielk1977 #endif
143613449892Sdrh   savedHasAgg = pNC->hasAgg;
143713449892Sdrh   pNC->hasAgg = 0;
1438b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1439fc976065Sdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
1440fc976065Sdanielk1977   pNC->pParse->nHeight -= pExpr->nHeight;
1441fc976065Sdanielk1977 #endif
1442b3bce662Sdanielk1977   if( pNC->nErr>0 ){
144373b211abSdrh     ExprSetProperty(pExpr, EP_Error);
144473b211abSdrh   }
144513449892Sdrh   if( pNC->hasAgg ){
144613449892Sdrh     ExprSetProperty(pExpr, EP_Agg);
144713449892Sdrh   }else if( savedHasAgg ){
144813449892Sdrh     pNC->hasAgg = 1;
144913449892Sdrh   }
145073b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1451626a879aSdrh }
1452626a879aSdrh 
14531398ad36Sdrh /*
14541398ad36Sdrh ** A pointer instance of this structure is used to pass information
14551398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
14561398ad36Sdrh */
14571398ad36Sdrh typedef struct QueryCoder QueryCoder;
14581398ad36Sdrh struct QueryCoder {
14591398ad36Sdrh   Parse *pParse;       /* The parsing context */
14601398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
14611398ad36Sdrh };
14621398ad36Sdrh 
1463626a879aSdrh 
1464626a879aSdrh /*
14659cbe6352Sdrh ** Generate code for scalar subqueries used as an expression
14669cbe6352Sdrh ** and IN operators.  Examples:
1467626a879aSdrh **
14689cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
14699cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
14709cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
14719cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1472fef5208cSdrh **
14739cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
14749cbe6352Sdrh ** operator or subquery.
1475cce7d176Sdrh */
147651522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1477b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
147857dbd7b3Sdrh   int testAddr = 0;                       /* One-time test address */
1479b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1480b3bce662Sdanielk1977   if( v==0 ) return;
1481b3bce662Sdanielk1977 
1482fc976065Sdanielk1977 
148357dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
148457dbd7b3Sdrh   ** if any of the following is true:
148557dbd7b3Sdrh   **
148657dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
148757dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
148857dbd7b3Sdrh   **    *  We are inside a trigger
148957dbd7b3Sdrh   **
149057dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
149157dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1492b3bce662Sdanielk1977   */
1493b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1494b3bce662Sdanielk1977     int mem = pParse->nMem++;
1495b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
149657dbd7b3Sdrh     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
14979e12800dSdanielk1977     assert( testAddr>0 || sqlite3MallocFailed() );
1498d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1499b3bce662Sdanielk1977   }
1500b3bce662Sdanielk1977 
1501cce7d176Sdrh   switch( pExpr->op ){
1502fef5208cSdrh     case TK_IN: {
1503e014a838Sdanielk1977       char affinity;
1504d3d39e93Sdrh       KeyInfo keyInfo;
1505b9bb7c18Sdrh       int addr;        /* Address of OP_OpenEphemeral instruction */
1506d3d39e93Sdrh 
1507bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1508e014a838Sdanielk1977 
1509e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
151057dbd7b3Sdrh       ** expression it is handled the same way. A virtual table is
1511e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1512e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1513fef5208cSdrh       **
1514e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1515e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1516e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1517e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1518e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1519e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1520e014a838Sdanielk1977       ** is used.
1521fef5208cSdrh       */
1522832508b7Sdrh       pExpr->iTable = pParse->nTab++;
1523b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
1524d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1525d3d39e93Sdrh       keyInfo.nField = 1;
1526f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1527e014a838Sdanielk1977 
1528e014a838Sdanielk1977       if( pExpr->pSelect ){
1529e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1530e014a838Sdanielk1977         **
1531e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1532e014a838Sdanielk1977         ** table allocated and opened above.
1533e014a838Sdanielk1977         */
1534e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1535be5c89acSdrh         ExprList *pEList;
1536e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
153794ccde58Sdrh         if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
153894ccde58Sdrh           return;
153994ccde58Sdrh         }
1540be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1541be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
1542*bcbb04e5Sdanielk1977           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1543be5c89acSdrh               pEList->a[0].pExpr);
15440202b29eSdanielk1977         }
1545fef5208cSdrh       }else if( pExpr->pList ){
1546fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1547fef5208cSdrh         **
1548e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
1549e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1550e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1551e014a838Sdanielk1977         ** a column, use numeric affinity.
1552fef5208cSdrh         */
1553e014a838Sdanielk1977         int i;
155457dbd7b3Sdrh         ExprList *pList = pExpr->pList;
155557dbd7b3Sdrh         struct ExprList_item *pItem;
155657dbd7b3Sdrh 
1557e014a838Sdanielk1977         if( !affinity ){
15588159a35fSdrh           affinity = SQLITE_AFF_NONE;
1559e014a838Sdanielk1977         }
15600202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1561e014a838Sdanielk1977 
1562e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
156357dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
156457dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1565e014a838Sdanielk1977 
156657dbd7b3Sdrh           /* If the expression is not constant then we will need to
156757dbd7b3Sdrh           ** disable the test that was generated above that makes sure
156857dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
156957dbd7b3Sdrh           ** expression we need to rerun this code each time.
157057dbd7b3Sdrh           */
15716c30be8eSdrh           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
1572f8875400Sdrh             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
157357dbd7b3Sdrh             testAddr = 0;
15744794b980Sdrh           }
1575e014a838Sdanielk1977 
1576e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
15774adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
157894a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1579f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1580fef5208cSdrh         }
1581fef5208cSdrh       }
15820202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1583b3bce662Sdanielk1977       break;
1584fef5208cSdrh     }
1585fef5208cSdrh 
158651522cd3Sdrh     case TK_EXISTS:
158719a775c2Sdrh     case TK_SELECT: {
1588fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1589fef5208cSdrh       ** value of this select in a memory cell and record the number
1590967e8b73Sdrh       ** of the memory cell in iColumn.
1591fef5208cSdrh       */
15922646da7eSdrh       static const Token one = { (u8*)"1", 0, 1 };
159351522cd3Sdrh       Select *pSel;
1594ec7429aeSdrh       int iMem;
1595ec7429aeSdrh       int sop;
15961398ad36Sdrh 
1597ec7429aeSdrh       pExpr->iColumn = iMem = pParse->nMem++;
159851522cd3Sdrh       pSel = pExpr->pSelect;
159951522cd3Sdrh       if( pExpr->op==TK_SELECT ){
160051522cd3Sdrh         sop = SRT_Mem;
1601ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1602ec7429aeSdrh         VdbeComment((v, "# Init subquery result"));
160351522cd3Sdrh       }else{
160451522cd3Sdrh         sop = SRT_Exists;
1605ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1606ec7429aeSdrh         VdbeComment((v, "# Init EXISTS result"));
160751522cd3Sdrh       }
1608ec7429aeSdrh       sqlite3ExprDelete(pSel->pLimit);
1609ec7429aeSdrh       pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
161094ccde58Sdrh       if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
161194ccde58Sdrh         return;
161294ccde58Sdrh       }
1613b3bce662Sdanielk1977       break;
161419a775c2Sdrh     }
1615cce7d176Sdrh   }
1616b3bce662Sdanielk1977 
161757dbd7b3Sdrh   if( testAddr ){
1618d654be80Sdrh     sqlite3VdbeJumpHere(v, testAddr);
1619b3bce662Sdanielk1977   }
1620fc976065Sdanielk1977 
1621b3bce662Sdanielk1977   return;
1622cce7d176Sdrh }
162351522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1624cce7d176Sdrh 
1625cce7d176Sdrh /*
1626fec19aadSdrh ** Generate an instruction that will put the integer describe by
1627fec19aadSdrh ** text z[0..n-1] on the stack.
1628fec19aadSdrh */
1629fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1630fec19aadSdrh   int i;
16316fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
16326fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
16336fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
163429dda4aeSdrh     sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1635fec19aadSdrh   }else{
1636fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1637fec19aadSdrh   }
1638fec19aadSdrh }
1639fec19aadSdrh 
1640945498f3Sdrh 
1641945498f3Sdrh /*
1642945498f3Sdrh ** Generate code that will extract the iColumn-th column from
1643945498f3Sdrh ** table pTab and push that column value on the stack.  There
1644945498f3Sdrh ** is an open cursor to pTab in iTable.  If iColumn<0 then
1645945498f3Sdrh ** code is generated that extracts the rowid.
1646945498f3Sdrh */
1647945498f3Sdrh void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
1648945498f3Sdrh   if( iColumn<0 ){
1649945498f3Sdrh     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
1650945498f3Sdrh     sqlite3VdbeAddOp(v, op, iTable, 0);
1651945498f3Sdrh   }else if( pTab==0 ){
1652945498f3Sdrh     sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
1653945498f3Sdrh   }else{
1654945498f3Sdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
1655945498f3Sdrh     sqlite3VdbeAddOp(v, op, iTable, iColumn);
1656945498f3Sdrh     sqlite3ColumnDefault(v, pTab, iColumn);
1657945498f3Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
1658945498f3Sdrh     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
1659945498f3Sdrh       sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
1660945498f3Sdrh     }
1661945498f3Sdrh #endif
1662945498f3Sdrh   }
1663945498f3Sdrh }
1664945498f3Sdrh 
1665fec19aadSdrh /*
1666cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
16671ccde15dSdrh ** expression and leave the result on the top of stack.
1668f2bc013cSdrh **
1669f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1670f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1671f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1672f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1673f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1674cce7d176Sdrh */
16754adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1676cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1677cce7d176Sdrh   int op;
1678ffe07b2dSdrh   int stackChng = 1;    /* Amount of change to stack depth */
1679ffe07b2dSdrh 
16807977a17fSdanielk1977   if( v==0 ) return;
16817977a17fSdanielk1977   if( pExpr==0 ){
1682f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
16837977a17fSdanielk1977     return;
16847977a17fSdanielk1977   }
1685f2bc013cSdrh   op = pExpr->op;
1686f2bc013cSdrh   switch( op ){
168713449892Sdrh     case TK_AGG_COLUMN: {
168813449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
168913449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
169013449892Sdrh       if( !pAggInfo->directMode ){
169113449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
169213449892Sdrh         break;
169313449892Sdrh       }else if( pAggInfo->useSortingIdx ){
169413449892Sdrh         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
169513449892Sdrh                               pCol->iSorterColumn);
169613449892Sdrh         break;
169713449892Sdrh       }
169813449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
169913449892Sdrh     }
1700967e8b73Sdrh     case TK_COLUMN: {
1701ffe07b2dSdrh       if( pExpr->iTable<0 ){
1702ffe07b2dSdrh         /* This only happens when coding check constraints */
1703ffe07b2dSdrh         assert( pParse->ckOffset>0 );
1704ffe07b2dSdrh         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1705c4a3c779Sdrh       }else{
1706945498f3Sdrh         sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
17072282792aSdrh       }
1708cce7d176Sdrh       break;
1709cce7d176Sdrh     }
1710cce7d176Sdrh     case TK_INTEGER: {
17112646da7eSdrh       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1712fec19aadSdrh       break;
171351e9a445Sdrh     }
1714fec19aadSdrh     case TK_FLOAT:
1715fec19aadSdrh     case TK_STRING: {
1716f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1717f2bc013cSdrh       assert( TK_STRING==OP_String8 );
1718d2687b77Sdrh       sqlite3DequoteExpr(pExpr);
17192646da7eSdrh       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1720cce7d176Sdrh       break;
1721cce7d176Sdrh     }
1722f0863fe5Sdrh     case TK_NULL: {
1723f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1724f0863fe5Sdrh       break;
1725f0863fe5Sdrh     }
17265338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1727c572ef7fSdanielk1977     case TK_BLOB: {
17286c8c6cecSdrh       int n;
17296c8c6cecSdrh       const char *z;
1730f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
17316c8c6cecSdrh       n = pExpr->token.n - 3;
17322646da7eSdrh       z = (char*)pExpr->token.z + 2;
17336c8c6cecSdrh       assert( n>=0 );
17346c8c6cecSdrh       if( n==0 ){
17356c8c6cecSdrh         z = "";
17366c8c6cecSdrh       }
17376c8c6cecSdrh       sqlite3VdbeOp3(v, op, 0, 0, z, n);
1738c572ef7fSdanielk1977       break;
1739c572ef7fSdanielk1977     }
17405338a5f7Sdanielk1977 #endif
174150457896Sdrh     case TK_VARIABLE: {
17424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1743895d7472Sdrh       if( pExpr->token.n>1 ){
17442646da7eSdrh         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1745895d7472Sdrh       }
174650457896Sdrh       break;
174750457896Sdrh     }
17484e0cff60Sdrh     case TK_REGISTER: {
17494e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
17504e0cff60Sdrh       break;
17514e0cff60Sdrh     }
1752487e262fSdrh #ifndef SQLITE_OMIT_CAST
1753487e262fSdrh     case TK_CAST: {
1754487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
1755f0113000Sdanielk1977       int aff, to_op;
1756487e262fSdrh       sqlite3ExprCode(pParse, pExpr->pLeft);
17578a51256cSdrh       aff = sqlite3AffinityType(&pExpr->token);
1758f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1759f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
1760f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
1761f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1762f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
1763f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
1764f0113000Sdanielk1977       sqlite3VdbeAddOp(v, to_op, 0, 0);
1765ffe07b2dSdrh       stackChng = 0;
1766487e262fSdrh       break;
1767487e262fSdrh     }
1768487e262fSdrh #endif /* SQLITE_OMIT_CAST */
1769c9b84a1fSdrh     case TK_LT:
1770c9b84a1fSdrh     case TK_LE:
1771c9b84a1fSdrh     case TK_GT:
1772c9b84a1fSdrh     case TK_GE:
1773c9b84a1fSdrh     case TK_NE:
1774c9b84a1fSdrh     case TK_EQ: {
1775f2bc013cSdrh       assert( TK_LT==OP_Lt );
1776f2bc013cSdrh       assert( TK_LE==OP_Le );
1777f2bc013cSdrh       assert( TK_GT==OP_Gt );
1778f2bc013cSdrh       assert( TK_GE==OP_Ge );
1779f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1780f2bc013cSdrh       assert( TK_NE==OP_Ne );
1781a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1782a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1783be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1784ffe07b2dSdrh       stackChng = -1;
1785a37cdde0Sdanielk1977       break;
1786c9b84a1fSdrh     }
1787cce7d176Sdrh     case TK_AND:
1788cce7d176Sdrh     case TK_OR:
1789cce7d176Sdrh     case TK_PLUS:
1790cce7d176Sdrh     case TK_STAR:
1791cce7d176Sdrh     case TK_MINUS:
1792bf4133cbSdrh     case TK_REM:
1793bf4133cbSdrh     case TK_BITAND:
1794bf4133cbSdrh     case TK_BITOR:
179517c40294Sdrh     case TK_SLASH:
1796bf4133cbSdrh     case TK_LSHIFT:
1797855eb1cfSdrh     case TK_RSHIFT:
17980040077dSdrh     case TK_CONCAT: {
1799f2bc013cSdrh       assert( TK_AND==OP_And );
1800f2bc013cSdrh       assert( TK_OR==OP_Or );
1801f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1802f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1803f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1804f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1805f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1806f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1807f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1808f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1809f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
18104adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18114adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1812855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
1813ffe07b2dSdrh       stackChng = -1;
18140040077dSdrh       break;
18150040077dSdrh     }
1816cce7d176Sdrh     case TK_UMINUS: {
1817fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1818fec19aadSdrh       assert( pLeft );
1819fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1820fec19aadSdrh         Token *p = &pLeft->token;
18219267bdceSdrh         char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
1822fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1823fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1824e6840900Sdrh         }else{
1825fec19aadSdrh           codeInteger(v, z, p->n+1);
1826e6840900Sdrh         }
18276e142f54Sdrh         sqliteFree(z);
18286e142f54Sdrh         break;
18296e142f54Sdrh       }
18301ccde15dSdrh       /* Fall through into TK_NOT */
18316e142f54Sdrh     }
1832bf4133cbSdrh     case TK_BITNOT:
18336e142f54Sdrh     case TK_NOT: {
1834f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1835f2bc013cSdrh       assert( TK_NOT==OP_Not );
18364adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18374adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1838ffe07b2dSdrh       stackChng = 0;
1839cce7d176Sdrh       break;
1840cce7d176Sdrh     }
1841cce7d176Sdrh     case TK_ISNULL:
1842cce7d176Sdrh     case TK_NOTNULL: {
1843cce7d176Sdrh       int dest;
1844f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1845f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
18464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
18474adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18484adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
18494adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
18504adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1851ffe07b2dSdrh       stackChng = 0;
1852a37cdde0Sdanielk1977       break;
1853f2bc013cSdrh     }
18542282792aSdrh     case TK_AGG_FUNCTION: {
185513449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
18567e56e711Sdrh       if( pInfo==0 ){
18577e56e711Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
18587e56e711Sdrh             &pExpr->span);
18597e56e711Sdrh       }else{
186013449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
18617e56e711Sdrh       }
18622282792aSdrh       break;
18632282792aSdrh     }
1864b71090fdSdrh     case TK_CONST_FUNC:
1865cce7d176Sdrh     case TK_FUNCTION: {
1866cce7d176Sdrh       ExprList *pList = pExpr->pList;
186789425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
18680bce8354Sdrh       FuncDef *pDef;
18694b59ab5eSdrh       int nId;
18704b59ab5eSdrh       const char *zId;
187113449892Sdrh       int constMask = 0;
1872682f68b0Sdanielk1977       int i;
187314db2665Sdanielk1977       u8 enc = ENC(pParse->db);
1874dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
18752646da7eSdrh       zId = (char*)pExpr->token.z;
1876b71090fdSdrh       nId = pExpr->token.n;
1877d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
18780bce8354Sdrh       assert( pDef!=0 );
1879f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1880b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1881a43fa227Sdrh       /* Possibly overload the function if the first argument is
1882a43fa227Sdrh       ** a virtual table column.
1883a43fa227Sdrh       **
1884a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1885a43fa227Sdrh       ** second argument, not the first, as the argument to test to
1886a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
1887a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
1888a43fa227Sdrh       ** control overloading) ends up as the second argument to the
1889a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
1890a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
1891a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
1892a43fa227Sdrh       */
18936a03a1c5Sdrh       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
18946a03a1c5Sdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[1].pExpr);
18956a03a1c5Sdrh       }else if( nExpr>0 ){
1896b7f6f68fSdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[0].pExpr);
1897b7f6f68fSdrh       }
1898b7f6f68fSdrh #endif
1899682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1900d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
190113449892Sdrh           constMask |= (1<<i);
1902d02eb1fdSdanielk1977         }
1903dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1904dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1905dc1bdc4fSdanielk1977         }
1906dc1bdc4fSdanielk1977       }
1907dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1908dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1909d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1910682f68b0Sdanielk1977       }
191113449892Sdrh       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1912ffe07b2dSdrh       stackChng = 1-nExpr;
19136ec2733bSdrh       break;
19146ec2733bSdrh     }
1915fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1916fe2093d7Sdrh     case TK_EXISTS:
191719a775c2Sdrh     case TK_SELECT: {
191841714d6fSdrh       if( pExpr->iColumn==0 ){
1919b3bce662Sdanielk1977         sqlite3CodeSubselect(pParse, pExpr);
192041714d6fSdrh       }
19214adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1922ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
192319a775c2Sdrh       break;
192419a775c2Sdrh     }
1925fef5208cSdrh     case TK_IN: {
1926fef5208cSdrh       int addr;
192794a11211Sdrh       char affinity;
1928afa5f680Sdrh       int ckOffset = pParse->ckOffset;
1929b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
1930e014a838Sdanielk1977 
1931e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1932e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1933ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1934e014a838Sdanielk1977       */
193594a11211Sdrh       affinity = comparisonAffinity(pExpr);
1936e014a838Sdanielk1977 
19374adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1938cdbd8effSdanielk1977       pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
1939e014a838Sdanielk1977 
1940e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1941e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1942e014a838Sdanielk1977       */
19434adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19444adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1945e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
19464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
1947f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1948e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
194994a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
1950e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1951e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1952e014a838Sdanielk1977 
1953fef5208cSdrh       break;
1954fef5208cSdrh     }
195593758c8dSdanielk1977 #endif
1956fef5208cSdrh     case TK_BETWEEN: {
1957be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1958be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1959be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1960be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
19614adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1962be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1963be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
19644adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1965be5c89acSdrh       pLItem++;
1966be5c89acSdrh       pRight = pLItem->pExpr;
1967be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1968be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
19694adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1970fef5208cSdrh       break;
1971fef5208cSdrh     }
19724f07e5fbSdrh     case TK_UPLUS: {
19734adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1974ffe07b2dSdrh       stackChng = 0;
1975a2e00042Sdrh       break;
1976a2e00042Sdrh     }
197717a7f8ddSdrh     case TK_CASE: {
197817a7f8ddSdrh       int expr_end_label;
1979f5905aa7Sdrh       int jumpInst;
1980f5905aa7Sdrh       int nExpr;
198117a7f8ddSdrh       int i;
1982be5c89acSdrh       ExprList *pEList;
1983be5c89acSdrh       struct ExprList_item *aListelem;
198417a7f8ddSdrh 
198517a7f8ddSdrh       assert(pExpr->pList);
198617a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
198717a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1988be5c89acSdrh       pEList = pExpr->pList;
1989be5c89acSdrh       aListelem = pEList->a;
1990be5c89acSdrh       nExpr = pEList->nExpr;
19914adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
199217a7f8ddSdrh       if( pExpr->pLeft ){
19934adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1994cce7d176Sdrh       }
1995f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1996be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
199717a7f8ddSdrh         if( pExpr->pLeft ){
19984adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1999be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
2000be5c89acSdrh                                  OP_Ne, 0, 1);
20014adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2002f5905aa7Sdrh         }else{
20034adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
200417a7f8ddSdrh         }
2005be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
20064adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
2007d654be80Sdrh         sqlite3VdbeJumpHere(v, jumpInst);
200817a7f8ddSdrh       }
2009f570f011Sdrh       if( pExpr->pLeft ){
20104adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2011f570f011Sdrh       }
201217a7f8ddSdrh       if( pExpr->pRight ){
20134adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
201417a7f8ddSdrh       }else{
2015f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
201617a7f8ddSdrh       }
20174adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
20186f34903eSdanielk1977       break;
20196f34903eSdanielk1977     }
20205338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
20216f34903eSdanielk1977     case TK_RAISE: {
20226f34903eSdanielk1977       if( !pParse->trigStack ){
20234adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
2024da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
20256f34903eSdanielk1977 	return;
20266f34903eSdanielk1977       }
2027ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
2028ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
20296f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
2030ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
2031d2687b77Sdrh          sqlite3DequoteExpr(pExpr);
20324adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
20332646da7eSdrh                         (char*)pExpr->token.z, pExpr->token.n);
20346f34903eSdanielk1977       } else {
20356f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
2036344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
2037ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
2038ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
20396f34903eSdanielk1977       }
2040ffe07b2dSdrh       stackChng = 0;
2041ffe07b2dSdrh       break;
204217a7f8ddSdrh     }
20435338a5f7Sdanielk1977 #endif
2044ffe07b2dSdrh   }
2045ffe07b2dSdrh 
2046ffe07b2dSdrh   if( pParse->ckOffset ){
2047ffe07b2dSdrh     pParse->ckOffset += stackChng;
2048ffe07b2dSdrh     assert( pParse->ckOffset );
204917a7f8ddSdrh   }
2050cce7d176Sdrh }
2051cce7d176Sdrh 
205293758c8dSdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
2053cce7d176Sdrh /*
205425303780Sdrh ** Generate code that evalutes the given expression and leaves the result
205525303780Sdrh ** on the stack.  See also sqlite3ExprCode().
205625303780Sdrh **
205725303780Sdrh ** This routine might also cache the result and modify the pExpr tree
205825303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
205925303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
206025303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
206125303780Sdrh ** memory location.
206225303780Sdrh */
206325303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
206425303780Sdrh   Vdbe *v = pParse->pVdbe;
206525303780Sdrh   int iMem;
206625303780Sdrh   int addr1, addr2;
206725303780Sdrh   if( v==0 ) return;
206825303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
206925303780Sdrh   sqlite3ExprCode(pParse, pExpr);
207025303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
207125303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
207225303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
207325303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
207425303780Sdrh     pExpr->op = TK_REGISTER;
207525303780Sdrh   }
207625303780Sdrh }
207793758c8dSdanielk1977 #endif
207825303780Sdrh 
207925303780Sdrh /*
2080268380caSdrh ** Generate code that pushes the value of every element of the given
2081f9b596ebSdrh ** expression list onto the stack.
2082268380caSdrh **
2083268380caSdrh ** Return the number of elements pushed onto the stack.
2084268380caSdrh */
20854adee20fSdanielk1977 int sqlite3ExprCodeExprList(
2086268380caSdrh   Parse *pParse,     /* Parsing context */
2087f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
2088268380caSdrh ){
2089268380caSdrh   struct ExprList_item *pItem;
2090268380caSdrh   int i, n;
2091268380caSdrh   if( pList==0 ) return 0;
2092268380caSdrh   n = pList->nExpr;
2093c182d163Sdrh   for(pItem=pList->a, i=n; i>0; i--, pItem++){
20944adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
2095268380caSdrh   }
2096f9b596ebSdrh   return n;
2097268380caSdrh }
2098268380caSdrh 
2099268380caSdrh /*
2100cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
2101cce7d176Sdrh ** to the label "dest" if the expression is true but execution
2102cce7d176Sdrh ** continues straight thru if the expression is false.
2103f5905aa7Sdrh **
2104f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
2105f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
2106f2bc013cSdrh **
2107f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
2108f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2109f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
2110f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
2111f2bc013cSdrh ** below verify that the numbers are aligned correctly.
2112cce7d176Sdrh */
21134adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2114cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2115cce7d176Sdrh   int op = 0;
2116ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2117daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2118f2bc013cSdrh   op = pExpr->op;
2119f2bc013cSdrh   switch( op ){
2120cce7d176Sdrh     case TK_AND: {
21214adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
21224adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
21234adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
21244adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2125cce7d176Sdrh       break;
2126cce7d176Sdrh     }
2127cce7d176Sdrh     case TK_OR: {
21284adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
21294adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2130cce7d176Sdrh       break;
2131cce7d176Sdrh     }
2132cce7d176Sdrh     case TK_NOT: {
21334adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2134cce7d176Sdrh       break;
2135cce7d176Sdrh     }
2136cce7d176Sdrh     case TK_LT:
2137cce7d176Sdrh     case TK_LE:
2138cce7d176Sdrh     case TK_GT:
2139cce7d176Sdrh     case TK_GE:
2140cce7d176Sdrh     case TK_NE:
21410ac65892Sdrh     case TK_EQ: {
2142f2bc013cSdrh       assert( TK_LT==OP_Lt );
2143f2bc013cSdrh       assert( TK_LE==OP_Le );
2144f2bc013cSdrh       assert( TK_GT==OP_Gt );
2145f2bc013cSdrh       assert( TK_GE==OP_Ge );
2146f2bc013cSdrh       assert( TK_EQ==OP_Eq );
2147f2bc013cSdrh       assert( TK_NE==OP_Ne );
21484adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
21494adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2150be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2151cce7d176Sdrh       break;
2152cce7d176Sdrh     }
2153cce7d176Sdrh     case TK_ISNULL:
2154cce7d176Sdrh     case TK_NOTNULL: {
2155f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
2156f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
21574adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
21584adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2159cce7d176Sdrh       break;
2160cce7d176Sdrh     }
2161fef5208cSdrh     case TK_BETWEEN: {
21620202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
21630202b29eSdanielk1977       **
21640202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
21650202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
21660202b29eSdanielk1977       ** 3 ...
21670202b29eSdanielk1977       */
2168f5905aa7Sdrh       int addr;
2169be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2170be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2171be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
21724adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2173be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2174be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
21750202b29eSdanielk1977 
2176be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2177be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2178be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
21790202b29eSdanielk1977 
21804adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2181d654be80Sdrh       sqlite3VdbeJumpHere(v, addr);
21824adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2183fef5208cSdrh       break;
2184fef5208cSdrh     }
2185cce7d176Sdrh     default: {
21864adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
21874adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
2188cce7d176Sdrh       break;
2189cce7d176Sdrh     }
2190cce7d176Sdrh   }
2191ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2192cce7d176Sdrh }
2193cce7d176Sdrh 
2194cce7d176Sdrh /*
219566b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
2196cce7d176Sdrh ** to the label "dest" if the expression is false but execution
2197cce7d176Sdrh ** continues straight thru if the expression is true.
2198f5905aa7Sdrh **
2199f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
2200f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
2201cce7d176Sdrh */
22024adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2203cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2204cce7d176Sdrh   int op = 0;
2205ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2206daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2207f2bc013cSdrh 
2208f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
2209f2bc013cSdrh   **
2210f2bc013cSdrh   **       pExpr->op            op
2211f2bc013cSdrh   **       ---------          ----------
2212f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
2213f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
2214f2bc013cSdrh   **       TK_NE              OP_Eq
2215f2bc013cSdrh   **       TK_EQ              OP_Ne
2216f2bc013cSdrh   **       TK_GT              OP_Le
2217f2bc013cSdrh   **       TK_LE              OP_Gt
2218f2bc013cSdrh   **       TK_GE              OP_Lt
2219f2bc013cSdrh   **       TK_LT              OP_Ge
2220f2bc013cSdrh   **
2221f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
2222f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
2223f2bc013cSdrh   ** can compute the mapping above using the following expression.
2224f2bc013cSdrh   ** Assert()s verify that the computation is correct.
2225f2bc013cSdrh   */
2226f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2227f2bc013cSdrh 
2228f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
2229f2bc013cSdrh   */
2230f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2231f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2232f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
2233f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
2234f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
2235f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
2236f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
2237f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
2238f2bc013cSdrh 
2239cce7d176Sdrh   switch( pExpr->op ){
2240cce7d176Sdrh     case TK_AND: {
22414adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
22424adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2243cce7d176Sdrh       break;
2244cce7d176Sdrh     }
2245cce7d176Sdrh     case TK_OR: {
22464adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
22474adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
22484adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
22494adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2250cce7d176Sdrh       break;
2251cce7d176Sdrh     }
2252cce7d176Sdrh     case TK_NOT: {
22534adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2254cce7d176Sdrh       break;
2255cce7d176Sdrh     }
2256cce7d176Sdrh     case TK_LT:
2257cce7d176Sdrh     case TK_LE:
2258cce7d176Sdrh     case TK_GT:
2259cce7d176Sdrh     case TK_GE:
2260cce7d176Sdrh     case TK_NE:
2261cce7d176Sdrh     case TK_EQ: {
22624adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
22634adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2264be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2265cce7d176Sdrh       break;
2266cce7d176Sdrh     }
2267cce7d176Sdrh     case TK_ISNULL:
2268cce7d176Sdrh     case TK_NOTNULL: {
22694adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
22704adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2271cce7d176Sdrh       break;
2272cce7d176Sdrh     }
2273fef5208cSdrh     case TK_BETWEEN: {
22740202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
22750202b29eSdanielk1977       **
22760202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
22770202b29eSdanielk1977       ** 2 GOTO <dest>
22780202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
22790202b29eSdanielk1977       */
2280fef5208cSdrh       int addr;
2281be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2282be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2283be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
22844adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2285be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
22864adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
2287be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2288be5c89acSdrh 
22894adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
22904adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2291be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2292be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2293be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2294fef5208cSdrh       break;
2295fef5208cSdrh     }
2296cce7d176Sdrh     default: {
22974adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
22984adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2299cce7d176Sdrh       break;
2300cce7d176Sdrh     }
2301cce7d176Sdrh   }
2302ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2303cce7d176Sdrh }
23042282792aSdrh 
23052282792aSdrh /*
23062282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
23072282792aSdrh ** if they are identical and return FALSE if they differ in any way.
2308d40aab0eSdrh **
2309d40aab0eSdrh ** Sometimes this routine will return FALSE even if the two expressions
2310d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
2311d40aab0eSdrh ** identical, we return FALSE just to be safe.  So if this routine
2312d40aab0eSdrh ** returns false, then you do not really know for certain if the two
2313d40aab0eSdrh ** expressions are the same.  But if you get a TRUE return, then you
2314d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
2315d40aab0eSdrh ** this routine is used, it does not hurt to get an extra FALSE - that
2316d40aab0eSdrh ** just might result in some slightly slower code.  But returning
2317d40aab0eSdrh ** an incorrect TRUE could lead to a malfunction.
23182282792aSdrh */
23194adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
23202282792aSdrh   int i;
23214b202ae2Sdanielk1977   if( pA==0||pB==0 ){
23224b202ae2Sdanielk1977     return pB==pA;
23232282792aSdrh   }
23242282792aSdrh   if( pA->op!=pB->op ) return 0;
2325fd357974Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
23264adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
23274adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
23282282792aSdrh   if( pA->pList ){
23292282792aSdrh     if( pB->pList==0 ) return 0;
23302282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
23312282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
23324adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
23332282792aSdrh         return 0;
23342282792aSdrh       }
23352282792aSdrh     }
23362282792aSdrh   }else if( pB->pList ){
23372282792aSdrh     return 0;
23382282792aSdrh   }
23392282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
23402f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
2341dd73521bSdrh   if( pA->op!=TK_COLUMN && pA->token.z ){
23422282792aSdrh     if( pB->token.z==0 ) return 0;
23436977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
23442646da7eSdrh     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
23452646da7eSdrh       return 0;
23462646da7eSdrh     }
23472282792aSdrh   }
23482282792aSdrh   return 1;
23492282792aSdrh }
23502282792aSdrh 
235113449892Sdrh 
23522282792aSdrh /*
235313449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
235413449892Sdrh ** the new element.  Return a negative number if malloc fails.
23552282792aSdrh */
235613449892Sdrh static int addAggInfoColumn(AggInfo *pInfo){
235713449892Sdrh   int i;
2358cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
2359cf643729Sdrh        pInfo->aCol,
2360cf643729Sdrh        sizeof(pInfo->aCol[0]),
2361cf643729Sdrh        3,
2362cf643729Sdrh        &pInfo->nColumn,
2363cf643729Sdrh        &pInfo->nColumnAlloc,
2364cf643729Sdrh        &i
2365cf643729Sdrh   );
236613449892Sdrh   return i;
23672282792aSdrh }
236813449892Sdrh 
236913449892Sdrh /*
237013449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
237113449892Sdrh ** the new element.  Return a negative number if malloc fails.
237213449892Sdrh */
237313449892Sdrh static int addAggInfoFunc(AggInfo *pInfo){
237413449892Sdrh   int i;
2375cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
2376cf643729Sdrh        pInfo->aFunc,
2377cf643729Sdrh        sizeof(pInfo->aFunc[0]),
2378cf643729Sdrh        3,
2379cf643729Sdrh        &pInfo->nFunc,
2380cf643729Sdrh        &pInfo->nFuncAlloc,
2381cf643729Sdrh        &i
2382cf643729Sdrh   );
238313449892Sdrh   return i;
23842282792aSdrh }
23852282792aSdrh 
23862282792aSdrh /*
2387626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
2388626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2389626a879aSdrh ** for additional information.
23902282792aSdrh **
2391626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
23922282792aSdrh */
2393626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
23942282792aSdrh   int i;
2395a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
2396a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
2397a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
239813449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
239913449892Sdrh 
24002282792aSdrh 
24012282792aSdrh   switch( pExpr->op ){
240289c69d00Sdrh     case TK_AGG_COLUMN:
2403967e8b73Sdrh     case TK_COLUMN: {
240413449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
240513449892Sdrh       ** clause of the aggregate query */
240613449892Sdrh       if( pSrcList ){
240713449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
240813449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
240913449892Sdrh           struct AggInfo_col *pCol;
241013449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
241113449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
241213449892Sdrh             ** that is in the FROM clause of the aggregate query.
241313449892Sdrh             **
241413449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
241513449892Sdrh             ** is not an entry there already.
241613449892Sdrh             */
24177f906d63Sdrh             int k;
241813449892Sdrh             pCol = pAggInfo->aCol;
24197f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
242013449892Sdrh               if( pCol->iTable==pExpr->iTable &&
242113449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
24222282792aSdrh                 break;
24232282792aSdrh               }
24242282792aSdrh             }
24257f906d63Sdrh             if( k>=pAggInfo->nColumn && (k = addAggInfoColumn(pAggInfo))>=0 ){
24267f906d63Sdrh               pCol = &pAggInfo->aCol[k];
24270817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
242813449892Sdrh               pCol->iTable = pExpr->iTable;
242913449892Sdrh               pCol->iColumn = pExpr->iColumn;
243013449892Sdrh               pCol->iMem = pParse->nMem++;
243113449892Sdrh               pCol->iSorterColumn = -1;
24325774b806Sdrh               pCol->pExpr = pExpr;
243313449892Sdrh               if( pAggInfo->pGroupBy ){
243413449892Sdrh                 int j, n;
243513449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
243613449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
243713449892Sdrh                 n = pGB->nExpr;
243813449892Sdrh                 for(j=0; j<n; j++, pTerm++){
243913449892Sdrh                   Expr *pE = pTerm->pExpr;
244013449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
244113449892Sdrh                       pE->iColumn==pExpr->iColumn ){
244213449892Sdrh                     pCol->iSorterColumn = j;
244313449892Sdrh                     break;
24442282792aSdrh                   }
244513449892Sdrh                 }
244613449892Sdrh               }
244713449892Sdrh               if( pCol->iSorterColumn<0 ){
244813449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
244913449892Sdrh               }
245013449892Sdrh             }
245113449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
245213449892Sdrh             ** because it was there before or because we just created it).
245313449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
245413449892Sdrh             ** pAggInfo->aCol[] entry.
245513449892Sdrh             */
245613449892Sdrh             pExpr->pAggInfo = pAggInfo;
245713449892Sdrh             pExpr->op = TK_AGG_COLUMN;
24587f906d63Sdrh             pExpr->iAgg = k;
245913449892Sdrh             break;
246013449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
246113449892Sdrh         } /* end loop over pSrcList */
2462a58fdfb1Sdanielk1977       }
2463626a879aSdrh       return 1;
24642282792aSdrh     }
24652282792aSdrh     case TK_AGG_FUNCTION: {
246613449892Sdrh       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
246713449892Sdrh       ** to be ignored */
2468a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
246913449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
247013449892Sdrh         ** function that is already in the pAggInfo structure
247113449892Sdrh         */
247213449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
247313449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
247413449892Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
24752282792aSdrh             break;
24762282792aSdrh           }
24772282792aSdrh         }
247813449892Sdrh         if( i>=pAggInfo->nFunc ){
247913449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
248013449892Sdrh           */
248114db2665Sdanielk1977           u8 enc = ENC(pParse->db);
248213449892Sdrh           i = addAggInfoFunc(pAggInfo);
248313449892Sdrh           if( i>=0 ){
248413449892Sdrh             pItem = &pAggInfo->aFunc[i];
248513449892Sdrh             pItem->pExpr = pExpr;
248613449892Sdrh             pItem->iMem = pParse->nMem++;
248713449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
24882646da7eSdrh                    (char*)pExpr->token.z, pExpr->token.n,
2489d8123366Sdanielk1977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2490fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
2491fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
2492fd357974Sdrh             }else{
2493fd357974Sdrh               pItem->iDistinct = -1;
2494fd357974Sdrh             }
24952282792aSdrh           }
249613449892Sdrh         }
249713449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
249813449892Sdrh         */
24992282792aSdrh         pExpr->iAgg = i;
250013449892Sdrh         pExpr->pAggInfo = pAggInfo;
2501626a879aSdrh         return 1;
25022282792aSdrh       }
25032282792aSdrh     }
2504a58fdfb1Sdanielk1977   }
250513449892Sdrh 
250613449892Sdrh   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
250713449892Sdrh   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
250813449892Sdrh   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
250913449892Sdrh   */
2510a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
2511a58fdfb1Sdanielk1977     pNC->nDepth++;
2512a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2513a58fdfb1Sdanielk1977     pNC->nDepth--;
2514a58fdfb1Sdanielk1977   }
2515626a879aSdrh   return 0;
25162282792aSdrh }
2517626a879aSdrh 
2518626a879aSdrh /*
2519626a879aSdrh ** Analyze the given expression looking for aggregate functions and
2520626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
2521626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
2522626a879aSdrh **
2523626a879aSdrh ** This routine should only be called after the expression has been
2524626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
2525626a879aSdrh **
2526626a879aSdrh ** If errors are seen, leave an error message in zErrMsg and return
2527626a879aSdrh ** the number of errors.
2528626a879aSdrh */
2529a58fdfb1Sdanielk1977 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2530a58fdfb1Sdanielk1977   int nErr = pNC->pParse->nErr;
2531a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
2532a58fdfb1Sdanielk1977   return pNC->pParse->nErr - nErr;
25332282792aSdrh }
25345d9a4af9Sdrh 
25355d9a4af9Sdrh /*
25365d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
25375d9a4af9Sdrh ** expression list.  Return the number of errors.
25385d9a4af9Sdrh **
25395d9a4af9Sdrh ** If an error is found, the analysis is cut short.
25405d9a4af9Sdrh */
25415d9a4af9Sdrh int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
25425d9a4af9Sdrh   struct ExprList_item *pItem;
25435d9a4af9Sdrh   int i;
25445d9a4af9Sdrh   int nErr = 0;
25455d9a4af9Sdrh   if( pList ){
25465d9a4af9Sdrh     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
25475d9a4af9Sdrh       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
25485d9a4af9Sdrh     }
25495d9a4af9Sdrh   }
25505d9a4af9Sdrh   return nErr;
25515d9a4af9Sdrh }
2552