xref: /sqlite-3.40.0/src/expr.c (revision 9bb575fd)
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*9bb575fdSdrh ** $Id: expr.c,v 1.160 2004/09/06 17:24:13 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
1804738cb9Sdrh #include <ctype.h>
19a2e00042Sdrh 
20e014a838Sdanielk1977 char const *sqlite3AffinityString(char affinity){
21e014a838Sdanielk1977   switch( affinity ){
22e014a838Sdanielk1977     case SQLITE_AFF_INTEGER: return "i";
23e014a838Sdanielk1977     case SQLITE_AFF_NUMERIC: return "n";
24e014a838Sdanielk1977     case SQLITE_AFF_TEXT:    return "t";
25e014a838Sdanielk1977     case SQLITE_AFF_NONE:    return "o";
26e014a838Sdanielk1977     default:
27e014a838Sdanielk1977       assert(0);
28e014a838Sdanielk1977   }
29e0d4b060Sdanielk1977   return 0;
30e014a838Sdanielk1977 }
31e014a838Sdanielk1977 
32e014a838Sdanielk1977 
33e014a838Sdanielk1977 /*
34e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
35e014a838Sdanielk1977 **
36e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
37e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
38e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
39e014a838Sdanielk1977 ** indicating no affinity for the expression.
40e014a838Sdanielk1977 **
41e014a838Sdanielk1977 ** i.e. the WHERE clause expresssions in the following statements all
42e014a838Sdanielk1977 ** have an affinity:
43e014a838Sdanielk1977 **
44e014a838Sdanielk1977 ** CREATE TABLE t1(a);
45e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
46e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
47e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
48e014a838Sdanielk1977 */
49bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
50a37cdde0Sdanielk1977   if( pExpr->op==TK_AS ){
51bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pLeft);
52a37cdde0Sdanielk1977   }
53a37cdde0Sdanielk1977   if( pExpr->op==TK_SELECT ){
54bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
55a37cdde0Sdanielk1977   }
56a37cdde0Sdanielk1977   return pExpr->affinity;
57a37cdde0Sdanielk1977 }
58a37cdde0Sdanielk1977 
5953db1458Sdrh /*
600202b29eSdanielk1977 ** Return the default collation sequence for the expression pExpr. If
610202b29eSdanielk1977 ** there is no default collation type, return 0.
620202b29eSdanielk1977 */
637cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
647cedc8d4Sdanielk1977   CollSeq *pColl = 0;
650202b29eSdanielk1977   if( pExpr ){
667cedc8d4Sdanielk1977     pColl = pExpr->pColl;
677cedc8d4Sdanielk1977     if( pExpr->op==TK_AS && !pColl ){
687cedc8d4Sdanielk1977       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
690202b29eSdanielk1977     }
700202b29eSdanielk1977   }
717cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
727cedc8d4Sdanielk1977     pColl = 0;
737cedc8d4Sdanielk1977   }
747cedc8d4Sdanielk1977   return pColl;
750202b29eSdanielk1977 }
760202b29eSdanielk1977 
770202b29eSdanielk1977 /*
7853db1458Sdrh ** pExpr is the left operand of a comparison operator.  aff2 is the
7953db1458Sdrh ** type affinity of the right operand.  This routine returns the
8053db1458Sdrh ** type affinity that should be used for the comparison operator.
8153db1458Sdrh */
82e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
83bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
84e014a838Sdanielk1977   if( aff1 && aff2 ){
85e014a838Sdanielk1977     /* Both sides of the comparison are columns. If one has numeric or
86e014a838Sdanielk1977     ** integer affinity, use that. Otherwise use no affinity.
87e014a838Sdanielk1977     */
88e014a838Sdanielk1977     if( aff1==SQLITE_AFF_INTEGER || aff2==SQLITE_AFF_INTEGER ){
89e014a838Sdanielk1977       return SQLITE_AFF_INTEGER;
90e014a838Sdanielk1977     }else if( aff1==SQLITE_AFF_NUMERIC || aff2==SQLITE_AFF_NUMERIC ){
91e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
92e014a838Sdanielk1977     }else{
93e014a838Sdanielk1977       return SQLITE_AFF_NONE;
94e014a838Sdanielk1977     }
95e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
965f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
975f6a87b3Sdrh     ** results directly.
98e014a838Sdanielk1977     */
995f6a87b3Sdrh     /* return SQLITE_AFF_NUMERIC;  // Ticket #805 */
1005f6a87b3Sdrh     return SQLITE_AFF_NONE;
101e014a838Sdanielk1977   }else{
102e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
103e014a838Sdanielk1977     return (aff1 + aff2);
104e014a838Sdanielk1977   }
105e014a838Sdanielk1977 }
106e014a838Sdanielk1977 
10753db1458Sdrh /*
10853db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
10953db1458Sdrh ** be applied to both operands prior to doing the comparison.
11053db1458Sdrh */
111e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
112e014a838Sdanielk1977   char aff;
113e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
114e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
115e014a838Sdanielk1977           pExpr->op==TK_NE );
116e014a838Sdanielk1977   assert( pExpr->pLeft );
117bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
118e014a838Sdanielk1977   if( pExpr->pRight ){
119e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
120e014a838Sdanielk1977   }
121e014a838Sdanielk1977   else if( pExpr->pSelect ){
122e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
123e014a838Sdanielk1977   }
124e014a838Sdanielk1977   else if( !aff ){
125e014a838Sdanielk1977     aff = SQLITE_AFF_NUMERIC;
126e014a838Sdanielk1977   }
127e014a838Sdanielk1977   return aff;
128e014a838Sdanielk1977 }
129e014a838Sdanielk1977 
130e014a838Sdanielk1977 /*
131e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
132e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
133e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
134e014a838Sdanielk1977 ** the comparison in pExpr.
135e014a838Sdanielk1977 */
136e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
137e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
138e014a838Sdanielk1977   return
139e014a838Sdanielk1977     (aff==SQLITE_AFF_NONE) ||
140e014a838Sdanielk1977     (aff==SQLITE_AFF_NUMERIC && idx_affinity==SQLITE_AFF_INTEGER) ||
141e014a838Sdanielk1977     (aff==SQLITE_AFF_INTEGER && idx_affinity==SQLITE_AFF_NUMERIC) ||
142e014a838Sdanielk1977     (aff==idx_affinity);
143e014a838Sdanielk1977 }
144e014a838Sdanielk1977 
145a37cdde0Sdanielk1977 /*
146a37cdde0Sdanielk1977 ** Return the P1 value that should be used for a binary comparison
147a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
148a37cdde0Sdanielk1977 ** If jumpIfNull is true, then set the low byte of the returned
149a37cdde0Sdanielk1977 ** P1 value to tell the opcode to jump if either expression
150a37cdde0Sdanielk1977 ** evaluates to NULL.
151a37cdde0Sdanielk1977 */
152e014a838Sdanielk1977 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
153bf3b721fSdanielk1977   char aff = sqlite3ExprAffinity(pExpr2);
154e014a838Sdanielk1977   return (((int)sqlite3CompareAffinity(pExpr1, aff))<<8)+(jumpIfNull?1:0);
155a37cdde0Sdanielk1977 }
156a37cdde0Sdanielk1977 
157a2e00042Sdrh /*
1580202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
1590202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
1600202b29eSdanielk1977 **
1610202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
1620202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
1630202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
1640202b29eSdanielk1977 ** type.
1650202b29eSdanielk1977 */
1667cedc8d4Sdanielk1977 static CollSeq* binaryCompareCollSeq(Parse *pParse, Expr *pLeft, Expr *pRight){
1677cedc8d4Sdanielk1977   CollSeq *pColl = sqlite3ExprCollSeq(pParse, pLeft);
1680202b29eSdanielk1977   if( !pColl ){
1697cedc8d4Sdanielk1977     pColl = sqlite3ExprCollSeq(pParse, pRight);
1700202b29eSdanielk1977   }
1710202b29eSdanielk1977   return pColl;
1720202b29eSdanielk1977 }
1730202b29eSdanielk1977 
1740202b29eSdanielk1977 /*
175be5c89acSdrh ** Generate code for a comparison operator.
176be5c89acSdrh */
177be5c89acSdrh static int codeCompare(
178be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
179be5c89acSdrh   Expr *pLeft,      /* The left operand */
180be5c89acSdrh   Expr *pRight,     /* The right operand */
181be5c89acSdrh   int opcode,       /* The comparison opcode */
182be5c89acSdrh   int dest,         /* Jump here if true.  */
183be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
184be5c89acSdrh ){
185be5c89acSdrh   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
186be5c89acSdrh   CollSeq *p3 = binaryCompareCollSeq(pParse, pLeft, pRight);
187be5c89acSdrh   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void *)p3, P3_COLLSEQ);
188be5c89acSdrh }
189be5c89acSdrh 
190be5c89acSdrh /*
191a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
192a76b5dfcSdrh ** for this node is obtained from sqliteMalloc().  The calling function
193a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
194a76b5dfcSdrh */
1954adee20fSdanielk1977 Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, Token *pToken){
196a76b5dfcSdrh   Expr *pNew;
197a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
198a76b5dfcSdrh   if( pNew==0 ){
1994efc4754Sdrh     /* When malloc fails, we leak memory from pLeft and pRight */
200a76b5dfcSdrh     return 0;
201a76b5dfcSdrh   }
202a76b5dfcSdrh   pNew->op = op;
203a76b5dfcSdrh   pNew->pLeft = pLeft;
204a76b5dfcSdrh   pNew->pRight = pRight;
205a76b5dfcSdrh   if( pToken ){
2064b59ab5eSdrh     assert( pToken->dyn==0 );
207a76b5dfcSdrh     pNew->token = *pToken;
2086977fea8Sdrh     pNew->span = *pToken;
209a76b5dfcSdrh   }else{
2104efc4754Sdrh     assert( pNew->token.dyn==0 );
2114efc4754Sdrh     assert( pNew->token.z==0 );
2124efc4754Sdrh     assert( pNew->token.n==0 );
2136977fea8Sdrh     if( pLeft && pRight ){
2144adee20fSdanielk1977       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
2156977fea8Sdrh     }else{
2166977fea8Sdrh       pNew->span = pNew->token;
2176977fea8Sdrh     }
218a76b5dfcSdrh   }
219a76b5dfcSdrh   return pNew;
220a76b5dfcSdrh }
221a76b5dfcSdrh 
222a76b5dfcSdrh /*
22391bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
22491bb0eedSdrh ** NULL, then just return the other expression.
22591bb0eedSdrh */
22691bb0eedSdrh Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
22791bb0eedSdrh   if( pLeft==0 ){
22891bb0eedSdrh     return pRight;
22991bb0eedSdrh   }else if( pRight==0 ){
23091bb0eedSdrh     return pLeft;
23191bb0eedSdrh   }else{
23291bb0eedSdrh     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
23391bb0eedSdrh   }
23491bb0eedSdrh }
23591bb0eedSdrh 
23691bb0eedSdrh /*
2376977fea8Sdrh ** Set the Expr.span field of the given expression to span all
238a76b5dfcSdrh ** text between the two given tokens.
239a76b5dfcSdrh */
2404adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
2414efc4754Sdrh   assert( pRight!=0 );
2424efc4754Sdrh   assert( pLeft!=0 );
24371c697efSdrh   if( !sqlite3_malloc_failed && pRight->z && pLeft->z ){
2444b59ab5eSdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
2456977fea8Sdrh       pExpr->span.z = pLeft->z;
2466977fea8Sdrh       pExpr->span.n = pRight->n + Addr(pRight->z) - Addr(pLeft->z);
2474b59ab5eSdrh     }else{
2486977fea8Sdrh       pExpr->span.z = 0;
2494b59ab5eSdrh     }
250a76b5dfcSdrh   }
251a76b5dfcSdrh }
252a76b5dfcSdrh 
253a76b5dfcSdrh /*
254a76b5dfcSdrh ** Construct a new expression node for a function with multiple
255a76b5dfcSdrh ** arguments.
256a76b5dfcSdrh */
2574adee20fSdanielk1977 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
258a76b5dfcSdrh   Expr *pNew;
259a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
260a76b5dfcSdrh   if( pNew==0 ){
2614adee20fSdanielk1977     /* sqlite3ExprListDelete(pList); // Leak pList when malloc fails */
262a76b5dfcSdrh     return 0;
263a76b5dfcSdrh   }
264a76b5dfcSdrh   pNew->op = TK_FUNCTION;
265a76b5dfcSdrh   pNew->pList = pList;
266a76b5dfcSdrh   if( pToken ){
2674b59ab5eSdrh     assert( pToken->dyn==0 );
268a76b5dfcSdrh     pNew->token = *pToken;
269a76b5dfcSdrh   }else{
270a76b5dfcSdrh     pNew->token.z = 0;
271a76b5dfcSdrh   }
2726977fea8Sdrh   pNew->span = pNew->token;
273a76b5dfcSdrh   return pNew;
274a76b5dfcSdrh }
275a76b5dfcSdrh 
276a76b5dfcSdrh /*
277a2e00042Sdrh ** Recursively delete an expression tree.
278a2e00042Sdrh */
2794adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
280a2e00042Sdrh   if( p==0 ) return;
2814efc4754Sdrh   if( p->span.dyn ) sqliteFree((char*)p->span.z);
2824efc4754Sdrh   if( p->token.dyn ) sqliteFree((char*)p->token.z);
2834adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
2844adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
2854adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
2864adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
287a2e00042Sdrh   sqliteFree(p);
288a2e00042Sdrh }
289a2e00042Sdrh 
290a76b5dfcSdrh 
291a76b5dfcSdrh /*
292ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
293ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
294ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
295ff78bd2fSdrh ** without effecting the originals.
296ff78bd2fSdrh **
2974adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
2984adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
299ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
300ff78bd2fSdrh **
301ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
302ff78bd2fSdrh */
3034adee20fSdanielk1977 Expr *sqlite3ExprDup(Expr *p){
304ff78bd2fSdrh   Expr *pNew;
305ff78bd2fSdrh   if( p==0 ) return 0;
306fcb78a49Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
307ff78bd2fSdrh   if( pNew==0 ) return 0;
3083b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
3096977fea8Sdrh   if( p->token.z!=0 ){
3104b59ab5eSdrh     pNew->token.z = sqliteStrDup(p->token.z);
3114b59ab5eSdrh     pNew->token.dyn = 1;
3124b59ab5eSdrh   }else{
3134efc4754Sdrh     assert( pNew->token.z==0 );
3144b59ab5eSdrh   }
3156977fea8Sdrh   pNew->span.z = 0;
3164adee20fSdanielk1977   pNew->pLeft = sqlite3ExprDup(p->pLeft);
3174adee20fSdanielk1977   pNew->pRight = sqlite3ExprDup(p->pRight);
3184adee20fSdanielk1977   pNew->pList = sqlite3ExprListDup(p->pList);
3194adee20fSdanielk1977   pNew->pSelect = sqlite3SelectDup(p->pSelect);
320ff78bd2fSdrh   return pNew;
321ff78bd2fSdrh }
3224adee20fSdanielk1977 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
3234b59ab5eSdrh   if( pTo->dyn ) sqliteFree((char*)pTo->z);
3244b59ab5eSdrh   if( pFrom->z ){
3254b59ab5eSdrh     pTo->n = pFrom->n;
3264b59ab5eSdrh     pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
3274b59ab5eSdrh     pTo->dyn = 1;
3284b59ab5eSdrh   }else{
3294b59ab5eSdrh     pTo->z = 0;
3304b59ab5eSdrh   }
3314b59ab5eSdrh }
3324adee20fSdanielk1977 ExprList *sqlite3ExprListDup(ExprList *p){
333ff78bd2fSdrh   ExprList *pNew;
3343e7bc9caSdrh   struct ExprList_item *pItem;
335ff78bd2fSdrh   int i;
336ff78bd2fSdrh   if( p==0 ) return 0;
337ff78bd2fSdrh   pNew = sqliteMalloc( sizeof(*pNew) );
338ff78bd2fSdrh   if( pNew==0 ) return 0;
3394305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
3403e7bc9caSdrh   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
341e0048400Sdanielk1977   if( pItem==0 ){
342e0048400Sdanielk1977     sqliteFree(pNew);
343e0048400Sdanielk1977     return 0;
344e0048400Sdanielk1977   }
3451bdd9b57Sdrh   for(i=0; i<p->nExpr; i++, pItem++){
3464b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
3474adee20fSdanielk1977     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = p->a[i].pExpr);
3486977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
3496977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
3504b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
3514b59ab5eSdrh       ** the names of columns in the result set needs this information */
3524adee20fSdanielk1977       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
3534b59ab5eSdrh     }
3541f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
35524b03fd0Sdanielk1977             || pOldExpr->span.z==0 || sqlite3_malloc_failed );
3563e7bc9caSdrh     pItem->zName = sqliteStrDup(p->a[i].zName);
3573e7bc9caSdrh     pItem->sortOrder = p->a[i].sortOrder;
3583e7bc9caSdrh     pItem->isAgg = p->a[i].isAgg;
3593e7bc9caSdrh     pItem->done = 0;
360ff78bd2fSdrh   }
361ff78bd2fSdrh   return pNew;
362ff78bd2fSdrh }
3634adee20fSdanielk1977 SrcList *sqlite3SrcListDup(SrcList *p){
364ad3cab52Sdrh   SrcList *pNew;
365ad3cab52Sdrh   int i;
366113088ecSdrh   int nByte;
367ad3cab52Sdrh   if( p==0 ) return 0;
368113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
3694efc4754Sdrh   pNew = sqliteMallocRaw( nByte );
370ad3cab52Sdrh   if( pNew==0 ) return 0;
3714305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
372ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
3734efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
3744efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
3754efc4754Sdrh     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
3764efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
3774efc4754Sdrh     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
3784efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
3794efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
3804efc4754Sdrh     pNewItem->pTab = 0;
3814adee20fSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
3824adee20fSdanielk1977     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
3834adee20fSdanielk1977     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
384ad3cab52Sdrh   }
385ad3cab52Sdrh   return pNew;
386ad3cab52Sdrh }
3874adee20fSdanielk1977 IdList *sqlite3IdListDup(IdList *p){
388ff78bd2fSdrh   IdList *pNew;
389ff78bd2fSdrh   int i;
390ff78bd2fSdrh   if( p==0 ) return 0;
3914efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*pNew) );
392ff78bd2fSdrh   if( pNew==0 ) return 0;
3934305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
3944efc4754Sdrh   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
395e4697f5eSdrh   if( pNew->a==0 ) return 0;
396ff78bd2fSdrh   for(i=0; i<p->nId; i++){
3974efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
3984efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
3994efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
4004efc4754Sdrh     pNewItem->idx = pOldItem->idx;
401ff78bd2fSdrh   }
402ff78bd2fSdrh   return pNew;
403ff78bd2fSdrh }
4044adee20fSdanielk1977 Select *sqlite3SelectDup(Select *p){
405ff78bd2fSdrh   Select *pNew;
406ff78bd2fSdrh   if( p==0 ) return 0;
4074efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
408ff78bd2fSdrh   if( pNew==0 ) return 0;
409ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
4104adee20fSdanielk1977   pNew->pEList = sqlite3ExprListDup(p->pEList);
4114adee20fSdanielk1977   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
4124adee20fSdanielk1977   pNew->pWhere = sqlite3ExprDup(p->pWhere);
4134adee20fSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
4144adee20fSdanielk1977   pNew->pHaving = sqlite3ExprDup(p->pHaving);
4154adee20fSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
416ff78bd2fSdrh   pNew->op = p->op;
4174adee20fSdanielk1977   pNew->pPrior = sqlite3SelectDup(p->pPrior);
418ff78bd2fSdrh   pNew->nLimit = p->nLimit;
419ff78bd2fSdrh   pNew->nOffset = p->nOffset;
420ff78bd2fSdrh   pNew->zSelect = 0;
4217b58daeaSdrh   pNew->iLimit = -1;
4227b58daeaSdrh   pNew->iOffset = -1;
423dc1bdc4fSdanielk1977   pNew->ppOpenTemp = 0;
424ff78bd2fSdrh   return pNew;
425ff78bd2fSdrh }
426ff78bd2fSdrh 
427ff78bd2fSdrh 
428ff78bd2fSdrh /*
429a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
430a76b5dfcSdrh ** initially NULL, then create a new expression list.
431a76b5dfcSdrh */
4324adee20fSdanielk1977 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
433a76b5dfcSdrh   if( pList==0 ){
434a76b5dfcSdrh     pList = sqliteMalloc( sizeof(ExprList) );
435a76b5dfcSdrh     if( pList==0 ){
4364adee20fSdanielk1977       /* sqlite3ExprDelete(pExpr); // Leak memory if malloc fails */
437a76b5dfcSdrh       return 0;
438a76b5dfcSdrh     }
4394efc4754Sdrh     assert( pList->nAlloc==0 );
440a76b5dfcSdrh   }
4414305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
4424305d103Sdrh     pList->nAlloc = pList->nAlloc*2 + 4;
4434efc4754Sdrh     pList->a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]));
4444efc4754Sdrh     if( pList->a==0 ){
4454adee20fSdanielk1977       /* sqlite3ExprDelete(pExpr); // Leak memory if malloc fails */
4464efc4754Sdrh       pList->nExpr = pList->nAlloc = 0;
447a76b5dfcSdrh       return pList;
448a76b5dfcSdrh     }
449a76b5dfcSdrh   }
4504efc4754Sdrh   assert( pList->a!=0 );
4514efc4754Sdrh   if( pExpr || pName ){
4524efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
4534efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
4544efc4754Sdrh     pItem->pExpr = pExpr;
455a99db3b6Sdrh     pItem->zName = sqlite3NameFromToken(pName);
456a76b5dfcSdrh   }
457a76b5dfcSdrh   return pList;
458a76b5dfcSdrh }
459a76b5dfcSdrh 
460a76b5dfcSdrh /*
461a76b5dfcSdrh ** Delete an entire expression list.
462a76b5dfcSdrh */
4634adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
464a76b5dfcSdrh   int i;
465be5c89acSdrh   struct ExprList_item *pItem;
466a76b5dfcSdrh   if( pList==0 ) return;
4671bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
4681bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
469be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
470be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
471be5c89acSdrh     sqliteFree(pItem->zName);
472a76b5dfcSdrh   }
473a76b5dfcSdrh   sqliteFree(pList->a);
474a76b5dfcSdrh   sqliteFree(pList);
475a76b5dfcSdrh }
476a76b5dfcSdrh 
477a76b5dfcSdrh /*
478fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
479fef5208cSdrh ** and 0 if it involves variables.
4802398937bSdrh **
4812398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
4822398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
4832398937bSdrh ** a constant.
484fef5208cSdrh */
4854adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
486fef5208cSdrh   switch( p->op ){
487fef5208cSdrh     case TK_ID:
488967e8b73Sdrh     case TK_COLUMN:
489fef5208cSdrh     case TK_DOT:
4907bdc0c1dSdrh     case TK_FUNCTION:
491fef5208cSdrh       return 0;
4927bdc0c1dSdrh     case TK_NULL:
4932398937bSdrh     case TK_STRING:
494c572ef7fSdanielk1977     case TK_BLOB:
4959208643dSdrh     case TK_INTEGER:
4969208643dSdrh     case TK_FLOAT:
49750457896Sdrh     case TK_VARIABLE:
4989208643dSdrh       return 1;
499fef5208cSdrh     default: {
5004adee20fSdanielk1977       if( p->pLeft && !sqlite3ExprIsConstant(p->pLeft) ) return 0;
5014adee20fSdanielk1977       if( p->pRight && !sqlite3ExprIsConstant(p->pRight) ) return 0;
502fef5208cSdrh       if( p->pList ){
503fef5208cSdrh         int i;
504fef5208cSdrh         for(i=0; i<p->pList->nExpr; i++){
5054adee20fSdanielk1977           if( !sqlite3ExprIsConstant(p->pList->a[i].pExpr) ) return 0;
506fef5208cSdrh         }
507fef5208cSdrh       }
5089208643dSdrh       return p->pLeft!=0 || p->pRight!=0 || (p->pList && p->pList->nExpr>0);
509fef5208cSdrh     }
510fef5208cSdrh   }
5119208643dSdrh   return 0;
512fef5208cSdrh }
513fef5208cSdrh 
514fef5208cSdrh /*
515202b2df7Sdrh ** If the given expression codes a constant integer that is small enough
516202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
517202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
518202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
519e4de1febSdrh */
5204adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
521e4de1febSdrh   switch( p->op ){
522e4de1febSdrh     case TK_INTEGER: {
523fec19aadSdrh       if( sqlite3GetInt32(p->token.z, pValue) ){
524e4de1febSdrh         return 1;
525e4de1febSdrh       }
526202b2df7Sdrh       break;
527202b2df7Sdrh     }
528e4de1febSdrh     case TK_STRING: {
5294c755c0fSdrh       const u8 *z = (u8*)p->token.z;
530e4de1febSdrh       int n = p->token.n;
531bd790ee3Sdrh       if( n>0 && z[0]=='-' ){ z++; n--; }
532e4de1febSdrh       while( n>0 && *z && isdigit(*z) ){ z++; n--; }
533fec19aadSdrh       if( n==0 && sqlite3GetInt32(p->token.z, pValue) ){
534e4de1febSdrh         return 1;
535e4de1febSdrh       }
536e4de1febSdrh       break;
537e4de1febSdrh     }
5384b59ab5eSdrh     case TK_UPLUS: {
5394adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
5404b59ab5eSdrh     }
541e4de1febSdrh     case TK_UMINUS: {
542e4de1febSdrh       int v;
5434adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
544e4de1febSdrh         *pValue = -v;
545e4de1febSdrh         return 1;
546e4de1febSdrh       }
547e4de1febSdrh       break;
548e4de1febSdrh     }
549e4de1febSdrh     default: break;
550e4de1febSdrh   }
551e4de1febSdrh   return 0;
552e4de1febSdrh }
553e4de1febSdrh 
554e4de1febSdrh /*
555c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
556c4a3c779Sdrh */
5574adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
5584adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
5594adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
5604adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
561c4a3c779Sdrh   return 0;
562c4a3c779Sdrh }
563c4a3c779Sdrh 
564c4a3c779Sdrh /*
5658141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
5668141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
5678141f61eSdrh ** expression node refer back to that source column.  The following changes
5688141f61eSdrh ** are made to pExpr:
5698141f61eSdrh **
5708141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
5718141f61eSdrh **                         the table.
5728141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
5738141f61eSdrh **                         from pSrcList.
5748141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
5758141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
5768141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
5778141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
5788141f61eSdrh **
5798141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
5808141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
5818141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
5828141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
5838141f61eSdrh ** means that the form of the name is Z and that columns from any table
5848141f61eSdrh ** can be used.
5858141f61eSdrh **
5868141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
5878141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
5888141f61eSdrh */
5898141f61eSdrh static int lookupName(
5908141f61eSdrh   Parse *pParse,      /* The parsing context */
5918141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
5928141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
5938141f61eSdrh   Token *pColumnToken, /* Name of the column. */
5948141f61eSdrh   SrcList *pSrcList,   /* List of tables used to resolve column names */
5958141f61eSdrh   ExprList *pEList,    /* List of expressions used to resolve "AS" */
5968141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
5978141f61eSdrh ){
5988141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
5998141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
6008141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
6018141f61eSdrh   int i, j;            /* Loop counters */
6028141f61eSdrh   int cnt = 0;         /* Number of matching column names */
6038141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
604*9bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
6058141f61eSdrh 
6068141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
607a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
608a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
609a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
61024b03fd0Sdanielk1977   if( sqlite3_malloc_failed ){
6118141f61eSdrh     return 1;  /* Leak memory (zDb and zTab) if malloc fails */
6128141f61eSdrh   }
6138141f61eSdrh   assert( zTab==0 || pEList==0 );
6148141f61eSdrh 
6158141f61eSdrh   pExpr->iTable = -1;
6168141f61eSdrh   for(i=0; i<pSrcList->nSrc; i++){
6178141f61eSdrh     struct SrcList_item *pItem = &pSrcList->a[i];
6188141f61eSdrh     Table *pTab = pItem->pTab;
6198141f61eSdrh     Column *pCol;
6208141f61eSdrh 
6218141f61eSdrh     if( pTab==0 ) continue;
6228141f61eSdrh     assert( pTab->nCol>0 );
6238141f61eSdrh     if( zTab ){
6248141f61eSdrh       if( pItem->zAlias ){
6258141f61eSdrh         char *zTabName = pItem->zAlias;
6264adee20fSdanielk1977         if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
6278141f61eSdrh       }else{
6288141f61eSdrh         char *zTabName = pTab->zName;
6294adee20fSdanielk1977         if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
6304adee20fSdanielk1977         if( zDb!=0 && sqlite3StrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
6318141f61eSdrh           continue;
6328141f61eSdrh         }
6338141f61eSdrh       }
6348141f61eSdrh     }
6358141f61eSdrh     if( 0==(cntTab++) ){
6368141f61eSdrh       pExpr->iTable = pItem->iCursor;
6378141f61eSdrh       pExpr->iDb = pTab->iDb;
6388141f61eSdrh     }
6398141f61eSdrh     for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
6404adee20fSdanielk1977       if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
6418141f61eSdrh         cnt++;
6428141f61eSdrh         pExpr->iTable = pItem->iCursor;
6438141f61eSdrh         pExpr->iDb = pTab->iDb;
6448141f61eSdrh         /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
6458141f61eSdrh         pExpr->iColumn = j==pTab->iPKey ? -1 : j;
646a37cdde0Sdanielk1977         pExpr->affinity = pTab->aCol[j].affinity;
6470202b29eSdanielk1977         pExpr->pColl = pTab->aCol[j].pColl;
6488141f61eSdrh         break;
6498141f61eSdrh       }
6508141f61eSdrh     }
6518141f61eSdrh   }
6528141f61eSdrh 
6538141f61eSdrh   /* If we have not already resolved the name, then maybe
6548141f61eSdrh   ** it is a new.* or old.* trigger argument reference
6558141f61eSdrh   */
6568141f61eSdrh   if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
6578141f61eSdrh     TriggerStack *pTriggerStack = pParse->trigStack;
6588141f61eSdrh     Table *pTab = 0;
6594adee20fSdanielk1977     if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
6608141f61eSdrh       pExpr->iTable = pTriggerStack->newIdx;
6618141f61eSdrh       assert( pTriggerStack->pTab );
6628141f61eSdrh       pTab = pTriggerStack->pTab;
6634adee20fSdanielk1977     }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab) == 0 ){
6648141f61eSdrh       pExpr->iTable = pTriggerStack->oldIdx;
6658141f61eSdrh       assert( pTriggerStack->pTab );
6668141f61eSdrh       pTab = pTriggerStack->pTab;
6678141f61eSdrh     }
6688141f61eSdrh 
6698141f61eSdrh     if( pTab ){
6708141f61eSdrh       int j;
6718141f61eSdrh       Column *pCol = pTab->aCol;
6728141f61eSdrh 
6738141f61eSdrh       pExpr->iDb = pTab->iDb;
6748141f61eSdrh       cntTab++;
6758141f61eSdrh       for(j=0; j < pTab->nCol; j++, pCol++) {
6764adee20fSdanielk1977         if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
6778141f61eSdrh           cnt++;
6788141f61eSdrh           pExpr->iColumn = j==pTab->iPKey ? -1 : j;
679a37cdde0Sdanielk1977           pExpr->affinity = pTab->aCol[j].affinity;
6800202b29eSdanielk1977           pExpr->pColl = pTab->aCol[j].pColl;
6818141f61eSdrh           break;
6828141f61eSdrh         }
6838141f61eSdrh       }
6848141f61eSdrh     }
6858141f61eSdrh   }
6868141f61eSdrh 
6878141f61eSdrh   /*
6888141f61eSdrh   ** Perhaps the name is a reference to the ROWID
6898141f61eSdrh   */
6904adee20fSdanielk1977   if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
6918141f61eSdrh     cnt = 1;
6928141f61eSdrh     pExpr->iColumn = -1;
693a37cdde0Sdanielk1977     pExpr->affinity = SQLITE_AFF_INTEGER;
6948141f61eSdrh   }
6958141f61eSdrh 
6968141f61eSdrh   /*
6978141f61eSdrh   ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
6988141f61eSdrh   ** might refer to an result-set alias.  This happens, for example, when
6998141f61eSdrh   ** we are resolving names in the WHERE clause of the following command:
7008141f61eSdrh   **
7018141f61eSdrh   **     SELECT a+b AS x FROM table WHERE x<10;
7028141f61eSdrh   **
7038141f61eSdrh   ** In cases like this, replace pExpr with a copy of the expression that
7048141f61eSdrh   ** forms the result set entry ("a+b" in the example) and return immediately.
7058141f61eSdrh   ** Note that the expression in the result set should have already been
7068141f61eSdrh   ** resolved by the time the WHERE clause is resolved.
7078141f61eSdrh   */
7088141f61eSdrh   if( cnt==0 && pEList!=0 ){
7098141f61eSdrh     for(j=0; j<pEList->nExpr; j++){
7108141f61eSdrh       char *zAs = pEList->a[j].zName;
7114adee20fSdanielk1977       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
7128141f61eSdrh         assert( pExpr->pLeft==0 && pExpr->pRight==0 );
7138141f61eSdrh         pExpr->op = TK_AS;
7148141f61eSdrh         pExpr->iColumn = j;
7154adee20fSdanielk1977         pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
7168141f61eSdrh         sqliteFree(zCol);
7178141f61eSdrh         assert( zTab==0 && zDb==0 );
7188141f61eSdrh         return 0;
7198141f61eSdrh       }
7208141f61eSdrh     }
7218141f61eSdrh   }
7228141f61eSdrh 
7238141f61eSdrh   /*
7248141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
7258141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
7268141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
7278141f61eSdrh   ** case, we need to return right away and not make any changes to
7288141f61eSdrh   ** pExpr.
7298141f61eSdrh   */
7308141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
7318141f61eSdrh     sqliteFree(zCol);
7328141f61eSdrh     return 0;
7338141f61eSdrh   }
7348141f61eSdrh 
7358141f61eSdrh   /*
7368141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
7378141f61eSdrh   ** more matches.  Either way, we have an error.
7388141f61eSdrh   */
7398141f61eSdrh   if( cnt!=1 ){
7408141f61eSdrh     char *z = 0;
7418141f61eSdrh     char *zErr;
7428141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
7438141f61eSdrh     if( zDb ){
7444adee20fSdanielk1977       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, 0);
7458141f61eSdrh     }else if( zTab ){
7464adee20fSdanielk1977       sqlite3SetString(&z, zTab, ".", zCol, 0);
7478141f61eSdrh     }else{
7488141f61eSdrh       z = sqliteStrDup(zCol);
7498141f61eSdrh     }
7504adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
7518141f61eSdrh     sqliteFree(z);
7528141f61eSdrh   }
7538141f61eSdrh 
7548141f61eSdrh   /* Clean up and return
7558141f61eSdrh   */
7568141f61eSdrh   sqliteFree(zDb);
7578141f61eSdrh   sqliteFree(zTab);
7588141f61eSdrh   sqliteFree(zCol);
7594adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
7608141f61eSdrh   pExpr->pLeft = 0;
7614adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
7628141f61eSdrh   pExpr->pRight = 0;
7638141f61eSdrh   pExpr->op = TK_COLUMN;
7644adee20fSdanielk1977   sqlite3AuthRead(pParse, pExpr, pSrcList);
7658141f61eSdrh   return cnt!=1;
7668141f61eSdrh }
7678141f61eSdrh 
7688141f61eSdrh /*
769cce7d176Sdrh ** This routine walks an expression tree and resolves references to
770967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
771aacc543eSdrh ** index to the table in the table list and a column offset.  The
772aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
773aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
774832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
775aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
776aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
777aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
778aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
779aacc543eSdrh ** alias for ROWID.
78019a775c2Sdrh **
781fef5208cSdrh ** We also check for instances of the IN operator.  IN comes in two
782fef5208cSdrh ** forms:
783fef5208cSdrh **
784fef5208cSdrh **           expr IN (exprlist)
785fef5208cSdrh ** and
786fef5208cSdrh **           expr IN (SELECT ...)
787fef5208cSdrh **
788fef5208cSdrh ** The first form is handled by creating a set holding the list
789fef5208cSdrh ** of allowed values.  The second form causes the SELECT to generate
790fef5208cSdrh ** a temporary table.
791fef5208cSdrh **
792fef5208cSdrh ** This routine also looks for scalar SELECTs that are part of an expression.
79319a775c2Sdrh ** If it finds any, it generates code to write the value of that select
79419a775c2Sdrh ** into a memory cell.
795cce7d176Sdrh **
796967e8b73Sdrh ** Unknown columns or tables provoke an error.  The function returns
797cce7d176Sdrh ** the number of errors seen and leaves an error message on pParse->zErrMsg.
798cce7d176Sdrh */
7994adee20fSdanielk1977 int sqlite3ExprResolveIds(
800a2e00042Sdrh   Parse *pParse,     /* The parser context */
8018141f61eSdrh   SrcList *pSrcList, /* List of tables used to resolve column names */
802a2e00042Sdrh   ExprList *pEList,  /* List of expressions used to resolve "AS" */
803a2e00042Sdrh   Expr *pExpr        /* The expression to be analyzed. */
804a2e00042Sdrh ){
8056a3ea0e6Sdrh   int i;
8066a3ea0e6Sdrh 
8078141f61eSdrh   if( pExpr==0 || pSrcList==0 ) return 0;
8088141f61eSdrh   for(i=0; i<pSrcList->nSrc; i++){
8098141f61eSdrh     assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab );
8106a3ea0e6Sdrh   }
811cce7d176Sdrh   switch( pExpr->op ){
8122398937bSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
8132398937bSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
8142398937bSdrh     ** strings (ex: 'abc') are always string literals.
8152398937bSdrh     */
8162398937bSdrh     case TK_STRING: {
8172398937bSdrh       if( pExpr->token.z[0]=='\'' ) break;
8182398937bSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
8192398937bSdrh     }
8208141f61eSdrh     /* A lone identifier is the name of a columnd.
821a2e00042Sdrh     */
822cce7d176Sdrh     case TK_ID: {
8238141f61eSdrh       if( lookupName(pParse, 0, 0, &pExpr->token, pSrcList, pEList, pExpr) ){
824cce7d176Sdrh         return 1;
825ed6c8671Sdrh       }
826cce7d176Sdrh       break;
827cce7d176Sdrh     }
828cce7d176Sdrh 
829d24cc427Sdrh     /* A table name and column name:     ID.ID
830d24cc427Sdrh     ** Or a database, table and column:  ID.ID.ID
831d24cc427Sdrh     */
832cce7d176Sdrh     case TK_DOT: {
8338141f61eSdrh       Token *pColumn;
8348141f61eSdrh       Token *pTable;
8358141f61eSdrh       Token *pDb;
8368141f61eSdrh       Expr *pRight;
837cce7d176Sdrh 
838cce7d176Sdrh       pRight = pExpr->pRight;
839d24cc427Sdrh       if( pRight->op==TK_ID ){
8408141f61eSdrh         pDb = 0;
8418141f61eSdrh         pTable = &pExpr->pLeft->token;
8428141f61eSdrh         pColumn = &pRight->token;
843d24cc427Sdrh       }else{
8448141f61eSdrh         assert( pRight->op==TK_DOT );
8458141f61eSdrh         pDb = &pExpr->pLeft->token;
8468141f61eSdrh         pTable = &pRight->pLeft->token;
8478141f61eSdrh         pColumn = &pRight->pRight->token;
848d24cc427Sdrh       }
8498141f61eSdrh       if( lookupName(pParse, pDb, pTable, pColumn, pSrcList, 0, pExpr) ){
850daffd0e5Sdrh         return 1;
851daffd0e5Sdrh       }
852cce7d176Sdrh       break;
853cce7d176Sdrh     }
854cce7d176Sdrh 
855fef5208cSdrh     case TK_IN: {
856e014a838Sdanielk1977       char affinity;
8574adee20fSdanielk1977       Vdbe *v = sqlite3GetVdbe(pParse);
858d3d39e93Sdrh       KeyInfo keyInfo;
8590202b29eSdanielk1977       int addr;        /* Address of OP_OpenTemp instruction */
860d3d39e93Sdrh 
861fef5208cSdrh       if( v==0 ) return 1;
8624adee20fSdanielk1977       if( sqlite3ExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
863cfab11bcSdrh         return 1;
864cfab11bcSdrh       }
865bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
866e014a838Sdanielk1977 
867e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
868e014a838Sdanielk1977       ** expression it is handled the same way. A temporary table is
869e014a838Sdanielk1977       ** filled with single-field index keys representing the results
870e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
871fef5208cSdrh       **
872e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
873e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
874e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
875e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
876e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
877e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
878e014a838Sdanielk1977       ** is used.
879fef5208cSdrh       */
880832508b7Sdrh       pExpr->iTable = pParse->nTab++;
8810202b29eSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, pExpr->iTable, 0);
882d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
883d3d39e93Sdrh       keyInfo.nField = 1;
884f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
885e014a838Sdanielk1977 
886e014a838Sdanielk1977       if( pExpr->pSelect ){
887e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
888e014a838Sdanielk1977         **
889e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
890e014a838Sdanielk1977         ** table allocated and opened above.
891e014a838Sdanielk1977         */
892e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
893be5c89acSdrh         ExprList *pEList;
894e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
895bf3b721fSdanielk1977         sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
896be5c89acSdrh         pEList = pExpr->pSelect->pEList;
897be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
8987cedc8d4Sdanielk1977           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
899be5c89acSdrh               pEList->a[0].pExpr);
9000202b29eSdanielk1977         }
901fef5208cSdrh       }else if( pExpr->pList ){
902fef5208cSdrh         /* Case 2:     expr IN (exprlist)
903fef5208cSdrh         **
904e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
905e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
906e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
907e014a838Sdanielk1977         ** a column, use numeric affinity.
908fef5208cSdrh         */
909e014a838Sdanielk1977         int i;
910e014a838Sdanielk1977         char const *affStr;
911e014a838Sdanielk1977         if( !affinity ){
912e014a838Sdanielk1977           affinity = SQLITE_AFF_NUMERIC;
913e014a838Sdanielk1977         }
914e014a838Sdanielk1977         affStr = sqlite3AffinityString(affinity);
9150202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
916e014a838Sdanielk1977 
917e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
918fef5208cSdrh         for(i=0; i<pExpr->pList->nExpr; i++){
919fef5208cSdrh           Expr *pE2 = pExpr->pList->a[i].pExpr;
920e014a838Sdanielk1977 
921e014a838Sdanielk1977           /* Check that the expression is constant and valid. */
9224adee20fSdanielk1977           if( !sqlite3ExprIsConstant(pE2) ){
9234adee20fSdanielk1977             sqlite3ErrorMsg(pParse,
924da93d238Sdrh               "right-hand side of IN operator must be constant");
925fef5208cSdrh             return 1;
926fef5208cSdrh           }
9274adee20fSdanielk1977           if( sqlite3ExprCheck(pParse, pE2, 0, 0) ){
9284794b980Sdrh             return 1;
9294794b980Sdrh           }
930e014a838Sdanielk1977 
931e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
9324adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
933ededfd5eSdanielk1977           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, affStr, P3_STATIC);
9340f69c1e3Sdanielk1977           sqlite3VdbeAddOp(v, OP_String8, 0, 0);
935e014a838Sdanielk1977           sqlite3VdbeAddOp(v, OP_PutStrKey, pExpr->iTable, 0);
936fef5208cSdrh         }
937fef5208cSdrh       }
9380202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
9390202b29eSdanielk1977 
940cfab11bcSdrh       break;
941fef5208cSdrh     }
942fef5208cSdrh 
94319a775c2Sdrh     case TK_SELECT: {
944fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
945fef5208cSdrh       ** value of this select in a memory cell and record the number
946967e8b73Sdrh       ** of the memory cell in iColumn.
947fef5208cSdrh       */
948967e8b73Sdrh       pExpr->iColumn = pParse->nMem++;
949bf3b721fSdanielk1977       if(sqlite3Select(pParse, pExpr->pSelect, SRT_Mem,pExpr->iColumn,0,0,0,0)){
95019a775c2Sdrh         return 1;
95119a775c2Sdrh       }
95219a775c2Sdrh       break;
95319a775c2Sdrh     }
95419a775c2Sdrh 
955cce7d176Sdrh     /* For all else, just recursively walk the tree */
956cce7d176Sdrh     default: {
957cce7d176Sdrh       if( pExpr->pLeft
9584adee20fSdanielk1977       && sqlite3ExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
959cce7d176Sdrh         return 1;
960cce7d176Sdrh       }
961cce7d176Sdrh       if( pExpr->pRight
9624adee20fSdanielk1977       && sqlite3ExprResolveIds(pParse, pSrcList, pEList, pExpr->pRight) ){
963cce7d176Sdrh         return 1;
964cce7d176Sdrh       }
965cce7d176Sdrh       if( pExpr->pList ){
966cce7d176Sdrh         int i;
967cce7d176Sdrh         ExprList *pList = pExpr->pList;
968cce7d176Sdrh         for(i=0; i<pList->nExpr; i++){
969832508b7Sdrh           Expr *pArg = pList->a[i].pExpr;
9704adee20fSdanielk1977           if( sqlite3ExprResolveIds(pParse, pSrcList, pEList, pArg) ){
971cce7d176Sdrh             return 1;
972cce7d176Sdrh           }
973cce7d176Sdrh         }
974cce7d176Sdrh       }
975cce7d176Sdrh     }
976cce7d176Sdrh   }
977cce7d176Sdrh   return 0;
978cce7d176Sdrh }
979cce7d176Sdrh 
980cce7d176Sdrh /*
9814b59ab5eSdrh ** pExpr is a node that defines a function of some kind.  It might
9824b59ab5eSdrh ** be a syntactic function like "count(x)" or it might be a function
9834b59ab5eSdrh ** that implements an operator, like "a LIKE b".
9844b59ab5eSdrh **
9854b59ab5eSdrh ** This routine makes *pzName point to the name of the function and
9864b59ab5eSdrh ** *pnName hold the number of characters in the function name.
9874b59ab5eSdrh */
9884b59ab5eSdrh static void getFunctionName(Expr *pExpr, const char **pzName, int *pnName){
9894b59ab5eSdrh   switch( pExpr->op ){
9904b59ab5eSdrh     case TK_FUNCTION: {
9914b59ab5eSdrh       *pzName = pExpr->token.z;
9926977fea8Sdrh       *pnName = pExpr->token.n;
9934b59ab5eSdrh       break;
9944b59ab5eSdrh     }
9954b59ab5eSdrh     case TK_LIKE: {
9964b59ab5eSdrh       *pzName = "like";
9974b59ab5eSdrh       *pnName = 4;
9984b59ab5eSdrh       break;
9994b59ab5eSdrh     }
10004b59ab5eSdrh     case TK_GLOB: {
10014b59ab5eSdrh       *pzName = "glob";
10024b59ab5eSdrh       *pnName = 4;
10034b59ab5eSdrh       break;
10044b59ab5eSdrh     }
10054b59ab5eSdrh     default: {
10064b59ab5eSdrh       *pzName = "can't happen";
10074b59ab5eSdrh       *pnName = 12;
10084b59ab5eSdrh       break;
10094b59ab5eSdrh     }
10104b59ab5eSdrh   }
10114b59ab5eSdrh }
10124b59ab5eSdrh 
10134b59ab5eSdrh /*
1014cce7d176Sdrh ** Error check the functions in an expression.  Make sure all
1015cce7d176Sdrh ** function names are recognized and all functions have the correct
1016cce7d176Sdrh ** number of arguments.  Leave an error message in pParse->zErrMsg
1017cce7d176Sdrh ** if anything is amiss.  Return the number of errors.
1018cce7d176Sdrh **
1019cce7d176Sdrh ** if pIsAgg is not null and this expression is an aggregate function
1020cce7d176Sdrh ** (like count(*) or max(value)) then write a 1 into *pIsAgg.
1021cce7d176Sdrh */
10224adee20fSdanielk1977 int sqlite3ExprCheck(Parse *pParse, Expr *pExpr, int allowAgg, int *pIsAgg){
1023cce7d176Sdrh   int nErr = 0;
1024cce7d176Sdrh   if( pExpr==0 ) return 0;
1025cce7d176Sdrh   switch( pExpr->op ){
10264b59ab5eSdrh     case TK_GLOB:
10274b59ab5eSdrh     case TK_LIKE:
1028cce7d176Sdrh     case TK_FUNCTION: {
1029c9b84a1fSdrh       int n = pExpr->pList ? pExpr->pList->nExpr : 0;  /* Number of arguments */
1030c9b84a1fSdrh       int no_such_func = 0;       /* True if no such function exists */
1031c9b84a1fSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1032c9b84a1fSdrh       int is_agg = 0;             /* True if is an aggregate function */
1033cce7d176Sdrh       int i;
10344b59ab5eSdrh       int nId;                    /* Number of characters in function name */
10354b59ab5eSdrh       const char *zId;            /* The function name. */
10360bce8354Sdrh       FuncDef *pDef;
1037d8123366Sdanielk1977       int enc = pParse->db->enc;
10380bce8354Sdrh 
10394b59ab5eSdrh       getFunctionName(pExpr, &zId, &nId);
1040d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
10410bce8354Sdrh       if( pDef==0 ){
1042d8123366Sdanielk1977         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
10430bce8354Sdrh         if( pDef==0 ){
1044cce7d176Sdrh           no_such_func = 1;
10458e0a2f90Sdrh         }else{
10468e0a2f90Sdrh           wrong_num_args = 1;
10478e0a2f90Sdrh         }
10488e0a2f90Sdrh       }else{
10490bce8354Sdrh         is_agg = pDef->xFunc==0;
1050cce7d176Sdrh       }
10518e0a2f90Sdrh       if( is_agg && !allowAgg ){
10524adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId, zId);
10538e0a2f90Sdrh         nErr++;
10548e0a2f90Sdrh         is_agg = 0;
10558e0a2f90Sdrh       }else if( no_such_func ){
10564adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1057cce7d176Sdrh         nErr++;
10588e0a2f90Sdrh       }else if( wrong_num_args ){
10594adee20fSdanielk1977         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1060f7a9e1acSdrh              nId, zId);
10618e0a2f90Sdrh         nErr++;
1062cce7d176Sdrh       }
1063f7a9e1acSdrh       if( is_agg ){
1064f7a9e1acSdrh         pExpr->op = TK_AGG_FUNCTION;
1065f7a9e1acSdrh         if( pIsAgg ) *pIsAgg = 1;
1066f7a9e1acSdrh       }
1067cce7d176Sdrh       for(i=0; nErr==0 && i<n; i++){
10684adee20fSdanielk1977         nErr = sqlite3ExprCheck(pParse, pExpr->pList->a[i].pExpr,
10694cfa7934Sdrh                                allowAgg && !is_agg, pIsAgg);
1070cce7d176Sdrh       }
10710202b29eSdanielk1977       /* FIX ME:  Compute pExpr->affinity based on the expected return
10720202b29eSdanielk1977       ** type of the function
10730202b29eSdanielk1977       */
1074cce7d176Sdrh     }
1075cce7d176Sdrh     default: {
1076cce7d176Sdrh       if( pExpr->pLeft ){
10774adee20fSdanielk1977         nErr = sqlite3ExprCheck(pParse, pExpr->pLeft, allowAgg, pIsAgg);
1078cce7d176Sdrh       }
1079cce7d176Sdrh       if( nErr==0 && pExpr->pRight ){
10804adee20fSdanielk1977         nErr = sqlite3ExprCheck(pParse, pExpr->pRight, allowAgg, pIsAgg);
1081cce7d176Sdrh       }
1082fef5208cSdrh       if( nErr==0 && pExpr->pList ){
1083fef5208cSdrh         int n = pExpr->pList->nExpr;
1084fef5208cSdrh         int i;
1085fef5208cSdrh         for(i=0; nErr==0 && i<n; i++){
10862282792aSdrh           Expr *pE2 = pExpr->pList->a[i].pExpr;
10874adee20fSdanielk1977           nErr = sqlite3ExprCheck(pParse, pE2, allowAgg, pIsAgg);
1088fef5208cSdrh         }
1089fef5208cSdrh       }
1090cce7d176Sdrh       break;
1091cce7d176Sdrh     }
1092cce7d176Sdrh   }
1093cce7d176Sdrh   return nErr;
1094cce7d176Sdrh }
1095cce7d176Sdrh 
1096cce7d176Sdrh /*
1097290c1948Sdrh ** Call sqlite3ExprResolveIds() followed by sqlite3ExprCheck().
1098290c1948Sdrh **
1099290c1948Sdrh ** This routine is provided as a convenience since it is very common
1100290c1948Sdrh ** to call ResolveIds() and Check() back to back.
1101290c1948Sdrh */
1102290c1948Sdrh int sqlite3ExprResolveAndCheck(
1103290c1948Sdrh   Parse *pParse,     /* The parser context */
1104290c1948Sdrh   SrcList *pSrcList, /* List of tables used to resolve column names */
1105290c1948Sdrh   ExprList *pEList,  /* List of expressions used to resolve "AS" */
1106290c1948Sdrh   Expr *pExpr,       /* The expression to be analyzed. */
1107290c1948Sdrh   int allowAgg,      /* True to allow aggregate expressions */
1108290c1948Sdrh   int *pIsAgg        /* Set to TRUE if aggregates are found */
1109290c1948Sdrh ){
1110290c1948Sdrh   if( pExpr==0 ) return 0;
1111290c1948Sdrh   if( sqlite3ExprResolveIds(pParse,pSrcList,pEList,pExpr) ){
1112290c1948Sdrh     return 1;
1113290c1948Sdrh   }
1114290c1948Sdrh   return sqlite3ExprCheck(pParse, pExpr, allowAgg, pIsAgg);
1115290c1948Sdrh }
1116290c1948Sdrh 
1117290c1948Sdrh /*
1118fec19aadSdrh ** Generate an instruction that will put the integer describe by
1119fec19aadSdrh ** text z[0..n-1] on the stack.
1120fec19aadSdrh */
1121fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1122fec19aadSdrh   int i;
11236fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
11246fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
11256fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
11266fec0762Sdrh     sqlite3VdbeOp3(v, OP_Integer, 0, 0, z, n);
1127fec19aadSdrh   }else{
1128fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1129fec19aadSdrh   }
1130fec19aadSdrh }
1131fec19aadSdrh 
1132fec19aadSdrh /*
1133cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
11341ccde15dSdrh ** expression and leave the result on the top of stack.
1135cce7d176Sdrh */
11364adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1137cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1138cce7d176Sdrh   int op;
1139daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1140cce7d176Sdrh   switch( pExpr->op ){
1141cce7d176Sdrh     case TK_PLUS:     op = OP_Add;      break;
1142cce7d176Sdrh     case TK_MINUS:    op = OP_Subtract; break;
1143cce7d176Sdrh     case TK_STAR:     op = OP_Multiply; break;
1144cce7d176Sdrh     case TK_SLASH:    op = OP_Divide;   break;
1145cce7d176Sdrh     case TK_AND:      op = OP_And;      break;
1146cce7d176Sdrh     case TK_OR:       op = OP_Or;       break;
1147cce7d176Sdrh     case TK_LT:       op = OP_Lt;       break;
1148cce7d176Sdrh     case TK_LE:       op = OP_Le;       break;
1149cce7d176Sdrh     case TK_GT:       op = OP_Gt;       break;
1150cce7d176Sdrh     case TK_GE:       op = OP_Ge;       break;
1151cce7d176Sdrh     case TK_NE:       op = OP_Ne;       break;
1152cce7d176Sdrh     case TK_EQ:       op = OP_Eq;       break;
1153cce7d176Sdrh     case TK_ISNULL:   op = OP_IsNull;   break;
1154cce7d176Sdrh     case TK_NOTNULL:  op = OP_NotNull;  break;
1155cce7d176Sdrh     case TK_NOT:      op = OP_Not;      break;
1156cce7d176Sdrh     case TK_UMINUS:   op = OP_Negative; break;
1157bf4133cbSdrh     case TK_BITAND:   op = OP_BitAnd;   break;
1158bf4133cbSdrh     case TK_BITOR:    op = OP_BitOr;    break;
1159bf4133cbSdrh     case TK_BITNOT:   op = OP_BitNot;   break;
1160bf4133cbSdrh     case TK_LSHIFT:   op = OP_ShiftLeft;  break;
1161bf4133cbSdrh     case TK_RSHIFT:   op = OP_ShiftRight; break;
1162bf4133cbSdrh     case TK_REM:      op = OP_Remainder;  break;
1163fec19aadSdrh     case TK_FLOAT:    op = OP_Real;       break;
11640f69c1e3Sdanielk1977     case TK_STRING:   op = OP_String8;    break;
1165c572ef7fSdanielk1977     case TK_BLOB:     op = OP_HexBlob;    break;
1166855eb1cfSdrh     case TK_CONCAT:   op = OP_Concat;     break;
1167cfe9a69fSdanielk1977     default: op = 0; break;
1168cce7d176Sdrh   }
1169cce7d176Sdrh   switch( pExpr->op ){
1170967e8b73Sdrh     case TK_COLUMN: {
11712282792aSdrh       if( pParse->useAgg ){
11724adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
1173c4a3c779Sdrh       }else if( pExpr->iColumn>=0 ){
11744adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
1175c4a3c779Sdrh       }else{
11764adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Recno, pExpr->iTable, 0);
11772282792aSdrh       }
1178cce7d176Sdrh       break;
1179cce7d176Sdrh     }
1180cce7d176Sdrh     case TK_INTEGER: {
1181fec19aadSdrh       codeInteger(v, pExpr->token.z, pExpr->token.n);
1182fec19aadSdrh       break;
118351e9a445Sdrh     }
1184fec19aadSdrh     case TK_FLOAT:
1185fec19aadSdrh     case TK_STRING: {
1186fec19aadSdrh       sqlite3VdbeOp3(v, op, 0, 0, pExpr->token.z, pExpr->token.n);
11874adee20fSdanielk1977       sqlite3VdbeDequoteP3(v, -1);
1188cce7d176Sdrh       break;
1189cce7d176Sdrh     }
1190c572ef7fSdanielk1977     case TK_BLOB: {
1191c572ef7fSdanielk1977       sqlite3VdbeOp3(v, op, 0, 0, pExpr->token.z+1, pExpr->token.n-1);
1192c572ef7fSdanielk1977       sqlite3VdbeDequoteP3(v, -1);
1193c572ef7fSdanielk1977       break;
1194c572ef7fSdanielk1977     }
1195cce7d176Sdrh     case TK_NULL: {
11960f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1197cce7d176Sdrh       break;
1198cce7d176Sdrh     }
119950457896Sdrh     case TK_VARIABLE: {
12004adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1201895d7472Sdrh       if( pExpr->token.n>1 ){
1202895d7472Sdrh         sqlite3VdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
1203895d7472Sdrh       }
120450457896Sdrh       break;
120550457896Sdrh     }
1206c9b84a1fSdrh     case TK_LT:
1207c9b84a1fSdrh     case TK_LE:
1208c9b84a1fSdrh     case TK_GT:
1209c9b84a1fSdrh     case TK_GE:
1210c9b84a1fSdrh     case TK_NE:
1211c9b84a1fSdrh     case TK_EQ: {
1212a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1213a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1214be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1215a37cdde0Sdanielk1977       break;
1216c9b84a1fSdrh     }
1217cce7d176Sdrh     case TK_AND:
1218cce7d176Sdrh     case TK_OR:
1219cce7d176Sdrh     case TK_PLUS:
1220cce7d176Sdrh     case TK_STAR:
1221cce7d176Sdrh     case TK_MINUS:
1222bf4133cbSdrh     case TK_REM:
1223bf4133cbSdrh     case TK_BITAND:
1224bf4133cbSdrh     case TK_BITOR:
122517c40294Sdrh     case TK_SLASH:
1226bf4133cbSdrh     case TK_LSHIFT:
1227855eb1cfSdrh     case TK_RSHIFT:
12280040077dSdrh     case TK_CONCAT: {
12294adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
12304adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1231855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
12320040077dSdrh       break;
12330040077dSdrh     }
1234cce7d176Sdrh     case TK_UMINUS: {
1235fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1236fec19aadSdrh       assert( pLeft );
1237fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1238fec19aadSdrh         Token *p = &pLeft->token;
12396e142f54Sdrh         char *z = sqliteMalloc( p->n + 2 );
12406e142f54Sdrh         sprintf(z, "-%.*s", p->n, p->z);
1241fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1242fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1243e6840900Sdrh         }else{
1244fec19aadSdrh           codeInteger(v, z, p->n+1);
1245e6840900Sdrh         }
12466e142f54Sdrh         sqliteFree(z);
12476e142f54Sdrh         break;
12486e142f54Sdrh       }
12491ccde15dSdrh       /* Fall through into TK_NOT */
12506e142f54Sdrh     }
1251bf4133cbSdrh     case TK_BITNOT:
12526e142f54Sdrh     case TK_NOT: {
12534adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
12544adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1255cce7d176Sdrh       break;
1256cce7d176Sdrh     }
1257cce7d176Sdrh     case TK_ISNULL:
1258cce7d176Sdrh     case TK_NOTNULL: {
1259cce7d176Sdrh       int dest;
12604adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
12614adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
12624adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
12634adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
12644adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1265cce7d176Sdrh     }
1266a37cdde0Sdanielk1977     break;
12672282792aSdrh     case TK_AGG_FUNCTION: {
12684adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
12692282792aSdrh       break;
12702282792aSdrh     }
12714b59ab5eSdrh     case TK_GLOB:
12724b59ab5eSdrh     case TK_LIKE:
1273cce7d176Sdrh     case TK_FUNCTION: {
1274cce7d176Sdrh       ExprList *pList = pExpr->pList;
127589425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
12760bce8354Sdrh       FuncDef *pDef;
12774b59ab5eSdrh       int nId;
12784b59ab5eSdrh       const char *zId;
1279682f68b0Sdanielk1977       int p2 = 0;
1280682f68b0Sdanielk1977       int i;
1281d8123366Sdanielk1977       u8 enc = pParse->db->enc;
1282dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
12834b59ab5eSdrh       getFunctionName(pExpr, &zId, &nId);
1284d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
12850bce8354Sdrh       assert( pDef!=0 );
1286f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1287682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1288d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
1289d02eb1fdSdanielk1977           p2 |= (1<<i);
1290d02eb1fdSdanielk1977         }
1291dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1292dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1293dc1bdc4fSdanielk1977         }
1294dc1bdc4fSdanielk1977       }
1295dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1296dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1297d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1298682f68b0Sdanielk1977       }
1299682f68b0Sdanielk1977       sqlite3VdbeOp3(v, OP_Function, nExpr, p2, (char*)pDef, P3_FUNCDEF);
13006ec2733bSdrh       break;
13016ec2733bSdrh     }
130219a775c2Sdrh     case TK_SELECT: {
13034adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
130419a775c2Sdrh       break;
130519a775c2Sdrh     }
1306fef5208cSdrh     case TK_IN: {
1307fef5208cSdrh       int addr;
1308e014a838Sdanielk1977       char const *affStr;
1309e014a838Sdanielk1977 
1310e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1311e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1312ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1313e014a838Sdanielk1977       */
1314e014a838Sdanielk1977       affStr = sqlite3AffinityString(comparisonAffinity(pExpr));
1315e014a838Sdanielk1977 
13164adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1317e014a838Sdanielk1977 
1318e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1319e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1320e014a838Sdanielk1977       */
13214adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
13224adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1323e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
13244adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
13250f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1326e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
1327ededfd5eSdanielk1977       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, affStr, P3_STATIC); /* addr + 4 */
1328e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1329e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1330e014a838Sdanielk1977 
1331fef5208cSdrh       break;
1332fef5208cSdrh     }
1333fef5208cSdrh     case TK_BETWEEN: {
1334be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1335be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1336be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1337be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
13384adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1339be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1340be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
13414adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1342be5c89acSdrh       pLItem++;
1343be5c89acSdrh       pRight = pLItem->pExpr;
1344be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1345be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
13464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1347fef5208cSdrh       break;
1348fef5208cSdrh     }
134951e9a445Sdrh     case TK_UPLUS:
1350a2e00042Sdrh     case TK_AS: {
13514adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1352a2e00042Sdrh       break;
1353a2e00042Sdrh     }
135417a7f8ddSdrh     case TK_CASE: {
135517a7f8ddSdrh       int expr_end_label;
1356f5905aa7Sdrh       int jumpInst;
1357f5905aa7Sdrh       int addr;
1358f5905aa7Sdrh       int nExpr;
135917a7f8ddSdrh       int i;
1360be5c89acSdrh       ExprList *pEList;
1361be5c89acSdrh       struct ExprList_item *aListelem;
136217a7f8ddSdrh 
136317a7f8ddSdrh       assert(pExpr->pList);
136417a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
136517a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1366be5c89acSdrh       pEList = pExpr->pList;
1367be5c89acSdrh       aListelem = pEList->a;
1368be5c89acSdrh       nExpr = pEList->nExpr;
13694adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
137017a7f8ddSdrh       if( pExpr->pLeft ){
13714adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1372cce7d176Sdrh       }
1373f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1374be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
137517a7f8ddSdrh         if( pExpr->pLeft ){
13764adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1377be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1378be5c89acSdrh                                  OP_Ne, 0, 1);
13794adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1380f5905aa7Sdrh         }else{
13814adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
138217a7f8ddSdrh         }
1383be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
13844adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
13854adee20fSdanielk1977         addr = sqlite3VdbeCurrentAddr(v);
13864adee20fSdanielk1977         sqlite3VdbeChangeP2(v, jumpInst, addr);
138717a7f8ddSdrh       }
1388f570f011Sdrh       if( pExpr->pLeft ){
13894adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1390f570f011Sdrh       }
139117a7f8ddSdrh       if( pExpr->pRight ){
13924adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
139317a7f8ddSdrh       }else{
13940f69c1e3Sdanielk1977         sqlite3VdbeAddOp(v, OP_String8, 0, 0);
139517a7f8ddSdrh       }
13964adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
13976f34903eSdanielk1977       break;
13986f34903eSdanielk1977     }
13996f34903eSdanielk1977     case TK_RAISE: {
14006f34903eSdanielk1977       if( !pParse->trigStack ){
14014adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1402da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
14036f34903eSdanielk1977         pParse->nErr++;
14046f34903eSdanielk1977 	return;
14056f34903eSdanielk1977       }
14066f34903eSdanielk1977       if( pExpr->iColumn == OE_Rollback ||
14076f34903eSdanielk1977 	  pExpr->iColumn == OE_Abort ||
14086f34903eSdanielk1977 	  pExpr->iColumn == OE_Fail ){
14094adee20fSdanielk1977 	  sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
1410701a0aebSdrh                            pExpr->token.z, pExpr->token.n);
14114adee20fSdanielk1977 	  sqlite3VdbeDequoteP3(v, -1);
14126f34903eSdanielk1977       } else {
14136f34903eSdanielk1977 	  assert( pExpr->iColumn == OE_Ignore );
14144adee20fSdanielk1977 	  sqlite3VdbeOp3(v, OP_Goto, 0, pParse->trigStack->ignoreJump,
1415701a0aebSdrh                            "(IGNORE jump)", 0);
14166f34903eSdanielk1977       }
141717a7f8ddSdrh     }
141817a7f8ddSdrh     break;
141917a7f8ddSdrh   }
1420cce7d176Sdrh }
1421cce7d176Sdrh 
1422cce7d176Sdrh /*
1423268380caSdrh ** Generate code that pushes the value of every element of the given
1424f9b596ebSdrh ** expression list onto the stack.
1425268380caSdrh **
1426268380caSdrh ** Return the number of elements pushed onto the stack.
1427268380caSdrh */
14284adee20fSdanielk1977 int sqlite3ExprCodeExprList(
1429268380caSdrh   Parse *pParse,     /* Parsing context */
1430f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
1431268380caSdrh ){
1432268380caSdrh   struct ExprList_item *pItem;
1433268380caSdrh   int i, n;
1434268380caSdrh   Vdbe *v;
1435268380caSdrh   if( pList==0 ) return 0;
14364adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1437268380caSdrh   n = pList->nExpr;
1438268380caSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
14394adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
1440268380caSdrh   }
1441f9b596ebSdrh   return n;
1442268380caSdrh }
1443268380caSdrh 
1444268380caSdrh /*
1445cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
1446cce7d176Sdrh ** to the label "dest" if the expression is true but execution
1447cce7d176Sdrh ** continues straight thru if the expression is false.
1448f5905aa7Sdrh **
1449f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
1450f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
1451cce7d176Sdrh */
14524adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1453cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1454cce7d176Sdrh   int op = 0;
1455daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1456cce7d176Sdrh   switch( pExpr->op ){
1457cce7d176Sdrh     case TK_LT:       op = OP_Lt;       break;
1458cce7d176Sdrh     case TK_LE:       op = OP_Le;       break;
1459cce7d176Sdrh     case TK_GT:       op = OP_Gt;       break;
1460cce7d176Sdrh     case TK_GE:       op = OP_Ge;       break;
1461cce7d176Sdrh     case TK_NE:       op = OP_Ne;       break;
1462cce7d176Sdrh     case TK_EQ:       op = OP_Eq;       break;
1463cce7d176Sdrh     case TK_ISNULL:   op = OP_IsNull;   break;
1464cce7d176Sdrh     case TK_NOTNULL:  op = OP_NotNull;  break;
1465cce7d176Sdrh     default:  break;
1466cce7d176Sdrh   }
1467cce7d176Sdrh   switch( pExpr->op ){
1468cce7d176Sdrh     case TK_AND: {
14694adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
14704adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
14714adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
14724adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1473cce7d176Sdrh       break;
1474cce7d176Sdrh     }
1475cce7d176Sdrh     case TK_OR: {
14764adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
14774adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1478cce7d176Sdrh       break;
1479cce7d176Sdrh     }
1480cce7d176Sdrh     case TK_NOT: {
14814adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1482cce7d176Sdrh       break;
1483cce7d176Sdrh     }
1484cce7d176Sdrh     case TK_LT:
1485cce7d176Sdrh     case TK_LE:
1486cce7d176Sdrh     case TK_GT:
1487cce7d176Sdrh     case TK_GE:
1488cce7d176Sdrh     case TK_NE:
14890ac65892Sdrh     case TK_EQ: {
14904adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
14914adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1492be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
1493cce7d176Sdrh       break;
1494cce7d176Sdrh     }
1495cce7d176Sdrh     case TK_ISNULL:
1496cce7d176Sdrh     case TK_NOTNULL: {
14974adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
14984adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
1499cce7d176Sdrh       break;
1500cce7d176Sdrh     }
1501fef5208cSdrh     case TK_BETWEEN: {
15020202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
15030202b29eSdanielk1977       **
15040202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
15050202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
15060202b29eSdanielk1977       ** 3 ...
15070202b29eSdanielk1977       */
1508f5905aa7Sdrh       int addr;
1509be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1510be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
1511be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
15124adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1513be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1514be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
15150202b29eSdanielk1977 
1516be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
1517be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1518be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
15190202b29eSdanielk1977 
15204adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
15214adee20fSdanielk1977       sqlite3VdbeChangeP2(v, addr, sqlite3VdbeCurrentAddr(v));
15224adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1523fef5208cSdrh       break;
1524fef5208cSdrh     }
1525cce7d176Sdrh     default: {
15264adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
15274adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
1528cce7d176Sdrh       break;
1529cce7d176Sdrh     }
1530cce7d176Sdrh   }
1531cce7d176Sdrh }
1532cce7d176Sdrh 
1533cce7d176Sdrh /*
153466b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
1535cce7d176Sdrh ** to the label "dest" if the expression is false but execution
1536cce7d176Sdrh ** continues straight thru if the expression is true.
1537f5905aa7Sdrh **
1538f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
1539f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
1540cce7d176Sdrh */
15414adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1542cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1543cce7d176Sdrh   int op = 0;
1544daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1545cce7d176Sdrh   switch( pExpr->op ){
1546cce7d176Sdrh     case TK_LT:       op = OP_Ge;       break;
1547cce7d176Sdrh     case TK_LE:       op = OP_Gt;       break;
1548cce7d176Sdrh     case TK_GT:       op = OP_Le;       break;
1549cce7d176Sdrh     case TK_GE:       op = OP_Lt;       break;
1550cce7d176Sdrh     case TK_NE:       op = OP_Eq;       break;
1551cce7d176Sdrh     case TK_EQ:       op = OP_Ne;       break;
1552cce7d176Sdrh     case TK_ISNULL:   op = OP_NotNull;  break;
1553cce7d176Sdrh     case TK_NOTNULL:  op = OP_IsNull;   break;
1554cce7d176Sdrh     default:  break;
1555cce7d176Sdrh   }
1556cce7d176Sdrh   switch( pExpr->op ){
1557cce7d176Sdrh     case TK_AND: {
15584adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
15594adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
1560cce7d176Sdrh       break;
1561cce7d176Sdrh     }
1562cce7d176Sdrh     case TK_OR: {
15634adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
15644adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
15654adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
15664adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1567cce7d176Sdrh       break;
1568cce7d176Sdrh     }
1569cce7d176Sdrh     case TK_NOT: {
15704adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
1571cce7d176Sdrh       break;
1572cce7d176Sdrh     }
1573cce7d176Sdrh     case TK_LT:
1574cce7d176Sdrh     case TK_LE:
1575cce7d176Sdrh     case TK_GT:
1576cce7d176Sdrh     case TK_GE:
1577cce7d176Sdrh     case TK_NE:
1578cce7d176Sdrh     case TK_EQ: {
15794adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
15804adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1581be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
1582cce7d176Sdrh       break;
1583cce7d176Sdrh     }
1584cce7d176Sdrh     case TK_ISNULL:
1585cce7d176Sdrh     case TK_NOTNULL: {
15864adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
15874adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
1588cce7d176Sdrh       break;
1589cce7d176Sdrh     }
1590fef5208cSdrh     case TK_BETWEEN: {
15910202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
15920202b29eSdanielk1977       **
15930202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
15940202b29eSdanielk1977       ** 2 GOTO <dest>
15950202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
15960202b29eSdanielk1977       */
1597fef5208cSdrh       int addr;
1598be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1599be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
1600be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
16014adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1602be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
16034adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1604be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
1605be5c89acSdrh 
16064adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
16074adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
1608be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
1609be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1610be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
1611fef5208cSdrh       break;
1612fef5208cSdrh     }
1613cce7d176Sdrh     default: {
16144adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
16154adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
1616cce7d176Sdrh       break;
1617cce7d176Sdrh     }
1618cce7d176Sdrh   }
1619cce7d176Sdrh }
16202282792aSdrh 
16212282792aSdrh /*
16222282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
16232282792aSdrh ** if they are identical and return FALSE if they differ in any way.
16242282792aSdrh */
16254adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
16262282792aSdrh   int i;
16272282792aSdrh   if( pA==0 ){
16282282792aSdrh     return pB==0;
16292282792aSdrh   }else if( pB==0 ){
16302282792aSdrh     return 0;
16312282792aSdrh   }
16322282792aSdrh   if( pA->op!=pB->op ) return 0;
16334adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
16344adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
16352282792aSdrh   if( pA->pList ){
16362282792aSdrh     if( pB->pList==0 ) return 0;
16372282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
16382282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
16394adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
16402282792aSdrh         return 0;
16412282792aSdrh       }
16422282792aSdrh     }
16432282792aSdrh   }else if( pB->pList ){
16442282792aSdrh     return 0;
16452282792aSdrh   }
16462282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
16472f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
16482282792aSdrh   if( pA->token.z ){
16492282792aSdrh     if( pB->token.z==0 ) return 0;
16506977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
16514adee20fSdanielk1977     if( sqlite3StrNICmp(pA->token.z, pB->token.z, pB->token.n)!=0 ) return 0;
16522282792aSdrh   }
16532282792aSdrh   return 1;
16542282792aSdrh }
16552282792aSdrh 
16562282792aSdrh /*
16572282792aSdrh ** Add a new element to the pParse->aAgg[] array and return its index.
16582282792aSdrh */
16592282792aSdrh static int appendAggInfo(Parse *pParse){
16602282792aSdrh   if( (pParse->nAgg & 0x7)==0 ){
16612282792aSdrh     int amt = pParse->nAgg + 8;
16626d4abfbeSdrh     AggExpr *aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
16636d4abfbeSdrh     if( aAgg==0 ){
16642282792aSdrh       return -1;
16652282792aSdrh     }
16666d4abfbeSdrh     pParse->aAgg = aAgg;
16672282792aSdrh   }
16682282792aSdrh   memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
16692282792aSdrh   return pParse->nAgg++;
16702282792aSdrh }
16712282792aSdrh 
16722282792aSdrh /*
16732282792aSdrh ** Analyze the given expression looking for aggregate functions and
16742282792aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
16752282792aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
16762282792aSdrh **
16772282792aSdrh ** This routine should only be called after the expression has been
16784adee20fSdanielk1977 ** analyzed by sqlite3ExprResolveIds() and sqlite3ExprCheck().
16792282792aSdrh **
16802282792aSdrh ** If errors are seen, leave an error message in zErrMsg and return
16812282792aSdrh ** the number of errors.
16822282792aSdrh */
16834adee20fSdanielk1977 int sqlite3ExprAnalyzeAggregates(Parse *pParse, Expr *pExpr){
16842282792aSdrh   int i;
16852282792aSdrh   AggExpr *aAgg;
16862282792aSdrh   int nErr = 0;
16872282792aSdrh 
16882282792aSdrh   if( pExpr==0 ) return 0;
16892282792aSdrh   switch( pExpr->op ){
1690967e8b73Sdrh     case TK_COLUMN: {
16912282792aSdrh       aAgg = pParse->aAgg;
16922282792aSdrh       for(i=0; i<pParse->nAgg; i++){
16932282792aSdrh         if( aAgg[i].isAgg ) continue;
16942282792aSdrh         if( aAgg[i].pExpr->iTable==pExpr->iTable
1695967e8b73Sdrh          && aAgg[i].pExpr->iColumn==pExpr->iColumn ){
16962282792aSdrh           break;
16972282792aSdrh         }
16982282792aSdrh       }
16992282792aSdrh       if( i>=pParse->nAgg ){
17002282792aSdrh         i = appendAggInfo(pParse);
17012282792aSdrh         if( i<0 ) return 1;
17022282792aSdrh         pParse->aAgg[i].isAgg = 0;
17032282792aSdrh         pParse->aAgg[i].pExpr = pExpr;
17042282792aSdrh       }
1705aaf88729Sdrh       pExpr->iAgg = i;
17062282792aSdrh       break;
17072282792aSdrh     }
17082282792aSdrh     case TK_AGG_FUNCTION: {
17092282792aSdrh       aAgg = pParse->aAgg;
17102282792aSdrh       for(i=0; i<pParse->nAgg; i++){
17112282792aSdrh         if( !aAgg[i].isAgg ) continue;
17124adee20fSdanielk1977         if( sqlite3ExprCompare(aAgg[i].pExpr, pExpr) ){
17132282792aSdrh           break;
17142282792aSdrh         }
17152282792aSdrh       }
17162282792aSdrh       if( i>=pParse->nAgg ){
1717d8123366Sdanielk1977         u8 enc = pParse->db->enc;
17182282792aSdrh         i = appendAggInfo(pParse);
17192282792aSdrh         if( i<0 ) return 1;
17202282792aSdrh         pParse->aAgg[i].isAgg = 1;
17212282792aSdrh         pParse->aAgg[i].pExpr = pExpr;
17224adee20fSdanielk1977         pParse->aAgg[i].pFunc = sqlite3FindFunction(pParse->db,
17236977fea8Sdrh              pExpr->token.z, pExpr->token.n,
1724d8123366Sdanielk1977              pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
17252282792aSdrh       }
17262282792aSdrh       pExpr->iAgg = i;
17272282792aSdrh       break;
17282282792aSdrh     }
17292282792aSdrh     default: {
17302282792aSdrh       if( pExpr->pLeft ){
17314adee20fSdanielk1977         nErr = sqlite3ExprAnalyzeAggregates(pParse, pExpr->pLeft);
17322282792aSdrh       }
17332282792aSdrh       if( nErr==0 && pExpr->pRight ){
17344adee20fSdanielk1977         nErr = sqlite3ExprAnalyzeAggregates(pParse, pExpr->pRight);
17352282792aSdrh       }
17362282792aSdrh       if( nErr==0 && pExpr->pList ){
17372282792aSdrh         int n = pExpr->pList->nExpr;
17382282792aSdrh         int i;
17392282792aSdrh         for(i=0; nErr==0 && i<n; i++){
17404adee20fSdanielk1977           nErr = sqlite3ExprAnalyzeAggregates(pParse, pExpr->pList->a[i].pExpr);
17412282792aSdrh         }
17422282792aSdrh       }
17432282792aSdrh       break;
17442282792aSdrh     }
17452282792aSdrh   }
17462282792aSdrh   return nErr;
17472282792aSdrh }
17488e0a2f90Sdrh 
17498e0a2f90Sdrh /*
1750d02eb1fdSdanielk1977 ** Locate a user function given a name, a number of arguments and a flag
1751d02eb1fdSdanielk1977 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
1752d02eb1fdSdanielk1977 ** pointer to the FuncDef structure that defines that function, or return
1753d02eb1fdSdanielk1977 ** NULL if the function does not exist.
17548e0a2f90Sdrh **
17550bce8354Sdrh ** If the createFlag argument is true, then a new (blank) FuncDef
17568e0a2f90Sdrh ** structure is created and liked into the "db" structure if a
17578e0a2f90Sdrh ** no matching function previously existed.  When createFlag is true
17588e0a2f90Sdrh ** and the nArg parameter is -1, then only a function that accepts
17598e0a2f90Sdrh ** any number of arguments will be returned.
17608e0a2f90Sdrh **
17618e0a2f90Sdrh ** If createFlag is false and nArg is -1, then the first valid
17628e0a2f90Sdrh ** function found is returned.  A function is valid if either xFunc
17638e0a2f90Sdrh ** or xStep is non-zero.
1764d02eb1fdSdanielk1977 **
1765d02eb1fdSdanielk1977 ** If createFlag is false, then a function with the required name and
1766d02eb1fdSdanielk1977 ** number of arguments may be returned even if the eTextRep flag does not
1767d02eb1fdSdanielk1977 ** match that requested.
17688e0a2f90Sdrh */
17694adee20fSdanielk1977 FuncDef *sqlite3FindFunction(
1770*9bb575fdSdrh   sqlite3 *db,       /* An open database */
17718e0a2f90Sdrh   const char *zName, /* Name of the function.  Not null-terminated */
17728e0a2f90Sdrh   int nName,         /* Number of characters in the name */
17738e0a2f90Sdrh   int nArg,          /* Number of arguments.  -1 means any number */
1774d8123366Sdanielk1977   u8 enc,            /* Preferred text encoding */
17758e0a2f90Sdrh   int createFlag     /* Create new entry if true and does not otherwise exist */
17768e0a2f90Sdrh ){
1777d02eb1fdSdanielk1977   FuncDef *p;         /* Iterator variable */
1778d02eb1fdSdanielk1977   FuncDef *pFirst;    /* First function with this name */
1779d02eb1fdSdanielk1977   FuncDef *pBest = 0; /* Best match found so far */
1780d8123366Sdanielk1977   int bestmatch = 0;
1781d02eb1fdSdanielk1977 
1782d8123366Sdanielk1977 
1783d8123366Sdanielk1977   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
1784d02eb1fdSdanielk1977   if( nArg<-1 ) nArg = -1;
1785d02eb1fdSdanielk1977 
1786d02eb1fdSdanielk1977   pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
1787d02eb1fdSdanielk1977   for(p=pFirst; p; p=p->pNext){
1788d8123366Sdanielk1977     /* During the search for the best function definition, bestmatch is set
1789d8123366Sdanielk1977     ** as follows to indicate the quality of the match with the definition
1790d8123366Sdanielk1977     ** pointed to by pBest:
1791d8123366Sdanielk1977     **
1792d8123366Sdanielk1977     ** 0: pBest is NULL. No match has been found.
1793d8123366Sdanielk1977     ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
1794d8123366Sdanielk1977     **    encoding is requested, or vice versa.
1795d8123366Sdanielk1977     ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
1796d8123366Sdanielk1977     **    requested, or vice versa.
1797d8123366Sdanielk1977     ** 3: A variable arguments function using the same text encoding.
1798d8123366Sdanielk1977     ** 4: A function with the exact number of arguments requested that
1799d8123366Sdanielk1977     **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
1800d8123366Sdanielk1977     ** 5: A function with the exact number of arguments requested that
1801d8123366Sdanielk1977     **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
1802d8123366Sdanielk1977     ** 6: An exact match.
1803d8123366Sdanielk1977     **
1804d8123366Sdanielk1977     ** A larger value of 'matchqual' indicates a more desirable match.
1805d8123366Sdanielk1977     */
1806e12c17baSdanielk1977     if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
1807d8123366Sdanielk1977       int match = 1;          /* Quality of this match */
1808d8123366Sdanielk1977       if( p->nArg==nArg || nArg==-1 ){
1809d8123366Sdanielk1977         match = 4;
18108e0a2f90Sdrh       }
1811d8123366Sdanielk1977       if( enc==p->iPrefEnc ){
1812d8123366Sdanielk1977         match += 2;
18138e0a2f90Sdrh       }
1814d8123366Sdanielk1977       else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
1815d8123366Sdanielk1977                (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
1816d8123366Sdanielk1977         match += 1;
1817d02eb1fdSdanielk1977       }
1818d8123366Sdanielk1977 
1819d8123366Sdanielk1977       if( match>bestmatch ){
1820d02eb1fdSdanielk1977         pBest = p;
1821d8123366Sdanielk1977         bestmatch = match;
1822d02eb1fdSdanielk1977       }
1823d02eb1fdSdanielk1977     }
1824d02eb1fdSdanielk1977   }
1825d02eb1fdSdanielk1977 
1826d8123366Sdanielk1977   /* If the createFlag parameter is true, and the seach did not reveal an
1827d8123366Sdanielk1977   ** exact match for the name, number of arguments and encoding, then add a
1828d8123366Sdanielk1977   ** new entry to the hash table and return it.
1829d8123366Sdanielk1977   */
1830d8123366Sdanielk1977   if( createFlag && bestmatch<6 &&
1831d02eb1fdSdanielk1977       (pBest = sqliteMalloc(sizeof(*pBest)+nName+1)) ){
1832d02eb1fdSdanielk1977     pBest->nArg = nArg;
1833d02eb1fdSdanielk1977     pBest->pNext = pFirst;
1834d02eb1fdSdanielk1977     pBest->zName = (char*)&pBest[1];
1835d8123366Sdanielk1977     pBest->iPrefEnc = enc;
1836d02eb1fdSdanielk1977     memcpy(pBest->zName, zName, nName);
1837d02eb1fdSdanielk1977     pBest->zName[nName] = 0;
1838d02eb1fdSdanielk1977     sqlite3HashInsert(&db->aFunc, pBest->zName, nName, (void*)pBest);
1839d02eb1fdSdanielk1977   }
1840d02eb1fdSdanielk1977 
1841d02eb1fdSdanielk1977   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
1842d02eb1fdSdanielk1977     return pBest;
1843d02eb1fdSdanielk1977   }
18448e0a2f90Sdrh   return 0;
18458e0a2f90Sdrh }
1846