xref: /sqlite-3.40.0/src/expr.c (revision 2c336549)
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*2c336549Sdanielk1977 ** $Id: expr.c,v 1.177 2005/01/13 02:14:25 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 /*
6553db1458Sdrh ** pExpr is the left operand of a comparison operator.  aff2 is the
6653db1458Sdrh ** type affinity of the right 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 ){
1864efc4754Sdrh     /* When malloc fails, we leak memory from pLeft and pRight */
187a76b5dfcSdrh     return 0;
188a76b5dfcSdrh   }
189a76b5dfcSdrh   pNew->op = op;
190a76b5dfcSdrh   pNew->pLeft = pLeft;
191a76b5dfcSdrh   pNew->pRight = pRight;
192a76b5dfcSdrh   if( pToken ){
1934b59ab5eSdrh     assert( pToken->dyn==0 );
194145716b3Sdrh     pNew->span = pNew->token = *pToken;
195145716b3Sdrh   }else if( pLeft && pRight ){
1964adee20fSdanielk1977     sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
197a76b5dfcSdrh   }
198a76b5dfcSdrh   return pNew;
199a76b5dfcSdrh }
200a76b5dfcSdrh 
201a76b5dfcSdrh /*
2024e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
2034e0cff60Sdrh ** that look like this:   #0 #1 #2 ...  These terms refer to elements
2044e0cff60Sdrh ** on the stack.  "#0" (or just "#") means the top of the stack.
2052958a4e6Sdrh ** "#1" means the next down on the stack.  And so forth.  #-1 means
2062958a4e6Sdrh ** memory location 0.  #-2 means memory location 1.  And so forth.
2074e0cff60Sdrh **
2084e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
2094e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
2104e0cff60Sdrh ** The returns an expression that will code to extract the value from
2114e0cff60Sdrh ** that memory location as needed.
2124e0cff60Sdrh */
2134e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
2144e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
2154e0cff60Sdrh   Expr *p;
2164e0cff60Sdrh   int depth;
2174e0cff60Sdrh   if( v==0 ) return 0;
2184e0cff60Sdrh   if( pParse->nested==0 ){
2194e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
2204e0cff60Sdrh     return 0;
2214e0cff60Sdrh   }
2224e0cff60Sdrh   p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
22373c42a13Sdrh   if( p==0 ){
22473c42a13Sdrh     return 0;  /* Malloc failed */
22573c42a13Sdrh   }
2264e0cff60Sdrh   depth = atoi(&pToken->z[1]);
2272958a4e6Sdrh   if( depth>=0 ){
2284e0cff60Sdrh     p->iTable = pParse->nMem++;
2294e0cff60Sdrh     sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
2304e0cff60Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
2312958a4e6Sdrh   }else{
2322958a4e6Sdrh     p->iTable = -1-depth;
2332958a4e6Sdrh   }
2344e0cff60Sdrh   return p;
2354e0cff60Sdrh }
2364e0cff60Sdrh 
2374e0cff60Sdrh /*
23891bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
23991bb0eedSdrh ** NULL, then just return the other expression.
24091bb0eedSdrh */
24191bb0eedSdrh Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
24291bb0eedSdrh   if( pLeft==0 ){
24391bb0eedSdrh     return pRight;
24491bb0eedSdrh   }else if( pRight==0 ){
24591bb0eedSdrh     return pLeft;
24691bb0eedSdrh   }else{
24791bb0eedSdrh     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
24891bb0eedSdrh   }
24991bb0eedSdrh }
25091bb0eedSdrh 
25191bb0eedSdrh /*
2526977fea8Sdrh ** Set the Expr.span field of the given expression to span all
253a76b5dfcSdrh ** text between the two given tokens.
254a76b5dfcSdrh */
2554adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
2564efc4754Sdrh   assert( pRight!=0 );
2574efc4754Sdrh   assert( pLeft!=0 );
25871c697efSdrh   if( !sqlite3_malloc_failed && pRight->z && pLeft->z ){
259ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
260145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
2616977fea8Sdrh       pExpr->span.z = pLeft->z;
2626977fea8Sdrh       pExpr->span.n = pRight->n + Addr(pRight->z) - Addr(pLeft->z);
2634b59ab5eSdrh     }else{
2646977fea8Sdrh       pExpr->span.z = 0;
2654b59ab5eSdrh     }
266a76b5dfcSdrh   }
267a76b5dfcSdrh }
268a76b5dfcSdrh 
269a76b5dfcSdrh /*
270a76b5dfcSdrh ** Construct a new expression node for a function with multiple
271a76b5dfcSdrh ** arguments.
272a76b5dfcSdrh */
2734adee20fSdanielk1977 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
274a76b5dfcSdrh   Expr *pNew;
275a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
276a76b5dfcSdrh   if( pNew==0 ){
2774adee20fSdanielk1977     /* sqlite3ExprListDelete(pList); // Leak pList when malloc fails */
278a76b5dfcSdrh     return 0;
279a76b5dfcSdrh   }
280a76b5dfcSdrh   pNew->op = TK_FUNCTION;
281a76b5dfcSdrh   pNew->pList = pList;
282a76b5dfcSdrh   if( pToken ){
2834b59ab5eSdrh     assert( pToken->dyn==0 );
284a76b5dfcSdrh     pNew->token = *pToken;
285a76b5dfcSdrh   }else{
286a76b5dfcSdrh     pNew->token.z = 0;
287a76b5dfcSdrh   }
2886977fea8Sdrh   pNew->span = pNew->token;
289a76b5dfcSdrh   return pNew;
290a76b5dfcSdrh }
291a76b5dfcSdrh 
292a76b5dfcSdrh /*
293fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
294fa6bc000Sdrh ** in the original SQL statement.
295fa6bc000Sdrh **
296fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
297fa6bc000Sdrh ** variable number.
298fa6bc000Sdrh **
299fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
300fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
301fa6bc000Sdrh ** the SQL statement comes from an external source.
302fa6bc000Sdrh **
303fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
304fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
305fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
306fa6bc000Sdrh ** assigned.
307fa6bc000Sdrh */
308fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
309fa6bc000Sdrh   Token *pToken;
310fa6bc000Sdrh   if( pExpr==0 ) return;
311fa6bc000Sdrh   pToken = &pExpr->token;
312fa6bc000Sdrh   assert( pToken->n>=1 );
313fa6bc000Sdrh   assert( pToken->z!=0 );
314fa6bc000Sdrh   assert( pToken->z[0]!=0 );
315fa6bc000Sdrh   if( pToken->n==1 ){
316fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
317fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
318fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
319fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
320fa6bc000Sdrh     ** use it as the variable number */
321fa6bc000Sdrh     int i;
322fa6bc000Sdrh     pExpr->iTable = i = atoi(&pToken->z[1]);
323fa6bc000Sdrh     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
324fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
325fa6bc000Sdrh           SQLITE_MAX_VARIABLE_NUMBER);
326fa6bc000Sdrh     }
327fa6bc000Sdrh     if( i>pParse->nVar ){
328fa6bc000Sdrh       pParse->nVar = i;
329fa6bc000Sdrh     }
330fa6bc000Sdrh   }else{
331fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
332fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
333fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
334fa6bc000Sdrh     */
335fa6bc000Sdrh     int i, n;
336fa6bc000Sdrh     n = pToken->n;
337fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
338fa6bc000Sdrh       Expr *pE;
339fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
340fa6bc000Sdrh           && pE->token.n==n
341fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
342fa6bc000Sdrh         pExpr->iTable = pE->iTable;
343fa6bc000Sdrh         break;
344fa6bc000Sdrh       }
345fa6bc000Sdrh     }
346fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
347fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
348fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
349fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
350fa6bc000Sdrh         pParse->apVarExpr = sqliteRealloc(pParse->apVarExpr,
351fa6bc000Sdrh                        pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
352fa6bc000Sdrh       }
353fa6bc000Sdrh       if( !sqlite3_malloc_failed ){
354fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
355fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
356fa6bc000Sdrh       }
357fa6bc000Sdrh     }
358fa6bc000Sdrh   }
359fa6bc000Sdrh }
360fa6bc000Sdrh 
361fa6bc000Sdrh /*
362a2e00042Sdrh ** Recursively delete an expression tree.
363a2e00042Sdrh */
3644adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
365a2e00042Sdrh   if( p==0 ) return;
3664efc4754Sdrh   if( p->span.dyn ) sqliteFree((char*)p->span.z);
3674efc4754Sdrh   if( p->token.dyn ) sqliteFree((char*)p->token.z);
3684adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
3694adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
3704adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
3714adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
372a2e00042Sdrh   sqliteFree(p);
373a2e00042Sdrh }
374a2e00042Sdrh 
375a76b5dfcSdrh 
376a76b5dfcSdrh /*
377ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
378ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
379ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
380ff78bd2fSdrh ** without effecting the originals.
381ff78bd2fSdrh **
3824adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
3834adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
384ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
385ff78bd2fSdrh **
386ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
387ff78bd2fSdrh */
3884adee20fSdanielk1977 Expr *sqlite3ExprDup(Expr *p){
389ff78bd2fSdrh   Expr *pNew;
390ff78bd2fSdrh   if( p==0 ) return 0;
391fcb78a49Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
392ff78bd2fSdrh   if( pNew==0 ) return 0;
3933b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
3946977fea8Sdrh   if( p->token.z!=0 ){
395b9ecf6faSdrh     pNew->token.z = sqliteStrNDup(p->token.z, p->token.n);
3964b59ab5eSdrh     pNew->token.dyn = 1;
3974b59ab5eSdrh   }else{
3984efc4754Sdrh     assert( pNew->token.z==0 );
3994b59ab5eSdrh   }
4006977fea8Sdrh   pNew->span.z = 0;
4014adee20fSdanielk1977   pNew->pLeft = sqlite3ExprDup(p->pLeft);
4024adee20fSdanielk1977   pNew->pRight = sqlite3ExprDup(p->pRight);
4034adee20fSdanielk1977   pNew->pList = sqlite3ExprListDup(p->pList);
4044adee20fSdanielk1977   pNew->pSelect = sqlite3SelectDup(p->pSelect);
405ff78bd2fSdrh   return pNew;
406ff78bd2fSdrh }
4074adee20fSdanielk1977 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
4084b59ab5eSdrh   if( pTo->dyn ) sqliteFree((char*)pTo->z);
4094b59ab5eSdrh   if( pFrom->z ){
4104b59ab5eSdrh     pTo->n = pFrom->n;
4114b59ab5eSdrh     pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
4124b59ab5eSdrh     pTo->dyn = 1;
4134b59ab5eSdrh   }else{
4144b59ab5eSdrh     pTo->z = 0;
4154b59ab5eSdrh   }
4164b59ab5eSdrh }
4174adee20fSdanielk1977 ExprList *sqlite3ExprListDup(ExprList *p){
418ff78bd2fSdrh   ExprList *pNew;
419145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
420ff78bd2fSdrh   int i;
421ff78bd2fSdrh   if( p==0 ) return 0;
422ff78bd2fSdrh   pNew = sqliteMalloc( sizeof(*pNew) );
423ff78bd2fSdrh   if( pNew==0 ) return 0;
4244305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
4253e7bc9caSdrh   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
426e0048400Sdanielk1977   if( pItem==0 ){
427e0048400Sdanielk1977     sqliteFree(pNew);
428e0048400Sdanielk1977     return 0;
429e0048400Sdanielk1977   }
430145716b3Sdrh   pOldItem = p->a;
431145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
4324b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
433145716b3Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
4346977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
4356977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
4364b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
4374b59ab5eSdrh       ** the names of columns in the result set needs this information */
4384adee20fSdanielk1977       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
4394b59ab5eSdrh     }
4401f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
44124b03fd0Sdanielk1977             || pOldExpr->span.z==0 || sqlite3_malloc_failed );
442145716b3Sdrh     pItem->zName = sqliteStrDup(pOldItem->zName);
443145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
444145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
4453e7bc9caSdrh     pItem->done = 0;
446ff78bd2fSdrh   }
447ff78bd2fSdrh   return pNew;
448ff78bd2fSdrh }
4494adee20fSdanielk1977 SrcList *sqlite3SrcListDup(SrcList *p){
450ad3cab52Sdrh   SrcList *pNew;
451ad3cab52Sdrh   int i;
452113088ecSdrh   int nByte;
453ad3cab52Sdrh   if( p==0 ) return 0;
454113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
4554efc4754Sdrh   pNew = sqliteMallocRaw( nByte );
456ad3cab52Sdrh   if( pNew==0 ) return 0;
4574305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
458ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
4594efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
4604efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
4614efc4754Sdrh     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
4624efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
4634efc4754Sdrh     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
4644efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
4654efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
4664efc4754Sdrh     pNewItem->pTab = 0;
4674adee20fSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
4684adee20fSdanielk1977     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
4694adee20fSdanielk1977     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
470ad3cab52Sdrh   }
471ad3cab52Sdrh   return pNew;
472ad3cab52Sdrh }
4734adee20fSdanielk1977 IdList *sqlite3IdListDup(IdList *p){
474ff78bd2fSdrh   IdList *pNew;
475ff78bd2fSdrh   int i;
476ff78bd2fSdrh   if( p==0 ) return 0;
4774efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*pNew) );
478ff78bd2fSdrh   if( pNew==0 ) return 0;
4794305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
4804efc4754Sdrh   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
481e4697f5eSdrh   if( pNew->a==0 ) return 0;
482ff78bd2fSdrh   for(i=0; i<p->nId; i++){
4834efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
4844efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
4854efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
4864efc4754Sdrh     pNewItem->idx = pOldItem->idx;
487ff78bd2fSdrh   }
488ff78bd2fSdrh   return pNew;
489ff78bd2fSdrh }
4904adee20fSdanielk1977 Select *sqlite3SelectDup(Select *p){
491ff78bd2fSdrh   Select *pNew;
492ff78bd2fSdrh   if( p==0 ) return 0;
4934efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
494ff78bd2fSdrh   if( pNew==0 ) return 0;
495ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
4964adee20fSdanielk1977   pNew->pEList = sqlite3ExprListDup(p->pEList);
4974adee20fSdanielk1977   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
4984adee20fSdanielk1977   pNew->pWhere = sqlite3ExprDup(p->pWhere);
4994adee20fSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
5004adee20fSdanielk1977   pNew->pHaving = sqlite3ExprDup(p->pHaving);
5014adee20fSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
502ff78bd2fSdrh   pNew->op = p->op;
5034adee20fSdanielk1977   pNew->pPrior = sqlite3SelectDup(p->pPrior);
504ff78bd2fSdrh   pNew->nLimit = p->nLimit;
505ff78bd2fSdrh   pNew->nOffset = p->nOffset;
5067b58daeaSdrh   pNew->iLimit = -1;
5077b58daeaSdrh   pNew->iOffset = -1;
508dc1bdc4fSdanielk1977   pNew->ppOpenTemp = 0;
509b6c29897Sdrh   pNew->pFetch = 0;
510ff78bd2fSdrh   return pNew;
511ff78bd2fSdrh }
512ff78bd2fSdrh 
513ff78bd2fSdrh 
514ff78bd2fSdrh /*
515a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
516a76b5dfcSdrh ** initially NULL, then create a new expression list.
517a76b5dfcSdrh */
5184adee20fSdanielk1977 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
519a76b5dfcSdrh   if( pList==0 ){
520a76b5dfcSdrh     pList = sqliteMalloc( sizeof(ExprList) );
521a76b5dfcSdrh     if( pList==0 ){
5224adee20fSdanielk1977       /* sqlite3ExprDelete(pExpr); // Leak memory if malloc fails */
523a76b5dfcSdrh       return 0;
524a76b5dfcSdrh     }
5254efc4754Sdrh     assert( pList->nAlloc==0 );
526a76b5dfcSdrh   }
5274305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
5284305d103Sdrh     pList->nAlloc = pList->nAlloc*2 + 4;
5294efc4754Sdrh     pList->a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]));
5304efc4754Sdrh     if( pList->a==0 ){
5314adee20fSdanielk1977       /* sqlite3ExprDelete(pExpr); // Leak memory if malloc fails */
5324efc4754Sdrh       pList->nExpr = pList->nAlloc = 0;
533a76b5dfcSdrh       return pList;
534a76b5dfcSdrh     }
535a76b5dfcSdrh   }
5364efc4754Sdrh   assert( pList->a!=0 );
5374efc4754Sdrh   if( pExpr || pName ){
5384efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
5394efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
5404efc4754Sdrh     pItem->pExpr = pExpr;
541a99db3b6Sdrh     pItem->zName = sqlite3NameFromToken(pName);
542a76b5dfcSdrh   }
543a76b5dfcSdrh   return pList;
544a76b5dfcSdrh }
545a76b5dfcSdrh 
546a76b5dfcSdrh /*
547a76b5dfcSdrh ** Delete an entire expression list.
548a76b5dfcSdrh */
5494adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
550a76b5dfcSdrh   int i;
551be5c89acSdrh   struct ExprList_item *pItem;
552a76b5dfcSdrh   if( pList==0 ) return;
5531bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
5541bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
555be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
556be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
557be5c89acSdrh     sqliteFree(pItem->zName);
558a76b5dfcSdrh   }
559a76b5dfcSdrh   sqliteFree(pList->a);
560a76b5dfcSdrh   sqliteFree(pList);
561a76b5dfcSdrh }
562a76b5dfcSdrh 
563a76b5dfcSdrh /*
564fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
565fef5208cSdrh ** and 0 if it involves variables.
5662398937bSdrh **
5672398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
5682398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
5692398937bSdrh ** a constant.
570fef5208cSdrh */
5714adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
572fef5208cSdrh   switch( p->op ){
573fef5208cSdrh     case TK_ID:
574967e8b73Sdrh     case TK_COLUMN:
575fef5208cSdrh     case TK_DOT:
5767bdc0c1dSdrh     case TK_FUNCTION:
577fef5208cSdrh       return 0;
5787bdc0c1dSdrh     case TK_NULL:
5792398937bSdrh     case TK_STRING:
580c572ef7fSdanielk1977     case TK_BLOB:
5819208643dSdrh     case TK_INTEGER:
5829208643dSdrh     case TK_FLOAT:
58350457896Sdrh     case TK_VARIABLE:
5847977a17fSdanielk1977     case TK_CTIME:
5857977a17fSdanielk1977     case TK_CTIMESTAMP:
5867977a17fSdanielk1977     case TK_CDATE:
5879208643dSdrh       return 1;
588fef5208cSdrh     default: {
5894adee20fSdanielk1977       if( p->pLeft && !sqlite3ExprIsConstant(p->pLeft) ) return 0;
5904adee20fSdanielk1977       if( p->pRight && !sqlite3ExprIsConstant(p->pRight) ) return 0;
591fef5208cSdrh       if( p->pList ){
592fef5208cSdrh         int i;
593fef5208cSdrh         for(i=0; i<p->pList->nExpr; i++){
5944adee20fSdanielk1977           if( !sqlite3ExprIsConstant(p->pList->a[i].pExpr) ) return 0;
595fef5208cSdrh         }
596fef5208cSdrh       }
5979208643dSdrh       return p->pLeft!=0 || p->pRight!=0 || (p->pList && p->pList->nExpr>0);
598fef5208cSdrh     }
599fef5208cSdrh   }
6009208643dSdrh   return 0;
601fef5208cSdrh }
602fef5208cSdrh 
603fef5208cSdrh /*
604202b2df7Sdrh ** If the given expression codes a constant integer that is small enough
605202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
606202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
607202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
608e4de1febSdrh */
6094adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
610e4de1febSdrh   switch( p->op ){
611e4de1febSdrh     case TK_INTEGER: {
612fec19aadSdrh       if( sqlite3GetInt32(p->token.z, pValue) ){
613e4de1febSdrh         return 1;
614e4de1febSdrh       }
615202b2df7Sdrh       break;
616202b2df7Sdrh     }
617e4de1febSdrh     case TK_STRING: {
6184c755c0fSdrh       const u8 *z = (u8*)p->token.z;
619e4de1febSdrh       int n = p->token.n;
620bd790ee3Sdrh       if( n>0 && z[0]=='-' ){ z++; n--; }
621e4de1febSdrh       while( n>0 && *z && isdigit(*z) ){ z++; n--; }
622fec19aadSdrh       if( n==0 && sqlite3GetInt32(p->token.z, pValue) ){
623e4de1febSdrh         return 1;
624e4de1febSdrh       }
625e4de1febSdrh       break;
626e4de1febSdrh     }
6274b59ab5eSdrh     case TK_UPLUS: {
6284adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
6294b59ab5eSdrh     }
630e4de1febSdrh     case TK_UMINUS: {
631e4de1febSdrh       int v;
6324adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
633e4de1febSdrh         *pValue = -v;
634e4de1febSdrh         return 1;
635e4de1febSdrh       }
636e4de1febSdrh       break;
637e4de1febSdrh     }
638e4de1febSdrh     default: break;
639e4de1febSdrh   }
640e4de1febSdrh   return 0;
641e4de1febSdrh }
642e4de1febSdrh 
643e4de1febSdrh /*
644c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
645c4a3c779Sdrh */
6464adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
6474adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
6484adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
6494adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
650c4a3c779Sdrh   return 0;
651c4a3c779Sdrh }
652c4a3c779Sdrh 
653c4a3c779Sdrh /*
6548141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
6558141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
6568141f61eSdrh ** expression node refer back to that source column.  The following changes
6578141f61eSdrh ** are made to pExpr:
6588141f61eSdrh **
6598141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
6608141f61eSdrh **                         the table.
6618141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
6628141f61eSdrh **                         from pSrcList.
6638141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
6648141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
6658141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
6668141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
6678141f61eSdrh **
6688141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
6698141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
6708141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
6718141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
6728141f61eSdrh ** means that the form of the name is Z and that columns from any table
6738141f61eSdrh ** can be used.
6748141f61eSdrh **
6758141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
6768141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
6778141f61eSdrh */
6788141f61eSdrh static int lookupName(
6798141f61eSdrh   Parse *pParse,      /* The parsing context */
6808141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
6818141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
6828141f61eSdrh   Token *pColumnToken, /* Name of the column. */
6838141f61eSdrh   SrcList *pSrcList,   /* List of tables used to resolve column names */
6848141f61eSdrh   ExprList *pEList,    /* List of expressions used to resolve "AS" */
6858141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
6868141f61eSdrh ){
6878141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
6888141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
6898141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
6908141f61eSdrh   int i, j;            /* Loop counters */
6918141f61eSdrh   int cnt = 0;         /* Number of matching column names */
6928141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
6939bb575fdSdrh   sqlite3 *db = pParse->db;         /* The database */
69451669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
69551669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
6968141f61eSdrh 
6978141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
698a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
699a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
700a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
70124b03fd0Sdanielk1977   if( sqlite3_malloc_failed ){
7028141f61eSdrh     return 1;  /* Leak memory (zDb and zTab) if malloc fails */
7038141f61eSdrh   }
7048141f61eSdrh   assert( zTab==0 || pEList==0 );
7058141f61eSdrh 
7068141f61eSdrh   pExpr->iTable = -1;
70751669863Sdrh   for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
7088141f61eSdrh     Table *pTab = pItem->pTab;
7098141f61eSdrh     Column *pCol;
7108141f61eSdrh 
7118141f61eSdrh     if( pTab==0 ) continue;
7128141f61eSdrh     assert( pTab->nCol>0 );
7138141f61eSdrh     if( zTab ){
7148141f61eSdrh       if( pItem->zAlias ){
7158141f61eSdrh         char *zTabName = pItem->zAlias;
7164adee20fSdanielk1977         if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
7178141f61eSdrh       }else{
7188141f61eSdrh         char *zTabName = pTab->zName;
7194adee20fSdanielk1977         if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
7204adee20fSdanielk1977         if( zDb!=0 && sqlite3StrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
7218141f61eSdrh           continue;
7228141f61eSdrh         }
7238141f61eSdrh       }
7248141f61eSdrh     }
7258141f61eSdrh     if( 0==(cntTab++) ){
7268141f61eSdrh       pExpr->iTable = pItem->iCursor;
7278141f61eSdrh       pExpr->iDb = pTab->iDb;
72851669863Sdrh       pMatch = pItem;
7298141f61eSdrh     }
7308141f61eSdrh     for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
7314adee20fSdanielk1977       if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
7328141f61eSdrh         cnt++;
7338141f61eSdrh         pExpr->iTable = pItem->iCursor;
73451669863Sdrh         pMatch = pItem;
7358141f61eSdrh         pExpr->iDb = pTab->iDb;
7368141f61eSdrh         /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
7378141f61eSdrh         pExpr->iColumn = j==pTab->iPKey ? -1 : j;
738a37cdde0Sdanielk1977         pExpr->affinity = pTab->aCol[j].affinity;
7390202b29eSdanielk1977         pExpr->pColl = pTab->aCol[j].pColl;
7408141f61eSdrh         break;
7418141f61eSdrh       }
7428141f61eSdrh     }
7438141f61eSdrh   }
7448141f61eSdrh 
745b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
7468141f61eSdrh   /* If we have not already resolved the name, then maybe
7478141f61eSdrh   ** it is a new.* or old.* trigger argument reference
7488141f61eSdrh   */
7498141f61eSdrh   if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
7508141f61eSdrh     TriggerStack *pTriggerStack = pParse->trigStack;
7518141f61eSdrh     Table *pTab = 0;
7524adee20fSdanielk1977     if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
7538141f61eSdrh       pExpr->iTable = pTriggerStack->newIdx;
7548141f61eSdrh       assert( pTriggerStack->pTab );
7558141f61eSdrh       pTab = pTriggerStack->pTab;
7564adee20fSdanielk1977     }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab) == 0 ){
7578141f61eSdrh       pExpr->iTable = pTriggerStack->oldIdx;
7588141f61eSdrh       assert( pTriggerStack->pTab );
7598141f61eSdrh       pTab = pTriggerStack->pTab;
7608141f61eSdrh     }
7618141f61eSdrh 
7628141f61eSdrh     if( pTab ){
7638141f61eSdrh       int j;
7648141f61eSdrh       Column *pCol = pTab->aCol;
7658141f61eSdrh 
7668141f61eSdrh       pExpr->iDb = pTab->iDb;
7678141f61eSdrh       cntTab++;
7688141f61eSdrh       for(j=0; j < pTab->nCol; j++, pCol++) {
7694adee20fSdanielk1977         if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
7708141f61eSdrh           cnt++;
7718141f61eSdrh           pExpr->iColumn = j==pTab->iPKey ? -1 : j;
772a37cdde0Sdanielk1977           pExpr->affinity = pTab->aCol[j].affinity;
7730202b29eSdanielk1977           pExpr->pColl = pTab->aCol[j].pColl;
7748141f61eSdrh           break;
7758141f61eSdrh         }
7768141f61eSdrh       }
7778141f61eSdrh     }
7788141f61eSdrh   }
779b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
7808141f61eSdrh 
7818141f61eSdrh   /*
7828141f61eSdrh   ** Perhaps the name is a reference to the ROWID
7838141f61eSdrh   */
7844adee20fSdanielk1977   if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
7858141f61eSdrh     cnt = 1;
7868141f61eSdrh     pExpr->iColumn = -1;
787a37cdde0Sdanielk1977     pExpr->affinity = SQLITE_AFF_INTEGER;
7888141f61eSdrh   }
7898141f61eSdrh 
7908141f61eSdrh   /*
7918141f61eSdrh   ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
7928141f61eSdrh   ** might refer to an result-set alias.  This happens, for example, when
7938141f61eSdrh   ** we are resolving names in the WHERE clause of the following command:
7948141f61eSdrh   **
7958141f61eSdrh   **     SELECT a+b AS x FROM table WHERE x<10;
7968141f61eSdrh   **
7978141f61eSdrh   ** In cases like this, replace pExpr with a copy of the expression that
7988141f61eSdrh   ** forms the result set entry ("a+b" in the example) and return immediately.
7998141f61eSdrh   ** Note that the expression in the result set should have already been
8008141f61eSdrh   ** resolved by the time the WHERE clause is resolved.
8018141f61eSdrh   */
8028141f61eSdrh   if( cnt==0 && pEList!=0 ){
8038141f61eSdrh     for(j=0; j<pEList->nExpr; j++){
8048141f61eSdrh       char *zAs = pEList->a[j].zName;
8054adee20fSdanielk1977       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
8068141f61eSdrh         assert( pExpr->pLeft==0 && pExpr->pRight==0 );
8078141f61eSdrh         pExpr->op = TK_AS;
8088141f61eSdrh         pExpr->iColumn = j;
8094adee20fSdanielk1977         pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
8108141f61eSdrh         sqliteFree(zCol);
8118141f61eSdrh         assert( zTab==0 && zDb==0 );
8128141f61eSdrh         return 0;
8138141f61eSdrh       }
8148141f61eSdrh     }
8158141f61eSdrh   }
8168141f61eSdrh 
8178141f61eSdrh   /*
8188141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
8198141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
8208141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
8218141f61eSdrh   ** case, we need to return right away and not make any changes to
8228141f61eSdrh   ** pExpr.
8238141f61eSdrh   */
8248141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
8258141f61eSdrh     sqliteFree(zCol);
8268141f61eSdrh     return 0;
8278141f61eSdrh   }
8288141f61eSdrh 
8298141f61eSdrh   /*
8308141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
8318141f61eSdrh   ** more matches.  Either way, we have an error.
8328141f61eSdrh   */
8338141f61eSdrh   if( cnt!=1 ){
8348141f61eSdrh     char *z = 0;
8358141f61eSdrh     char *zErr;
8368141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
8378141f61eSdrh     if( zDb ){
8384adee20fSdanielk1977       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, 0);
8398141f61eSdrh     }else if( zTab ){
8404adee20fSdanielk1977       sqlite3SetString(&z, zTab, ".", zCol, 0);
8418141f61eSdrh     }else{
8428141f61eSdrh       z = sqliteStrDup(zCol);
8438141f61eSdrh     }
8444adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
8458141f61eSdrh     sqliteFree(z);
8468141f61eSdrh   }
8478141f61eSdrh 
84851669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
84951669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
85051669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
85151669863Sdrh   ** column number is greater than the number of bits in the bitmask
85251669863Sdrh   ** then set the high-order bit of the bitmask.
85351669863Sdrh   */
85451669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
85551669863Sdrh     int n = pExpr->iColumn;
85651669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
85751669863Sdrh       n = sizeof(Bitmask)*8-1;
85851669863Sdrh     }
85951669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
86051669863Sdrh     pMatch->colUsed |= 1<<n;
86151669863Sdrh   }
86251669863Sdrh 
8638141f61eSdrh   /* Clean up and return
8648141f61eSdrh   */
8658141f61eSdrh   sqliteFree(zDb);
8668141f61eSdrh   sqliteFree(zTab);
8678141f61eSdrh   sqliteFree(zCol);
8684adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
8698141f61eSdrh   pExpr->pLeft = 0;
8704adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
8718141f61eSdrh   pExpr->pRight = 0;
8728141f61eSdrh   pExpr->op = TK_COLUMN;
8734adee20fSdanielk1977   sqlite3AuthRead(pParse, pExpr, pSrcList);
8748141f61eSdrh   return cnt!=1;
8758141f61eSdrh }
8768141f61eSdrh 
8778141f61eSdrh /*
878cce7d176Sdrh ** This routine walks an expression tree and resolves references to
879967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
880aacc543eSdrh ** index to the table in the table list and a column offset.  The
881aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
882aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
883832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
884aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
885aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
886aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
887aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
888aacc543eSdrh ** alias for ROWID.
88919a775c2Sdrh **
890fef5208cSdrh ** We also check for instances of the IN operator.  IN comes in two
891fef5208cSdrh ** forms:
892fef5208cSdrh **
893fef5208cSdrh **           expr IN (exprlist)
894fef5208cSdrh ** and
895fef5208cSdrh **           expr IN (SELECT ...)
896fef5208cSdrh **
897fef5208cSdrh ** The first form is handled by creating a set holding the list
898fef5208cSdrh ** of allowed values.  The second form causes the SELECT to generate
899fef5208cSdrh ** a temporary table.
900fef5208cSdrh **
901fef5208cSdrh ** This routine also looks for scalar SELECTs that are part of an expression.
90219a775c2Sdrh ** If it finds any, it generates code to write the value of that select
90319a775c2Sdrh ** into a memory cell.
904cce7d176Sdrh **
905967e8b73Sdrh ** Unknown columns or tables provoke an error.  The function returns
906cce7d176Sdrh ** the number of errors seen and leaves an error message on pParse->zErrMsg.
907cce7d176Sdrh */
9084adee20fSdanielk1977 int sqlite3ExprResolveIds(
909a2e00042Sdrh   Parse *pParse,     /* The parser context */
9108141f61eSdrh   SrcList *pSrcList, /* List of tables used to resolve column names */
911a2e00042Sdrh   ExprList *pEList,  /* List of expressions used to resolve "AS" */
912a2e00042Sdrh   Expr *pExpr        /* The expression to be analyzed. */
913a2e00042Sdrh ){
9146a3ea0e6Sdrh   int i;
9156a3ea0e6Sdrh 
9168141f61eSdrh   if( pExpr==0 || pSrcList==0 ) return 0;
9178141f61eSdrh   for(i=0; i<pSrcList->nSrc; i++){
9188141f61eSdrh     assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab );
9196a3ea0e6Sdrh   }
920cce7d176Sdrh   switch( pExpr->op ){
9212398937bSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
9222398937bSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
9232398937bSdrh     ** strings (ex: 'abc') are always string literals.
9242398937bSdrh     */
9252398937bSdrh     case TK_STRING: {
9262398937bSdrh       if( pExpr->token.z[0]=='\'' ) break;
9272398937bSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
9282398937bSdrh     }
9298141f61eSdrh     /* A lone identifier is the name of a columnd.
930a2e00042Sdrh     */
931cce7d176Sdrh     case TK_ID: {
9328141f61eSdrh       if( lookupName(pParse, 0, 0, &pExpr->token, pSrcList, pEList, pExpr) ){
933cce7d176Sdrh         return 1;
934ed6c8671Sdrh       }
935cce7d176Sdrh       break;
936cce7d176Sdrh     }
937cce7d176Sdrh 
938d24cc427Sdrh     /* A table name and column name:     ID.ID
939d24cc427Sdrh     ** Or a database, table and column:  ID.ID.ID
940d24cc427Sdrh     */
941cce7d176Sdrh     case TK_DOT: {
9428141f61eSdrh       Token *pColumn;
9438141f61eSdrh       Token *pTable;
9448141f61eSdrh       Token *pDb;
9458141f61eSdrh       Expr *pRight;
946cce7d176Sdrh 
947cce7d176Sdrh       pRight = pExpr->pRight;
948d24cc427Sdrh       if( pRight->op==TK_ID ){
9498141f61eSdrh         pDb = 0;
9508141f61eSdrh         pTable = &pExpr->pLeft->token;
9518141f61eSdrh         pColumn = &pRight->token;
952d24cc427Sdrh       }else{
9538141f61eSdrh         assert( pRight->op==TK_DOT );
9548141f61eSdrh         pDb = &pExpr->pLeft->token;
9558141f61eSdrh         pTable = &pRight->pLeft->token;
9568141f61eSdrh         pColumn = &pRight->pRight->token;
957d24cc427Sdrh       }
9588141f61eSdrh       if( lookupName(pParse, pDb, pTable, pColumn, pSrcList, 0, pExpr) ){
959daffd0e5Sdrh         return 1;
960daffd0e5Sdrh       }
961cce7d176Sdrh       break;
962cce7d176Sdrh     }
963cce7d176Sdrh 
964fef5208cSdrh     case TK_IN: {
965e014a838Sdanielk1977       char affinity;
9664adee20fSdanielk1977       Vdbe *v = sqlite3GetVdbe(pParse);
967d3d39e93Sdrh       KeyInfo keyInfo;
9680202b29eSdanielk1977       int addr;        /* Address of OP_OpenTemp instruction */
969d3d39e93Sdrh 
970fef5208cSdrh       if( v==0 ) return 1;
9714adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
972cfab11bcSdrh         return 1;
973cfab11bcSdrh       }
974bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
975e014a838Sdanielk1977 
976e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
977e014a838Sdanielk1977       ** expression it is handled the same way. A temporary table is
978e014a838Sdanielk1977       ** filled with single-field index keys representing the results
979e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
980fef5208cSdrh       **
981e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
982e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
983e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
984e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
985e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
986e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
987e014a838Sdanielk1977       ** is used.
988fef5208cSdrh       */
989832508b7Sdrh       pExpr->iTable = pParse->nTab++;
9900202b29eSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, pExpr->iTable, 0);
991d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
992d3d39e93Sdrh       keyInfo.nField = 1;
993f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
994e014a838Sdanielk1977 
995e014a838Sdanielk1977       if( pExpr->pSelect ){
996e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
997e014a838Sdanielk1977         **
998e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
999e014a838Sdanielk1977         ** table allocated and opened above.
1000e014a838Sdanielk1977         */
1001e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1002be5c89acSdrh         ExprList *pEList;
1003e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1004bf3b721fSdanielk1977         sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
1005be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1006be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
10077cedc8d4Sdanielk1977           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
1008be5c89acSdrh               pEList->a[0].pExpr);
10090202b29eSdanielk1977         }
1010fef5208cSdrh       }else if( pExpr->pList ){
1011fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1012fef5208cSdrh         **
1013e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
1014e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1015e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1016e014a838Sdanielk1977         ** a column, use numeric affinity.
1017fef5208cSdrh         */
1018e014a838Sdanielk1977         int i;
1019e014a838Sdanielk1977         if( !affinity ){
1020e014a838Sdanielk1977           affinity = SQLITE_AFF_NUMERIC;
1021e014a838Sdanielk1977         }
10220202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1023e014a838Sdanielk1977 
1024e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
1025fef5208cSdrh         for(i=0; i<pExpr->pList->nExpr; i++){
1026fef5208cSdrh           Expr *pE2 = pExpr->pList->a[i].pExpr;
1027e014a838Sdanielk1977 
1028e014a838Sdanielk1977           /* Check that the expression is constant and valid. */
10294adee20fSdanielk1977           if( !sqlite3ExprIsConstant(pE2) ){
10304adee20fSdanielk1977             sqlite3ErrorMsg(pParse,
1031da93d238Sdrh               "right-hand side of IN operator must be constant");
1032fef5208cSdrh             return 1;
1033fef5208cSdrh           }
10344adee20fSdanielk1977           if( sqlite3ExprCheck(pParse, pE2, 0, 0) ){
10354794b980Sdrh             return 1;
10364794b980Sdrh           }
1037e014a838Sdanielk1977 
1038e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
10394adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
104094a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
10410f69c1e3Sdanielk1977           sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1042e014a838Sdanielk1977           sqlite3VdbeAddOp(v, OP_PutStrKey, pExpr->iTable, 0);
1043fef5208cSdrh         }
1044fef5208cSdrh       }
10450202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
10460202b29eSdanielk1977 
1047cfab11bcSdrh       break;
1048fef5208cSdrh     }
1049fef5208cSdrh 
105019a775c2Sdrh     case TK_SELECT: {
1051fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1052fef5208cSdrh       ** value of this select in a memory cell and record the number
1053967e8b73Sdrh       ** of the memory cell in iColumn.
1054fef5208cSdrh       */
1055967e8b73Sdrh       pExpr->iColumn = pParse->nMem++;
1056bf3b721fSdanielk1977       if(sqlite3Select(pParse, pExpr->pSelect, SRT_Mem,pExpr->iColumn,0,0,0,0)){
105719a775c2Sdrh         return 1;
105819a775c2Sdrh       }
105919a775c2Sdrh       break;
106019a775c2Sdrh     }
106119a775c2Sdrh 
1062cce7d176Sdrh     /* For all else, just recursively walk the tree */
1063cce7d176Sdrh     default: {
1064cce7d176Sdrh       if( pExpr->pLeft
10654adee20fSdanielk1977       && sqlite3ExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
1066cce7d176Sdrh         return 1;
1067cce7d176Sdrh       }
1068cce7d176Sdrh       if( pExpr->pRight
10694adee20fSdanielk1977       && sqlite3ExprResolveIds(pParse, pSrcList, pEList, pExpr->pRight) ){
1070cce7d176Sdrh         return 1;
1071cce7d176Sdrh       }
1072cce7d176Sdrh       if( pExpr->pList ){
1073cce7d176Sdrh         int i;
1074cce7d176Sdrh         ExprList *pList = pExpr->pList;
1075cce7d176Sdrh         for(i=0; i<pList->nExpr; i++){
1076832508b7Sdrh           Expr *pArg = pList->a[i].pExpr;
10774adee20fSdanielk1977           if( sqlite3ExprResolveIds(pParse, pSrcList, pEList, pArg) ){
1078cce7d176Sdrh             return 1;
1079cce7d176Sdrh           }
1080cce7d176Sdrh         }
1081cce7d176Sdrh       }
1082cce7d176Sdrh     }
1083cce7d176Sdrh   }
1084cce7d176Sdrh   return 0;
1085cce7d176Sdrh }
1086cce7d176Sdrh 
1087cce7d176Sdrh /*
10884b59ab5eSdrh ** pExpr is a node that defines a function of some kind.  It might
10894b59ab5eSdrh ** be a syntactic function like "count(x)" or it might be a function
10904b59ab5eSdrh ** that implements an operator, like "a LIKE b".
10914b59ab5eSdrh **
10924b59ab5eSdrh ** This routine makes *pzName point to the name of the function and
10934b59ab5eSdrh ** *pnName hold the number of characters in the function name.
10944b59ab5eSdrh */
10954b59ab5eSdrh static void getFunctionName(Expr *pExpr, const char **pzName, int *pnName){
10964b59ab5eSdrh   switch( pExpr->op ){
10974b59ab5eSdrh     case TK_FUNCTION: {
10984b59ab5eSdrh       *pzName = pExpr->token.z;
10996977fea8Sdrh       *pnName = pExpr->token.n;
11004b59ab5eSdrh       break;
11014b59ab5eSdrh     }
11024b59ab5eSdrh     case TK_LIKE: {
11034b59ab5eSdrh       *pzName = "like";
11044b59ab5eSdrh       *pnName = 4;
11054b59ab5eSdrh       break;
11064b59ab5eSdrh     }
11074b59ab5eSdrh     case TK_GLOB: {
11084b59ab5eSdrh       *pzName = "glob";
11094b59ab5eSdrh       *pnName = 4;
11104b59ab5eSdrh       break;
11114b59ab5eSdrh     }
11127977a17fSdanielk1977     case TK_CTIME: {
11137977a17fSdanielk1977       *pzName = "current_time";
11147977a17fSdanielk1977       *pnName = 12;
11157977a17fSdanielk1977       break;
11167977a17fSdanielk1977     }
11177977a17fSdanielk1977     case TK_CDATE: {
11187977a17fSdanielk1977       *pzName = "current_date";
11197977a17fSdanielk1977       *pnName = 12;
11207977a17fSdanielk1977       break;
11217977a17fSdanielk1977     }
11227977a17fSdanielk1977     case TK_CTIMESTAMP: {
11237977a17fSdanielk1977       *pzName = "current_timestamp";
11247977a17fSdanielk1977       *pnName = 17;
11257977a17fSdanielk1977       break;
11267977a17fSdanielk1977     }
11274b59ab5eSdrh     default: {
11284b59ab5eSdrh       *pzName = "can't happen";
11294b59ab5eSdrh       *pnName = 12;
11304b59ab5eSdrh       break;
11314b59ab5eSdrh     }
11324b59ab5eSdrh   }
11334b59ab5eSdrh }
11344b59ab5eSdrh 
11354b59ab5eSdrh /*
1136cce7d176Sdrh ** Error check the functions in an expression.  Make sure all
1137cce7d176Sdrh ** function names are recognized and all functions have the correct
1138cce7d176Sdrh ** number of arguments.  Leave an error message in pParse->zErrMsg
1139cce7d176Sdrh ** if anything is amiss.  Return the number of errors.
1140cce7d176Sdrh **
1141cce7d176Sdrh ** if pIsAgg is not null and this expression is an aggregate function
1142cce7d176Sdrh ** (like count(*) or max(value)) then write a 1 into *pIsAgg.
1143cce7d176Sdrh */
11444adee20fSdanielk1977 int sqlite3ExprCheck(Parse *pParse, Expr *pExpr, int allowAgg, int *pIsAgg){
1145cce7d176Sdrh   int nErr = 0;
1146cce7d176Sdrh   if( pExpr==0 ) return 0;
1147cce7d176Sdrh   switch( pExpr->op ){
11487977a17fSdanielk1977     case TK_CTIME:
11497977a17fSdanielk1977     case TK_CTIMESTAMP:
11507977a17fSdanielk1977     case TK_CDATE:
11517977a17fSdanielk1977     /* Note: The above three were a seperate case in sqlmoto. Reason? */
11524b59ab5eSdrh     case TK_GLOB:
11534b59ab5eSdrh     case TK_LIKE:
1154cce7d176Sdrh     case TK_FUNCTION: {
1155c9b84a1fSdrh       int n = pExpr->pList ? pExpr->pList->nExpr : 0;  /* Number of arguments */
1156c9b84a1fSdrh       int no_such_func = 0;       /* True if no such function exists */
1157c9b84a1fSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1158c9b84a1fSdrh       int is_agg = 0;             /* True if is an aggregate function */
1159cce7d176Sdrh       int i;
11604b59ab5eSdrh       int nId;                    /* Number of characters in function name */
11614b59ab5eSdrh       const char *zId;            /* The function name. */
11620bce8354Sdrh       FuncDef *pDef;
1163d8123366Sdanielk1977       int enc = pParse->db->enc;
11640bce8354Sdrh 
11654b59ab5eSdrh       getFunctionName(pExpr, &zId, &nId);
1166d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
11670bce8354Sdrh       if( pDef==0 ){
1168d8123366Sdanielk1977         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
11690bce8354Sdrh         if( pDef==0 ){
1170cce7d176Sdrh           no_such_func = 1;
11718e0a2f90Sdrh         }else{
11728e0a2f90Sdrh           wrong_num_args = 1;
11738e0a2f90Sdrh         }
11748e0a2f90Sdrh       }else{
11750bce8354Sdrh         is_agg = pDef->xFunc==0;
1176cce7d176Sdrh       }
11778e0a2f90Sdrh       if( is_agg && !allowAgg ){
11784adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId, zId);
11798e0a2f90Sdrh         nErr++;
11808e0a2f90Sdrh         is_agg = 0;
11818e0a2f90Sdrh       }else if( no_such_func ){
11824adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1183cce7d176Sdrh         nErr++;
11848e0a2f90Sdrh       }else if( wrong_num_args ){
11854adee20fSdanielk1977         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1186f7a9e1acSdrh              nId, zId);
11878e0a2f90Sdrh         nErr++;
1188cce7d176Sdrh       }
1189f7a9e1acSdrh       if( is_agg ){
1190f7a9e1acSdrh         pExpr->op = TK_AGG_FUNCTION;
1191f7a9e1acSdrh         if( pIsAgg ) *pIsAgg = 1;
1192f7a9e1acSdrh       }
1193cce7d176Sdrh       for(i=0; nErr==0 && i<n; i++){
11944adee20fSdanielk1977         nErr = sqlite3ExprCheck(pParse, pExpr->pList->a[i].pExpr,
11954cfa7934Sdrh                                allowAgg && !is_agg, pIsAgg);
1196cce7d176Sdrh       }
11970202b29eSdanielk1977       /* FIX ME:  Compute pExpr->affinity based on the expected return
11980202b29eSdanielk1977       ** type of the function
11990202b29eSdanielk1977       */
1200cce7d176Sdrh     }
1201cce7d176Sdrh     default: {
1202cce7d176Sdrh       if( pExpr->pLeft ){
12034adee20fSdanielk1977         nErr = sqlite3ExprCheck(pParse, pExpr->pLeft, allowAgg, pIsAgg);
1204cce7d176Sdrh       }
1205cce7d176Sdrh       if( nErr==0 && pExpr->pRight ){
12064adee20fSdanielk1977         nErr = sqlite3ExprCheck(pParse, pExpr->pRight, allowAgg, pIsAgg);
1207cce7d176Sdrh       }
1208fef5208cSdrh       if( nErr==0 && pExpr->pList ){
1209fef5208cSdrh         int n = pExpr->pList->nExpr;
1210fef5208cSdrh         int i;
1211fef5208cSdrh         for(i=0; nErr==0 && i<n; i++){
12122282792aSdrh           Expr *pE2 = pExpr->pList->a[i].pExpr;
12134adee20fSdanielk1977           nErr = sqlite3ExprCheck(pParse, pE2, allowAgg, pIsAgg);
1214fef5208cSdrh         }
1215fef5208cSdrh       }
1216cce7d176Sdrh       break;
1217cce7d176Sdrh     }
1218cce7d176Sdrh   }
1219cce7d176Sdrh   return nErr;
1220cce7d176Sdrh }
1221cce7d176Sdrh 
1222cce7d176Sdrh /*
1223290c1948Sdrh ** Call sqlite3ExprResolveIds() followed by sqlite3ExprCheck().
1224290c1948Sdrh **
1225290c1948Sdrh ** This routine is provided as a convenience since it is very common
1226290c1948Sdrh ** to call ResolveIds() and Check() back to back.
1227290c1948Sdrh */
1228290c1948Sdrh int sqlite3ExprResolveAndCheck(
1229290c1948Sdrh   Parse *pParse,     /* The parser context */
1230290c1948Sdrh   SrcList *pSrcList, /* List of tables used to resolve column names */
1231290c1948Sdrh   ExprList *pEList,  /* List of expressions used to resolve "AS" */
1232290c1948Sdrh   Expr *pExpr,       /* The expression to be analyzed. */
1233290c1948Sdrh   int allowAgg,      /* True to allow aggregate expressions */
1234290c1948Sdrh   int *pIsAgg        /* Set to TRUE if aggregates are found */
1235290c1948Sdrh ){
1236290c1948Sdrh   if( pExpr==0 ) return 0;
1237290c1948Sdrh   if( sqlite3ExprResolveIds(pParse,pSrcList,pEList,pExpr) ){
1238290c1948Sdrh     return 1;
1239290c1948Sdrh   }
1240290c1948Sdrh   return sqlite3ExprCheck(pParse, pExpr, allowAgg, pIsAgg);
1241290c1948Sdrh }
1242290c1948Sdrh 
1243290c1948Sdrh /*
1244fec19aadSdrh ** Generate an instruction that will put the integer describe by
1245fec19aadSdrh ** text z[0..n-1] on the stack.
1246fec19aadSdrh */
1247fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1248fec19aadSdrh   int i;
12496fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
12506fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
12516fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
12526fec0762Sdrh     sqlite3VdbeOp3(v, OP_Integer, 0, 0, z, n);
1253fec19aadSdrh   }else{
1254fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1255fec19aadSdrh   }
1256fec19aadSdrh }
1257fec19aadSdrh 
1258fec19aadSdrh /*
1259cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
12601ccde15dSdrh ** expression and leave the result on the top of stack.
1261f2bc013cSdrh **
1262f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1263f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1264f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1265f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1266f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1267cce7d176Sdrh */
12684adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1269cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1270cce7d176Sdrh   int op;
12717977a17fSdanielk1977   if( v==0 ) return;
12727977a17fSdanielk1977   if( pExpr==0 ){
12737977a17fSdanielk1977     sqlite3VdbeAddOp(v, OP_String8, 0, 0);  /* Empty expression evals to NULL */
12747977a17fSdanielk1977     return;
12757977a17fSdanielk1977   }
1276f2bc013cSdrh   op = pExpr->op;
1277f2bc013cSdrh   switch( op ){
1278967e8b73Sdrh     case TK_COLUMN: {
12792282792aSdrh       if( pParse->useAgg ){
12804adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
1281c4a3c779Sdrh       }else if( pExpr->iColumn>=0 ){
12824adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
1283145716b3Sdrh #ifndef NDEBUG
1284145716b3Sdrh         if( pExpr->span.z && pExpr->span.n>0 && pExpr->span.n<100 ){
1285ad6d9460Sdrh           VdbeComment((v, "# %T", &pExpr->span));
1286145716b3Sdrh         }
1287145716b3Sdrh #endif
1288c4a3c779Sdrh       }else{
12894adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Recno, pExpr->iTable, 0);
12902282792aSdrh       }
1291cce7d176Sdrh       break;
1292cce7d176Sdrh     }
1293cce7d176Sdrh     case TK_INTEGER: {
1294fec19aadSdrh       codeInteger(v, pExpr->token.z, pExpr->token.n);
1295fec19aadSdrh       break;
129651e9a445Sdrh     }
1297fec19aadSdrh     case TK_FLOAT:
1298fec19aadSdrh     case TK_STRING: {
1299f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1300f2bc013cSdrh       assert( TK_STRING==OP_String8 );
1301fec19aadSdrh       sqlite3VdbeOp3(v, op, 0, 0, pExpr->token.z, pExpr->token.n);
13024adee20fSdanielk1977       sqlite3VdbeDequoteP3(v, -1);
1303cce7d176Sdrh       break;
1304cce7d176Sdrh     }
1305c572ef7fSdanielk1977     case TK_BLOB: {
1306f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
1307c572ef7fSdanielk1977       sqlite3VdbeOp3(v, op, 0, 0, pExpr->token.z+1, pExpr->token.n-1);
1308c572ef7fSdanielk1977       sqlite3VdbeDequoteP3(v, -1);
1309c572ef7fSdanielk1977       break;
1310c572ef7fSdanielk1977     }
1311cce7d176Sdrh     case TK_NULL: {
13120f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1313cce7d176Sdrh       break;
1314cce7d176Sdrh     }
131550457896Sdrh     case TK_VARIABLE: {
13164adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1317895d7472Sdrh       if( pExpr->token.n>1 ){
1318895d7472Sdrh         sqlite3VdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
1319895d7472Sdrh       }
132050457896Sdrh       break;
132150457896Sdrh     }
13224e0cff60Sdrh     case TK_REGISTER: {
13234e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
13244e0cff60Sdrh       break;
13254e0cff60Sdrh     }
1326c9b84a1fSdrh     case TK_LT:
1327c9b84a1fSdrh     case TK_LE:
1328c9b84a1fSdrh     case TK_GT:
1329c9b84a1fSdrh     case TK_GE:
1330c9b84a1fSdrh     case TK_NE:
1331c9b84a1fSdrh     case TK_EQ: {
1332f2bc013cSdrh       assert( TK_LT==OP_Lt );
1333f2bc013cSdrh       assert( TK_LE==OP_Le );
1334f2bc013cSdrh       assert( TK_GT==OP_Gt );
1335f2bc013cSdrh       assert( TK_GE==OP_Ge );
1336f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1337f2bc013cSdrh       assert( TK_NE==OP_Ne );
1338a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1339a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1340be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1341a37cdde0Sdanielk1977       break;
1342c9b84a1fSdrh     }
1343cce7d176Sdrh     case TK_AND:
1344cce7d176Sdrh     case TK_OR:
1345cce7d176Sdrh     case TK_PLUS:
1346cce7d176Sdrh     case TK_STAR:
1347cce7d176Sdrh     case TK_MINUS:
1348bf4133cbSdrh     case TK_REM:
1349bf4133cbSdrh     case TK_BITAND:
1350bf4133cbSdrh     case TK_BITOR:
135117c40294Sdrh     case TK_SLASH:
1352bf4133cbSdrh     case TK_LSHIFT:
1353855eb1cfSdrh     case TK_RSHIFT:
13540040077dSdrh     case TK_CONCAT: {
1355f2bc013cSdrh       assert( TK_AND==OP_And );
1356f2bc013cSdrh       assert( TK_OR==OP_Or );
1357f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1358f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1359f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1360f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1361f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1362f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1363f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1364f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1365f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
13664adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
13674adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1368855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
13690040077dSdrh       break;
13700040077dSdrh     }
1371cce7d176Sdrh     case TK_UMINUS: {
1372fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1373fec19aadSdrh       assert( pLeft );
1374fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1375fec19aadSdrh         Token *p = &pLeft->token;
13766e142f54Sdrh         char *z = sqliteMalloc( p->n + 2 );
13776e142f54Sdrh         sprintf(z, "-%.*s", p->n, p->z);
1378fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1379fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1380e6840900Sdrh         }else{
1381fec19aadSdrh           codeInteger(v, z, p->n+1);
1382e6840900Sdrh         }
13836e142f54Sdrh         sqliteFree(z);
13846e142f54Sdrh         break;
13856e142f54Sdrh       }
13861ccde15dSdrh       /* Fall through into TK_NOT */
13876e142f54Sdrh     }
1388bf4133cbSdrh     case TK_BITNOT:
13896e142f54Sdrh     case TK_NOT: {
1390f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1391f2bc013cSdrh       assert( TK_NOT==OP_Not );
13924adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
13934adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1394cce7d176Sdrh       break;
1395cce7d176Sdrh     }
1396cce7d176Sdrh     case TK_ISNULL:
1397cce7d176Sdrh     case TK_NOTNULL: {
1398cce7d176Sdrh       int dest;
1399f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1400f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
14014adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
14024adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
14034adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
14044adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
14054adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1406a37cdde0Sdanielk1977       break;
1407f2bc013cSdrh     }
14082282792aSdrh     case TK_AGG_FUNCTION: {
14094adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
14102282792aSdrh       break;
14112282792aSdrh     }
14127977a17fSdanielk1977     case TK_CDATE:
14137977a17fSdanielk1977     case TK_CTIME:
14147977a17fSdanielk1977     case TK_CTIMESTAMP:
14154b59ab5eSdrh     case TK_GLOB:
14164b59ab5eSdrh     case TK_LIKE:
1417cce7d176Sdrh     case TK_FUNCTION: {
1418cce7d176Sdrh       ExprList *pList = pExpr->pList;
141989425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
14200bce8354Sdrh       FuncDef *pDef;
14214b59ab5eSdrh       int nId;
14224b59ab5eSdrh       const char *zId;
1423682f68b0Sdanielk1977       int p2 = 0;
1424682f68b0Sdanielk1977       int i;
1425d8123366Sdanielk1977       u8 enc = pParse->db->enc;
1426dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
14274b59ab5eSdrh       getFunctionName(pExpr, &zId, &nId);
1428d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
14290bce8354Sdrh       assert( pDef!=0 );
1430f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1431682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1432d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
1433d02eb1fdSdanielk1977           p2 |= (1<<i);
1434d02eb1fdSdanielk1977         }
1435dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1436dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1437dc1bdc4fSdanielk1977         }
1438dc1bdc4fSdanielk1977       }
1439dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1440dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1441d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1442682f68b0Sdanielk1977       }
1443682f68b0Sdanielk1977       sqlite3VdbeOp3(v, OP_Function, nExpr, p2, (char*)pDef, P3_FUNCDEF);
14446ec2733bSdrh       break;
14456ec2733bSdrh     }
144619a775c2Sdrh     case TK_SELECT: {
14474adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1448ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
144919a775c2Sdrh       break;
145019a775c2Sdrh     }
1451fef5208cSdrh     case TK_IN: {
1452fef5208cSdrh       int addr;
145394a11211Sdrh       char affinity;
1454e014a838Sdanielk1977 
1455e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1456e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1457ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1458e014a838Sdanielk1977       */
145994a11211Sdrh       affinity = comparisonAffinity(pExpr);
1460e014a838Sdanielk1977 
14614adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1462e014a838Sdanielk1977 
1463e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1464e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1465e014a838Sdanielk1977       */
14664adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
14674adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1468e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
14694adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
14700f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1471e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
147294a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
1473e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1474e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1475e014a838Sdanielk1977 
1476fef5208cSdrh       break;
1477fef5208cSdrh     }
1478fef5208cSdrh     case TK_BETWEEN: {
1479be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1480be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1481be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1482be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
14834adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1484be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1485be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
14864adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1487be5c89acSdrh       pLItem++;
1488be5c89acSdrh       pRight = pLItem->pExpr;
1489be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1490be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
14914adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1492fef5208cSdrh       break;
1493fef5208cSdrh     }
149451e9a445Sdrh     case TK_UPLUS:
1495a2e00042Sdrh     case TK_AS: {
14964adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1497a2e00042Sdrh       break;
1498a2e00042Sdrh     }
149917a7f8ddSdrh     case TK_CASE: {
150017a7f8ddSdrh       int expr_end_label;
1501f5905aa7Sdrh       int jumpInst;
1502f5905aa7Sdrh       int addr;
1503f5905aa7Sdrh       int nExpr;
150417a7f8ddSdrh       int i;
1505be5c89acSdrh       ExprList *pEList;
1506be5c89acSdrh       struct ExprList_item *aListelem;
150717a7f8ddSdrh 
150817a7f8ddSdrh       assert(pExpr->pList);
150917a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
151017a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1511be5c89acSdrh       pEList = pExpr->pList;
1512be5c89acSdrh       aListelem = pEList->a;
1513be5c89acSdrh       nExpr = pEList->nExpr;
15144adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
151517a7f8ddSdrh       if( pExpr->pLeft ){
15164adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1517cce7d176Sdrh       }
1518f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1519be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
152017a7f8ddSdrh         if( pExpr->pLeft ){
15214adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1522be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1523be5c89acSdrh                                  OP_Ne, 0, 1);
15244adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1525f5905aa7Sdrh         }else{
15264adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
152717a7f8ddSdrh         }
1528be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
15294adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
15304adee20fSdanielk1977         addr = sqlite3VdbeCurrentAddr(v);
15314adee20fSdanielk1977         sqlite3VdbeChangeP2(v, jumpInst, addr);
153217a7f8ddSdrh       }
1533f570f011Sdrh       if( pExpr->pLeft ){
15344adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1535f570f011Sdrh       }
153617a7f8ddSdrh       if( pExpr->pRight ){
15374adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
153817a7f8ddSdrh       }else{
15390f69c1e3Sdanielk1977         sqlite3VdbeAddOp(v, OP_String8, 0, 0);
154017a7f8ddSdrh       }
15414adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
15426f34903eSdanielk1977       break;
15436f34903eSdanielk1977     }
15446f34903eSdanielk1977     case TK_RAISE: {
15456f34903eSdanielk1977       if( !pParse->trigStack ){
15464adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1547da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
15486f34903eSdanielk1977 	return;
15496f34903eSdanielk1977       }
1550ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
1551ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
15526f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
1553ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
15544adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
1555701a0aebSdrh                         pExpr->token.z, pExpr->token.n);
15564adee20fSdanielk1977          sqlite3VdbeDequoteP3(v, -1);
15576f34903eSdanielk1977       } else {
15586f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
1559344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
1560ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
1561ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
15626f34903eSdanielk1977       }
156317a7f8ddSdrh     }
156417a7f8ddSdrh     break;
156517a7f8ddSdrh   }
1566cce7d176Sdrh }
1567cce7d176Sdrh 
1568cce7d176Sdrh /*
156925303780Sdrh ** Generate code that evalutes the given expression and leaves the result
157025303780Sdrh ** on the stack.  See also sqlite3ExprCode().
157125303780Sdrh **
157225303780Sdrh ** This routine might also cache the result and modify the pExpr tree
157325303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
157425303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
157525303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
157625303780Sdrh ** memory location.
157725303780Sdrh */
157825303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
157925303780Sdrh   Vdbe *v = pParse->pVdbe;
158025303780Sdrh   int iMem;
158125303780Sdrh   int addr1, addr2;
158225303780Sdrh   if( v==0 ) return;
158325303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
158425303780Sdrh   sqlite3ExprCode(pParse, pExpr);
158525303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
158625303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
158725303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
158825303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
158925303780Sdrh     pExpr->op = TK_REGISTER;
159025303780Sdrh   }
159125303780Sdrh }
159225303780Sdrh 
159325303780Sdrh /*
1594268380caSdrh ** Generate code that pushes the value of every element of the given
1595f9b596ebSdrh ** expression list onto the stack.
1596268380caSdrh **
1597268380caSdrh ** Return the number of elements pushed onto the stack.
1598268380caSdrh */
15994adee20fSdanielk1977 int sqlite3ExprCodeExprList(
1600268380caSdrh   Parse *pParse,     /* Parsing context */
1601f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
1602268380caSdrh ){
1603268380caSdrh   struct ExprList_item *pItem;
1604268380caSdrh   int i, n;
1605268380caSdrh   Vdbe *v;
1606268380caSdrh   if( pList==0 ) return 0;
16074adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1608268380caSdrh   n = pList->nExpr;
1609268380caSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
16104adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
1611268380caSdrh   }
1612f9b596ebSdrh   return n;
1613268380caSdrh }
1614268380caSdrh 
1615268380caSdrh /*
1616cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
1617cce7d176Sdrh ** to the label "dest" if the expression is true but execution
1618cce7d176Sdrh ** continues straight thru if the expression is false.
1619f5905aa7Sdrh **
1620f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
1621f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
1622f2bc013cSdrh **
1623f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1624f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1625f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1626f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1627f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1628cce7d176Sdrh */
16294adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1630cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1631cce7d176Sdrh   int op = 0;
1632daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1633f2bc013cSdrh   op = pExpr->op;
1634f2bc013cSdrh   switch( op ){
1635cce7d176Sdrh     case TK_AND: {
16364adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
16374adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
16384adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
16394adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1640cce7d176Sdrh       break;
1641cce7d176Sdrh     }
1642cce7d176Sdrh     case TK_OR: {
16434adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
16444adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1645cce7d176Sdrh       break;
1646cce7d176Sdrh     }
1647cce7d176Sdrh     case TK_NOT: {
16484adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1649cce7d176Sdrh       break;
1650cce7d176Sdrh     }
1651cce7d176Sdrh     case TK_LT:
1652cce7d176Sdrh     case TK_LE:
1653cce7d176Sdrh     case TK_GT:
1654cce7d176Sdrh     case TK_GE:
1655cce7d176Sdrh     case TK_NE:
16560ac65892Sdrh     case TK_EQ: {
1657f2bc013cSdrh       assert( TK_LT==OP_Lt );
1658f2bc013cSdrh       assert( TK_LE==OP_Le );
1659f2bc013cSdrh       assert( TK_GT==OP_Gt );
1660f2bc013cSdrh       assert( TK_GE==OP_Ge );
1661f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1662f2bc013cSdrh       assert( TK_NE==OP_Ne );
16634adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16644adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1665be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
1666cce7d176Sdrh       break;
1667cce7d176Sdrh     }
1668cce7d176Sdrh     case TK_ISNULL:
1669cce7d176Sdrh     case TK_NOTNULL: {
1670f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1671f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
16724adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16734adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
1674cce7d176Sdrh       break;
1675cce7d176Sdrh     }
1676fef5208cSdrh     case TK_BETWEEN: {
16770202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
16780202b29eSdanielk1977       **
16790202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
16800202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
16810202b29eSdanielk1977       ** 3 ...
16820202b29eSdanielk1977       */
1683f5905aa7Sdrh       int addr;
1684be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1685be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
1686be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
16874adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1688be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1689be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
16900202b29eSdanielk1977 
1691be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
1692be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1693be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
16940202b29eSdanielk1977 
16954adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
16964adee20fSdanielk1977       sqlite3VdbeChangeP2(v, addr, sqlite3VdbeCurrentAddr(v));
16974adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1698fef5208cSdrh       break;
1699fef5208cSdrh     }
1700cce7d176Sdrh     default: {
17014adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
17024adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
1703cce7d176Sdrh       break;
1704cce7d176Sdrh     }
1705cce7d176Sdrh   }
1706cce7d176Sdrh }
1707cce7d176Sdrh 
1708cce7d176Sdrh /*
170966b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
1710cce7d176Sdrh ** to the label "dest" if the expression is false but execution
1711cce7d176Sdrh ** continues straight thru if the expression is true.
1712f5905aa7Sdrh **
1713f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
1714f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
1715cce7d176Sdrh */
17164adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1717cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1718cce7d176Sdrh   int op = 0;
1719daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1720f2bc013cSdrh 
1721f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
1722f2bc013cSdrh   **
1723f2bc013cSdrh   **       pExpr->op            op
1724f2bc013cSdrh   **       ---------          ----------
1725f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
1726f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
1727f2bc013cSdrh   **       TK_NE              OP_Eq
1728f2bc013cSdrh   **       TK_EQ              OP_Ne
1729f2bc013cSdrh   **       TK_GT              OP_Le
1730f2bc013cSdrh   **       TK_LE              OP_Gt
1731f2bc013cSdrh   **       TK_GE              OP_Lt
1732f2bc013cSdrh   **       TK_LT              OP_Ge
1733f2bc013cSdrh   **
1734f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
1735f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
1736f2bc013cSdrh   ** can compute the mapping above using the following expression.
1737f2bc013cSdrh   ** Assert()s verify that the computation is correct.
1738f2bc013cSdrh   */
1739f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
1740f2bc013cSdrh 
1741f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
1742f2bc013cSdrh   */
1743f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
1744f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
1745f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
1746f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
1747f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
1748f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
1749f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
1750f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
1751f2bc013cSdrh 
1752cce7d176Sdrh   switch( pExpr->op ){
1753cce7d176Sdrh     case TK_AND: {
17544adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
17554adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
1756cce7d176Sdrh       break;
1757cce7d176Sdrh     }
1758cce7d176Sdrh     case TK_OR: {
17594adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
17604adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
17614adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
17624adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1763cce7d176Sdrh       break;
1764cce7d176Sdrh     }
1765cce7d176Sdrh     case TK_NOT: {
17664adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
1767cce7d176Sdrh       break;
1768cce7d176Sdrh     }
1769cce7d176Sdrh     case TK_LT:
1770cce7d176Sdrh     case TK_LE:
1771cce7d176Sdrh     case TK_GT:
1772cce7d176Sdrh     case TK_GE:
1773cce7d176Sdrh     case TK_NE:
1774cce7d176Sdrh     case TK_EQ: {
17754adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17764adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1777be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
1778cce7d176Sdrh       break;
1779cce7d176Sdrh     }
1780cce7d176Sdrh     case TK_ISNULL:
1781cce7d176Sdrh     case TK_NOTNULL: {
17824adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17834adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
1784cce7d176Sdrh       break;
1785cce7d176Sdrh     }
1786fef5208cSdrh     case TK_BETWEEN: {
17870202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
17880202b29eSdanielk1977       **
17890202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
17900202b29eSdanielk1977       ** 2 GOTO <dest>
17910202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
17920202b29eSdanielk1977       */
1793fef5208cSdrh       int addr;
1794be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1795be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
1796be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
17974adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1798be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
17994adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1800be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
1801be5c89acSdrh 
18024adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
18034adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
1804be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
1805be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1806be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
1807fef5208cSdrh       break;
1808fef5208cSdrh     }
1809cce7d176Sdrh     default: {
18104adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
18114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
1812cce7d176Sdrh       break;
1813cce7d176Sdrh     }
1814cce7d176Sdrh   }
1815cce7d176Sdrh }
18162282792aSdrh 
18172282792aSdrh /*
18182282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
18192282792aSdrh ** if they are identical and return FALSE if they differ in any way.
18202282792aSdrh */
18214adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
18222282792aSdrh   int i;
18232282792aSdrh   if( pA==0 ){
18242282792aSdrh     return pB==0;
18252282792aSdrh   }else if( pB==0 ){
18262282792aSdrh     return 0;
18272282792aSdrh   }
18282282792aSdrh   if( pA->op!=pB->op ) return 0;
18294adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
18304adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
18312282792aSdrh   if( pA->pList ){
18322282792aSdrh     if( pB->pList==0 ) return 0;
18332282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
18342282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
18354adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
18362282792aSdrh         return 0;
18372282792aSdrh       }
18382282792aSdrh     }
18392282792aSdrh   }else if( pB->pList ){
18402282792aSdrh     return 0;
18412282792aSdrh   }
18422282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
18432f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
18442282792aSdrh   if( pA->token.z ){
18452282792aSdrh     if( pB->token.z==0 ) return 0;
18466977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
18474adee20fSdanielk1977     if( sqlite3StrNICmp(pA->token.z, pB->token.z, pB->token.n)!=0 ) return 0;
18482282792aSdrh   }
18492282792aSdrh   return 1;
18502282792aSdrh }
18512282792aSdrh 
18522282792aSdrh /*
18532282792aSdrh ** Add a new element to the pParse->aAgg[] array and return its index.
18542282792aSdrh */
18552282792aSdrh static int appendAggInfo(Parse *pParse){
18562282792aSdrh   if( (pParse->nAgg & 0x7)==0 ){
18572282792aSdrh     int amt = pParse->nAgg + 8;
18586d4abfbeSdrh     AggExpr *aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
18596d4abfbeSdrh     if( aAgg==0 ){
18602282792aSdrh       return -1;
18612282792aSdrh     }
18626d4abfbeSdrh     pParse->aAgg = aAgg;
18632282792aSdrh   }
18642282792aSdrh   memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
18652282792aSdrh   return pParse->nAgg++;
18662282792aSdrh }
18672282792aSdrh 
18682282792aSdrh /*
18692282792aSdrh ** Analyze the given expression looking for aggregate functions and
18702282792aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
18712282792aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
18722282792aSdrh **
18732282792aSdrh ** This routine should only be called after the expression has been
18744adee20fSdanielk1977 ** analyzed by sqlite3ExprResolveIds() and sqlite3ExprCheck().
18752282792aSdrh **
18762282792aSdrh ** If errors are seen, leave an error message in zErrMsg and return
18772282792aSdrh ** the number of errors.
18782282792aSdrh */
18794adee20fSdanielk1977 int sqlite3ExprAnalyzeAggregates(Parse *pParse, Expr *pExpr){
18802282792aSdrh   int i;
18812282792aSdrh   AggExpr *aAgg;
18822282792aSdrh   int nErr = 0;
18832282792aSdrh 
18842282792aSdrh   if( pExpr==0 ) return 0;
18852282792aSdrh   switch( pExpr->op ){
1886967e8b73Sdrh     case TK_COLUMN: {
18872282792aSdrh       aAgg = pParse->aAgg;
18882282792aSdrh       for(i=0; i<pParse->nAgg; i++){
18892282792aSdrh         if( aAgg[i].isAgg ) continue;
18902282792aSdrh         if( aAgg[i].pExpr->iTable==pExpr->iTable
1891967e8b73Sdrh          && aAgg[i].pExpr->iColumn==pExpr->iColumn ){
18922282792aSdrh           break;
18932282792aSdrh         }
18942282792aSdrh       }
18952282792aSdrh       if( i>=pParse->nAgg ){
18962282792aSdrh         i = appendAggInfo(pParse);
18972282792aSdrh         if( i<0 ) return 1;
18982282792aSdrh         pParse->aAgg[i].isAgg = 0;
18992282792aSdrh         pParse->aAgg[i].pExpr = pExpr;
19002282792aSdrh       }
1901aaf88729Sdrh       pExpr->iAgg = i;
19022282792aSdrh       break;
19032282792aSdrh     }
19042282792aSdrh     case TK_AGG_FUNCTION: {
19052282792aSdrh       aAgg = pParse->aAgg;
19062282792aSdrh       for(i=0; i<pParse->nAgg; i++){
19072282792aSdrh         if( !aAgg[i].isAgg ) continue;
19084adee20fSdanielk1977         if( sqlite3ExprCompare(aAgg[i].pExpr, pExpr) ){
19092282792aSdrh           break;
19102282792aSdrh         }
19112282792aSdrh       }
19122282792aSdrh       if( i>=pParse->nAgg ){
1913d8123366Sdanielk1977         u8 enc = pParse->db->enc;
19142282792aSdrh         i = appendAggInfo(pParse);
19152282792aSdrh         if( i<0 ) return 1;
19162282792aSdrh         pParse->aAgg[i].isAgg = 1;
19172282792aSdrh         pParse->aAgg[i].pExpr = pExpr;
19184adee20fSdanielk1977         pParse->aAgg[i].pFunc = sqlite3FindFunction(pParse->db,
19196977fea8Sdrh              pExpr->token.z, pExpr->token.n,
1920d8123366Sdanielk1977              pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
19212282792aSdrh       }
19222282792aSdrh       pExpr->iAgg = i;
19232282792aSdrh       break;
19242282792aSdrh     }
19252282792aSdrh     default: {
19262282792aSdrh       if( pExpr->pLeft ){
19274adee20fSdanielk1977         nErr = sqlite3ExprAnalyzeAggregates(pParse, pExpr->pLeft);
19282282792aSdrh       }
19292282792aSdrh       if( nErr==0 && pExpr->pRight ){
19304adee20fSdanielk1977         nErr = sqlite3ExprAnalyzeAggregates(pParse, pExpr->pRight);
19312282792aSdrh       }
19322282792aSdrh       if( nErr==0 && pExpr->pList ){
19332282792aSdrh         int n = pExpr->pList->nExpr;
19342282792aSdrh         int i;
19352282792aSdrh         for(i=0; nErr==0 && i<n; i++){
19364adee20fSdanielk1977           nErr = sqlite3ExprAnalyzeAggregates(pParse, pExpr->pList->a[i].pExpr);
19372282792aSdrh         }
19382282792aSdrh       }
19392282792aSdrh       break;
19402282792aSdrh     }
19412282792aSdrh   }
19422282792aSdrh   return nErr;
19432282792aSdrh }
19448e0a2f90Sdrh 
19458e0a2f90Sdrh /*
1946d02eb1fdSdanielk1977 ** Locate a user function given a name, a number of arguments and a flag
1947d02eb1fdSdanielk1977 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
1948d02eb1fdSdanielk1977 ** pointer to the FuncDef structure that defines that function, or return
1949d02eb1fdSdanielk1977 ** NULL if the function does not exist.
19508e0a2f90Sdrh **
19510bce8354Sdrh ** If the createFlag argument is true, then a new (blank) FuncDef
19528e0a2f90Sdrh ** structure is created and liked into the "db" structure if a
19538e0a2f90Sdrh ** no matching function previously existed.  When createFlag is true
19548e0a2f90Sdrh ** and the nArg parameter is -1, then only a function that accepts
19558e0a2f90Sdrh ** any number of arguments will be returned.
19568e0a2f90Sdrh **
19578e0a2f90Sdrh ** If createFlag is false and nArg is -1, then the first valid
19588e0a2f90Sdrh ** function found is returned.  A function is valid if either xFunc
19598e0a2f90Sdrh ** or xStep is non-zero.
1960d02eb1fdSdanielk1977 **
1961d02eb1fdSdanielk1977 ** If createFlag is false, then a function with the required name and
1962d02eb1fdSdanielk1977 ** number of arguments may be returned even if the eTextRep flag does not
1963d02eb1fdSdanielk1977 ** match that requested.
19648e0a2f90Sdrh */
19654adee20fSdanielk1977 FuncDef *sqlite3FindFunction(
19669bb575fdSdrh   sqlite3 *db,       /* An open database */
19678e0a2f90Sdrh   const char *zName, /* Name of the function.  Not null-terminated */
19688e0a2f90Sdrh   int nName,         /* Number of characters in the name */
19698e0a2f90Sdrh   int nArg,          /* Number of arguments.  -1 means any number */
1970d8123366Sdanielk1977   u8 enc,            /* Preferred text encoding */
19718e0a2f90Sdrh   int createFlag     /* Create new entry if true and does not otherwise exist */
19728e0a2f90Sdrh ){
1973d02eb1fdSdanielk1977   FuncDef *p;         /* Iterator variable */
1974d02eb1fdSdanielk1977   FuncDef *pFirst;    /* First function with this name */
1975d02eb1fdSdanielk1977   FuncDef *pBest = 0; /* Best match found so far */
1976d8123366Sdanielk1977   int bestmatch = 0;
1977d02eb1fdSdanielk1977 
1978d8123366Sdanielk1977 
1979d8123366Sdanielk1977   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
1980d02eb1fdSdanielk1977   if( nArg<-1 ) nArg = -1;
1981d02eb1fdSdanielk1977 
1982d02eb1fdSdanielk1977   pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
1983d02eb1fdSdanielk1977   for(p=pFirst; p; p=p->pNext){
1984d8123366Sdanielk1977     /* During the search for the best function definition, bestmatch is set
1985d8123366Sdanielk1977     ** as follows to indicate the quality of the match with the definition
1986d8123366Sdanielk1977     ** pointed to by pBest:
1987d8123366Sdanielk1977     **
1988d8123366Sdanielk1977     ** 0: pBest is NULL. No match has been found.
1989d8123366Sdanielk1977     ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
1990d8123366Sdanielk1977     **    encoding is requested, or vice versa.
1991d8123366Sdanielk1977     ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
1992d8123366Sdanielk1977     **    requested, or vice versa.
1993d8123366Sdanielk1977     ** 3: A variable arguments function using the same text encoding.
1994d8123366Sdanielk1977     ** 4: A function with the exact number of arguments requested that
1995d8123366Sdanielk1977     **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
1996d8123366Sdanielk1977     ** 5: A function with the exact number of arguments requested that
1997d8123366Sdanielk1977     **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
1998d8123366Sdanielk1977     ** 6: An exact match.
1999d8123366Sdanielk1977     **
2000d8123366Sdanielk1977     ** A larger value of 'matchqual' indicates a more desirable match.
2001d8123366Sdanielk1977     */
2002e12c17baSdanielk1977     if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
2003d8123366Sdanielk1977       int match = 1;          /* Quality of this match */
2004d8123366Sdanielk1977       if( p->nArg==nArg || nArg==-1 ){
2005d8123366Sdanielk1977         match = 4;
20068e0a2f90Sdrh       }
2007d8123366Sdanielk1977       if( enc==p->iPrefEnc ){
2008d8123366Sdanielk1977         match += 2;
20098e0a2f90Sdrh       }
2010d8123366Sdanielk1977       else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
2011d8123366Sdanielk1977                (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
2012d8123366Sdanielk1977         match += 1;
2013d02eb1fdSdanielk1977       }
2014d8123366Sdanielk1977 
2015d8123366Sdanielk1977       if( match>bestmatch ){
2016d02eb1fdSdanielk1977         pBest = p;
2017d8123366Sdanielk1977         bestmatch = match;
2018d02eb1fdSdanielk1977       }
2019d02eb1fdSdanielk1977     }
2020d02eb1fdSdanielk1977   }
2021d02eb1fdSdanielk1977 
2022d8123366Sdanielk1977   /* If the createFlag parameter is true, and the seach did not reveal an
2023d8123366Sdanielk1977   ** exact match for the name, number of arguments and encoding, then add a
2024d8123366Sdanielk1977   ** new entry to the hash table and return it.
2025d8123366Sdanielk1977   */
2026d8123366Sdanielk1977   if( createFlag && bestmatch<6 &&
2027d02eb1fdSdanielk1977       (pBest = sqliteMalloc(sizeof(*pBest)+nName+1)) ){
2028d02eb1fdSdanielk1977     pBest->nArg = nArg;
2029d02eb1fdSdanielk1977     pBest->pNext = pFirst;
2030d02eb1fdSdanielk1977     pBest->zName = (char*)&pBest[1];
2031d8123366Sdanielk1977     pBest->iPrefEnc = enc;
2032d02eb1fdSdanielk1977     memcpy(pBest->zName, zName, nName);
2033d02eb1fdSdanielk1977     pBest->zName[nName] = 0;
2034*2c336549Sdanielk1977     if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
2035*2c336549Sdanielk1977       sqliteFree(pBest);
2036*2c336549Sdanielk1977       return 0;
2037*2c336549Sdanielk1977     }
2038d02eb1fdSdanielk1977   }
2039d02eb1fdSdanielk1977 
2040d02eb1fdSdanielk1977   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
2041d02eb1fdSdanielk1977     return pBest;
2042d02eb1fdSdanielk1977   }
20438e0a2f90Sdrh   return 0;
20448e0a2f90Sdrh }
2045