xref: /sqlite-3.40.0/src/expr.c (revision d5d56523)
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*d5d56523Sdanielk1977 ** $Id: expr.c,v 1.196 2005/03/16 12:15:21 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){
37a37cdde0Sdanielk1977   if( pExpr->op==TK_AS ){
38bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pLeft);
39a37cdde0Sdanielk1977   }
40a37cdde0Sdanielk1977   if( pExpr->op==TK_SELECT ){
41bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
42a37cdde0Sdanielk1977   }
43a37cdde0Sdanielk1977   return pExpr->affinity;
44a37cdde0Sdanielk1977 }
45a37cdde0Sdanielk1977 
4653db1458Sdrh /*
470202b29eSdanielk1977 ** Return the default collation sequence for the expression pExpr. If
480202b29eSdanielk1977 ** there is no default collation type, return 0.
490202b29eSdanielk1977 */
507cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
517cedc8d4Sdanielk1977   CollSeq *pColl = 0;
520202b29eSdanielk1977   if( pExpr ){
537cedc8d4Sdanielk1977     pColl = pExpr->pColl;
547cedc8d4Sdanielk1977     if( pExpr->op==TK_AS && !pColl ){
557cedc8d4Sdanielk1977       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
560202b29eSdanielk1977     }
570202b29eSdanielk1977   }
587cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
597cedc8d4Sdanielk1977     pColl = 0;
607cedc8d4Sdanielk1977   }
617cedc8d4Sdanielk1977   return pColl;
620202b29eSdanielk1977 }
630202b29eSdanielk1977 
640202b29eSdanielk1977 /*
65626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
66626a879aSdrh ** type affinity of the other operand.  This routine returns the
6753db1458Sdrh ** type affinity that should be used for the comparison operator.
6853db1458Sdrh */
69e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
70bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
71e014a838Sdanielk1977   if( aff1 && aff2 ){
72e014a838Sdanielk1977     /* Both sides of the comparison are columns. If one has numeric or
73e014a838Sdanielk1977     ** integer affinity, use that. Otherwise use no affinity.
74e014a838Sdanielk1977     */
75e014a838Sdanielk1977     if( aff1==SQLITE_AFF_INTEGER || aff2==SQLITE_AFF_INTEGER ){
76e014a838Sdanielk1977       return SQLITE_AFF_INTEGER;
77e014a838Sdanielk1977     }else if( aff1==SQLITE_AFF_NUMERIC || aff2==SQLITE_AFF_NUMERIC ){
78e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
79e014a838Sdanielk1977     }else{
80e014a838Sdanielk1977       return SQLITE_AFF_NONE;
81e014a838Sdanielk1977     }
82e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
835f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
845f6a87b3Sdrh     ** results directly.
85e014a838Sdanielk1977     */
865f6a87b3Sdrh     /* return SQLITE_AFF_NUMERIC;  // Ticket #805 */
875f6a87b3Sdrh     return SQLITE_AFF_NONE;
88e014a838Sdanielk1977   }else{
89e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
90e014a838Sdanielk1977     return (aff1 + aff2);
91e014a838Sdanielk1977   }
92e014a838Sdanielk1977 }
93e014a838Sdanielk1977 
9453db1458Sdrh /*
9553db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
9653db1458Sdrh ** be applied to both operands prior to doing the comparison.
9753db1458Sdrh */
98e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
99e014a838Sdanielk1977   char aff;
100e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
101e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
102e014a838Sdanielk1977           pExpr->op==TK_NE );
103e014a838Sdanielk1977   assert( pExpr->pLeft );
104bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
105e014a838Sdanielk1977   if( pExpr->pRight ){
106e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
107e014a838Sdanielk1977   }
108e014a838Sdanielk1977   else if( pExpr->pSelect ){
109e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
110e014a838Sdanielk1977   }
111e014a838Sdanielk1977   else if( !aff ){
112e014a838Sdanielk1977     aff = SQLITE_AFF_NUMERIC;
113e014a838Sdanielk1977   }
114e014a838Sdanielk1977   return aff;
115e014a838Sdanielk1977 }
116e014a838Sdanielk1977 
117e014a838Sdanielk1977 /*
118e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
119e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
120e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
121e014a838Sdanielk1977 ** the comparison in pExpr.
122e014a838Sdanielk1977 */
123e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
124e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
125e014a838Sdanielk1977   return
126e014a838Sdanielk1977     (aff==SQLITE_AFF_NONE) ||
127e014a838Sdanielk1977     (aff==SQLITE_AFF_NUMERIC && idx_affinity==SQLITE_AFF_INTEGER) ||
128e014a838Sdanielk1977     (aff==SQLITE_AFF_INTEGER && idx_affinity==SQLITE_AFF_NUMERIC) ||
129e014a838Sdanielk1977     (aff==idx_affinity);
130e014a838Sdanielk1977 }
131e014a838Sdanielk1977 
132a37cdde0Sdanielk1977 /*
133a37cdde0Sdanielk1977 ** Return the P1 value that should be used for a binary comparison
134a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
135a37cdde0Sdanielk1977 ** If jumpIfNull is true, then set the low byte of the returned
136a37cdde0Sdanielk1977 ** P1 value to tell the opcode to jump if either expression
137a37cdde0Sdanielk1977 ** evaluates to NULL.
138a37cdde0Sdanielk1977 */
139e014a838Sdanielk1977 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
140bf3b721fSdanielk1977   char aff = sqlite3ExprAffinity(pExpr2);
141e014a838Sdanielk1977   return (((int)sqlite3CompareAffinity(pExpr1, aff))<<8)+(jumpIfNull?1:0);
142a37cdde0Sdanielk1977 }
143a37cdde0Sdanielk1977 
144a2e00042Sdrh /*
1450202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
1460202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
1470202b29eSdanielk1977 **
1480202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
1490202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
1500202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
1510202b29eSdanielk1977 ** type.
1520202b29eSdanielk1977 */
1537cedc8d4Sdanielk1977 static CollSeq* binaryCompareCollSeq(Parse *pParse, Expr *pLeft, Expr *pRight){
1547cedc8d4Sdanielk1977   CollSeq *pColl = sqlite3ExprCollSeq(pParse, pLeft);
1550202b29eSdanielk1977   if( !pColl ){
1567cedc8d4Sdanielk1977     pColl = sqlite3ExprCollSeq(pParse, pRight);
1570202b29eSdanielk1977   }
1580202b29eSdanielk1977   return pColl;
1590202b29eSdanielk1977 }
1600202b29eSdanielk1977 
1610202b29eSdanielk1977 /*
162be5c89acSdrh ** Generate code for a comparison operator.
163be5c89acSdrh */
164be5c89acSdrh static int codeCompare(
165be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
166be5c89acSdrh   Expr *pLeft,      /* The left operand */
167be5c89acSdrh   Expr *pRight,     /* The right operand */
168be5c89acSdrh   int opcode,       /* The comparison opcode */
169be5c89acSdrh   int dest,         /* Jump here if true.  */
170be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
171be5c89acSdrh ){
172be5c89acSdrh   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
173be5c89acSdrh   CollSeq *p3 = binaryCompareCollSeq(pParse, pLeft, pRight);
174be5c89acSdrh   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
175be5c89acSdrh }
176be5c89acSdrh 
177be5c89acSdrh /*
178a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
179a76b5dfcSdrh ** for this node is obtained from sqliteMalloc().  The calling function
180a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
181a76b5dfcSdrh */
182e4e72072Sdrh Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
183a76b5dfcSdrh   Expr *pNew;
184a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
185a76b5dfcSdrh   if( pNew==0 ){
186*d5d56523Sdanielk1977     /* When malloc fails, delete pLeft and pRight. Expressions passed to
187*d5d56523Sdanielk1977     ** this function must always be allocated with sqlite3Expr() for this
188*d5d56523Sdanielk1977     ** reason.
189*d5d56523Sdanielk1977     */
190*d5d56523Sdanielk1977     sqlite3ExprDelete(pLeft);
191*d5d56523Sdanielk1977     sqlite3ExprDelete(pRight);
192a76b5dfcSdrh     return 0;
193a76b5dfcSdrh   }
194a76b5dfcSdrh   pNew->op = op;
195a76b5dfcSdrh   pNew->pLeft = pLeft;
196a76b5dfcSdrh   pNew->pRight = pRight;
197a58fdfb1Sdanielk1977   pNew->iAgg = -1;
198a76b5dfcSdrh   if( pToken ){
1994b59ab5eSdrh     assert( pToken->dyn==0 );
200145716b3Sdrh     pNew->span = pNew->token = *pToken;
201145716b3Sdrh   }else if( pLeft && pRight ){
2024adee20fSdanielk1977     sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
203a76b5dfcSdrh   }
204a76b5dfcSdrh   return pNew;
205a76b5dfcSdrh }
206a76b5dfcSdrh 
207a76b5dfcSdrh /*
2084e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
2094e0cff60Sdrh ** that look like this:   #0 #1 #2 ...  These terms refer to elements
2104e0cff60Sdrh ** on the stack.  "#0" (or just "#") means the top of the stack.
2112958a4e6Sdrh ** "#1" means the next down on the stack.  And so forth.  #-1 means
2122958a4e6Sdrh ** memory location 0.  #-2 means memory location 1.  And so forth.
2134e0cff60Sdrh **
2144e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
2154e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
2164e0cff60Sdrh ** The returns an expression that will code to extract the value from
2174e0cff60Sdrh ** that memory location as needed.
2184e0cff60Sdrh */
2194e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
2204e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
2214e0cff60Sdrh   Expr *p;
2224e0cff60Sdrh   int depth;
2234e0cff60Sdrh   if( v==0 ) return 0;
2244e0cff60Sdrh   if( pParse->nested==0 ){
2254e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
2264e0cff60Sdrh     return 0;
2274e0cff60Sdrh   }
2284e0cff60Sdrh   p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
22973c42a13Sdrh   if( p==0 ){
23073c42a13Sdrh     return 0;  /* Malloc failed */
23173c42a13Sdrh   }
2324e0cff60Sdrh   depth = atoi(&pToken->z[1]);
2332958a4e6Sdrh   if( depth>=0 ){
2344e0cff60Sdrh     p->iTable = pParse->nMem++;
2354e0cff60Sdrh     sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
2364e0cff60Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
2372958a4e6Sdrh   }else{
2382958a4e6Sdrh     p->iTable = -1-depth;
2392958a4e6Sdrh   }
2404e0cff60Sdrh   return p;
2414e0cff60Sdrh }
2424e0cff60Sdrh 
2434e0cff60Sdrh /*
24491bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
24591bb0eedSdrh ** NULL, then just return the other expression.
24691bb0eedSdrh */
24791bb0eedSdrh Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
24891bb0eedSdrh   if( pLeft==0 ){
24991bb0eedSdrh     return pRight;
25091bb0eedSdrh   }else if( pRight==0 ){
25191bb0eedSdrh     return pLeft;
25291bb0eedSdrh   }else{
25391bb0eedSdrh     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
25491bb0eedSdrh   }
25591bb0eedSdrh }
25691bb0eedSdrh 
25791bb0eedSdrh /*
2586977fea8Sdrh ** Set the Expr.span field of the given expression to span all
259a76b5dfcSdrh ** text between the two given tokens.
260a76b5dfcSdrh */
2614adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
2624efc4754Sdrh   assert( pRight!=0 );
2634efc4754Sdrh   assert( pLeft!=0 );
26471c697efSdrh   if( !sqlite3_malloc_failed && pRight->z && pLeft->z ){
265ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
266145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
2676977fea8Sdrh       pExpr->span.z = pLeft->z;
2686977fea8Sdrh       pExpr->span.n = pRight->n + Addr(pRight->z) - Addr(pLeft->z);
2694b59ab5eSdrh     }else{
2706977fea8Sdrh       pExpr->span.z = 0;
2714b59ab5eSdrh     }
272a76b5dfcSdrh   }
273a76b5dfcSdrh }
274a76b5dfcSdrh 
275a76b5dfcSdrh /*
276a76b5dfcSdrh ** Construct a new expression node for a function with multiple
277a76b5dfcSdrh ** arguments.
278a76b5dfcSdrh */
2794adee20fSdanielk1977 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
280a76b5dfcSdrh   Expr *pNew;
281a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
282a76b5dfcSdrh   if( pNew==0 ){
283*d5d56523Sdanielk1977     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
284a76b5dfcSdrh     return 0;
285a76b5dfcSdrh   }
286a76b5dfcSdrh   pNew->op = TK_FUNCTION;
287a76b5dfcSdrh   pNew->pList = pList;
288a76b5dfcSdrh   if( pToken ){
2894b59ab5eSdrh     assert( pToken->dyn==0 );
290a76b5dfcSdrh     pNew->token = *pToken;
291a76b5dfcSdrh   }else{
292a76b5dfcSdrh     pNew->token.z = 0;
293a76b5dfcSdrh   }
2946977fea8Sdrh   pNew->span = pNew->token;
295a76b5dfcSdrh   return pNew;
296a76b5dfcSdrh }
297a76b5dfcSdrh 
298a76b5dfcSdrh /*
299fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
300fa6bc000Sdrh ** in the original SQL statement.
301fa6bc000Sdrh **
302fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
303fa6bc000Sdrh ** variable number.
304fa6bc000Sdrh **
305fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
306fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
307fa6bc000Sdrh ** the SQL statement comes from an external source.
308fa6bc000Sdrh **
309fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
310fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
311fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
312fa6bc000Sdrh ** assigned.
313fa6bc000Sdrh */
314fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
315fa6bc000Sdrh   Token *pToken;
316fa6bc000Sdrh   if( pExpr==0 ) return;
317fa6bc000Sdrh   pToken = &pExpr->token;
318fa6bc000Sdrh   assert( pToken->n>=1 );
319fa6bc000Sdrh   assert( pToken->z!=0 );
320fa6bc000Sdrh   assert( pToken->z[0]!=0 );
321fa6bc000Sdrh   if( pToken->n==1 ){
322fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
323fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
324fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
325fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
326fa6bc000Sdrh     ** use it as the variable number */
327fa6bc000Sdrh     int i;
328fa6bc000Sdrh     pExpr->iTable = i = atoi(&pToken->z[1]);
329fa6bc000Sdrh     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
330fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
331fa6bc000Sdrh           SQLITE_MAX_VARIABLE_NUMBER);
332fa6bc000Sdrh     }
333fa6bc000Sdrh     if( i>pParse->nVar ){
334fa6bc000Sdrh       pParse->nVar = i;
335fa6bc000Sdrh     }
336fa6bc000Sdrh   }else{
337fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
338fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
339fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
340fa6bc000Sdrh     */
341fa6bc000Sdrh     int i, n;
342fa6bc000Sdrh     n = pToken->n;
343fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
344fa6bc000Sdrh       Expr *pE;
345fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
346fa6bc000Sdrh           && pE->token.n==n
347fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
348fa6bc000Sdrh         pExpr->iTable = pE->iTable;
349fa6bc000Sdrh         break;
350fa6bc000Sdrh       }
351fa6bc000Sdrh     }
352fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
353fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
354fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
355fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
356fa6bc000Sdrh         pParse->apVarExpr = sqliteRealloc(pParse->apVarExpr,
357fa6bc000Sdrh                        pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
358fa6bc000Sdrh       }
359fa6bc000Sdrh       if( !sqlite3_malloc_failed ){
360fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
361fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
362fa6bc000Sdrh       }
363fa6bc000Sdrh     }
364fa6bc000Sdrh   }
365fa6bc000Sdrh }
366fa6bc000Sdrh 
367fa6bc000Sdrh /*
368a2e00042Sdrh ** Recursively delete an expression tree.
369a2e00042Sdrh */
3704adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
371a2e00042Sdrh   if( p==0 ) return;
3724efc4754Sdrh   if( p->span.dyn ) sqliteFree((char*)p->span.z);
3734efc4754Sdrh   if( p->token.dyn ) sqliteFree((char*)p->token.z);
3744adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
3754adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
3764adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
3774adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
378a2e00042Sdrh   sqliteFree(p);
379a2e00042Sdrh }
380a2e00042Sdrh 
381a76b5dfcSdrh 
382a76b5dfcSdrh /*
383ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
384ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
385ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
386ff78bd2fSdrh ** without effecting the originals.
387ff78bd2fSdrh **
3884adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
3894adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
390ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
391ff78bd2fSdrh **
392ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
393ff78bd2fSdrh */
3944adee20fSdanielk1977 Expr *sqlite3ExprDup(Expr *p){
395ff78bd2fSdrh   Expr *pNew;
396ff78bd2fSdrh   if( p==0 ) return 0;
397fcb78a49Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
398ff78bd2fSdrh   if( pNew==0 ) return 0;
3993b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
4006977fea8Sdrh   if( p->token.z!=0 ){
401b9ecf6faSdrh     pNew->token.z = sqliteStrNDup(p->token.z, p->token.n);
4024b59ab5eSdrh     pNew->token.dyn = 1;
4034b59ab5eSdrh   }else{
4044efc4754Sdrh     assert( pNew->token.z==0 );
4054b59ab5eSdrh   }
4066977fea8Sdrh   pNew->span.z = 0;
4074adee20fSdanielk1977   pNew->pLeft = sqlite3ExprDup(p->pLeft);
4084adee20fSdanielk1977   pNew->pRight = sqlite3ExprDup(p->pRight);
4094adee20fSdanielk1977   pNew->pList = sqlite3ExprListDup(p->pList);
4104adee20fSdanielk1977   pNew->pSelect = sqlite3SelectDup(p->pSelect);
411aee18ef8Sdanielk1977   pNew->pTab = p->pTab;
412ff78bd2fSdrh   return pNew;
413ff78bd2fSdrh }
4144adee20fSdanielk1977 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
4154b59ab5eSdrh   if( pTo->dyn ) sqliteFree((char*)pTo->z);
4164b59ab5eSdrh   if( pFrom->z ){
4174b59ab5eSdrh     pTo->n = pFrom->n;
4184b59ab5eSdrh     pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
4194b59ab5eSdrh     pTo->dyn = 1;
4204b59ab5eSdrh   }else{
4214b59ab5eSdrh     pTo->z = 0;
4224b59ab5eSdrh   }
4234b59ab5eSdrh }
4244adee20fSdanielk1977 ExprList *sqlite3ExprListDup(ExprList *p){
425ff78bd2fSdrh   ExprList *pNew;
426145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
427ff78bd2fSdrh   int i;
428ff78bd2fSdrh   if( p==0 ) return 0;
429ff78bd2fSdrh   pNew = sqliteMalloc( sizeof(*pNew) );
430ff78bd2fSdrh   if( pNew==0 ) return 0;
4314305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
4323e7bc9caSdrh   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
433e0048400Sdanielk1977   if( pItem==0 ){
434e0048400Sdanielk1977     sqliteFree(pNew);
435e0048400Sdanielk1977     return 0;
436e0048400Sdanielk1977   }
437145716b3Sdrh   pOldItem = p->a;
438145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
4394b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
440145716b3Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
4416977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
4426977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
4434b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
4444b59ab5eSdrh       ** the names of columns in the result set needs this information */
4454adee20fSdanielk1977       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
4464b59ab5eSdrh     }
4471f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
44824b03fd0Sdanielk1977             || pOldExpr->span.z==0 || sqlite3_malloc_failed );
449145716b3Sdrh     pItem->zName = sqliteStrDup(pOldItem->zName);
450145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
451145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
4523e7bc9caSdrh     pItem->done = 0;
453ff78bd2fSdrh   }
454ff78bd2fSdrh   return pNew;
455ff78bd2fSdrh }
45693758c8dSdanielk1977 
45793758c8dSdanielk1977 /*
45893758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
45993758c8dSdanielk1977 ** the build, then none of the following routines, except for
46093758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
46193758c8dSdanielk1977 ** called with a NULL argument.
46293758c8dSdanielk1977 */
4636a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
4646a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
4654adee20fSdanielk1977 SrcList *sqlite3SrcListDup(SrcList *p){
466ad3cab52Sdrh   SrcList *pNew;
467ad3cab52Sdrh   int i;
468113088ecSdrh   int nByte;
469ad3cab52Sdrh   if( p==0 ) return 0;
470113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
4714efc4754Sdrh   pNew = sqliteMallocRaw( nByte );
472ad3cab52Sdrh   if( pNew==0 ) return 0;
4734305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
474ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
4754efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
4764efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
4774efc4754Sdrh     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
4784efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
4794efc4754Sdrh     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
4804efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
4814efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
482a1cb183dSdanielk1977     pNewItem->pTab = pOldItem->pTab;
483a1cb183dSdanielk1977     if( pNewItem->pTab ){
484a1cb183dSdanielk1977       pNewItem->pTab->isTransient = 0;
485a1cb183dSdanielk1977     }
4864adee20fSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
4874adee20fSdanielk1977     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
4884adee20fSdanielk1977     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
4896c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
490ad3cab52Sdrh   }
491ad3cab52Sdrh   return pNew;
492ad3cab52Sdrh }
4934adee20fSdanielk1977 IdList *sqlite3IdListDup(IdList *p){
494ff78bd2fSdrh   IdList *pNew;
495ff78bd2fSdrh   int i;
496ff78bd2fSdrh   if( p==0 ) return 0;
4974efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*pNew) );
498ff78bd2fSdrh   if( pNew==0 ) return 0;
4994305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
5004efc4754Sdrh   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
501*d5d56523Sdanielk1977   if( pNew->a==0 ){
502*d5d56523Sdanielk1977     sqliteFree(pNew);
503*d5d56523Sdanielk1977     return 0;
504*d5d56523Sdanielk1977   }
505ff78bd2fSdrh   for(i=0; i<p->nId; i++){
5064efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
5074efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
5084efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5094efc4754Sdrh     pNewItem->idx = pOldItem->idx;
510ff78bd2fSdrh   }
511ff78bd2fSdrh   return pNew;
512ff78bd2fSdrh }
5134adee20fSdanielk1977 Select *sqlite3SelectDup(Select *p){
514ff78bd2fSdrh   Select *pNew;
515ff78bd2fSdrh   if( p==0 ) return 0;
5164efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
517ff78bd2fSdrh   if( pNew==0 ) return 0;
518ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
5194adee20fSdanielk1977   pNew->pEList = sqlite3ExprListDup(p->pEList);
5204adee20fSdanielk1977   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
5214adee20fSdanielk1977   pNew->pWhere = sqlite3ExprDup(p->pWhere);
5224adee20fSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
5234adee20fSdanielk1977   pNew->pHaving = sqlite3ExprDup(p->pHaving);
5244adee20fSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
525ff78bd2fSdrh   pNew->op = p->op;
5264adee20fSdanielk1977   pNew->pPrior = sqlite3SelectDup(p->pPrior);
527a2dc3b1aSdanielk1977   pNew->pLimit = sqlite3ExprDup(p->pLimit);
528a2dc3b1aSdanielk1977   pNew->pOffset = sqlite3ExprDup(p->pOffset);
5297b58daeaSdrh   pNew->iLimit = -1;
5307b58daeaSdrh   pNew->iOffset = -1;
531dc1bdc4fSdanielk1977   pNew->ppOpenTemp = 0;
532b6c29897Sdrh   pNew->pFetch = 0;
533a1cb183dSdanielk1977   pNew->isResolved = p->isResolved;
534a1cb183dSdanielk1977   pNew->isAgg = p->isAgg;
535ff78bd2fSdrh   return pNew;
536ff78bd2fSdrh }
53793758c8dSdanielk1977 #else
53893758c8dSdanielk1977 Select *sqlite3SelectDup(Select *p){
53993758c8dSdanielk1977   assert( p==0 );
54093758c8dSdanielk1977   return 0;
54193758c8dSdanielk1977 }
54293758c8dSdanielk1977 #endif
543ff78bd2fSdrh 
544ff78bd2fSdrh 
545ff78bd2fSdrh /*
546a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
547a76b5dfcSdrh ** initially NULL, then create a new expression list.
548a76b5dfcSdrh */
5494adee20fSdanielk1977 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
550a76b5dfcSdrh   if( pList==0 ){
551a76b5dfcSdrh     pList = sqliteMalloc( sizeof(ExprList) );
552a76b5dfcSdrh     if( pList==0 ){
553*d5d56523Sdanielk1977       goto no_mem;
554a76b5dfcSdrh     }
5554efc4754Sdrh     assert( pList->nAlloc==0 );
556a76b5dfcSdrh   }
5574305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
558*d5d56523Sdanielk1977     struct ExprList_item *a;
559*d5d56523Sdanielk1977     int n = pList->nAlloc*2 + 4;
560*d5d56523Sdanielk1977     a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
561*d5d56523Sdanielk1977     if( a==0 ){
562*d5d56523Sdanielk1977       goto no_mem;
563a76b5dfcSdrh     }
564*d5d56523Sdanielk1977     pList->a = a;
565*d5d56523Sdanielk1977     pList->nAlloc = n;
566a76b5dfcSdrh   }
5674efc4754Sdrh   assert( pList->a!=0 );
5684efc4754Sdrh   if( pExpr || pName ){
5694efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
5704efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
5714efc4754Sdrh     pItem->pExpr = pExpr;
572a99db3b6Sdrh     pItem->zName = sqlite3NameFromToken(pName);
573a76b5dfcSdrh   }
574a76b5dfcSdrh   return pList;
575*d5d56523Sdanielk1977 
576*d5d56523Sdanielk1977 no_mem:
577*d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
578*d5d56523Sdanielk1977   sqlite3ExprDelete(pExpr);
579*d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
580*d5d56523Sdanielk1977   return 0;
581a76b5dfcSdrh }
582a76b5dfcSdrh 
583a76b5dfcSdrh /*
584a76b5dfcSdrh ** Delete an entire expression list.
585a76b5dfcSdrh */
5864adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
587a76b5dfcSdrh   int i;
588be5c89acSdrh   struct ExprList_item *pItem;
589a76b5dfcSdrh   if( pList==0 ) return;
5901bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
5911bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
592be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
593be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
594be5c89acSdrh     sqliteFree(pItem->zName);
595a76b5dfcSdrh   }
596a76b5dfcSdrh   sqliteFree(pList->a);
597a76b5dfcSdrh   sqliteFree(pList);
598a76b5dfcSdrh }
599a76b5dfcSdrh 
600a76b5dfcSdrh /*
601626a879aSdrh ** Walk an expression tree.  Call xFunc for each node visited.
60273b211abSdrh **
603626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
604626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
605626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
606626a879aSdrh ** the tree walk completely.
607626a879aSdrh **
608626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
609626a879aSdrh ** and 0 to continue.
610626a879aSdrh */
611a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
612626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
613626a879aSdrh   int rc;
614626a879aSdrh   if( pExpr==0 ) return 0;
615626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
616626a879aSdrh   if( rc==0 ){
617626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
618626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
619a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
620626a879aSdrh   }
621626a879aSdrh   return rc>1;
622626a879aSdrh }
623626a879aSdrh 
624626a879aSdrh /*
625a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
626a58fdfb1Sdanielk1977 */
627a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
628a58fdfb1Sdanielk1977   int i;
629a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
630a58fdfb1Sdanielk1977   if( !p ) return 0;
631a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
632a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
633a58fdfb1Sdanielk1977   }
634a58fdfb1Sdanielk1977   return 0;
635a58fdfb1Sdanielk1977 }
636a58fdfb1Sdanielk1977 
637a58fdfb1Sdanielk1977 /*
638a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
639a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
640a58fdfb1Sdanielk1977 ** or OFFSET expressions..
641a58fdfb1Sdanielk1977 */
642a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
643a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
644a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
645a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
646a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
647a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
648a58fdfb1Sdanielk1977   return 0;
649a58fdfb1Sdanielk1977 }
650a58fdfb1Sdanielk1977 
651a58fdfb1Sdanielk1977 
652a58fdfb1Sdanielk1977 /*
653626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
654626a879aSdrh **
655626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
65673b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
65773b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
65873b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
65973b211abSdrh ** then do nothing.
66073b211abSdrh **
66173b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
66273b211abSdrh ** the expression as constant, then we assume the whole expression
66373b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
664626a879aSdrh */
665626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
666626a879aSdrh   switch( pExpr->op ){
667626a879aSdrh     case TK_ID:
668626a879aSdrh     case TK_COLUMN:
669626a879aSdrh     case TK_DOT:
670626a879aSdrh     case TK_AGG_FUNCTION:
671626a879aSdrh     case TK_FUNCTION:
672fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
673fe2093d7Sdrh     case TK_SELECT:
674fe2093d7Sdrh     case TK_EXISTS:
675fe2093d7Sdrh #endif
676626a879aSdrh       *((int*)pArg) = 0;
677626a879aSdrh       return 2;
678626a879aSdrh     default:
679626a879aSdrh       return 0;
680626a879aSdrh   }
681626a879aSdrh }
682626a879aSdrh 
683626a879aSdrh /*
684fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
685fef5208cSdrh ** and 0 if it involves variables.
6862398937bSdrh **
6872398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
6882398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
6892398937bSdrh ** a constant.
690fef5208cSdrh */
6914adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
692626a879aSdrh   int isConst = 1;
693626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
694626a879aSdrh   return isConst;
695fef5208cSdrh }
696fef5208cSdrh 
697fef5208cSdrh /*
69873b211abSdrh ** If the expression p codes a constant integer that is small enough
699202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
700202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
701202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
702e4de1febSdrh */
7034adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
704e4de1febSdrh   switch( p->op ){
705e4de1febSdrh     case TK_INTEGER: {
706fec19aadSdrh       if( sqlite3GetInt32(p->token.z, pValue) ){
707e4de1febSdrh         return 1;
708e4de1febSdrh       }
709202b2df7Sdrh       break;
710202b2df7Sdrh     }
7114b59ab5eSdrh     case TK_UPLUS: {
7124adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
7134b59ab5eSdrh     }
714e4de1febSdrh     case TK_UMINUS: {
715e4de1febSdrh       int v;
7164adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
717e4de1febSdrh         *pValue = -v;
718e4de1febSdrh         return 1;
719e4de1febSdrh       }
720e4de1febSdrh       break;
721e4de1febSdrh     }
722e4de1febSdrh     default: break;
723e4de1febSdrh   }
724e4de1febSdrh   return 0;
725e4de1febSdrh }
726e4de1febSdrh 
727e4de1febSdrh /*
728c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
729c4a3c779Sdrh */
7304adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
7314adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
7324adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
7334adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
734c4a3c779Sdrh   return 0;
735c4a3c779Sdrh }
736c4a3c779Sdrh 
737c4a3c779Sdrh /*
7388141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
7398141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
7408141f61eSdrh ** expression node refer back to that source column.  The following changes
7418141f61eSdrh ** are made to pExpr:
7428141f61eSdrh **
7438141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
7448141f61eSdrh **                         the table.
7458141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
7468141f61eSdrh **                         from pSrcList.
7478141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
7488141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
7498141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
7508141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
7518141f61eSdrh **
7528141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
7538141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
7548141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
7558141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
7568141f61eSdrh ** means that the form of the name is Z and that columns from any table
7578141f61eSdrh ** can be used.
7588141f61eSdrh **
7598141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
7608141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
7618141f61eSdrh */
7628141f61eSdrh static int lookupName(
7638141f61eSdrh   Parse *pParse,      /* The parsing context */
7648141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
7658141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
7668141f61eSdrh   Token *pColumnToken, /* Name of the column. */
767626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
7688141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
7698141f61eSdrh ){
7708141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
7718141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
7728141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
7738141f61eSdrh   int i, j;            /* Loop counters */
7748141f61eSdrh   int cnt = 0;         /* Number of matching column names */
7758141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
7769bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
77751669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
77851669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
77973b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
7808141f61eSdrh 
7818141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
782a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
783a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
784a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
78524b03fd0Sdanielk1977   if( sqlite3_malloc_failed ){
786*d5d56523Sdanielk1977     goto lookupname_end;
7878141f61eSdrh   }
7888141f61eSdrh 
7898141f61eSdrh   pExpr->iTable = -1;
790626a879aSdrh   while( pNC && cnt==0 ){
791626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
792626a879aSdrh     ExprList *pEList = pNC->pEList;
793626a879aSdrh 
794626a879aSdrh     pNC->nRef++;
795626a879aSdrh     /* assert( zTab==0 || pEList==0 ); */
796b3bce662Sdanielk1977     if( pSrcList ){
79751669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
7988141f61eSdrh         Table *pTab = pItem->pTab;
7998141f61eSdrh         Column *pCol;
8008141f61eSdrh 
8018141f61eSdrh         if( pTab==0 ) continue;
8028141f61eSdrh         assert( pTab->nCol>0 );
8038141f61eSdrh         if( zTab ){
8048141f61eSdrh           if( pItem->zAlias ){
8058141f61eSdrh             char *zTabName = pItem->zAlias;
8064adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
8078141f61eSdrh           }else{
8088141f61eSdrh             char *zTabName = pTab->zName;
8094adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
8104adee20fSdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
8118141f61eSdrh               continue;
8128141f61eSdrh             }
8138141f61eSdrh           }
8148141f61eSdrh         }
8158141f61eSdrh         if( 0==(cntTab++) ){
8168141f61eSdrh           pExpr->iTable = pItem->iCursor;
8178141f61eSdrh           pExpr->iDb = pTab->iDb;
81851669863Sdrh           pMatch = pItem;
8198141f61eSdrh         }
8208141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
8214adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
8228141f61eSdrh             cnt++;
8238141f61eSdrh             pExpr->iTable = pItem->iCursor;
82451669863Sdrh             pMatch = pItem;
8258141f61eSdrh             pExpr->iDb = pTab->iDb;
8268141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
8278141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
828a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
8290202b29eSdanielk1977             pExpr->pColl = pTab->aCol[j].pColl;
8308141f61eSdrh             break;
8318141f61eSdrh           }
8328141f61eSdrh         }
8338141f61eSdrh       }
834b3bce662Sdanielk1977     }
8358141f61eSdrh 
836b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
8378141f61eSdrh     /* If we have not already resolved the name, then maybe
8388141f61eSdrh     ** it is a new.* or old.* trigger argument reference
8398141f61eSdrh     */
8408141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
8418141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
8428141f61eSdrh       Table *pTab = 0;
8434adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
8448141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
8458141f61eSdrh         assert( pTriggerStack->pTab );
8468141f61eSdrh         pTab = pTriggerStack->pTab;
8474adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
8488141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
8498141f61eSdrh         assert( pTriggerStack->pTab );
8508141f61eSdrh         pTab = pTriggerStack->pTab;
8518141f61eSdrh       }
8528141f61eSdrh 
8538141f61eSdrh       if( pTab ){
8548141f61eSdrh         int j;
8558141f61eSdrh         Column *pCol = pTab->aCol;
8568141f61eSdrh 
8578141f61eSdrh         pExpr->iDb = pTab->iDb;
8588141f61eSdrh         cntTab++;
8598141f61eSdrh         for(j=0; j < pTab->nCol; j++, pCol++) {
8604adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
8618141f61eSdrh             cnt++;
8628141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
863a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
8640202b29eSdanielk1977             pExpr->pColl = pTab->aCol[j].pColl;
865aee18ef8Sdanielk1977             pExpr->pTab = pTab;
8668141f61eSdrh             break;
8678141f61eSdrh           }
8688141f61eSdrh         }
8698141f61eSdrh       }
8708141f61eSdrh     }
871b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
8728141f61eSdrh 
8738141f61eSdrh     /*
8748141f61eSdrh     ** Perhaps the name is a reference to the ROWID
8758141f61eSdrh     */
8764adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
8778141f61eSdrh       cnt = 1;
8788141f61eSdrh       pExpr->iColumn = -1;
879a37cdde0Sdanielk1977       pExpr->affinity = SQLITE_AFF_INTEGER;
8808141f61eSdrh     }
8818141f61eSdrh 
8828141f61eSdrh     /*
8838141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
8848141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
8858141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
8868141f61eSdrh     **
8878141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
8888141f61eSdrh     **
8898141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
8908141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
8918141f61eSdrh     ** Note that the expression in the result set should have already been
8928141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
8938141f61eSdrh     */
89479d5f63fSdrh     if( cnt==0 && pEList!=0 && zTab==0 ){
8958141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
8968141f61eSdrh         char *zAs = pEList->a[j].zName;
8974adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
8988141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
8998141f61eSdrh           pExpr->op = TK_AS;
9008141f61eSdrh           pExpr->iColumn = j;
9014adee20fSdanielk1977           pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
9028141f61eSdrh           sqliteFree(zCol);
9038141f61eSdrh           assert( zTab==0 && zDb==0 );
9048141f61eSdrh           return 0;
9058141f61eSdrh         }
9068141f61eSdrh       }
9078141f61eSdrh     }
9088141f61eSdrh 
909626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
910626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
911626a879aSdrh     */
912626a879aSdrh     if( cnt==0 ){
913626a879aSdrh       pNC = pNC->pNext;
914626a879aSdrh     }
915626a879aSdrh   }
916626a879aSdrh 
9178141f61eSdrh   /*
9188141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
9198141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
9208141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
9218141f61eSdrh   ** case, we need to return right away and not make any changes to
9228141f61eSdrh   ** pExpr.
9238141f61eSdrh   */
9248141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
9258141f61eSdrh     sqliteFree(zCol);
9268141f61eSdrh     return 0;
9278141f61eSdrh   }
9288141f61eSdrh 
9298141f61eSdrh   /*
9308141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
9318141f61eSdrh   ** more matches.  Either way, we have an error.
9328141f61eSdrh   */
9338141f61eSdrh   if( cnt!=1 ){
9348141f61eSdrh     char *z = 0;
9358141f61eSdrh     char *zErr;
9368141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
9378141f61eSdrh     if( zDb ){
9384adee20fSdanielk1977       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, 0);
9398141f61eSdrh     }else if( zTab ){
9404adee20fSdanielk1977       sqlite3SetString(&z, zTab, ".", zCol, 0);
9418141f61eSdrh     }else{
9428141f61eSdrh       z = sqliteStrDup(zCol);
9438141f61eSdrh     }
9444adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
9458141f61eSdrh     sqliteFree(z);
94673b211abSdrh     pTopNC->nErr++;
9478141f61eSdrh   }
9488141f61eSdrh 
94951669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
95051669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
95151669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
95251669863Sdrh   ** column number is greater than the number of bits in the bitmask
95351669863Sdrh   ** then set the high-order bit of the bitmask.
95451669863Sdrh   */
95551669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
95651669863Sdrh     int n = pExpr->iColumn;
95751669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
95851669863Sdrh       n = sizeof(Bitmask)*8-1;
95951669863Sdrh     }
96051669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
96151669863Sdrh     pMatch->colUsed |= 1<<n;
96251669863Sdrh   }
96351669863Sdrh 
964*d5d56523Sdanielk1977 lookupname_end:
9658141f61eSdrh   /* Clean up and return
9668141f61eSdrh   */
9678141f61eSdrh   sqliteFree(zDb);
9688141f61eSdrh   sqliteFree(zTab);
9698141f61eSdrh   sqliteFree(zCol);
9704adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
9718141f61eSdrh   pExpr->pLeft = 0;
9724adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
9738141f61eSdrh   pExpr->pRight = 0;
9748141f61eSdrh   pExpr->op = TK_COLUMN;
975626a879aSdrh   if( cnt==1 ){
976b3bce662Sdanielk1977     assert( pNC!=0 );
977626a879aSdrh     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
978aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
979aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
980aee18ef8Sdanielk1977     }
981626a879aSdrh   }
9828141f61eSdrh   return cnt!=1;
9838141f61eSdrh }
9848141f61eSdrh 
9858141f61eSdrh /*
986626a879aSdrh ** pExpr is a node that defines a function of some kind.  It might
987626a879aSdrh ** be a syntactic function like "count(x)" or it might be a function
988626a879aSdrh ** that implements an operator, like "a LIKE b".
989626a879aSdrh **
990626a879aSdrh ** This routine makes *pzName point to the name of the function and
991626a879aSdrh ** *pnName hold the number of characters in the function name.
992626a879aSdrh */
993626a879aSdrh static void getFunctionName(Expr *pExpr, const char **pzName, int *pnName){
994626a879aSdrh   switch( pExpr->op ){
995626a879aSdrh     case TK_FUNCTION: {
996626a879aSdrh       *pzName = pExpr->token.z;
997626a879aSdrh       *pnName = pExpr->token.n;
998626a879aSdrh       break;
999626a879aSdrh     }
1000626a879aSdrh     case TK_LIKE: {
1001626a879aSdrh       *pzName = "like";
1002626a879aSdrh       *pnName = 4;
1003626a879aSdrh       break;
1004626a879aSdrh     }
1005626a879aSdrh     case TK_GLOB: {
1006626a879aSdrh       *pzName = "glob";
1007626a879aSdrh       *pnName = 4;
1008626a879aSdrh       break;
1009626a879aSdrh     }
1010626a879aSdrh     case TK_CTIME: {
1011626a879aSdrh       *pzName = "current_time";
1012626a879aSdrh       *pnName = 12;
1013626a879aSdrh       break;
1014626a879aSdrh     }
1015626a879aSdrh     case TK_CDATE: {
1016626a879aSdrh       *pzName = "current_date";
1017626a879aSdrh       *pnName = 12;
1018626a879aSdrh       break;
1019626a879aSdrh     }
1020626a879aSdrh     case TK_CTIMESTAMP: {
1021626a879aSdrh       *pzName = "current_timestamp";
1022626a879aSdrh       *pnName = 17;
1023626a879aSdrh       break;
1024626a879aSdrh     }
1025626a879aSdrh   }
1026626a879aSdrh }
1027626a879aSdrh 
1028626a879aSdrh /*
1029626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1030626a879aSdrh **
103173b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1032626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
103373b211abSdrh ** the tree or 2 to abort the tree walk.
103473b211abSdrh **
103573b211abSdrh ** This routine also does error checking and name resolution for
103673b211abSdrh ** function names.  The operator for aggregate functions is changed
103773b211abSdrh ** to TK_AGG_FUNCTION.
1038626a879aSdrh */
1039626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1040626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1041626a879aSdrh   SrcList *pSrcList;
1042626a879aSdrh   Parse *pParse;
1043626a879aSdrh 
1044b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1045626a879aSdrh   assert( pNC!=0 );
1046626a879aSdrh   pSrcList = pNC->pSrcList;
1047626a879aSdrh   pParse = pNC->pParse;
1048b3bce662Sdanielk1977 
1049626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1050626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1051626a879aSdrh #ifndef NDEBUG
1052626a879aSdrh   if( pSrcList ){
1053940fac9dSdanielk1977     int i;
1054626a879aSdrh     for(i=0; i<pSrcList->nSrc; i++){
1055626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1056626a879aSdrh     }
1057626a879aSdrh   }
1058626a879aSdrh #endif
1059626a879aSdrh   switch( pExpr->op ){
1060626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1061626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1062626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1063626a879aSdrh     */
1064626a879aSdrh     case TK_STRING: {
1065626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1066626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1067626a879aSdrh     }
1068626a879aSdrh     /* A lone identifier is the name of a column.
1069626a879aSdrh     */
1070626a879aSdrh     case TK_ID: {
1071626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1072626a879aSdrh       return 1;
1073626a879aSdrh     }
1074626a879aSdrh 
1075626a879aSdrh     /* A table name and column name:     ID.ID
1076626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1077626a879aSdrh     */
1078626a879aSdrh     case TK_DOT: {
1079626a879aSdrh       Token *pColumn;
1080626a879aSdrh       Token *pTable;
1081626a879aSdrh       Token *pDb;
1082626a879aSdrh       Expr *pRight;
1083626a879aSdrh 
1084b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1085626a879aSdrh       pRight = pExpr->pRight;
1086626a879aSdrh       if( pRight->op==TK_ID ){
1087626a879aSdrh         pDb = 0;
1088626a879aSdrh         pTable = &pExpr->pLeft->token;
1089626a879aSdrh         pColumn = &pRight->token;
1090626a879aSdrh       }else{
1091626a879aSdrh         assert( pRight->op==TK_DOT );
1092626a879aSdrh         pDb = &pExpr->pLeft->token;
1093626a879aSdrh         pTable = &pRight->pLeft->token;
1094626a879aSdrh         pColumn = &pRight->pRight->token;
1095626a879aSdrh       }
1096626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1097626a879aSdrh       return 1;
1098626a879aSdrh     }
1099626a879aSdrh 
1100626a879aSdrh     /* Resolve function names
1101626a879aSdrh     */
1102626a879aSdrh     case TK_CTIME:
1103626a879aSdrh     case TK_CTIMESTAMP:
1104626a879aSdrh     case TK_CDATE:
1105626a879aSdrh     case TK_GLOB:
1106626a879aSdrh     case TK_LIKE:
1107626a879aSdrh     case TK_FUNCTION: {
1108626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1109626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1110626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1111626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1112626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1113626a879aSdrh       int i;
1114626a879aSdrh       int nId;                    /* Number of characters in function name */
1115626a879aSdrh       const char *zId;            /* The function name. */
111673b211abSdrh       FuncDef *pDef;              /* Information about the function */
111773b211abSdrh       int enc = pParse->db->enc;  /* The database encoding */
1118626a879aSdrh 
1119626a879aSdrh       getFunctionName(pExpr, &zId, &nId);
1120626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1121626a879aSdrh       if( pDef==0 ){
1122626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1123626a879aSdrh         if( pDef==0 ){
1124626a879aSdrh           no_such_func = 1;
1125626a879aSdrh         }else{
1126626a879aSdrh           wrong_num_args = 1;
1127626a879aSdrh         }
1128626a879aSdrh       }else{
1129626a879aSdrh         is_agg = pDef->xFunc==0;
1130626a879aSdrh       }
1131626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1132626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1133626a879aSdrh         pNC->nErr++;
1134626a879aSdrh         is_agg = 0;
1135626a879aSdrh       }else if( no_such_func ){
1136626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1137626a879aSdrh         pNC->nErr++;
1138626a879aSdrh       }else if( wrong_num_args ){
1139626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1140626a879aSdrh              nId, zId);
1141626a879aSdrh         pNC->nErr++;
1142626a879aSdrh       }
1143626a879aSdrh       if( is_agg ){
1144626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1145626a879aSdrh         pNC->hasAgg = 1;
1146626a879aSdrh       }
114773b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1148626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
114973b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1150626a879aSdrh       }
115173b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1152626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1153626a879aSdrh       ** type of the function
1154626a879aSdrh       */
1155626a879aSdrh       return is_agg;
1156626a879aSdrh     }
1157b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1158b3bce662Sdanielk1977     case TK_SELECT:
1159b3bce662Sdanielk1977     case TK_EXISTS:
1160b3bce662Sdanielk1977 #endif
1161b3bce662Sdanielk1977     case TK_IN: {
1162b3bce662Sdanielk1977       if( pExpr->pSelect ){
1163b3bce662Sdanielk1977         int nRef = pNC->nRef;
1164b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1165b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1166b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1167b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1168b3bce662Sdanielk1977         }
1169b3bce662Sdanielk1977       }
1170b3bce662Sdanielk1977     }
1171626a879aSdrh   }
1172626a879aSdrh   return 0;
1173626a879aSdrh }
1174626a879aSdrh 
1175626a879aSdrh /*
1176cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1177967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1178aacc543eSdrh ** index to the table in the table list and a column offset.  The
1179aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1180aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1181832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1182aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1183aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1184aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1185aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1186aacc543eSdrh ** alias for ROWID.
118719a775c2Sdrh **
1188626a879aSdrh ** Also resolve function names and check the functions for proper
1189626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1190626a879aSdrh ** have the correct number of arguments.  Leave an error message
1191626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1192626a879aSdrh **
119373b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
119473b211abSdrh ** property on the expression.
1195626a879aSdrh */
1196626a879aSdrh int sqlite3ExprResolveNames(
1197b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1198b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1199626a879aSdrh ){
120073b211abSdrh   if( pExpr==0 ) return 0;
1201b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1202b3bce662Sdanielk1977   if( pNC->nErr>0 ){
120373b211abSdrh     ExprSetProperty(pExpr, EP_Error);
120473b211abSdrh   }
120573b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1206626a879aSdrh }
1207626a879aSdrh 
12081398ad36Sdrh /*
12091398ad36Sdrh ** A pointer instance of this structure is used to pass information
12101398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
12111398ad36Sdrh */
12121398ad36Sdrh typedef struct QueryCoder QueryCoder;
12131398ad36Sdrh struct QueryCoder {
12141398ad36Sdrh   Parse *pParse;       /* The parsing context */
12151398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
12161398ad36Sdrh };
12171398ad36Sdrh 
1218626a879aSdrh 
1219626a879aSdrh /*
1220626a879aSdrh ** Generate code for subqueries and IN operators.
1221626a879aSdrh **
122273b211abSdrh ** IN operators comes in two forms:
1223fef5208cSdrh **
1224fef5208cSdrh **           expr IN (exprlist)
1225fef5208cSdrh ** and
1226fef5208cSdrh **           expr IN (SELECT ...)
1227fef5208cSdrh **
1228fef5208cSdrh ** The first form is handled by creating a set holding the list
1229fef5208cSdrh ** of allowed values.  The second form causes the SELECT to generate
1230fef5208cSdrh ** a temporary table.
1231cce7d176Sdrh */
123251522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1233b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
1234b3bce662Sdanielk1977   int label = 0;                         /* Address after sub-select code */
1235b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1236b3bce662Sdanielk1977   if( v==0 ) return;
1237b3bce662Sdanielk1977 
1238b3bce662Sdanielk1977   /* If this is not a variable (correlated) select, then execute
1239b3bce662Sdanielk1977   ** it only once. Unless this is part of a trigger program. In
1240b3bce662Sdanielk1977   ** that case re-execute every time (this could be optimized).
1241b3bce662Sdanielk1977   */
1242b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1243b3bce662Sdanielk1977     int mem = pParse->nMem++;
1244b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
1245b3bce662Sdanielk1977     label = sqlite3VdbeMakeLabel(v);
1246b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_If, 0, label);
1247b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1248b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, mem, 1);
1249b3bce662Sdanielk1977   }
1250b3bce662Sdanielk1977 
1251b3bce662Sdanielk1977   if( pExpr->pSelect ){
1252b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_AggContextPush, 0, 0);
1253b3bce662Sdanielk1977   }
12546a3ea0e6Sdrh 
1255cce7d176Sdrh   switch( pExpr->op ){
1256fef5208cSdrh     case TK_IN: {
1257e014a838Sdanielk1977       char affinity;
1258d3d39e93Sdrh       KeyInfo keyInfo;
12590202b29eSdanielk1977       int addr;        /* Address of OP_OpenTemp instruction */
1260d3d39e93Sdrh 
1261bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1262e014a838Sdanielk1977 
1263e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1264e014a838Sdanielk1977       ** expression it is handled the same way. A temporary table is
1265e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1266e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1267fef5208cSdrh       **
1268e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1269e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1270e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1271e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1272e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1273e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1274e014a838Sdanielk1977       ** is used.
1275fef5208cSdrh       */
1276832508b7Sdrh       pExpr->iTable = pParse->nTab++;
12770202b29eSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, pExpr->iTable, 0);
1278d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1279d3d39e93Sdrh       keyInfo.nField = 1;
1280f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1281e014a838Sdanielk1977 
1282e014a838Sdanielk1977       if( pExpr->pSelect ){
1283e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1284e014a838Sdanielk1977         **
1285e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1286e014a838Sdanielk1977         ** table allocated and opened above.
1287e014a838Sdanielk1977         */
1288e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1289be5c89acSdrh         ExprList *pEList;
1290e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1291b3bce662Sdanielk1977         sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
1292be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1293be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
12947cedc8d4Sdanielk1977           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
1295be5c89acSdrh               pEList->a[0].pExpr);
12960202b29eSdanielk1977         }
1297fef5208cSdrh       }else if( pExpr->pList ){
1298fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1299fef5208cSdrh         **
1300e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
1301e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1302e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1303e014a838Sdanielk1977         ** a column, use numeric affinity.
1304fef5208cSdrh         */
1305e014a838Sdanielk1977         int i;
1306e014a838Sdanielk1977         if( !affinity ){
1307e014a838Sdanielk1977           affinity = SQLITE_AFF_NUMERIC;
1308e014a838Sdanielk1977         }
13090202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1310e014a838Sdanielk1977 
1311e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
1312fef5208cSdrh         for(i=0; i<pExpr->pList->nExpr; i++){
1313fef5208cSdrh           Expr *pE2 = pExpr->pList->a[i].pExpr;
1314e014a838Sdanielk1977 
1315e014a838Sdanielk1977           /* Check that the expression is constant and valid. */
13164adee20fSdanielk1977           if( !sqlite3ExprIsConstant(pE2) ){
13174adee20fSdanielk1977             sqlite3ErrorMsg(pParse,
1318da93d238Sdrh               "right-hand side of IN operator must be constant");
1319b3bce662Sdanielk1977             return;
13204794b980Sdrh           }
1321e014a838Sdanielk1977 
1322e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
13234adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
132494a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
13250f69c1e3Sdanielk1977           sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1326e014a838Sdanielk1977           sqlite3VdbeAddOp(v, OP_PutStrKey, pExpr->iTable, 0);
1327fef5208cSdrh         }
1328fef5208cSdrh       }
13290202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1330b3bce662Sdanielk1977       break;
1331fef5208cSdrh     }
1332fef5208cSdrh 
133351522cd3Sdrh     case TK_EXISTS:
133419a775c2Sdrh     case TK_SELECT: {
1335fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1336fef5208cSdrh       ** value of this select in a memory cell and record the number
1337967e8b73Sdrh       ** of the memory cell in iColumn.
1338fef5208cSdrh       */
133951522cd3Sdrh       int sop;
134051522cd3Sdrh       Select *pSel;
13411398ad36Sdrh 
1342967e8b73Sdrh       pExpr->iColumn = pParse->nMem++;
134351522cd3Sdrh       pSel = pExpr->pSelect;
134451522cd3Sdrh       if( pExpr->op==TK_SELECT ){
134551522cd3Sdrh         sop = SRT_Mem;
134651522cd3Sdrh       }else{
134751522cd3Sdrh         static const Token one = { "1", 0, 1 };
134851522cd3Sdrh         sop = SRT_Exists;
134951522cd3Sdrh         sqlite3ExprListDelete(pSel->pEList);
135051522cd3Sdrh         pSel->pEList = sqlite3ExprListAppend(0,
135151522cd3Sdrh                           sqlite3Expr(TK_INTEGER, 0, 0, &one), 0);
135251522cd3Sdrh       }
1353b3bce662Sdanielk1977       sqlite3Select(pParse, pSel, sop, pExpr->iColumn, 0, 0, 0, 0);
1354b3bce662Sdanielk1977       break;
135519a775c2Sdrh     }
1356cce7d176Sdrh   }
1357b3bce662Sdanielk1977 
1358b3bce662Sdanielk1977   if( pExpr->pSelect ){
1359b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_AggContextPop, 0, 0);
1360b3bce662Sdanielk1977   }
1361b3bce662Sdanielk1977   if( label<0 ){
1362b3bce662Sdanielk1977     sqlite3VdbeResolveLabel(v, label);
1363b3bce662Sdanielk1977   }
1364b3bce662Sdanielk1977   return;
1365cce7d176Sdrh }
136651522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1367cce7d176Sdrh 
1368cce7d176Sdrh /*
1369fec19aadSdrh ** Generate an instruction that will put the integer describe by
1370fec19aadSdrh ** text z[0..n-1] on the stack.
1371fec19aadSdrh */
1372fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1373fec19aadSdrh   int i;
13746fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
13756fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
13766fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
13776fec0762Sdrh     sqlite3VdbeOp3(v, OP_Integer, 0, 0, z, n);
1378fec19aadSdrh   }else{
1379fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1380fec19aadSdrh   }
1381fec19aadSdrh }
1382fec19aadSdrh 
1383fec19aadSdrh /*
1384cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
13851ccde15dSdrh ** expression and leave the result on the top of stack.
1386f2bc013cSdrh **
1387f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1388f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1389f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1390f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1391f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1392cce7d176Sdrh */
13934adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1394cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1395cce7d176Sdrh   int op;
13967977a17fSdanielk1977   if( v==0 ) return;
13977977a17fSdanielk1977   if( pExpr==0 ){
13987977a17fSdanielk1977     sqlite3VdbeAddOp(v, OP_String8, 0, 0);  /* Empty expression evals to NULL */
13997977a17fSdanielk1977     return;
14007977a17fSdanielk1977   }
1401f2bc013cSdrh   op = pExpr->op;
1402f2bc013cSdrh   switch( op ){
1403967e8b73Sdrh     case TK_COLUMN: {
1404a58fdfb1Sdanielk1977       if( !pParse->fillAgg && pExpr->iAgg>=0 ){
1405a58fdfb1Sdanielk1977         sqlite3VdbeAddOp(v, OP_AggGet, pExpr->iAggCtx, pExpr->iAgg);
1406c4a3c779Sdrh       }else if( pExpr->iColumn>=0 ){
14074adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
1408aee18ef8Sdanielk1977         sqlite3ColumnDefault(v, pExpr->pTab, pExpr->iColumn);
1409c4a3c779Sdrh       }else{
14104adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Recno, pExpr->iTable, 0);
14112282792aSdrh       }
1412cce7d176Sdrh       break;
1413cce7d176Sdrh     }
1414cce7d176Sdrh     case TK_INTEGER: {
1415fec19aadSdrh       codeInteger(v, pExpr->token.z, pExpr->token.n);
1416fec19aadSdrh       break;
141751e9a445Sdrh     }
1418fec19aadSdrh     case TK_FLOAT:
1419fec19aadSdrh     case TK_STRING: {
1420f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1421f2bc013cSdrh       assert( TK_STRING==OP_String8 );
1422fec19aadSdrh       sqlite3VdbeOp3(v, op, 0, 0, pExpr->token.z, pExpr->token.n);
14234adee20fSdanielk1977       sqlite3VdbeDequoteP3(v, -1);
1424cce7d176Sdrh       break;
1425cce7d176Sdrh     }
14265338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1427c572ef7fSdanielk1977     case TK_BLOB: {
1428f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
1429c572ef7fSdanielk1977       sqlite3VdbeOp3(v, op, 0, 0, pExpr->token.z+1, pExpr->token.n-1);
1430c572ef7fSdanielk1977       sqlite3VdbeDequoteP3(v, -1);
1431c572ef7fSdanielk1977       break;
1432c572ef7fSdanielk1977     }
14335338a5f7Sdanielk1977 #endif
1434cce7d176Sdrh     case TK_NULL: {
14350f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1436cce7d176Sdrh       break;
1437cce7d176Sdrh     }
143850457896Sdrh     case TK_VARIABLE: {
14394adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1440895d7472Sdrh       if( pExpr->token.n>1 ){
1441895d7472Sdrh         sqlite3VdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
1442895d7472Sdrh       }
144350457896Sdrh       break;
144450457896Sdrh     }
14454e0cff60Sdrh     case TK_REGISTER: {
14464e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
14474e0cff60Sdrh       break;
14484e0cff60Sdrh     }
1449c9b84a1fSdrh     case TK_LT:
1450c9b84a1fSdrh     case TK_LE:
1451c9b84a1fSdrh     case TK_GT:
1452c9b84a1fSdrh     case TK_GE:
1453c9b84a1fSdrh     case TK_NE:
1454c9b84a1fSdrh     case TK_EQ: {
1455f2bc013cSdrh       assert( TK_LT==OP_Lt );
1456f2bc013cSdrh       assert( TK_LE==OP_Le );
1457f2bc013cSdrh       assert( TK_GT==OP_Gt );
1458f2bc013cSdrh       assert( TK_GE==OP_Ge );
1459f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1460f2bc013cSdrh       assert( TK_NE==OP_Ne );
1461a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1462a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1463be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1464a37cdde0Sdanielk1977       break;
1465c9b84a1fSdrh     }
1466cce7d176Sdrh     case TK_AND:
1467cce7d176Sdrh     case TK_OR:
1468cce7d176Sdrh     case TK_PLUS:
1469cce7d176Sdrh     case TK_STAR:
1470cce7d176Sdrh     case TK_MINUS:
1471bf4133cbSdrh     case TK_REM:
1472bf4133cbSdrh     case TK_BITAND:
1473bf4133cbSdrh     case TK_BITOR:
147417c40294Sdrh     case TK_SLASH:
1475bf4133cbSdrh     case TK_LSHIFT:
1476855eb1cfSdrh     case TK_RSHIFT:
14770040077dSdrh     case TK_CONCAT: {
1478f2bc013cSdrh       assert( TK_AND==OP_And );
1479f2bc013cSdrh       assert( TK_OR==OP_Or );
1480f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1481f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1482f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1483f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1484f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1485f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1486f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1487f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1488f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
14894adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
14904adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1491855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
14920040077dSdrh       break;
14930040077dSdrh     }
1494cce7d176Sdrh     case TK_UMINUS: {
1495fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1496fec19aadSdrh       assert( pLeft );
1497fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1498fec19aadSdrh         Token *p = &pLeft->token;
14996e142f54Sdrh         char *z = sqliteMalloc( p->n + 2 );
15006e142f54Sdrh         sprintf(z, "-%.*s", p->n, p->z);
1501fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1502fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1503e6840900Sdrh         }else{
1504fec19aadSdrh           codeInteger(v, z, p->n+1);
1505e6840900Sdrh         }
15066e142f54Sdrh         sqliteFree(z);
15076e142f54Sdrh         break;
15086e142f54Sdrh       }
15091ccde15dSdrh       /* Fall through into TK_NOT */
15106e142f54Sdrh     }
1511bf4133cbSdrh     case TK_BITNOT:
15126e142f54Sdrh     case TK_NOT: {
1513f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1514f2bc013cSdrh       assert( TK_NOT==OP_Not );
15154adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
15164adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1517cce7d176Sdrh       break;
1518cce7d176Sdrh     }
1519cce7d176Sdrh     case TK_ISNULL:
1520cce7d176Sdrh     case TK_NOTNULL: {
1521cce7d176Sdrh       int dest;
1522f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1523f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
15244adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
15254adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
15264adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
15274adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
15284adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1529a37cdde0Sdanielk1977       break;
1530f2bc013cSdrh     }
15312282792aSdrh     case TK_AGG_FUNCTION: {
15324adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
15332282792aSdrh       break;
15342282792aSdrh     }
15357977a17fSdanielk1977     case TK_CDATE:
15367977a17fSdanielk1977     case TK_CTIME:
15377977a17fSdanielk1977     case TK_CTIMESTAMP:
15384b59ab5eSdrh     case TK_GLOB:
15394b59ab5eSdrh     case TK_LIKE:
1540cce7d176Sdrh     case TK_FUNCTION: {
1541cce7d176Sdrh       ExprList *pList = pExpr->pList;
154289425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
15430bce8354Sdrh       FuncDef *pDef;
15444b59ab5eSdrh       int nId;
15454b59ab5eSdrh       const char *zId;
1546682f68b0Sdanielk1977       int p2 = 0;
1547682f68b0Sdanielk1977       int i;
1548d8123366Sdanielk1977       u8 enc = pParse->db->enc;
1549dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
15504b59ab5eSdrh       getFunctionName(pExpr, &zId, &nId);
1551d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
15520bce8354Sdrh       assert( pDef!=0 );
1553f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1554682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1555d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
1556d02eb1fdSdanielk1977           p2 |= (1<<i);
1557d02eb1fdSdanielk1977         }
1558dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1559dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1560dc1bdc4fSdanielk1977         }
1561dc1bdc4fSdanielk1977       }
1562dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1563dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1564d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1565682f68b0Sdanielk1977       }
1566682f68b0Sdanielk1977       sqlite3VdbeOp3(v, OP_Function, nExpr, p2, (char*)pDef, P3_FUNCDEF);
15676ec2733bSdrh       break;
15686ec2733bSdrh     }
1569fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1570fe2093d7Sdrh     case TK_EXISTS:
157119a775c2Sdrh     case TK_SELECT: {
1572b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
15734adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1574ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
157519a775c2Sdrh       break;
157619a775c2Sdrh     }
1577fef5208cSdrh     case TK_IN: {
1578fef5208cSdrh       int addr;
157994a11211Sdrh       char affinity;
1580b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
1581e014a838Sdanielk1977 
1582e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1583e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1584ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1585e014a838Sdanielk1977       */
158694a11211Sdrh       affinity = comparisonAffinity(pExpr);
1587e014a838Sdanielk1977 
15884adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1589e014a838Sdanielk1977 
1590e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1591e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1592e014a838Sdanielk1977       */
15934adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
15944adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1595e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
15964adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
15970f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1598e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
159994a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
1600e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1601e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1602e014a838Sdanielk1977 
1603fef5208cSdrh       break;
1604fef5208cSdrh     }
160593758c8dSdanielk1977 #endif
1606fef5208cSdrh     case TK_BETWEEN: {
1607be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1608be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1609be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1610be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
16114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1612be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1613be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
16144adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1615be5c89acSdrh       pLItem++;
1616be5c89acSdrh       pRight = pLItem->pExpr;
1617be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1618be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
16194adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1620fef5208cSdrh       break;
1621fef5208cSdrh     }
162251e9a445Sdrh     case TK_UPLUS:
1623a2e00042Sdrh     case TK_AS: {
16244adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1625a2e00042Sdrh       break;
1626a2e00042Sdrh     }
162717a7f8ddSdrh     case TK_CASE: {
162817a7f8ddSdrh       int expr_end_label;
1629f5905aa7Sdrh       int jumpInst;
1630f5905aa7Sdrh       int addr;
1631f5905aa7Sdrh       int nExpr;
163217a7f8ddSdrh       int i;
1633be5c89acSdrh       ExprList *pEList;
1634be5c89acSdrh       struct ExprList_item *aListelem;
163517a7f8ddSdrh 
163617a7f8ddSdrh       assert(pExpr->pList);
163717a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
163817a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1639be5c89acSdrh       pEList = pExpr->pList;
1640be5c89acSdrh       aListelem = pEList->a;
1641be5c89acSdrh       nExpr = pEList->nExpr;
16424adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
164317a7f8ddSdrh       if( pExpr->pLeft ){
16444adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1645cce7d176Sdrh       }
1646f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1647be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
164817a7f8ddSdrh         if( pExpr->pLeft ){
16494adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1650be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1651be5c89acSdrh                                  OP_Ne, 0, 1);
16524adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1653f5905aa7Sdrh         }else{
16544adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
165517a7f8ddSdrh         }
1656be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
16574adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
16584adee20fSdanielk1977         addr = sqlite3VdbeCurrentAddr(v);
16594adee20fSdanielk1977         sqlite3VdbeChangeP2(v, jumpInst, addr);
166017a7f8ddSdrh       }
1661f570f011Sdrh       if( pExpr->pLeft ){
16624adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1663f570f011Sdrh       }
166417a7f8ddSdrh       if( pExpr->pRight ){
16654adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
166617a7f8ddSdrh       }else{
16670f69c1e3Sdanielk1977         sqlite3VdbeAddOp(v, OP_String8, 0, 0);
166817a7f8ddSdrh       }
16694adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
16706f34903eSdanielk1977       break;
16716f34903eSdanielk1977     }
16725338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
16736f34903eSdanielk1977     case TK_RAISE: {
16746f34903eSdanielk1977       if( !pParse->trigStack ){
16754adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1676da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
16776f34903eSdanielk1977 	return;
16786f34903eSdanielk1977       }
1679ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
1680ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
16816f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
1682ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
16834adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
1684701a0aebSdrh                         pExpr->token.z, pExpr->token.n);
16854adee20fSdanielk1977          sqlite3VdbeDequoteP3(v, -1);
16866f34903eSdanielk1977       } else {
16876f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
1688344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
1689ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
1690ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
16916f34903eSdanielk1977       }
169217a7f8ddSdrh     }
16935338a5f7Sdanielk1977 #endif
169417a7f8ddSdrh     break;
169517a7f8ddSdrh   }
1696cce7d176Sdrh }
1697cce7d176Sdrh 
169893758c8dSdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
1699cce7d176Sdrh /*
170025303780Sdrh ** Generate code that evalutes the given expression and leaves the result
170125303780Sdrh ** on the stack.  See also sqlite3ExprCode().
170225303780Sdrh **
170325303780Sdrh ** This routine might also cache the result and modify the pExpr tree
170425303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
170525303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
170625303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
170725303780Sdrh ** memory location.
170825303780Sdrh */
170925303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
171025303780Sdrh   Vdbe *v = pParse->pVdbe;
171125303780Sdrh   int iMem;
171225303780Sdrh   int addr1, addr2;
171325303780Sdrh   if( v==0 ) return;
171425303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
171525303780Sdrh   sqlite3ExprCode(pParse, pExpr);
171625303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
171725303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
171825303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
171925303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
172025303780Sdrh     pExpr->op = TK_REGISTER;
172125303780Sdrh   }
172225303780Sdrh }
172393758c8dSdanielk1977 #endif
172425303780Sdrh 
172525303780Sdrh /*
1726268380caSdrh ** Generate code that pushes the value of every element of the given
1727f9b596ebSdrh ** expression list onto the stack.
1728268380caSdrh **
1729268380caSdrh ** Return the number of elements pushed onto the stack.
1730268380caSdrh */
17314adee20fSdanielk1977 int sqlite3ExprCodeExprList(
1732268380caSdrh   Parse *pParse,     /* Parsing context */
1733f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
1734268380caSdrh ){
1735268380caSdrh   struct ExprList_item *pItem;
1736268380caSdrh   int i, n;
1737268380caSdrh   Vdbe *v;
1738268380caSdrh   if( pList==0 ) return 0;
17394adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1740268380caSdrh   n = pList->nExpr;
1741268380caSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
17424adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
1743268380caSdrh   }
1744f9b596ebSdrh   return n;
1745268380caSdrh }
1746268380caSdrh 
1747268380caSdrh /*
1748cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
1749cce7d176Sdrh ** to the label "dest" if the expression is true but execution
1750cce7d176Sdrh ** continues straight thru if the expression is false.
1751f5905aa7Sdrh **
1752f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
1753f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
1754f2bc013cSdrh **
1755f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1756f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1757f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1758f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1759f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1760cce7d176Sdrh */
17614adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1762cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1763cce7d176Sdrh   int op = 0;
1764daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1765f2bc013cSdrh   op = pExpr->op;
1766f2bc013cSdrh   switch( op ){
1767cce7d176Sdrh     case TK_AND: {
17684adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
17694adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
17704adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
17714adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1772cce7d176Sdrh       break;
1773cce7d176Sdrh     }
1774cce7d176Sdrh     case TK_OR: {
17754adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
17764adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1777cce7d176Sdrh       break;
1778cce7d176Sdrh     }
1779cce7d176Sdrh     case TK_NOT: {
17804adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1781cce7d176Sdrh       break;
1782cce7d176Sdrh     }
1783cce7d176Sdrh     case TK_LT:
1784cce7d176Sdrh     case TK_LE:
1785cce7d176Sdrh     case TK_GT:
1786cce7d176Sdrh     case TK_GE:
1787cce7d176Sdrh     case TK_NE:
17880ac65892Sdrh     case TK_EQ: {
1789f2bc013cSdrh       assert( TK_LT==OP_Lt );
1790f2bc013cSdrh       assert( TK_LE==OP_Le );
1791f2bc013cSdrh       assert( TK_GT==OP_Gt );
1792f2bc013cSdrh       assert( TK_GE==OP_Ge );
1793f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1794f2bc013cSdrh       assert( TK_NE==OP_Ne );
17954adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17964adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1797be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
1798cce7d176Sdrh       break;
1799cce7d176Sdrh     }
1800cce7d176Sdrh     case TK_ISNULL:
1801cce7d176Sdrh     case TK_NOTNULL: {
1802f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1803f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
18044adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
18054adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
1806cce7d176Sdrh       break;
1807cce7d176Sdrh     }
1808fef5208cSdrh     case TK_BETWEEN: {
18090202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
18100202b29eSdanielk1977       **
18110202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
18120202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
18130202b29eSdanielk1977       ** 3 ...
18140202b29eSdanielk1977       */
1815f5905aa7Sdrh       int addr;
1816be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1817be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
1818be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
18194adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1820be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1821be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
18220202b29eSdanielk1977 
1823be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
1824be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1825be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
18260202b29eSdanielk1977 
18274adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
18284adee20fSdanielk1977       sqlite3VdbeChangeP2(v, addr, sqlite3VdbeCurrentAddr(v));
18294adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1830fef5208cSdrh       break;
1831fef5208cSdrh     }
1832cce7d176Sdrh     default: {
18334adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
18344adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
1835cce7d176Sdrh       break;
1836cce7d176Sdrh     }
1837cce7d176Sdrh   }
1838cce7d176Sdrh }
1839cce7d176Sdrh 
1840cce7d176Sdrh /*
184166b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
1842cce7d176Sdrh ** to the label "dest" if the expression is false but execution
1843cce7d176Sdrh ** continues straight thru if the expression is true.
1844f5905aa7Sdrh **
1845f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
1846f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
1847cce7d176Sdrh */
18484adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1849cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1850cce7d176Sdrh   int op = 0;
1851daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1852f2bc013cSdrh 
1853f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
1854f2bc013cSdrh   **
1855f2bc013cSdrh   **       pExpr->op            op
1856f2bc013cSdrh   **       ---------          ----------
1857f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
1858f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
1859f2bc013cSdrh   **       TK_NE              OP_Eq
1860f2bc013cSdrh   **       TK_EQ              OP_Ne
1861f2bc013cSdrh   **       TK_GT              OP_Le
1862f2bc013cSdrh   **       TK_LE              OP_Gt
1863f2bc013cSdrh   **       TK_GE              OP_Lt
1864f2bc013cSdrh   **       TK_LT              OP_Ge
1865f2bc013cSdrh   **
1866f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
1867f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
1868f2bc013cSdrh   ** can compute the mapping above using the following expression.
1869f2bc013cSdrh   ** Assert()s verify that the computation is correct.
1870f2bc013cSdrh   */
1871f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
1872f2bc013cSdrh 
1873f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
1874f2bc013cSdrh   */
1875f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
1876f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
1877f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
1878f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
1879f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
1880f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
1881f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
1882f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
1883f2bc013cSdrh 
1884cce7d176Sdrh   switch( pExpr->op ){
1885cce7d176Sdrh     case TK_AND: {
18864adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
18874adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
1888cce7d176Sdrh       break;
1889cce7d176Sdrh     }
1890cce7d176Sdrh     case TK_OR: {
18914adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
18924adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
18934adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
18944adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1895cce7d176Sdrh       break;
1896cce7d176Sdrh     }
1897cce7d176Sdrh     case TK_NOT: {
18984adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
1899cce7d176Sdrh       break;
1900cce7d176Sdrh     }
1901cce7d176Sdrh     case TK_LT:
1902cce7d176Sdrh     case TK_LE:
1903cce7d176Sdrh     case TK_GT:
1904cce7d176Sdrh     case TK_GE:
1905cce7d176Sdrh     case TK_NE:
1906cce7d176Sdrh     case TK_EQ: {
19074adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19084adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1909be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
1910cce7d176Sdrh       break;
1911cce7d176Sdrh     }
1912cce7d176Sdrh     case TK_ISNULL:
1913cce7d176Sdrh     case TK_NOTNULL: {
19144adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19154adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
1916cce7d176Sdrh       break;
1917cce7d176Sdrh     }
1918fef5208cSdrh     case TK_BETWEEN: {
19190202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
19200202b29eSdanielk1977       **
19210202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
19220202b29eSdanielk1977       ** 2 GOTO <dest>
19230202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
19240202b29eSdanielk1977       */
1925fef5208cSdrh       int addr;
1926be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1927be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
1928be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
19294adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1930be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
19314adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1932be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
1933be5c89acSdrh 
19344adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
19354adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
1936be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
1937be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1938be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
1939fef5208cSdrh       break;
1940fef5208cSdrh     }
1941cce7d176Sdrh     default: {
19424adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
19434adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
1944cce7d176Sdrh       break;
1945cce7d176Sdrh     }
1946cce7d176Sdrh   }
1947cce7d176Sdrh }
19482282792aSdrh 
19492282792aSdrh /*
19502282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
19512282792aSdrh ** if they are identical and return FALSE if they differ in any way.
19522282792aSdrh */
19534adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
19542282792aSdrh   int i;
19552282792aSdrh   if( pA==0 ){
19562282792aSdrh     return pB==0;
19572282792aSdrh   }else if( pB==0 ){
19582282792aSdrh     return 0;
19592282792aSdrh   }
19602282792aSdrh   if( pA->op!=pB->op ) return 0;
19614adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
19624adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
19632282792aSdrh   if( pA->pList ){
19642282792aSdrh     if( pB->pList==0 ) return 0;
19652282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
19662282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
19674adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
19682282792aSdrh         return 0;
19692282792aSdrh       }
19702282792aSdrh     }
19712282792aSdrh   }else if( pB->pList ){
19722282792aSdrh     return 0;
19732282792aSdrh   }
19742282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
19752f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
19762282792aSdrh   if( pA->token.z ){
19772282792aSdrh     if( pB->token.z==0 ) return 0;
19786977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
19794adee20fSdanielk1977     if( sqlite3StrNICmp(pA->token.z, pB->token.z, pB->token.n)!=0 ) return 0;
19802282792aSdrh   }
19812282792aSdrh   return 1;
19822282792aSdrh }
19832282792aSdrh 
19842282792aSdrh /*
19852282792aSdrh ** Add a new element to the pParse->aAgg[] array and return its index.
198673b211abSdrh ** The new element is initialized to zero.  The calling function is
198773b211abSdrh ** expected to fill it in.
19882282792aSdrh */
19892282792aSdrh static int appendAggInfo(Parse *pParse){
19902282792aSdrh   if( (pParse->nAgg & 0x7)==0 ){
19912282792aSdrh     int amt = pParse->nAgg + 8;
19926d4abfbeSdrh     AggExpr *aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
19936d4abfbeSdrh     if( aAgg==0 ){
19942282792aSdrh       return -1;
19952282792aSdrh     }
19966d4abfbeSdrh     pParse->aAgg = aAgg;
19972282792aSdrh   }
19982282792aSdrh   memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
19992282792aSdrh   return pParse->nAgg++;
20002282792aSdrh }
20012282792aSdrh 
20022282792aSdrh /*
2003626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
2004626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2005626a879aSdrh ** for additional information.
20062282792aSdrh **
2007626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
20082282792aSdrh */
2009626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
20102282792aSdrh   int i;
20112282792aSdrh   AggExpr *aAgg;
2012a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
2013a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
2014a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
20152282792aSdrh 
20162282792aSdrh   switch( pExpr->op ){
2017967e8b73Sdrh     case TK_COLUMN: {
2018a58fdfb1Sdanielk1977       for(i=0; pSrcList && i<pSrcList->nSrc; i++){
2019a58fdfb1Sdanielk1977         if( pExpr->iTable==pSrcList->a[i].iCursor ){
20202282792aSdrh           aAgg = pParse->aAgg;
20212282792aSdrh           for(i=0; i<pParse->nAgg; i++){
20222282792aSdrh             if( aAgg[i].isAgg ) continue;
20232282792aSdrh             if( aAgg[i].pExpr->iTable==pExpr->iTable
2024967e8b73Sdrh              && aAgg[i].pExpr->iColumn==pExpr->iColumn ){
20252282792aSdrh               break;
20262282792aSdrh             }
20272282792aSdrh           }
20282282792aSdrh           if( i>=pParse->nAgg ){
20292282792aSdrh             i = appendAggInfo(pParse);
20302282792aSdrh             if( i<0 ) return 1;
20312282792aSdrh             pParse->aAgg[i].isAgg = 0;
20322282792aSdrh             pParse->aAgg[i].pExpr = pExpr;
20332282792aSdrh           }
2034aaf88729Sdrh           pExpr->iAgg = i;
2035a58fdfb1Sdanielk1977           pExpr->iAggCtx = pNC->nDepth;
2036a58fdfb1Sdanielk1977           return 1;
2037a58fdfb1Sdanielk1977         }
2038a58fdfb1Sdanielk1977       }
2039626a879aSdrh       return 1;
20402282792aSdrh     }
20412282792aSdrh     case TK_AGG_FUNCTION: {
2042a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
20432282792aSdrh         aAgg = pParse->aAgg;
20442282792aSdrh         for(i=0; i<pParse->nAgg; i++){
20452282792aSdrh           if( !aAgg[i].isAgg ) continue;
20464adee20fSdanielk1977           if( sqlite3ExprCompare(aAgg[i].pExpr, pExpr) ){
20472282792aSdrh             break;
20482282792aSdrh           }
20492282792aSdrh         }
20502282792aSdrh         if( i>=pParse->nAgg ){
2051d8123366Sdanielk1977           u8 enc = pParse->db->enc;
20522282792aSdrh           i = appendAggInfo(pParse);
20532282792aSdrh           if( i<0 ) return 1;
20542282792aSdrh           pParse->aAgg[i].isAgg = 1;
20552282792aSdrh           pParse->aAgg[i].pExpr = pExpr;
20564adee20fSdanielk1977           pParse->aAgg[i].pFunc = sqlite3FindFunction(pParse->db,
20576977fea8Sdrh                pExpr->token.z, pExpr->token.n,
2058d8123366Sdanielk1977                pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
20592282792aSdrh         }
20602282792aSdrh         pExpr->iAgg = i;
2061626a879aSdrh         return 1;
20622282792aSdrh       }
20632282792aSdrh     }
2064a58fdfb1Sdanielk1977   }
2065a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
2066a58fdfb1Sdanielk1977     pNC->nDepth++;
2067a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2068a58fdfb1Sdanielk1977     pNC->nDepth--;
2069a58fdfb1Sdanielk1977   }
2070626a879aSdrh   return 0;
20712282792aSdrh }
2072626a879aSdrh 
2073626a879aSdrh /*
2074626a879aSdrh ** Analyze the given expression looking for aggregate functions and
2075626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
2076626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
2077626a879aSdrh **
2078626a879aSdrh ** This routine should only be called after the expression has been
2079626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
2080626a879aSdrh **
2081626a879aSdrh ** If errors are seen, leave an error message in zErrMsg and return
2082626a879aSdrh ** the number of errors.
2083626a879aSdrh */
2084a58fdfb1Sdanielk1977 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2085a58fdfb1Sdanielk1977   int nErr = pNC->pParse->nErr;
2086a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
2087a58fdfb1Sdanielk1977   return pNC->pParse->nErr - nErr;
20882282792aSdrh }
20898e0a2f90Sdrh 
20908e0a2f90Sdrh /*
2091d02eb1fdSdanielk1977 ** Locate a user function given a name, a number of arguments and a flag
2092d02eb1fdSdanielk1977 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
2093d02eb1fdSdanielk1977 ** pointer to the FuncDef structure that defines that function, or return
2094d02eb1fdSdanielk1977 ** NULL if the function does not exist.
20958e0a2f90Sdrh **
20960bce8354Sdrh ** If the createFlag argument is true, then a new (blank) FuncDef
20978e0a2f90Sdrh ** structure is created and liked into the "db" structure if a
20988e0a2f90Sdrh ** no matching function previously existed.  When createFlag is true
20998e0a2f90Sdrh ** and the nArg parameter is -1, then only a function that accepts
21008e0a2f90Sdrh ** any number of arguments will be returned.
21018e0a2f90Sdrh **
21028e0a2f90Sdrh ** If createFlag is false and nArg is -1, then the first valid
21038e0a2f90Sdrh ** function found is returned.  A function is valid if either xFunc
21048e0a2f90Sdrh ** or xStep is non-zero.
2105d02eb1fdSdanielk1977 **
2106d02eb1fdSdanielk1977 ** If createFlag is false, then a function with the required name and
2107d02eb1fdSdanielk1977 ** number of arguments may be returned even if the eTextRep flag does not
2108d02eb1fdSdanielk1977 ** match that requested.
21098e0a2f90Sdrh */
21104adee20fSdanielk1977 FuncDef *sqlite3FindFunction(
21119bb575fdSdrh   sqlite3 *db,       /* An open database */
21128e0a2f90Sdrh   const char *zName, /* Name of the function.  Not null-terminated */
21138e0a2f90Sdrh   int nName,         /* Number of characters in the name */
21148e0a2f90Sdrh   int nArg,          /* Number of arguments.  -1 means any number */
2115d8123366Sdanielk1977   u8 enc,            /* Preferred text encoding */
21168e0a2f90Sdrh   int createFlag     /* Create new entry if true and does not otherwise exist */
21178e0a2f90Sdrh ){
2118d02eb1fdSdanielk1977   FuncDef *p;         /* Iterator variable */
2119d02eb1fdSdanielk1977   FuncDef *pFirst;    /* First function with this name */
2120d02eb1fdSdanielk1977   FuncDef *pBest = 0; /* Best match found so far */
2121d8123366Sdanielk1977   int bestmatch = 0;
2122d02eb1fdSdanielk1977 
2123d8123366Sdanielk1977 
2124d8123366Sdanielk1977   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
2125d02eb1fdSdanielk1977   if( nArg<-1 ) nArg = -1;
2126d02eb1fdSdanielk1977 
2127d02eb1fdSdanielk1977   pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
2128d02eb1fdSdanielk1977   for(p=pFirst; p; p=p->pNext){
2129d8123366Sdanielk1977     /* During the search for the best function definition, bestmatch is set
2130d8123366Sdanielk1977     ** as follows to indicate the quality of the match with the definition
2131d8123366Sdanielk1977     ** pointed to by pBest:
2132d8123366Sdanielk1977     **
2133d8123366Sdanielk1977     ** 0: pBest is NULL. No match has been found.
2134d8123366Sdanielk1977     ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
2135d8123366Sdanielk1977     **    encoding is requested, or vice versa.
2136d8123366Sdanielk1977     ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
2137d8123366Sdanielk1977     **    requested, or vice versa.
2138d8123366Sdanielk1977     ** 3: A variable arguments function using the same text encoding.
2139d8123366Sdanielk1977     ** 4: A function with the exact number of arguments requested that
2140d8123366Sdanielk1977     **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
2141d8123366Sdanielk1977     ** 5: A function with the exact number of arguments requested that
2142d8123366Sdanielk1977     **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
2143d8123366Sdanielk1977     ** 6: An exact match.
2144d8123366Sdanielk1977     **
2145d8123366Sdanielk1977     ** A larger value of 'matchqual' indicates a more desirable match.
2146d8123366Sdanielk1977     */
2147e12c17baSdanielk1977     if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
2148d8123366Sdanielk1977       int match = 1;          /* Quality of this match */
2149d8123366Sdanielk1977       if( p->nArg==nArg || nArg==-1 ){
2150d8123366Sdanielk1977         match = 4;
21518e0a2f90Sdrh       }
2152d8123366Sdanielk1977       if( enc==p->iPrefEnc ){
2153d8123366Sdanielk1977         match += 2;
21548e0a2f90Sdrh       }
2155d8123366Sdanielk1977       else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
2156d8123366Sdanielk1977                (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
2157d8123366Sdanielk1977         match += 1;
2158d02eb1fdSdanielk1977       }
2159d8123366Sdanielk1977 
2160d8123366Sdanielk1977       if( match>bestmatch ){
2161d02eb1fdSdanielk1977         pBest = p;
2162d8123366Sdanielk1977         bestmatch = match;
2163d02eb1fdSdanielk1977       }
2164d02eb1fdSdanielk1977     }
2165d02eb1fdSdanielk1977   }
2166d02eb1fdSdanielk1977 
2167d8123366Sdanielk1977   /* If the createFlag parameter is true, and the seach did not reveal an
2168d8123366Sdanielk1977   ** exact match for the name, number of arguments and encoding, then add a
2169d8123366Sdanielk1977   ** new entry to the hash table and return it.
2170d8123366Sdanielk1977   */
2171d8123366Sdanielk1977   if( createFlag && bestmatch<6 &&
2172d02eb1fdSdanielk1977       (pBest = sqliteMalloc(sizeof(*pBest)+nName+1)) ){
2173d02eb1fdSdanielk1977     pBest->nArg = nArg;
2174d02eb1fdSdanielk1977     pBest->pNext = pFirst;
2175d02eb1fdSdanielk1977     pBest->zName = (char*)&pBest[1];
2176d8123366Sdanielk1977     pBest->iPrefEnc = enc;
2177d02eb1fdSdanielk1977     memcpy(pBest->zName, zName, nName);
2178d02eb1fdSdanielk1977     pBest->zName[nName] = 0;
21792c336549Sdanielk1977     if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
21802c336549Sdanielk1977       sqliteFree(pBest);
21812c336549Sdanielk1977       return 0;
21822c336549Sdanielk1977     }
2183d02eb1fdSdanielk1977   }
2184d02eb1fdSdanielk1977 
2185d02eb1fdSdanielk1977   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
2186d02eb1fdSdanielk1977     return pBest;
2187d02eb1fdSdanielk1977   }
21888e0a2f90Sdrh   return 0;
21898e0a2f90Sdrh }
2190