xref: /sqlite-3.40.0/src/expr.c (revision ca83ac51)
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*ca83ac51Sdrh ** $Id: expr.c,v 1.272 2007/02/01 01:40:44 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
1804738cb9Sdrh #include <ctype.h>
19a2e00042Sdrh 
20e014a838Sdanielk1977 /*
21e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
22e014a838Sdanielk1977 **
23e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
24e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
25e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
26e014a838Sdanielk1977 ** indicating no affinity for the expression.
27e014a838Sdanielk1977 **
28e014a838Sdanielk1977 ** i.e. the WHERE clause expresssions in the following statements all
29e014a838Sdanielk1977 ** have an affinity:
30e014a838Sdanielk1977 **
31e014a838Sdanielk1977 ** CREATE TABLE t1(a);
32e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
33e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
34e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
35e014a838Sdanielk1977 */
36bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
37487e262fSdrh   int op = pExpr->op;
38487e262fSdrh   if( op==TK_AS ){
39bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pLeft);
40a37cdde0Sdanielk1977   }
41487e262fSdrh   if( op==TK_SELECT ){
42bf3b721fSdanielk1977     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
43a37cdde0Sdanielk1977   }
44487e262fSdrh #ifndef SQLITE_OMIT_CAST
45487e262fSdrh   if( op==TK_CAST ){
468a51256cSdrh     return sqlite3AffinityType(&pExpr->token);
47487e262fSdrh   }
48487e262fSdrh #endif
49a37cdde0Sdanielk1977   return pExpr->affinity;
50a37cdde0Sdanielk1977 }
51a37cdde0Sdanielk1977 
5253db1458Sdrh /*
530202b29eSdanielk1977 ** Return the default collation sequence for the expression pExpr. If
540202b29eSdanielk1977 ** there is no default collation type, return 0.
550202b29eSdanielk1977 */
567cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
577cedc8d4Sdanielk1977   CollSeq *pColl = 0;
580202b29eSdanielk1977   if( pExpr ){
597cedc8d4Sdanielk1977     pColl = pExpr->pColl;
60487e262fSdrh     if( (pExpr->op==TK_AS || pExpr->op==TK_CAST) && !pColl ){
617cedc8d4Sdanielk1977       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
620202b29eSdanielk1977     }
630202b29eSdanielk1977   }
647cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
657cedc8d4Sdanielk1977     pColl = 0;
667cedc8d4Sdanielk1977   }
677cedc8d4Sdanielk1977   return pColl;
680202b29eSdanielk1977 }
690202b29eSdanielk1977 
700202b29eSdanielk1977 /*
71626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
72626a879aSdrh ** type affinity of the other operand.  This routine returns the
7353db1458Sdrh ** type affinity that should be used for the comparison operator.
7453db1458Sdrh */
75e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
76bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
77e014a838Sdanielk1977   if( aff1 && aff2 ){
788df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
798df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
80e014a838Sdanielk1977     */
818a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
82e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
83e014a838Sdanielk1977     }else{
84e014a838Sdanielk1977       return SQLITE_AFF_NONE;
85e014a838Sdanielk1977     }
86e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
875f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
885f6a87b3Sdrh     ** results directly.
89e014a838Sdanielk1977     */
905f6a87b3Sdrh     return SQLITE_AFF_NONE;
91e014a838Sdanielk1977   }else{
92e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
93fe05af87Sdrh     assert( aff1==0 || aff2==0 );
94e014a838Sdanielk1977     return (aff1 + aff2);
95e014a838Sdanielk1977   }
96e014a838Sdanielk1977 }
97e014a838Sdanielk1977 
9853db1458Sdrh /*
9953db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
10053db1458Sdrh ** be applied to both operands prior to doing the comparison.
10153db1458Sdrh */
102e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
103e014a838Sdanielk1977   char aff;
104e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
105e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
106e014a838Sdanielk1977           pExpr->op==TK_NE );
107e014a838Sdanielk1977   assert( pExpr->pLeft );
108bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
109e014a838Sdanielk1977   if( pExpr->pRight ){
110e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
111e014a838Sdanielk1977   }
112e014a838Sdanielk1977   else if( pExpr->pSelect ){
113e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
114e014a838Sdanielk1977   }
115e014a838Sdanielk1977   else if( !aff ){
116e014a838Sdanielk1977     aff = SQLITE_AFF_NUMERIC;
117e014a838Sdanielk1977   }
118e014a838Sdanielk1977   return aff;
119e014a838Sdanielk1977 }
120e014a838Sdanielk1977 
121e014a838Sdanielk1977 /*
122e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
123e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
124e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
125e014a838Sdanielk1977 ** the comparison in pExpr.
126e014a838Sdanielk1977 */
127e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
128e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
1298a51256cSdrh   switch( aff ){
1308a51256cSdrh     case SQLITE_AFF_NONE:
1318a51256cSdrh       return 1;
1328a51256cSdrh     case SQLITE_AFF_TEXT:
1338a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
1348a51256cSdrh     default:
1358a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
1368a51256cSdrh   }
137e014a838Sdanielk1977 }
138e014a838Sdanielk1977 
139a37cdde0Sdanielk1977 /*
140a37cdde0Sdanielk1977 ** Return the P1 value that should be used for a binary comparison
141a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
142a37cdde0Sdanielk1977 ** If jumpIfNull is true, then set the low byte of the returned
143a37cdde0Sdanielk1977 ** P1 value to tell the opcode to jump if either expression
144a37cdde0Sdanielk1977 ** evaluates to NULL.
145a37cdde0Sdanielk1977 */
146e014a838Sdanielk1977 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
147bf3b721fSdanielk1977   char aff = sqlite3ExprAffinity(pExpr2);
148f0863fe5Sdrh   return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
149a37cdde0Sdanielk1977 }
150a37cdde0Sdanielk1977 
151a2e00042Sdrh /*
1520202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
1530202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
1540202b29eSdanielk1977 **
1550202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
1560202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
1570202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
1580202b29eSdanielk1977 ** type.
1590202b29eSdanielk1977 */
1607cedc8d4Sdanielk1977 static CollSeq* binaryCompareCollSeq(Parse *pParse, Expr *pLeft, Expr *pRight){
1617cedc8d4Sdanielk1977   CollSeq *pColl = sqlite3ExprCollSeq(pParse, pLeft);
1620202b29eSdanielk1977   if( !pColl ){
1637cedc8d4Sdanielk1977     pColl = sqlite3ExprCollSeq(pParse, pRight);
1640202b29eSdanielk1977   }
1650202b29eSdanielk1977   return pColl;
1660202b29eSdanielk1977 }
1670202b29eSdanielk1977 
1680202b29eSdanielk1977 /*
169be5c89acSdrh ** Generate code for a comparison operator.
170be5c89acSdrh */
171be5c89acSdrh static int codeCompare(
172be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
173be5c89acSdrh   Expr *pLeft,      /* The left operand */
174be5c89acSdrh   Expr *pRight,     /* The right operand */
175be5c89acSdrh   int opcode,       /* The comparison opcode */
176be5c89acSdrh   int dest,         /* Jump here if true.  */
177be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
178be5c89acSdrh ){
179be5c89acSdrh   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
180be5c89acSdrh   CollSeq *p3 = binaryCompareCollSeq(pParse, pLeft, pRight);
181be5c89acSdrh   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
182be5c89acSdrh }
183be5c89acSdrh 
184be5c89acSdrh /*
185a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
186a76b5dfcSdrh ** for this node is obtained from sqliteMalloc().  The calling function
187a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
188a76b5dfcSdrh */
189e4e72072Sdrh Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
190a76b5dfcSdrh   Expr *pNew;
191a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
192a76b5dfcSdrh   if( pNew==0 ){
193d5d56523Sdanielk1977     /* When malloc fails, delete pLeft and pRight. Expressions passed to
194d5d56523Sdanielk1977     ** this function must always be allocated with sqlite3Expr() for this
195d5d56523Sdanielk1977     ** reason.
196d5d56523Sdanielk1977     */
197d5d56523Sdanielk1977     sqlite3ExprDelete(pLeft);
198d5d56523Sdanielk1977     sqlite3ExprDelete(pRight);
199a76b5dfcSdrh     return 0;
200a76b5dfcSdrh   }
201a76b5dfcSdrh   pNew->op = op;
202a76b5dfcSdrh   pNew->pLeft = pLeft;
203a76b5dfcSdrh   pNew->pRight = pRight;
204a58fdfb1Sdanielk1977   pNew->iAgg = -1;
205a76b5dfcSdrh   if( pToken ){
2064b59ab5eSdrh     assert( pToken->dyn==0 );
207145716b3Sdrh     pNew->span = pNew->token = *pToken;
208145716b3Sdrh   }else if( pLeft && pRight ){
2094adee20fSdanielk1977     sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
210a76b5dfcSdrh   }
211a76b5dfcSdrh   return pNew;
212a76b5dfcSdrh }
213a76b5dfcSdrh 
214a76b5dfcSdrh /*
215206f3d96Sdrh ** Works like sqlite3Expr() but frees its pLeft and pRight arguments
216206f3d96Sdrh ** if it fails due to a malloc problem.
217206f3d96Sdrh */
218206f3d96Sdrh Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
219206f3d96Sdrh   Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
220206f3d96Sdrh   if( pNew==0 ){
221206f3d96Sdrh     sqlite3ExprDelete(pLeft);
222206f3d96Sdrh     sqlite3ExprDelete(pRight);
223206f3d96Sdrh   }
224206f3d96Sdrh   return pNew;
225206f3d96Sdrh }
226206f3d96Sdrh 
227206f3d96Sdrh /*
2284e0cff60Sdrh ** When doing a nested parse, you can include terms in an expression
2294e0cff60Sdrh ** that look like this:   #0 #1 #2 ...  These terms refer to elements
230288d37f1Sdrh ** on the stack.  "#0" means the top of the stack.
231288d37f1Sdrh ** "#1" means the next down on the stack.  And so forth.
2324e0cff60Sdrh **
2334e0cff60Sdrh ** This routine is called by the parser to deal with on of those terms.
2344e0cff60Sdrh ** It immediately generates code to store the value in a memory location.
2354e0cff60Sdrh ** The returns an expression that will code to extract the value from
2364e0cff60Sdrh ** that memory location as needed.
2374e0cff60Sdrh */
2384e0cff60Sdrh Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
2394e0cff60Sdrh   Vdbe *v = pParse->pVdbe;
2404e0cff60Sdrh   Expr *p;
2414e0cff60Sdrh   int depth;
2424e0cff60Sdrh   if( pParse->nested==0 ){
2434e0cff60Sdrh     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
2444e0cff60Sdrh     return 0;
2454e0cff60Sdrh   }
246bb7ac00bSdrh   if( v==0 ) return 0;
2474e0cff60Sdrh   p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
24873c42a13Sdrh   if( p==0 ){
24973c42a13Sdrh     return 0;  /* Malloc failed */
25073c42a13Sdrh   }
2512646da7eSdrh   depth = atoi((char*)&pToken->z[1]);
2524e0cff60Sdrh   p->iTable = pParse->nMem++;
2534e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
2544e0cff60Sdrh   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
2554e0cff60Sdrh   return p;
2564e0cff60Sdrh }
2574e0cff60Sdrh 
2584e0cff60Sdrh /*
25991bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
26091bb0eedSdrh ** NULL, then just return the other expression.
26191bb0eedSdrh */
26291bb0eedSdrh Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
26391bb0eedSdrh   if( pLeft==0 ){
26491bb0eedSdrh     return pRight;
26591bb0eedSdrh   }else if( pRight==0 ){
26691bb0eedSdrh     return pLeft;
26791bb0eedSdrh   }else{
26891bb0eedSdrh     return sqlite3Expr(TK_AND, pLeft, pRight, 0);
26991bb0eedSdrh   }
27091bb0eedSdrh }
27191bb0eedSdrh 
27291bb0eedSdrh /*
2736977fea8Sdrh ** Set the Expr.span field of the given expression to span all
274a76b5dfcSdrh ** text between the two given tokens.
275a76b5dfcSdrh */
2764adee20fSdanielk1977 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
2774efc4754Sdrh   assert( pRight!=0 );
2784efc4754Sdrh   assert( pLeft!=0 );
2799e12800dSdanielk1977   if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
280ad6d9460Sdrh     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
281145716b3Sdrh     if( pLeft->dyn==0 && pRight->dyn==0 ){
2826977fea8Sdrh       pExpr->span.z = pLeft->z;
28397903fefSdrh       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
2844b59ab5eSdrh     }else{
2856977fea8Sdrh       pExpr->span.z = 0;
2864b59ab5eSdrh     }
287a76b5dfcSdrh   }
288a76b5dfcSdrh }
289a76b5dfcSdrh 
290a76b5dfcSdrh /*
291a76b5dfcSdrh ** Construct a new expression node for a function with multiple
292a76b5dfcSdrh ** arguments.
293a76b5dfcSdrh */
2944adee20fSdanielk1977 Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
295a76b5dfcSdrh   Expr *pNew;
2964b202ae2Sdanielk1977   assert( pToken );
297a76b5dfcSdrh   pNew = sqliteMalloc( sizeof(Expr) );
298a76b5dfcSdrh   if( pNew==0 ){
299d5d56523Sdanielk1977     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
300a76b5dfcSdrh     return 0;
301a76b5dfcSdrh   }
302a76b5dfcSdrh   pNew->op = TK_FUNCTION;
303a76b5dfcSdrh   pNew->pList = pList;
3044b59ab5eSdrh   assert( pToken->dyn==0 );
305a76b5dfcSdrh   pNew->token = *pToken;
3066977fea8Sdrh   pNew->span = pNew->token;
307a76b5dfcSdrh   return pNew;
308a76b5dfcSdrh }
309a76b5dfcSdrh 
310a76b5dfcSdrh /*
311fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
312fa6bc000Sdrh ** in the original SQL statement.
313fa6bc000Sdrh **
314fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
315fa6bc000Sdrh ** variable number.
316fa6bc000Sdrh **
317fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
318fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
319fa6bc000Sdrh ** the SQL statement comes from an external source.
320fa6bc000Sdrh **
321fa6bc000Sdrh ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
322fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
323fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
324fa6bc000Sdrh ** assigned.
325fa6bc000Sdrh */
326fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
327fa6bc000Sdrh   Token *pToken;
328fa6bc000Sdrh   if( pExpr==0 ) return;
329fa6bc000Sdrh   pToken = &pExpr->token;
330fa6bc000Sdrh   assert( pToken->n>=1 );
331fa6bc000Sdrh   assert( pToken->z!=0 );
332fa6bc000Sdrh   assert( pToken->z[0]!=0 );
333fa6bc000Sdrh   if( pToken->n==1 ){
334fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
335fa6bc000Sdrh     pExpr->iTable = ++pParse->nVar;
336fa6bc000Sdrh   }else if( pToken->z[0]=='?' ){
337fa6bc000Sdrh     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
338fa6bc000Sdrh     ** use it as the variable number */
339fa6bc000Sdrh     int i;
3402646da7eSdrh     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
341fa6bc000Sdrh     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
342fa6bc000Sdrh       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
343fa6bc000Sdrh           SQLITE_MAX_VARIABLE_NUMBER);
344fa6bc000Sdrh     }
345fa6bc000Sdrh     if( i>pParse->nVar ){
346fa6bc000Sdrh       pParse->nVar = i;
347fa6bc000Sdrh     }
348fa6bc000Sdrh   }else{
349fa6bc000Sdrh     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
350fa6bc000Sdrh     ** number as the prior appearance of the same name, or if the name
351fa6bc000Sdrh     ** has never appeared before, reuse the same variable number
352fa6bc000Sdrh     */
353fa6bc000Sdrh     int i, n;
354fa6bc000Sdrh     n = pToken->n;
355fa6bc000Sdrh     for(i=0; i<pParse->nVarExpr; i++){
356fa6bc000Sdrh       Expr *pE;
357fa6bc000Sdrh       if( (pE = pParse->apVarExpr[i])!=0
358fa6bc000Sdrh           && pE->token.n==n
359fa6bc000Sdrh           && memcmp(pE->token.z, pToken->z, n)==0 ){
360fa6bc000Sdrh         pExpr->iTable = pE->iTable;
361fa6bc000Sdrh         break;
362fa6bc000Sdrh       }
363fa6bc000Sdrh     }
364fa6bc000Sdrh     if( i>=pParse->nVarExpr ){
365fa6bc000Sdrh       pExpr->iTable = ++pParse->nVar;
366fa6bc000Sdrh       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
367fa6bc000Sdrh         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
368e7259296Sdanielk1977         sqliteReallocOrFree((void**)&pParse->apVarExpr,
369fa6bc000Sdrh                        pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
370fa6bc000Sdrh       }
3719e12800dSdanielk1977       if( !sqlite3MallocFailed() ){
372fa6bc000Sdrh         assert( pParse->apVarExpr!=0 );
373fa6bc000Sdrh         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
374fa6bc000Sdrh       }
375fa6bc000Sdrh     }
376fa6bc000Sdrh   }
377fa6bc000Sdrh }
378fa6bc000Sdrh 
379fa6bc000Sdrh /*
380a2e00042Sdrh ** Recursively delete an expression tree.
381a2e00042Sdrh */
3824adee20fSdanielk1977 void sqlite3ExprDelete(Expr *p){
383a2e00042Sdrh   if( p==0 ) return;
3844efc4754Sdrh   if( p->span.dyn ) sqliteFree((char*)p->span.z);
3854efc4754Sdrh   if( p->token.dyn ) sqliteFree((char*)p->token.z);
3864adee20fSdanielk1977   sqlite3ExprDelete(p->pLeft);
3874adee20fSdanielk1977   sqlite3ExprDelete(p->pRight);
3884adee20fSdanielk1977   sqlite3ExprListDelete(p->pList);
3894adee20fSdanielk1977   sqlite3SelectDelete(p->pSelect);
390a2e00042Sdrh   sqliteFree(p);
391a2e00042Sdrh }
392a2e00042Sdrh 
393d2687b77Sdrh /*
394d2687b77Sdrh ** The Expr.token field might be a string literal that is quoted.
395d2687b77Sdrh ** If so, remove the quotation marks.
396d2687b77Sdrh */
397d2687b77Sdrh void sqlite3DequoteExpr(Expr *p){
398d2687b77Sdrh   if( ExprHasAnyProperty(p, EP_Dequoted) ){
399d2687b77Sdrh     return;
400d2687b77Sdrh   }
401d2687b77Sdrh   ExprSetProperty(p, EP_Dequoted);
402d2687b77Sdrh   if( p->token.dyn==0 ){
403d2687b77Sdrh     sqlite3TokenCopy(&p->token, &p->token);
404d2687b77Sdrh   }
405d2687b77Sdrh   sqlite3Dequote((char*)p->token.z);
406d2687b77Sdrh }
407d2687b77Sdrh 
408a76b5dfcSdrh 
409a76b5dfcSdrh /*
410ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
411ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
412ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
413ff78bd2fSdrh ** without effecting the originals.
414ff78bd2fSdrh **
4154adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
4164adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
417ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
418ff78bd2fSdrh **
419ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
420ff78bd2fSdrh */
4214adee20fSdanielk1977 Expr *sqlite3ExprDup(Expr *p){
422ff78bd2fSdrh   Expr *pNew;
423ff78bd2fSdrh   if( p==0 ) return 0;
424fcb78a49Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
425ff78bd2fSdrh   if( pNew==0 ) return 0;
4263b167c75Sdrh   memcpy(pNew, p, sizeof(*pNew));
4276977fea8Sdrh   if( p->token.z!=0 ){
4282646da7eSdrh     pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
4294b59ab5eSdrh     pNew->token.dyn = 1;
4304b59ab5eSdrh   }else{
4314efc4754Sdrh     assert( pNew->token.z==0 );
4324b59ab5eSdrh   }
4336977fea8Sdrh   pNew->span.z = 0;
4344adee20fSdanielk1977   pNew->pLeft = sqlite3ExprDup(p->pLeft);
4354adee20fSdanielk1977   pNew->pRight = sqlite3ExprDup(p->pRight);
4364adee20fSdanielk1977   pNew->pList = sqlite3ExprListDup(p->pList);
4374adee20fSdanielk1977   pNew->pSelect = sqlite3SelectDup(p->pSelect);
438aee18ef8Sdanielk1977   pNew->pTab = p->pTab;
439ff78bd2fSdrh   return pNew;
440ff78bd2fSdrh }
4414adee20fSdanielk1977 void sqlite3TokenCopy(Token *pTo, Token *pFrom){
4424b59ab5eSdrh   if( pTo->dyn ) sqliteFree((char*)pTo->z);
4434b59ab5eSdrh   if( pFrom->z ){
4444b59ab5eSdrh     pTo->n = pFrom->n;
4452646da7eSdrh     pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
4464b59ab5eSdrh     pTo->dyn = 1;
4474b59ab5eSdrh   }else{
4484b59ab5eSdrh     pTo->z = 0;
4494b59ab5eSdrh   }
4504b59ab5eSdrh }
4514adee20fSdanielk1977 ExprList *sqlite3ExprListDup(ExprList *p){
452ff78bd2fSdrh   ExprList *pNew;
453145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
454ff78bd2fSdrh   int i;
455ff78bd2fSdrh   if( p==0 ) return 0;
456ff78bd2fSdrh   pNew = sqliteMalloc( sizeof(*pNew) );
457ff78bd2fSdrh   if( pNew==0 ) return 0;
4584305d103Sdrh   pNew->nExpr = pNew->nAlloc = p->nExpr;
4593e7bc9caSdrh   pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
460e0048400Sdanielk1977   if( pItem==0 ){
461e0048400Sdanielk1977     sqliteFree(pNew);
462e0048400Sdanielk1977     return 0;
463e0048400Sdanielk1977   }
464145716b3Sdrh   pOldItem = p->a;
465145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
4664b59ab5eSdrh     Expr *pNewExpr, *pOldExpr;
467145716b3Sdrh     pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
4686977fea8Sdrh     if( pOldExpr->span.z!=0 && pNewExpr ){
4696977fea8Sdrh       /* Always make a copy of the span for top-level expressions in the
4704b59ab5eSdrh       ** expression list.  The logic in SELECT processing that determines
4714b59ab5eSdrh       ** the names of columns in the result set needs this information */
4724adee20fSdanielk1977       sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
4734b59ab5eSdrh     }
4741f3e905cSdrh     assert( pNewExpr==0 || pNewExpr->span.z!=0
4756f7adc8aSdrh             || pOldExpr->span.z==0
4769e12800dSdanielk1977             || sqlite3MallocFailed() );
477145716b3Sdrh     pItem->zName = sqliteStrDup(pOldItem->zName);
478145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
479145716b3Sdrh     pItem->isAgg = pOldItem->isAgg;
4803e7bc9caSdrh     pItem->done = 0;
481ff78bd2fSdrh   }
482ff78bd2fSdrh   return pNew;
483ff78bd2fSdrh }
48493758c8dSdanielk1977 
48593758c8dSdanielk1977 /*
48693758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
48793758c8dSdanielk1977 ** the build, then none of the following routines, except for
48893758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
48993758c8dSdanielk1977 ** called with a NULL argument.
49093758c8dSdanielk1977 */
4916a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
4926a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
4934adee20fSdanielk1977 SrcList *sqlite3SrcListDup(SrcList *p){
494ad3cab52Sdrh   SrcList *pNew;
495ad3cab52Sdrh   int i;
496113088ecSdrh   int nByte;
497ad3cab52Sdrh   if( p==0 ) return 0;
498113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
4994efc4754Sdrh   pNew = sqliteMallocRaw( nByte );
500ad3cab52Sdrh   if( pNew==0 ) return 0;
5014305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
502ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
5034efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
5044efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
505ed8a3bb1Sdrh     Table *pTab;
5064efc4754Sdrh     pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
5074efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5084efc4754Sdrh     pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
5094efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
5104efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
5111787ccabSdanielk1977     pNewItem->isPopulated = pOldItem->isPopulated;
512ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
513ed8a3bb1Sdrh     if( pTab ){
514ed8a3bb1Sdrh       pTab->nRef++;
515a1cb183dSdanielk1977     }
5164adee20fSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
5174adee20fSdanielk1977     pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
5184adee20fSdanielk1977     pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
5196c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
520ad3cab52Sdrh   }
521ad3cab52Sdrh   return pNew;
522ad3cab52Sdrh }
5234adee20fSdanielk1977 IdList *sqlite3IdListDup(IdList *p){
524ff78bd2fSdrh   IdList *pNew;
525ff78bd2fSdrh   int i;
526ff78bd2fSdrh   if( p==0 ) return 0;
5274efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*pNew) );
528ff78bd2fSdrh   if( pNew==0 ) return 0;
5294305d103Sdrh   pNew->nId = pNew->nAlloc = p->nId;
5304efc4754Sdrh   pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
531d5d56523Sdanielk1977   if( pNew->a==0 ){
532d5d56523Sdanielk1977     sqliteFree(pNew);
533d5d56523Sdanielk1977     return 0;
534d5d56523Sdanielk1977   }
535ff78bd2fSdrh   for(i=0; i<p->nId; i++){
5364efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
5374efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
5384efc4754Sdrh     pNewItem->zName = sqliteStrDup(pOldItem->zName);
5394efc4754Sdrh     pNewItem->idx = pOldItem->idx;
540ff78bd2fSdrh   }
541ff78bd2fSdrh   return pNew;
542ff78bd2fSdrh }
5434adee20fSdanielk1977 Select *sqlite3SelectDup(Select *p){
544ff78bd2fSdrh   Select *pNew;
545ff78bd2fSdrh   if( p==0 ) return 0;
5464efc4754Sdrh   pNew = sqliteMallocRaw( sizeof(*p) );
547ff78bd2fSdrh   if( pNew==0 ) return 0;
548ff78bd2fSdrh   pNew->isDistinct = p->isDistinct;
5494adee20fSdanielk1977   pNew->pEList = sqlite3ExprListDup(p->pEList);
5504adee20fSdanielk1977   pNew->pSrc = sqlite3SrcListDup(p->pSrc);
5514adee20fSdanielk1977   pNew->pWhere = sqlite3ExprDup(p->pWhere);
5524adee20fSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
5534adee20fSdanielk1977   pNew->pHaving = sqlite3ExprDup(p->pHaving);
5544adee20fSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
555ff78bd2fSdrh   pNew->op = p->op;
5564adee20fSdanielk1977   pNew->pPrior = sqlite3SelectDup(p->pPrior);
557a2dc3b1aSdanielk1977   pNew->pLimit = sqlite3ExprDup(p->pLimit);
558a2dc3b1aSdanielk1977   pNew->pOffset = sqlite3ExprDup(p->pOffset);
5597b58daeaSdrh   pNew->iLimit = -1;
5607b58daeaSdrh   pNew->iOffset = -1;
561a1cb183dSdanielk1977   pNew->isResolved = p->isResolved;
562a1cb183dSdanielk1977   pNew->isAgg = p->isAgg;
563b9bb7c18Sdrh   pNew->usesEphm = 0;
5648e647b81Sdrh   pNew->disallowOrderBy = 0;
5650342b1f5Sdrh   pNew->pRightmost = 0;
566b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
567b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
568b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
569ff78bd2fSdrh   return pNew;
570ff78bd2fSdrh }
57193758c8dSdanielk1977 #else
57293758c8dSdanielk1977 Select *sqlite3SelectDup(Select *p){
57393758c8dSdanielk1977   assert( p==0 );
57493758c8dSdanielk1977   return 0;
57593758c8dSdanielk1977 }
57693758c8dSdanielk1977 #endif
577ff78bd2fSdrh 
578ff78bd2fSdrh 
579ff78bd2fSdrh /*
580a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
581a76b5dfcSdrh ** initially NULL, then create a new expression list.
582a76b5dfcSdrh */
5834adee20fSdanielk1977 ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
584a76b5dfcSdrh   if( pList==0 ){
585a76b5dfcSdrh     pList = sqliteMalloc( sizeof(ExprList) );
586a76b5dfcSdrh     if( pList==0 ){
587d5d56523Sdanielk1977       goto no_mem;
588a76b5dfcSdrh     }
5894efc4754Sdrh     assert( pList->nAlloc==0 );
590a76b5dfcSdrh   }
5914305d103Sdrh   if( pList->nAlloc<=pList->nExpr ){
592d5d56523Sdanielk1977     struct ExprList_item *a;
593d5d56523Sdanielk1977     int n = pList->nAlloc*2 + 4;
594d5d56523Sdanielk1977     a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
595d5d56523Sdanielk1977     if( a==0 ){
596d5d56523Sdanielk1977       goto no_mem;
597a76b5dfcSdrh     }
598d5d56523Sdanielk1977     pList->a = a;
599d5d56523Sdanielk1977     pList->nAlloc = n;
600a76b5dfcSdrh   }
6014efc4754Sdrh   assert( pList->a!=0 );
6024efc4754Sdrh   if( pExpr || pName ){
6034efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
6044efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
605a99db3b6Sdrh     pItem->zName = sqlite3NameFromToken(pName);
606e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
607a76b5dfcSdrh   }
608a76b5dfcSdrh   return pList;
609d5d56523Sdanielk1977 
610d5d56523Sdanielk1977 no_mem:
611d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
612d5d56523Sdanielk1977   sqlite3ExprDelete(pExpr);
613d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
614d5d56523Sdanielk1977   return 0;
615a76b5dfcSdrh }
616a76b5dfcSdrh 
617a76b5dfcSdrh /*
618a76b5dfcSdrh ** Delete an entire expression list.
619a76b5dfcSdrh */
6204adee20fSdanielk1977 void sqlite3ExprListDelete(ExprList *pList){
621a76b5dfcSdrh   int i;
622be5c89acSdrh   struct ExprList_item *pItem;
623a76b5dfcSdrh   if( pList==0 ) return;
6241bdd9b57Sdrh   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
6251bdd9b57Sdrh   assert( pList->nExpr<=pList->nAlloc );
626be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
627be5c89acSdrh     sqlite3ExprDelete(pItem->pExpr);
628be5c89acSdrh     sqliteFree(pItem->zName);
629a76b5dfcSdrh   }
630a76b5dfcSdrh   sqliteFree(pList->a);
631a76b5dfcSdrh   sqliteFree(pList);
632a76b5dfcSdrh }
633a76b5dfcSdrh 
634a76b5dfcSdrh /*
635626a879aSdrh ** Walk an expression tree.  Call xFunc for each node visited.
63673b211abSdrh **
637626a879aSdrh ** The return value from xFunc determines whether the tree walk continues.
638626a879aSdrh ** 0 means continue walking the tree.  1 means do not walk children
639626a879aSdrh ** of the current node but continue with siblings.  2 means abandon
640626a879aSdrh ** the tree walk completely.
641626a879aSdrh **
642626a879aSdrh ** The return value from this routine is 1 to abandon the tree walk
643626a879aSdrh ** and 0 to continue.
64487abf5c0Sdrh **
64587abf5c0Sdrh ** NOTICE:  This routine does *not* descend into subqueries.
646626a879aSdrh */
647a58fdfb1Sdanielk1977 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
648626a879aSdrh static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
649626a879aSdrh   int rc;
650626a879aSdrh   if( pExpr==0 ) return 0;
651626a879aSdrh   rc = (*xFunc)(pArg, pExpr);
652626a879aSdrh   if( rc==0 ){
653626a879aSdrh     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
654626a879aSdrh     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
655a58fdfb1Sdanielk1977     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
656626a879aSdrh   }
657626a879aSdrh   return rc>1;
658626a879aSdrh }
659626a879aSdrh 
660626a879aSdrh /*
661a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in list p.
662a58fdfb1Sdanielk1977 */
663a58fdfb1Sdanielk1977 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
664a58fdfb1Sdanielk1977   int i;
665a58fdfb1Sdanielk1977   struct ExprList_item *pItem;
666a58fdfb1Sdanielk1977   if( !p ) return 0;
667a58fdfb1Sdanielk1977   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
668a58fdfb1Sdanielk1977     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
669a58fdfb1Sdanielk1977   }
670a58fdfb1Sdanielk1977   return 0;
671a58fdfb1Sdanielk1977 }
672a58fdfb1Sdanielk1977 
673a58fdfb1Sdanielk1977 /*
674a58fdfb1Sdanielk1977 ** Call walkExprTree() for every expression in Select p, not including
675a58fdfb1Sdanielk1977 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
676a58fdfb1Sdanielk1977 ** or OFFSET expressions..
677a58fdfb1Sdanielk1977 */
678a58fdfb1Sdanielk1977 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
679a58fdfb1Sdanielk1977   walkExprList(p->pEList, xFunc, pArg);
680a58fdfb1Sdanielk1977   walkExprTree(p->pWhere, xFunc, pArg);
681a58fdfb1Sdanielk1977   walkExprList(p->pGroupBy, xFunc, pArg);
682a58fdfb1Sdanielk1977   walkExprTree(p->pHaving, xFunc, pArg);
683a58fdfb1Sdanielk1977   walkExprList(p->pOrderBy, xFunc, pArg);
684a58fdfb1Sdanielk1977   return 0;
685a58fdfb1Sdanielk1977 }
686a58fdfb1Sdanielk1977 
687a58fdfb1Sdanielk1977 
688a58fdfb1Sdanielk1977 /*
689626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
690626a879aSdrh **
691626a879aSdrh ** pArg is really a pointer to an integer.  If we can tell by looking
69273b211abSdrh ** at pExpr that the expression that contains pExpr is not a constant
69373b211abSdrh ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
69473b211abSdrh ** If pExpr does does not disqualify the expression from being a constant
69573b211abSdrh ** then do nothing.
69673b211abSdrh **
69773b211abSdrh ** After walking the whole tree, if no nodes are found that disqualify
69873b211abSdrh ** the expression as constant, then we assume the whole expression
69973b211abSdrh ** is constant.  See sqlite3ExprIsConstant() for additional information.
700626a879aSdrh */
701626a879aSdrh static int exprNodeIsConstant(void *pArg, Expr *pExpr){
702626a879aSdrh   switch( pExpr->op ){
703eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
704eb55bd2fSdrh     ** and *pArg==2 */
705eb55bd2fSdrh     case TK_FUNCTION:
706eb55bd2fSdrh       if( *((int*)pArg)==2 ) return 0;
707eb55bd2fSdrh       /* Fall through */
708626a879aSdrh     case TK_ID:
709626a879aSdrh     case TK_COLUMN:
710626a879aSdrh     case TK_DOT:
711626a879aSdrh     case TK_AGG_FUNCTION:
71213449892Sdrh     case TK_AGG_COLUMN:
713fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
714fe2093d7Sdrh     case TK_SELECT:
715fe2093d7Sdrh     case TK_EXISTS:
716fe2093d7Sdrh #endif
717626a879aSdrh       *((int*)pArg) = 0;
718626a879aSdrh       return 2;
71987abf5c0Sdrh     case TK_IN:
72087abf5c0Sdrh       if( pExpr->pSelect ){
72187abf5c0Sdrh         *((int*)pArg) = 0;
72287abf5c0Sdrh         return 2;
72387abf5c0Sdrh       }
724626a879aSdrh     default:
725626a879aSdrh       return 0;
726626a879aSdrh   }
727626a879aSdrh }
728626a879aSdrh 
729626a879aSdrh /*
730fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
731eb55bd2fSdrh ** and 0 if it involves variables or function calls.
7322398937bSdrh **
7332398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
7342398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
7352398937bSdrh ** a constant.
736fef5208cSdrh */
7374adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
738626a879aSdrh   int isConst = 1;
739626a879aSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
740626a879aSdrh   return isConst;
741fef5208cSdrh }
742fef5208cSdrh 
743fef5208cSdrh /*
744eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
745eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
746eb55bd2fSdrh ** are any variables.
747eb55bd2fSdrh **
748eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
749eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
750eb55bd2fSdrh ** a constant.
751eb55bd2fSdrh */
752eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
753eb55bd2fSdrh   int isConst = 2;
754eb55bd2fSdrh   walkExprTree(p, exprNodeIsConstant, &isConst);
755eb55bd2fSdrh   return isConst!=0;
756eb55bd2fSdrh }
757eb55bd2fSdrh 
758eb55bd2fSdrh /*
75973b211abSdrh ** If the expression p codes a constant integer that is small enough
760202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
761202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
762202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
763e4de1febSdrh */
7644adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
765e4de1febSdrh   switch( p->op ){
766e4de1febSdrh     case TK_INTEGER: {
7672646da7eSdrh       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
768e4de1febSdrh         return 1;
769e4de1febSdrh       }
770202b2df7Sdrh       break;
771202b2df7Sdrh     }
7724b59ab5eSdrh     case TK_UPLUS: {
7734adee20fSdanielk1977       return sqlite3ExprIsInteger(p->pLeft, pValue);
7744b59ab5eSdrh     }
775e4de1febSdrh     case TK_UMINUS: {
776e4de1febSdrh       int v;
7774adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
778e4de1febSdrh         *pValue = -v;
779e4de1febSdrh         return 1;
780e4de1febSdrh       }
781e4de1febSdrh       break;
782e4de1febSdrh     }
783e4de1febSdrh     default: break;
784e4de1febSdrh   }
785e4de1febSdrh   return 0;
786e4de1febSdrh }
787e4de1febSdrh 
788e4de1febSdrh /*
789c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
790c4a3c779Sdrh */
7914adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
7924adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
7934adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
7944adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
795c4a3c779Sdrh   return 0;
796c4a3c779Sdrh }
797c4a3c779Sdrh 
798c4a3c779Sdrh /*
7998141f61eSdrh ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
8008141f61eSdrh ** that name in the set of source tables in pSrcList and make the pExpr
8018141f61eSdrh ** expression node refer back to that source column.  The following changes
8028141f61eSdrh ** are made to pExpr:
8038141f61eSdrh **
8048141f61eSdrh **    pExpr->iDb           Set the index in db->aDb[] of the database holding
8058141f61eSdrh **                         the table.
8068141f61eSdrh **    pExpr->iTable        Set to the cursor number for the table obtained
8078141f61eSdrh **                         from pSrcList.
8088141f61eSdrh **    pExpr->iColumn       Set to the column number within the table.
8098141f61eSdrh **    pExpr->op            Set to TK_COLUMN.
8108141f61eSdrh **    pExpr->pLeft         Any expression this points to is deleted
8118141f61eSdrh **    pExpr->pRight        Any expression this points to is deleted.
8128141f61eSdrh **
8138141f61eSdrh ** The pDbToken is the name of the database (the "X").  This value may be
8148141f61eSdrh ** NULL meaning that name is of the form Y.Z or Z.  Any available database
8158141f61eSdrh ** can be used.  The pTableToken is the name of the table (the "Y").  This
8168141f61eSdrh ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
8178141f61eSdrh ** means that the form of the name is Z and that columns from any table
8188141f61eSdrh ** can be used.
8198141f61eSdrh **
8208141f61eSdrh ** If the name cannot be resolved unambiguously, leave an error message
8218141f61eSdrh ** in pParse and return non-zero.  Return zero on success.
8228141f61eSdrh */
8238141f61eSdrh static int lookupName(
8248141f61eSdrh   Parse *pParse,       /* The parsing context */
8258141f61eSdrh   Token *pDbToken,     /* Name of the database containing table, or NULL */
8268141f61eSdrh   Token *pTableToken,  /* Name of table containing column, or NULL */
8278141f61eSdrh   Token *pColumnToken, /* Name of the column. */
828626a879aSdrh   NameContext *pNC,    /* The name context used to resolve the name */
8298141f61eSdrh   Expr *pExpr          /* Make this EXPR node point to the selected column */
8308141f61eSdrh ){
8318141f61eSdrh   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
8328141f61eSdrh   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
8338141f61eSdrh   char *zCol = 0;      /* Name of the column.  The "Z" */
8348141f61eSdrh   int i, j;            /* Loop counters */
8358141f61eSdrh   int cnt = 0;         /* Number of matching column names */
8368141f61eSdrh   int cntTab = 0;      /* Number of matching table names */
8379bb575fdSdrh   sqlite3 *db = pParse->db;  /* The database */
83851669863Sdrh   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
83951669863Sdrh   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
84073b211abSdrh   NameContext *pTopNC = pNC;        /* First namecontext in the list */
8418141f61eSdrh 
8428141f61eSdrh   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
843a99db3b6Sdrh   zDb = sqlite3NameFromToken(pDbToken);
844a99db3b6Sdrh   zTab = sqlite3NameFromToken(pTableToken);
845a99db3b6Sdrh   zCol = sqlite3NameFromToken(pColumnToken);
8469e12800dSdanielk1977   if( sqlite3MallocFailed() ){
847d5d56523Sdanielk1977     goto lookupname_end;
8488141f61eSdrh   }
8498141f61eSdrh 
8508141f61eSdrh   pExpr->iTable = -1;
851626a879aSdrh   while( pNC && cnt==0 ){
852ffe07b2dSdrh     ExprList *pEList;
853626a879aSdrh     SrcList *pSrcList = pNC->pSrcList;
854626a879aSdrh 
855b3bce662Sdanielk1977     if( pSrcList ){
85651669863Sdrh       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
85743617e9aSdrh         Table *pTab;
85843617e9aSdrh         int iDb;
8598141f61eSdrh         Column *pCol;
8608141f61eSdrh 
86143617e9aSdrh         pTab = pItem->pTab;
86243617e9aSdrh         assert( pTab!=0 );
86343617e9aSdrh         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
8648141f61eSdrh         assert( pTab->nCol>0 );
8658141f61eSdrh         if( zTab ){
8668141f61eSdrh           if( pItem->zAlias ){
8678141f61eSdrh             char *zTabName = pItem->zAlias;
8684adee20fSdanielk1977             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
8698141f61eSdrh           }else{
8708141f61eSdrh             char *zTabName = pTab->zName;
8714adee20fSdanielk1977             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
872da184236Sdanielk1977             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
8738141f61eSdrh               continue;
8748141f61eSdrh             }
8758141f61eSdrh           }
8768141f61eSdrh         }
8778141f61eSdrh         if( 0==(cntTab++) ){
8788141f61eSdrh           pExpr->iTable = pItem->iCursor;
879da184236Sdanielk1977           pExpr->pSchema = pTab->pSchema;
88051669863Sdrh           pMatch = pItem;
8818141f61eSdrh         }
8828141f61eSdrh         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
8834adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
884b3bf556eSdanielk1977             const char *zColl = pTab->aCol[j].zColl;
885873fac0cSdrh             IdList *pUsing;
8868141f61eSdrh             cnt++;
8878141f61eSdrh             pExpr->iTable = pItem->iCursor;
88851669863Sdrh             pMatch = pItem;
889da184236Sdanielk1977             pExpr->pSchema = pTab->pSchema;
8908141f61eSdrh             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
8918141f61eSdrh             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
892a37cdde0Sdanielk1977             pExpr->affinity = pTab->aCol[j].affinity;
893b3bf556eSdanielk1977             pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
89461dfc31dSdrh             if( i<pSrcList->nSrc-1 ){
89561dfc31dSdrh               if( pItem[1].jointype & JT_NATURAL ){
896355ef361Sdrh                 /* If this match occurred in the left table of a natural join,
897355ef361Sdrh                 ** then skip the right table to avoid a duplicate match */
898355ef361Sdrh                 pItem++;
899355ef361Sdrh                 i++;
90061dfc31dSdrh               }else if( (pUsing = pItem[1].pUsing)!=0 ){
901873fac0cSdrh                 /* If this match occurs on a column that is in the USING clause
902873fac0cSdrh                 ** of a join, skip the search of the right table of the join
903873fac0cSdrh                 ** to avoid a duplicate match there. */
904873fac0cSdrh                 int k;
905873fac0cSdrh                 for(k=0; k<pUsing->nId; k++){
906873fac0cSdrh                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
907873fac0cSdrh                     pItem++;
908873fac0cSdrh                     i++;
909873fac0cSdrh                     break;
910873fac0cSdrh                   }
911873fac0cSdrh                 }
912873fac0cSdrh               }
91361dfc31dSdrh             }
9148141f61eSdrh             break;
9158141f61eSdrh           }
9168141f61eSdrh         }
9178141f61eSdrh       }
918b3bce662Sdanielk1977     }
9198141f61eSdrh 
920b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
9218141f61eSdrh     /* If we have not already resolved the name, then maybe
9228141f61eSdrh     ** it is a new.* or old.* trigger argument reference
9238141f61eSdrh     */
9248141f61eSdrh     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
9258141f61eSdrh       TriggerStack *pTriggerStack = pParse->trigStack;
9268141f61eSdrh       Table *pTab = 0;
9274adee20fSdanielk1977       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
9288141f61eSdrh         pExpr->iTable = pTriggerStack->newIdx;
9298141f61eSdrh         assert( pTriggerStack->pTab );
9308141f61eSdrh         pTab = pTriggerStack->pTab;
9314adee20fSdanielk1977       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
9328141f61eSdrh         pExpr->iTable = pTriggerStack->oldIdx;
9338141f61eSdrh         assert( pTriggerStack->pTab );
9348141f61eSdrh         pTab = pTriggerStack->pTab;
9358141f61eSdrh       }
9368141f61eSdrh 
9378141f61eSdrh       if( pTab ){
938f0113000Sdanielk1977         int iCol;
9398141f61eSdrh         Column *pCol = pTab->aCol;
9408141f61eSdrh 
941da184236Sdanielk1977         pExpr->pSchema = pTab->pSchema;
9428141f61eSdrh         cntTab++;
943f0113000Sdanielk1977         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
9444adee20fSdanielk1977           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
945f0113000Sdanielk1977             const char *zColl = pTab->aCol[iCol].zColl;
9468141f61eSdrh             cnt++;
947f0113000Sdanielk1977             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
948f0113000Sdanielk1977             pExpr->affinity = pTab->aCol[iCol].affinity;
949b3bf556eSdanielk1977             pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
950aee18ef8Sdanielk1977             pExpr->pTab = pTab;
9518141f61eSdrh             break;
9528141f61eSdrh           }
9538141f61eSdrh         }
9548141f61eSdrh       }
9558141f61eSdrh     }
956b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_TRIGGER) */
9578141f61eSdrh 
9588141f61eSdrh     /*
9598141f61eSdrh     ** Perhaps the name is a reference to the ROWID
9608141f61eSdrh     */
9614adee20fSdanielk1977     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
9628141f61eSdrh       cnt = 1;
9638141f61eSdrh       pExpr->iColumn = -1;
9648a51256cSdrh       pExpr->affinity = SQLITE_AFF_INTEGER;
9658141f61eSdrh     }
9668141f61eSdrh 
9678141f61eSdrh     /*
9688141f61eSdrh     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
9698141f61eSdrh     ** might refer to an result-set alias.  This happens, for example, when
9708141f61eSdrh     ** we are resolving names in the WHERE clause of the following command:
9718141f61eSdrh     **
9728141f61eSdrh     **     SELECT a+b AS x FROM table WHERE x<10;
9738141f61eSdrh     **
9748141f61eSdrh     ** In cases like this, replace pExpr with a copy of the expression that
9758141f61eSdrh     ** forms the result set entry ("a+b" in the example) and return immediately.
9768141f61eSdrh     ** Note that the expression in the result set should have already been
9778141f61eSdrh     ** resolved by the time the WHERE clause is resolved.
9788141f61eSdrh     */
979ffe07b2dSdrh     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
9808141f61eSdrh       for(j=0; j<pEList->nExpr; j++){
9818141f61eSdrh         char *zAs = pEList->a[j].zName;
9824adee20fSdanielk1977         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
9838141f61eSdrh           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
9848141f61eSdrh           pExpr->op = TK_AS;
9858141f61eSdrh           pExpr->iColumn = j;
9864adee20fSdanielk1977           pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
98715ccce1cSdrh           cnt = 1;
9888141f61eSdrh           assert( zTab==0 && zDb==0 );
98915ccce1cSdrh           goto lookupname_end_2;
9908141f61eSdrh         }
9918141f61eSdrh       }
9928141f61eSdrh     }
9938141f61eSdrh 
994626a879aSdrh     /* Advance to the next name context.  The loop will exit when either
995626a879aSdrh     ** we have a match (cnt>0) or when we run out of name contexts.
996626a879aSdrh     */
997626a879aSdrh     if( cnt==0 ){
998626a879aSdrh       pNC = pNC->pNext;
999626a879aSdrh     }
1000626a879aSdrh   }
1001626a879aSdrh 
10028141f61eSdrh   /*
10038141f61eSdrh   ** If X and Y are NULL (in other words if only the column name Z is
10048141f61eSdrh   ** supplied) and the value of Z is enclosed in double-quotes, then
10058141f61eSdrh   ** Z is a string literal if it doesn't match any column names.  In that
10068141f61eSdrh   ** case, we need to return right away and not make any changes to
10078141f61eSdrh   ** pExpr.
100815ccce1cSdrh   **
100915ccce1cSdrh   ** Because no reference was made to outer contexts, the pNC->nRef
101015ccce1cSdrh   ** fields are not changed in any context.
10118141f61eSdrh   */
10128141f61eSdrh   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
10138141f61eSdrh     sqliteFree(zCol);
10148141f61eSdrh     return 0;
10158141f61eSdrh   }
10168141f61eSdrh 
10178141f61eSdrh   /*
10188141f61eSdrh   ** cnt==0 means there was not match.  cnt>1 means there were two or
10198141f61eSdrh   ** more matches.  Either way, we have an error.
10208141f61eSdrh   */
10218141f61eSdrh   if( cnt!=1 ){
10228141f61eSdrh     char *z = 0;
10238141f61eSdrh     char *zErr;
10248141f61eSdrh     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
10258141f61eSdrh     if( zDb ){
1026f93339deSdrh       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
10278141f61eSdrh     }else if( zTab ){
1028f93339deSdrh       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
10298141f61eSdrh     }else{
10308141f61eSdrh       z = sqliteStrDup(zCol);
10318141f61eSdrh     }
10324adee20fSdanielk1977     sqlite3ErrorMsg(pParse, zErr, z);
10338141f61eSdrh     sqliteFree(z);
103473b211abSdrh     pTopNC->nErr++;
10358141f61eSdrh   }
10368141f61eSdrh 
103751669863Sdrh   /* If a column from a table in pSrcList is referenced, then record
103851669863Sdrh   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
103951669863Sdrh   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
104051669863Sdrh   ** column number is greater than the number of bits in the bitmask
104151669863Sdrh   ** then set the high-order bit of the bitmask.
104251669863Sdrh   */
104351669863Sdrh   if( pExpr->iColumn>=0 && pMatch!=0 ){
104451669863Sdrh     int n = pExpr->iColumn;
104551669863Sdrh     if( n>=sizeof(Bitmask)*8 ){
104651669863Sdrh       n = sizeof(Bitmask)*8-1;
104751669863Sdrh     }
104851669863Sdrh     assert( pMatch->iCursor==pExpr->iTable );
1049*ca83ac51Sdrh     pMatch->colUsed |= ((Bitmask)1)<<n;
105051669863Sdrh   }
105151669863Sdrh 
1052d5d56523Sdanielk1977 lookupname_end:
10538141f61eSdrh   /* Clean up and return
10548141f61eSdrh   */
10558141f61eSdrh   sqliteFree(zDb);
10568141f61eSdrh   sqliteFree(zTab);
10574adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pLeft);
10588141f61eSdrh   pExpr->pLeft = 0;
10594adee20fSdanielk1977   sqlite3ExprDelete(pExpr->pRight);
10608141f61eSdrh   pExpr->pRight = 0;
10618141f61eSdrh   pExpr->op = TK_COLUMN;
106215ccce1cSdrh lookupname_end_2:
106315ccce1cSdrh   sqliteFree(zCol);
1064626a879aSdrh   if( cnt==1 ){
1065b3bce662Sdanielk1977     assert( pNC!=0 );
1066626a879aSdrh     sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1067aee18ef8Sdanielk1977     if( pMatch && !pMatch->pSelect ){
1068aee18ef8Sdanielk1977       pExpr->pTab = pMatch->pTab;
1069aee18ef8Sdanielk1977     }
107015ccce1cSdrh     /* Increment the nRef value on all name contexts from TopNC up to
107115ccce1cSdrh     ** the point where the name matched. */
107215ccce1cSdrh     for(;;){
107315ccce1cSdrh       assert( pTopNC!=0 );
107415ccce1cSdrh       pTopNC->nRef++;
107515ccce1cSdrh       if( pTopNC==pNC ) break;
107615ccce1cSdrh       pTopNC = pTopNC->pNext;
1077626a879aSdrh     }
107815ccce1cSdrh     return 0;
107915ccce1cSdrh   } else {
108015ccce1cSdrh     return 1;
108115ccce1cSdrh   }
10828141f61eSdrh }
10838141f61eSdrh 
10848141f61eSdrh /*
1085626a879aSdrh ** This routine is designed as an xFunc for walkExprTree().
1086626a879aSdrh **
108773b211abSdrh ** Resolve symbolic names into TK_COLUMN operators for the current
1088626a879aSdrh ** node in the expression tree.  Return 0 to continue the search down
108973b211abSdrh ** the tree or 2 to abort the tree walk.
109073b211abSdrh **
109173b211abSdrh ** This routine also does error checking and name resolution for
109273b211abSdrh ** function names.  The operator for aggregate functions is changed
109373b211abSdrh ** to TK_AGG_FUNCTION.
1094626a879aSdrh */
1095626a879aSdrh static int nameResolverStep(void *pArg, Expr *pExpr){
1096626a879aSdrh   NameContext *pNC = (NameContext*)pArg;
1097626a879aSdrh   Parse *pParse;
1098626a879aSdrh 
1099b3bce662Sdanielk1977   if( pExpr==0 ) return 1;
1100626a879aSdrh   assert( pNC!=0 );
1101626a879aSdrh   pParse = pNC->pParse;
1102b3bce662Sdanielk1977 
1103626a879aSdrh   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1104626a879aSdrh   ExprSetProperty(pExpr, EP_Resolved);
1105626a879aSdrh #ifndef NDEBUG
1106f0113000Sdanielk1977   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1107f0113000Sdanielk1977     SrcList *pSrcList = pNC->pSrcList;
1108940fac9dSdanielk1977     int i;
1109f0113000Sdanielk1977     for(i=0; i<pNC->pSrcList->nSrc; i++){
1110626a879aSdrh       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1111626a879aSdrh     }
1112626a879aSdrh   }
1113626a879aSdrh #endif
1114626a879aSdrh   switch( pExpr->op ){
1115626a879aSdrh     /* Double-quoted strings (ex: "abc") are used as identifiers if
1116626a879aSdrh     ** possible.  Otherwise they remain as strings.  Single-quoted
1117626a879aSdrh     ** strings (ex: 'abc') are always string literals.
1118626a879aSdrh     */
1119626a879aSdrh     case TK_STRING: {
1120626a879aSdrh       if( pExpr->token.z[0]=='\'' ) break;
1121626a879aSdrh       /* Fall thru into the TK_ID case if this is a double-quoted string */
1122626a879aSdrh     }
1123626a879aSdrh     /* A lone identifier is the name of a column.
1124626a879aSdrh     */
1125626a879aSdrh     case TK_ID: {
1126626a879aSdrh       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1127626a879aSdrh       return 1;
1128626a879aSdrh     }
1129626a879aSdrh 
1130626a879aSdrh     /* A table name and column name:     ID.ID
1131626a879aSdrh     ** Or a database, table and column:  ID.ID.ID
1132626a879aSdrh     */
1133626a879aSdrh     case TK_DOT: {
1134626a879aSdrh       Token *pColumn;
1135626a879aSdrh       Token *pTable;
1136626a879aSdrh       Token *pDb;
1137626a879aSdrh       Expr *pRight;
1138626a879aSdrh 
1139b3bce662Sdanielk1977       /* if( pSrcList==0 ) break; */
1140626a879aSdrh       pRight = pExpr->pRight;
1141626a879aSdrh       if( pRight->op==TK_ID ){
1142626a879aSdrh         pDb = 0;
1143626a879aSdrh         pTable = &pExpr->pLeft->token;
1144626a879aSdrh         pColumn = &pRight->token;
1145626a879aSdrh       }else{
1146626a879aSdrh         assert( pRight->op==TK_DOT );
1147626a879aSdrh         pDb = &pExpr->pLeft->token;
1148626a879aSdrh         pTable = &pRight->pLeft->token;
1149626a879aSdrh         pColumn = &pRight->pRight->token;
1150626a879aSdrh       }
1151626a879aSdrh       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1152626a879aSdrh       return 1;
1153626a879aSdrh     }
1154626a879aSdrh 
1155626a879aSdrh     /* Resolve function names
1156626a879aSdrh     */
1157b71090fdSdrh     case TK_CONST_FUNC:
1158626a879aSdrh     case TK_FUNCTION: {
1159626a879aSdrh       ExprList *pList = pExpr->pList;    /* The argument list */
1160626a879aSdrh       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
1161626a879aSdrh       int no_such_func = 0;       /* True if no such function exists */
1162626a879aSdrh       int wrong_num_args = 0;     /* True if wrong number of arguments */
1163626a879aSdrh       int is_agg = 0;             /* True if is an aggregate function */
1164626a879aSdrh       int i;
11655169bbc6Sdrh       int auth;                   /* Authorization to use the function */
1166626a879aSdrh       int nId;                    /* Number of characters in function name */
1167626a879aSdrh       const char *zId;            /* The function name. */
116873b211abSdrh       FuncDef *pDef;              /* Information about the function */
116914db2665Sdanielk1977       int enc = ENC(pParse->db);  /* The database encoding */
1170626a879aSdrh 
11712646da7eSdrh       zId = (char*)pExpr->token.z;
1172b71090fdSdrh       nId = pExpr->token.n;
1173626a879aSdrh       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1174626a879aSdrh       if( pDef==0 ){
1175626a879aSdrh         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1176626a879aSdrh         if( pDef==0 ){
1177626a879aSdrh           no_such_func = 1;
1178626a879aSdrh         }else{
1179626a879aSdrh           wrong_num_args = 1;
1180626a879aSdrh         }
1181626a879aSdrh       }else{
1182626a879aSdrh         is_agg = pDef->xFunc==0;
1183626a879aSdrh       }
11842fca7fefSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
11855169bbc6Sdrh       if( pDef ){
11865169bbc6Sdrh         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
11875169bbc6Sdrh         if( auth!=SQLITE_OK ){
11885169bbc6Sdrh           if( auth==SQLITE_DENY ){
11895169bbc6Sdrh             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
11905169bbc6Sdrh                                     pDef->zName);
11915169bbc6Sdrh             pNC->nErr++;
11925169bbc6Sdrh           }
11935169bbc6Sdrh           pExpr->op = TK_NULL;
11945169bbc6Sdrh           return 1;
11955169bbc6Sdrh         }
11965169bbc6Sdrh       }
1197b8b14219Sdrh #endif
1198626a879aSdrh       if( is_agg && !pNC->allowAgg ){
1199626a879aSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1200626a879aSdrh         pNC->nErr++;
1201626a879aSdrh         is_agg = 0;
1202626a879aSdrh       }else if( no_such_func ){
1203626a879aSdrh         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1204626a879aSdrh         pNC->nErr++;
1205626a879aSdrh       }else if( wrong_num_args ){
1206626a879aSdrh         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1207626a879aSdrh              nId, zId);
1208626a879aSdrh         pNC->nErr++;
1209626a879aSdrh       }
1210626a879aSdrh       if( is_agg ){
1211626a879aSdrh         pExpr->op = TK_AGG_FUNCTION;
1212626a879aSdrh         pNC->hasAgg = 1;
1213626a879aSdrh       }
121473b211abSdrh       if( is_agg ) pNC->allowAgg = 0;
1215626a879aSdrh       for(i=0; pNC->nErr==0 && i<n; i++){
121673b211abSdrh         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1217626a879aSdrh       }
121873b211abSdrh       if( is_agg ) pNC->allowAgg = 1;
1219626a879aSdrh       /* FIX ME:  Compute pExpr->affinity based on the expected return
1220626a879aSdrh       ** type of the function
1221626a879aSdrh       */
1222626a879aSdrh       return is_agg;
1223626a879aSdrh     }
1224b3bce662Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1225b3bce662Sdanielk1977     case TK_SELECT:
1226b3bce662Sdanielk1977     case TK_EXISTS:
1227b3bce662Sdanielk1977 #endif
1228b3bce662Sdanielk1977     case TK_IN: {
1229b3bce662Sdanielk1977       if( pExpr->pSelect ){
12308a9f38feSdrh         int nRef = pNC->nRef;
123106f6541eSdrh #ifndef SQLITE_OMIT_CHECK
123206f6541eSdrh         if( pNC->isCheck ){
123306f6541eSdrh           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
123406f6541eSdrh         }
123506f6541eSdrh #endif
1236b3bce662Sdanielk1977         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1237b3bce662Sdanielk1977         assert( pNC->nRef>=nRef );
1238b3bce662Sdanielk1977         if( nRef!=pNC->nRef ){
1239b3bce662Sdanielk1977           ExprSetProperty(pExpr, EP_VarSelect);
1240b3bce662Sdanielk1977         }
1241b3bce662Sdanielk1977       }
12424284fb07Sdrh       break;
1243b3bce662Sdanielk1977     }
12444284fb07Sdrh #ifndef SQLITE_OMIT_CHECK
12454284fb07Sdrh     case TK_VARIABLE: {
12464284fb07Sdrh       if( pNC->isCheck ){
12474284fb07Sdrh         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
12484284fb07Sdrh       }
12494284fb07Sdrh       break;
12504284fb07Sdrh     }
12514284fb07Sdrh #endif
1252626a879aSdrh   }
1253626a879aSdrh   return 0;
1254626a879aSdrh }
1255626a879aSdrh 
1256626a879aSdrh /*
1257cce7d176Sdrh ** This routine walks an expression tree and resolves references to
1258967e8b73Sdrh ** table columns.  Nodes of the form ID.ID or ID resolve into an
1259aacc543eSdrh ** index to the table in the table list and a column offset.  The
1260aacc543eSdrh ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
1261aacc543eSdrh ** value is changed to the index of the referenced table in pTabList
1262832508b7Sdrh ** plus the "base" value.  The base value will ultimately become the
1263aacc543eSdrh ** VDBE cursor number for a cursor that is pointing into the referenced
1264aacc543eSdrh ** table.  The Expr.iColumn value is changed to the index of the column
1265aacc543eSdrh ** of the referenced table.  The Expr.iColumn value for the special
1266aacc543eSdrh ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
1267aacc543eSdrh ** alias for ROWID.
126819a775c2Sdrh **
1269626a879aSdrh ** Also resolve function names and check the functions for proper
1270626a879aSdrh ** usage.  Make sure all function names are recognized and all functions
1271626a879aSdrh ** have the correct number of arguments.  Leave an error message
1272626a879aSdrh ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
1273626a879aSdrh **
127473b211abSdrh ** If the expression contains aggregate functions then set the EP_Agg
127573b211abSdrh ** property on the expression.
1276626a879aSdrh */
1277626a879aSdrh int sqlite3ExprResolveNames(
1278b3bce662Sdanielk1977   NameContext *pNC,       /* Namespace to resolve expressions in. */
1279b3bce662Sdanielk1977   Expr *pExpr             /* The expression to be analyzed. */
1280626a879aSdrh ){
128113449892Sdrh   int savedHasAgg;
128273b211abSdrh   if( pExpr==0 ) return 0;
128313449892Sdrh   savedHasAgg = pNC->hasAgg;
128413449892Sdrh   pNC->hasAgg = 0;
1285b3bce662Sdanielk1977   walkExprTree(pExpr, nameResolverStep, pNC);
1286b3bce662Sdanielk1977   if( pNC->nErr>0 ){
128773b211abSdrh     ExprSetProperty(pExpr, EP_Error);
128873b211abSdrh   }
128913449892Sdrh   if( pNC->hasAgg ){
129013449892Sdrh     ExprSetProperty(pExpr, EP_Agg);
129113449892Sdrh   }else if( savedHasAgg ){
129213449892Sdrh     pNC->hasAgg = 1;
129313449892Sdrh   }
129473b211abSdrh   return ExprHasProperty(pExpr, EP_Error);
1295626a879aSdrh }
1296626a879aSdrh 
12971398ad36Sdrh /*
12981398ad36Sdrh ** A pointer instance of this structure is used to pass information
12991398ad36Sdrh ** through walkExprTree into codeSubqueryStep().
13001398ad36Sdrh */
13011398ad36Sdrh typedef struct QueryCoder QueryCoder;
13021398ad36Sdrh struct QueryCoder {
13031398ad36Sdrh   Parse *pParse;       /* The parsing context */
13041398ad36Sdrh   NameContext *pNC;    /* Namespace of first enclosing query */
13051398ad36Sdrh };
13061398ad36Sdrh 
1307626a879aSdrh 
1308626a879aSdrh /*
13099cbe6352Sdrh ** Generate code for scalar subqueries used as an expression
13109cbe6352Sdrh ** and IN operators.  Examples:
1311626a879aSdrh **
13129cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
13139cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
13149cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
13159cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1316fef5208cSdrh **
13179cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
13189cbe6352Sdrh ** operator or subquery.
1319cce7d176Sdrh */
132051522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1321b3bce662Sdanielk1977 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
132257dbd7b3Sdrh   int testAddr = 0;                       /* One-time test address */
1323b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
1324b3bce662Sdanielk1977   if( v==0 ) return;
1325b3bce662Sdanielk1977 
132657dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
132757dbd7b3Sdrh   ** if any of the following is true:
132857dbd7b3Sdrh   **
132957dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
133057dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
133157dbd7b3Sdrh   **    *  We are inside a trigger
133257dbd7b3Sdrh   **
133357dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
133457dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1335b3bce662Sdanielk1977   */
1336b3bce662Sdanielk1977   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1337b3bce662Sdanielk1977     int mem = pParse->nMem++;
1338b3bce662Sdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
133957dbd7b3Sdrh     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
13409e12800dSdanielk1977     assert( testAddr>0 || sqlite3MallocFailed() );
1341d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1342b3bce662Sdanielk1977   }
1343b3bce662Sdanielk1977 
1344cce7d176Sdrh   switch( pExpr->op ){
1345fef5208cSdrh     case TK_IN: {
1346e014a838Sdanielk1977       char affinity;
1347d3d39e93Sdrh       KeyInfo keyInfo;
1348b9bb7c18Sdrh       int addr;        /* Address of OP_OpenEphemeral instruction */
1349d3d39e93Sdrh 
1350bf3b721fSdanielk1977       affinity = sqlite3ExprAffinity(pExpr->pLeft);
1351e014a838Sdanielk1977 
1352e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
135357dbd7b3Sdrh       ** expression it is handled the same way. A virtual table is
1354e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1355e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1356fef5208cSdrh       **
1357e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1358e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1359e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1360e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1361e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1362e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1363e014a838Sdanielk1977       ** is used.
1364fef5208cSdrh       */
1365832508b7Sdrh       pExpr->iTable = pParse->nTab++;
1366b9bb7c18Sdrh       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
1367d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1368d3d39e93Sdrh       keyInfo.nField = 1;
1369f3218feaSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1370e014a838Sdanielk1977 
1371e014a838Sdanielk1977       if( pExpr->pSelect ){
1372e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1373e014a838Sdanielk1977         **
1374e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1375e014a838Sdanielk1977         ** table allocated and opened above.
1376e014a838Sdanielk1977         */
1377e014a838Sdanielk1977         int iParm = pExpr->iTable +  (((int)affinity)<<16);
1378be5c89acSdrh         ExprList *pEList;
1379e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1380b3bce662Sdanielk1977         sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
1381be5c89acSdrh         pEList = pExpr->pSelect->pEList;
1382be5c89acSdrh         if( pEList && pEList->nExpr>0 ){
13837cedc8d4Sdanielk1977           keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
1384be5c89acSdrh               pEList->a[0].pExpr);
13850202b29eSdanielk1977         }
1386fef5208cSdrh       }else if( pExpr->pList ){
1387fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1388fef5208cSdrh         **
1389e014a838Sdanielk1977 	** For each expression, build an index key from the evaluation and
1390e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1391e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1392e014a838Sdanielk1977         ** a column, use numeric affinity.
1393fef5208cSdrh         */
1394e014a838Sdanielk1977         int i;
139557dbd7b3Sdrh         ExprList *pList = pExpr->pList;
139657dbd7b3Sdrh         struct ExprList_item *pItem;
139757dbd7b3Sdrh 
1398e014a838Sdanielk1977         if( !affinity ){
13998159a35fSdrh           affinity = SQLITE_AFF_NONE;
1400e014a838Sdanielk1977         }
14010202b29eSdanielk1977         keyInfo.aColl[0] = pExpr->pLeft->pColl;
1402e014a838Sdanielk1977 
1403e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
140457dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
140557dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1406e014a838Sdanielk1977 
140757dbd7b3Sdrh           /* If the expression is not constant then we will need to
140857dbd7b3Sdrh           ** disable the test that was generated above that makes sure
140957dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
141057dbd7b3Sdrh           ** expression we need to rerun this code each time.
141157dbd7b3Sdrh           */
14126c30be8eSdrh           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
1413f8875400Sdrh             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
141457dbd7b3Sdrh             testAddr = 0;
14154794b980Sdrh           }
1416e014a838Sdanielk1977 
1417e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
14184adee20fSdanielk1977           sqlite3ExprCode(pParse, pE2);
141994a11211Sdrh           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1420f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1421fef5208cSdrh         }
1422fef5208cSdrh       }
14230202b29eSdanielk1977       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1424b3bce662Sdanielk1977       break;
1425fef5208cSdrh     }
1426fef5208cSdrh 
142751522cd3Sdrh     case TK_EXISTS:
142819a775c2Sdrh     case TK_SELECT: {
1429fef5208cSdrh       /* This has to be a scalar SELECT.  Generate code to put the
1430fef5208cSdrh       ** value of this select in a memory cell and record the number
1431967e8b73Sdrh       ** of the memory cell in iColumn.
1432fef5208cSdrh       */
14332646da7eSdrh       static const Token one = { (u8*)"1", 0, 1 };
143451522cd3Sdrh       Select *pSel;
1435ec7429aeSdrh       int iMem;
1436ec7429aeSdrh       int sop;
14371398ad36Sdrh 
1438ec7429aeSdrh       pExpr->iColumn = iMem = pParse->nMem++;
143951522cd3Sdrh       pSel = pExpr->pSelect;
144051522cd3Sdrh       if( pExpr->op==TK_SELECT ){
144151522cd3Sdrh         sop = SRT_Mem;
1442ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1443ec7429aeSdrh         VdbeComment((v, "# Init subquery result"));
144451522cd3Sdrh       }else{
144551522cd3Sdrh         sop = SRT_Exists;
1446ec7429aeSdrh         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1447ec7429aeSdrh         VdbeComment((v, "# Init EXISTS result"));
144851522cd3Sdrh       }
1449ec7429aeSdrh       sqlite3ExprDelete(pSel->pLimit);
1450ec7429aeSdrh       pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
1451ec7429aeSdrh       sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0);
1452b3bce662Sdanielk1977       break;
145319a775c2Sdrh     }
1454cce7d176Sdrh   }
1455b3bce662Sdanielk1977 
145657dbd7b3Sdrh   if( testAddr ){
1457d654be80Sdrh     sqlite3VdbeJumpHere(v, testAddr);
1458b3bce662Sdanielk1977   }
1459b3bce662Sdanielk1977   return;
1460cce7d176Sdrh }
146151522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1462cce7d176Sdrh 
1463cce7d176Sdrh /*
1464fec19aadSdrh ** Generate an instruction that will put the integer describe by
1465fec19aadSdrh ** text z[0..n-1] on the stack.
1466fec19aadSdrh */
1467fec19aadSdrh static void codeInteger(Vdbe *v, const char *z, int n){
1468fec19aadSdrh   int i;
14696fec0762Sdrh   if( sqlite3GetInt32(z, &i) ){
14706fec0762Sdrh     sqlite3VdbeAddOp(v, OP_Integer, i, 0);
14716fec0762Sdrh   }else if( sqlite3FitsIn64Bits(z) ){
147229dda4aeSdrh     sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1473fec19aadSdrh   }else{
1474fec19aadSdrh     sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1475fec19aadSdrh   }
1476fec19aadSdrh }
1477fec19aadSdrh 
1478fec19aadSdrh /*
1479cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
14801ccde15dSdrh ** expression and leave the result on the top of stack.
1481f2bc013cSdrh **
1482f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1483f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1484f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1485f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1486f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1487cce7d176Sdrh */
14884adee20fSdanielk1977 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1489cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1490cce7d176Sdrh   int op;
1491ffe07b2dSdrh   int stackChng = 1;    /* Amount of change to stack depth */
1492ffe07b2dSdrh 
14937977a17fSdanielk1977   if( v==0 ) return;
14947977a17fSdanielk1977   if( pExpr==0 ){
1495f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
14967977a17fSdanielk1977     return;
14977977a17fSdanielk1977   }
1498f2bc013cSdrh   op = pExpr->op;
1499f2bc013cSdrh   switch( op ){
150013449892Sdrh     case TK_AGG_COLUMN: {
150113449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
150213449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
150313449892Sdrh       if( !pAggInfo->directMode ){
150413449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
150513449892Sdrh         break;
150613449892Sdrh       }else if( pAggInfo->useSortingIdx ){
150713449892Sdrh         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
150813449892Sdrh                               pCol->iSorterColumn);
150913449892Sdrh         break;
151013449892Sdrh       }
151113449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
151213449892Sdrh     }
1513967e8b73Sdrh     case TK_COLUMN: {
1514ffe07b2dSdrh       if( pExpr->iTable<0 ){
1515ffe07b2dSdrh         /* This only happens when coding check constraints */
1516ffe07b2dSdrh         assert( pParse->ckOffset>0 );
1517ffe07b2dSdrh         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1518ffe07b2dSdrh       }else if( pExpr->iColumn>=0 ){
15198a51256cSdrh         Table *pTab = pExpr->pTab;
15208a51256cSdrh         int iCol = pExpr->iColumn;
15214cbdda9eSdrh         int op = (pTab && IsVirtual(pTab)) ? OP_VColumn : OP_Column;
15227dabaa12Sdanielk1977         sqlite3VdbeAddOp(v, op, pExpr->iTable, iCol);
15238a51256cSdrh         sqlite3ColumnDefault(v, pTab, iCol);
15248a51256cSdrh #ifndef SQLITE_OMIT_FLOATING_POINT
15258a51256cSdrh         if( pTab && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
15268a51256cSdrh           sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
15278a51256cSdrh         }
15288a51256cSdrh #endif
1529c4a3c779Sdrh       }else{
15307dabaa12Sdanielk1977         Table *pTab = pExpr->pTab;
15314cbdda9eSdrh         int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
15327dabaa12Sdanielk1977         sqlite3VdbeAddOp(v, op, pExpr->iTable, 0);
15332282792aSdrh       }
1534cce7d176Sdrh       break;
1535cce7d176Sdrh     }
1536cce7d176Sdrh     case TK_INTEGER: {
15372646da7eSdrh       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1538fec19aadSdrh       break;
153951e9a445Sdrh     }
1540fec19aadSdrh     case TK_FLOAT:
1541fec19aadSdrh     case TK_STRING: {
1542f2bc013cSdrh       assert( TK_FLOAT==OP_Real );
1543f2bc013cSdrh       assert( TK_STRING==OP_String8 );
1544d2687b77Sdrh       sqlite3DequoteExpr(pExpr);
15452646da7eSdrh       sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1546cce7d176Sdrh       break;
1547cce7d176Sdrh     }
1548f0863fe5Sdrh     case TK_NULL: {
1549f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1550f0863fe5Sdrh       break;
1551f0863fe5Sdrh     }
15525338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1553c572ef7fSdanielk1977     case TK_BLOB: {
15546c8c6cecSdrh       int n;
15556c8c6cecSdrh       const char *z;
1556f2bc013cSdrh       assert( TK_BLOB==OP_HexBlob );
15576c8c6cecSdrh       n = pExpr->token.n - 3;
15582646da7eSdrh       z = (char*)pExpr->token.z + 2;
15596c8c6cecSdrh       assert( n>=0 );
15606c8c6cecSdrh       if( n==0 ){
15616c8c6cecSdrh         z = "";
15626c8c6cecSdrh       }
15636c8c6cecSdrh       sqlite3VdbeOp3(v, op, 0, 0, z, n);
1564c572ef7fSdanielk1977       break;
1565c572ef7fSdanielk1977     }
15665338a5f7Sdanielk1977 #endif
156750457896Sdrh     case TK_VARIABLE: {
15684adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1569895d7472Sdrh       if( pExpr->token.n>1 ){
15702646da7eSdrh         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1571895d7472Sdrh       }
157250457896Sdrh       break;
157350457896Sdrh     }
15744e0cff60Sdrh     case TK_REGISTER: {
15754e0cff60Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
15764e0cff60Sdrh       break;
15774e0cff60Sdrh     }
1578487e262fSdrh #ifndef SQLITE_OMIT_CAST
1579487e262fSdrh     case TK_CAST: {
1580487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
1581f0113000Sdanielk1977       int aff, to_op;
1582487e262fSdrh       sqlite3ExprCode(pParse, pExpr->pLeft);
15838a51256cSdrh       aff = sqlite3AffinityType(&pExpr->token);
1584f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1585f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
1586f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
1587f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1588f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
1589f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
1590f0113000Sdanielk1977       sqlite3VdbeAddOp(v, to_op, 0, 0);
1591ffe07b2dSdrh       stackChng = 0;
1592487e262fSdrh       break;
1593487e262fSdrh     }
1594487e262fSdrh #endif /* SQLITE_OMIT_CAST */
1595c9b84a1fSdrh     case TK_LT:
1596c9b84a1fSdrh     case TK_LE:
1597c9b84a1fSdrh     case TK_GT:
1598c9b84a1fSdrh     case TK_GE:
1599c9b84a1fSdrh     case TK_NE:
1600c9b84a1fSdrh     case TK_EQ: {
1601f2bc013cSdrh       assert( TK_LT==OP_Lt );
1602f2bc013cSdrh       assert( TK_LE==OP_Le );
1603f2bc013cSdrh       assert( TK_GT==OP_Gt );
1604f2bc013cSdrh       assert( TK_GE==OP_Ge );
1605f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1606f2bc013cSdrh       assert( TK_NE==OP_Ne );
1607a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1608a37cdde0Sdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1609be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1610ffe07b2dSdrh       stackChng = -1;
1611a37cdde0Sdanielk1977       break;
1612c9b84a1fSdrh     }
1613cce7d176Sdrh     case TK_AND:
1614cce7d176Sdrh     case TK_OR:
1615cce7d176Sdrh     case TK_PLUS:
1616cce7d176Sdrh     case TK_STAR:
1617cce7d176Sdrh     case TK_MINUS:
1618bf4133cbSdrh     case TK_REM:
1619bf4133cbSdrh     case TK_BITAND:
1620bf4133cbSdrh     case TK_BITOR:
162117c40294Sdrh     case TK_SLASH:
1622bf4133cbSdrh     case TK_LSHIFT:
1623855eb1cfSdrh     case TK_RSHIFT:
16240040077dSdrh     case TK_CONCAT: {
1625f2bc013cSdrh       assert( TK_AND==OP_And );
1626f2bc013cSdrh       assert( TK_OR==OP_Or );
1627f2bc013cSdrh       assert( TK_PLUS==OP_Add );
1628f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
1629f2bc013cSdrh       assert( TK_REM==OP_Remainder );
1630f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
1631f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
1632f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
1633f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
1634f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
1635f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
16364adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16374adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1638855eb1cfSdrh       sqlite3VdbeAddOp(v, op, 0, 0);
1639ffe07b2dSdrh       stackChng = -1;
16400040077dSdrh       break;
16410040077dSdrh     }
1642cce7d176Sdrh     case TK_UMINUS: {
1643fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
1644fec19aadSdrh       assert( pLeft );
1645fec19aadSdrh       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1646fec19aadSdrh         Token *p = &pLeft->token;
16479267bdceSdrh         char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
1648fec19aadSdrh         if( pLeft->op==TK_FLOAT ){
1649fec19aadSdrh           sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1650e6840900Sdrh         }else{
1651fec19aadSdrh           codeInteger(v, z, p->n+1);
1652e6840900Sdrh         }
16536e142f54Sdrh         sqliteFree(z);
16546e142f54Sdrh         break;
16556e142f54Sdrh       }
16561ccde15dSdrh       /* Fall through into TK_NOT */
16576e142f54Sdrh     }
1658bf4133cbSdrh     case TK_BITNOT:
16596e142f54Sdrh     case TK_NOT: {
1660f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
1661f2bc013cSdrh       assert( TK_NOT==OP_Not );
16624adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16634adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 0, 0);
1664ffe07b2dSdrh       stackChng = 0;
1665cce7d176Sdrh       break;
1666cce7d176Sdrh     }
1667cce7d176Sdrh     case TK_ISNULL:
1668cce7d176Sdrh     case TK_NOTNULL: {
1669cce7d176Sdrh       int dest;
1670f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1671f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
16724adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
16734adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
16744adee20fSdanielk1977       dest = sqlite3VdbeCurrentAddr(v) + 2;
16754adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
16764adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1677ffe07b2dSdrh       stackChng = 0;
1678a37cdde0Sdanielk1977       break;
1679f2bc013cSdrh     }
16802282792aSdrh     case TK_AGG_FUNCTION: {
168113449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
16827e56e711Sdrh       if( pInfo==0 ){
16837e56e711Sdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
16847e56e711Sdrh             &pExpr->span);
16857e56e711Sdrh       }else{
168613449892Sdrh         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
16877e56e711Sdrh       }
16882282792aSdrh       break;
16892282792aSdrh     }
1690b71090fdSdrh     case TK_CONST_FUNC:
1691cce7d176Sdrh     case TK_FUNCTION: {
1692cce7d176Sdrh       ExprList *pList = pExpr->pList;
169389425d5eSdrh       int nExpr = pList ? pList->nExpr : 0;
16940bce8354Sdrh       FuncDef *pDef;
16954b59ab5eSdrh       int nId;
16964b59ab5eSdrh       const char *zId;
169713449892Sdrh       int constMask = 0;
1698682f68b0Sdanielk1977       int i;
169914db2665Sdanielk1977       u8 enc = ENC(pParse->db);
1700dc1bdc4fSdanielk1977       CollSeq *pColl = 0;
17012646da7eSdrh       zId = (char*)pExpr->token.z;
1702b71090fdSdrh       nId = pExpr->token.n;
1703d8123366Sdanielk1977       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
17040bce8354Sdrh       assert( pDef!=0 );
1705f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pList);
1706b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1707a43fa227Sdrh       /* Possibly overload the function if the first argument is
1708a43fa227Sdrh       ** a virtual table column.
1709a43fa227Sdrh       **
1710a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1711a43fa227Sdrh       ** second argument, not the first, as the argument to test to
1712a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
1713a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
1714a43fa227Sdrh       ** control overloading) ends up as the second argument to the
1715a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
1716a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
1717a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
1718a43fa227Sdrh       */
17196a03a1c5Sdrh       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
17206a03a1c5Sdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[1].pExpr);
17216a03a1c5Sdrh       }else if( nExpr>0 ){
1722b7f6f68fSdrh         pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[0].pExpr);
1723b7f6f68fSdrh       }
1724b7f6f68fSdrh #endif
1725682f68b0Sdanielk1977       for(i=0; i<nExpr && i<32; i++){
1726d02eb1fdSdanielk1977         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
172713449892Sdrh           constMask |= (1<<i);
1728d02eb1fdSdanielk1977         }
1729dc1bdc4fSdanielk1977         if( pDef->needCollSeq && !pColl ){
1730dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1731dc1bdc4fSdanielk1977         }
1732dc1bdc4fSdanielk1977       }
1733dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
1734dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
1735d8123366Sdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1736682f68b0Sdanielk1977       }
173713449892Sdrh       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1738ffe07b2dSdrh       stackChng = 1-nExpr;
17396ec2733bSdrh       break;
17406ec2733bSdrh     }
1741fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1742fe2093d7Sdrh     case TK_EXISTS:
174319a775c2Sdrh     case TK_SELECT: {
174441714d6fSdrh       if( pExpr->iColumn==0 ){
1745b3bce662Sdanielk1977         sqlite3CodeSubselect(pParse, pExpr);
174641714d6fSdrh       }
17474adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1748ad6d9460Sdrh       VdbeComment((v, "# load subquery result"));
174919a775c2Sdrh       break;
175019a775c2Sdrh     }
1751fef5208cSdrh     case TK_IN: {
1752fef5208cSdrh       int addr;
175394a11211Sdrh       char affinity;
1754afa5f680Sdrh       int ckOffset = pParse->ckOffset;
1755b3bce662Sdanielk1977       sqlite3CodeSubselect(pParse, pExpr);
1756e014a838Sdanielk1977 
1757e014a838Sdanielk1977       /* Figure out the affinity to use to create a key from the results
1758e014a838Sdanielk1977       ** of the expression. affinityStr stores a static string suitable for
1759ededfd5eSdanielk1977       ** P3 of OP_MakeRecord.
1760e014a838Sdanielk1977       */
176194a11211Sdrh       affinity = comparisonAffinity(pExpr);
1762e014a838Sdanielk1977 
17634adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1764afa5f680Sdrh       pParse->ckOffset = ckOffset+1;
1765e014a838Sdanielk1977 
1766e014a838Sdanielk1977       /* Code the <expr> from "<expr> IN (...)". The temporary table
1767e014a838Sdanielk1977       ** pExpr->iTable contains the values that make up the (...) set.
1768e014a838Sdanielk1977       */
17694adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
17704adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
1771e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
17724adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
1773f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1774e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
177594a11211Sdrh       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
1776e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1777e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
1778e014a838Sdanielk1977 
1779fef5208cSdrh       break;
1780fef5208cSdrh     }
178193758c8dSdanielk1977 #endif
1782fef5208cSdrh     case TK_BETWEEN: {
1783be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1784be5c89acSdrh       struct ExprList_item *pLItem = pExpr->pList->a;
1785be5c89acSdrh       Expr *pRight = pLItem->pExpr;
1786be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
17874adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1788be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1789be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
17904adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1791be5c89acSdrh       pLItem++;
1792be5c89acSdrh       pRight = pLItem->pExpr;
1793be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
1794be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
17954adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_And, 0, 0);
1796fef5208cSdrh       break;
1797fef5208cSdrh     }
179851e9a445Sdrh     case TK_UPLUS:
1799a2e00042Sdrh     case TK_AS: {
18004adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
1801ffe07b2dSdrh       stackChng = 0;
1802a2e00042Sdrh       break;
1803a2e00042Sdrh     }
180417a7f8ddSdrh     case TK_CASE: {
180517a7f8ddSdrh       int expr_end_label;
1806f5905aa7Sdrh       int jumpInst;
1807f5905aa7Sdrh       int nExpr;
180817a7f8ddSdrh       int i;
1809be5c89acSdrh       ExprList *pEList;
1810be5c89acSdrh       struct ExprList_item *aListelem;
181117a7f8ddSdrh 
181217a7f8ddSdrh       assert(pExpr->pList);
181317a7f8ddSdrh       assert((pExpr->pList->nExpr % 2) == 0);
181417a7f8ddSdrh       assert(pExpr->pList->nExpr > 0);
1815be5c89acSdrh       pEList = pExpr->pList;
1816be5c89acSdrh       aListelem = pEList->a;
1817be5c89acSdrh       nExpr = pEList->nExpr;
18184adee20fSdanielk1977       expr_end_label = sqlite3VdbeMakeLabel(v);
181917a7f8ddSdrh       if( pExpr->pLeft ){
18204adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pLeft);
1821cce7d176Sdrh       }
1822f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
1823be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i].pExpr);
182417a7f8ddSdrh         if( pExpr->pLeft ){
18254adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
1826be5c89acSdrh           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1827be5c89acSdrh                                  OP_Ne, 0, 1);
18284adee20fSdanielk1977           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1829f5905aa7Sdrh         }else{
18304adee20fSdanielk1977           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
183117a7f8ddSdrh         }
1832be5c89acSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
18334adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
1834d654be80Sdrh         sqlite3VdbeJumpHere(v, jumpInst);
183517a7f8ddSdrh       }
1836f570f011Sdrh       if( pExpr->pLeft ){
18374adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1838f570f011Sdrh       }
183917a7f8ddSdrh       if( pExpr->pRight ){
18404adee20fSdanielk1977         sqlite3ExprCode(pParse, pExpr->pRight);
184117a7f8ddSdrh       }else{
1842f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
184317a7f8ddSdrh       }
18444adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, expr_end_label);
18456f34903eSdanielk1977       break;
18466f34903eSdanielk1977     }
18475338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
18486f34903eSdanielk1977     case TK_RAISE: {
18496f34903eSdanielk1977       if( !pParse->trigStack ){
18504adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1851da93d238Sdrh                        "RAISE() may only be used within a trigger-program");
18526f34903eSdanielk1977 	return;
18536f34903eSdanielk1977       }
1854ad6d9460Sdrh       if( pExpr->iColumn!=OE_Ignore ){
1855ad6d9460Sdrh          assert( pExpr->iColumn==OE_Rollback ||
18566f34903eSdanielk1977                  pExpr->iColumn == OE_Abort ||
1857ad6d9460Sdrh                  pExpr->iColumn == OE_Fail );
1858d2687b77Sdrh          sqlite3DequoteExpr(pExpr);
18594adee20fSdanielk1977          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
18602646da7eSdrh                         (char*)pExpr->token.z, pExpr->token.n);
18616f34903eSdanielk1977       } else {
18626f34903eSdanielk1977          assert( pExpr->iColumn == OE_Ignore );
1863344737f6Sdrh          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
1864ad6d9460Sdrh          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
1865ad6d9460Sdrh          VdbeComment((v, "# raise(IGNORE)"));
18666f34903eSdanielk1977       }
1867ffe07b2dSdrh       stackChng = 0;
1868ffe07b2dSdrh       break;
186917a7f8ddSdrh     }
18705338a5f7Sdanielk1977 #endif
1871ffe07b2dSdrh   }
1872ffe07b2dSdrh 
1873ffe07b2dSdrh   if( pParse->ckOffset ){
1874ffe07b2dSdrh     pParse->ckOffset += stackChng;
1875ffe07b2dSdrh     assert( pParse->ckOffset );
187617a7f8ddSdrh   }
1877cce7d176Sdrh }
1878cce7d176Sdrh 
187993758c8dSdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
1880cce7d176Sdrh /*
188125303780Sdrh ** Generate code that evalutes the given expression and leaves the result
188225303780Sdrh ** on the stack.  See also sqlite3ExprCode().
188325303780Sdrh **
188425303780Sdrh ** This routine might also cache the result and modify the pExpr tree
188525303780Sdrh ** so that it will make use of the cached result on subsequent evaluations
188625303780Sdrh ** rather than evaluate the whole expression again.  Trivial expressions are
188725303780Sdrh ** not cached.  If the expression is cached, its result is stored in a
188825303780Sdrh ** memory location.
188925303780Sdrh */
189025303780Sdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
189125303780Sdrh   Vdbe *v = pParse->pVdbe;
189225303780Sdrh   int iMem;
189325303780Sdrh   int addr1, addr2;
189425303780Sdrh   if( v==0 ) return;
189525303780Sdrh   addr1 = sqlite3VdbeCurrentAddr(v);
189625303780Sdrh   sqlite3ExprCode(pParse, pExpr);
189725303780Sdrh   addr2 = sqlite3VdbeCurrentAddr(v);
189825303780Sdrh   if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
189925303780Sdrh     iMem = pExpr->iTable = pParse->nMem++;
190025303780Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
190125303780Sdrh     pExpr->op = TK_REGISTER;
190225303780Sdrh   }
190325303780Sdrh }
190493758c8dSdanielk1977 #endif
190525303780Sdrh 
190625303780Sdrh /*
1907268380caSdrh ** Generate code that pushes the value of every element of the given
1908f9b596ebSdrh ** expression list onto the stack.
1909268380caSdrh **
1910268380caSdrh ** Return the number of elements pushed onto the stack.
1911268380caSdrh */
19124adee20fSdanielk1977 int sqlite3ExprCodeExprList(
1913268380caSdrh   Parse *pParse,     /* Parsing context */
1914f9b596ebSdrh   ExprList *pList    /* The expression list to be coded */
1915268380caSdrh ){
1916268380caSdrh   struct ExprList_item *pItem;
1917268380caSdrh   int i, n;
1918268380caSdrh   if( pList==0 ) return 0;
1919268380caSdrh   n = pList->nExpr;
1920c182d163Sdrh   for(pItem=pList->a, i=n; i>0; i--, pItem++){
19214adee20fSdanielk1977     sqlite3ExprCode(pParse, pItem->pExpr);
1922268380caSdrh   }
1923f9b596ebSdrh   return n;
1924268380caSdrh }
1925268380caSdrh 
1926268380caSdrh /*
1927cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
1928cce7d176Sdrh ** to the label "dest" if the expression is true but execution
1929cce7d176Sdrh ** continues straight thru if the expression is false.
1930f5905aa7Sdrh **
1931f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
1932f5905aa7Sdrh ** take the jump if the jumpIfNull flag is true.
1933f2bc013cSdrh **
1934f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
1935f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1936f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
1937f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
1938f2bc013cSdrh ** below verify that the numbers are aligned correctly.
1939cce7d176Sdrh */
19404adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1941cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
1942cce7d176Sdrh   int op = 0;
1943ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
1944daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
1945f2bc013cSdrh   op = pExpr->op;
1946f2bc013cSdrh   switch( op ){
1947cce7d176Sdrh     case TK_AND: {
19484adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
19494adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
19504adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
19514adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
1952cce7d176Sdrh       break;
1953cce7d176Sdrh     }
1954cce7d176Sdrh     case TK_OR: {
19554adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
19564adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1957cce7d176Sdrh       break;
1958cce7d176Sdrh     }
1959cce7d176Sdrh     case TK_NOT: {
19604adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1961cce7d176Sdrh       break;
1962cce7d176Sdrh     }
1963cce7d176Sdrh     case TK_LT:
1964cce7d176Sdrh     case TK_LE:
1965cce7d176Sdrh     case TK_GT:
1966cce7d176Sdrh     case TK_GE:
1967cce7d176Sdrh     case TK_NE:
19680ac65892Sdrh     case TK_EQ: {
1969f2bc013cSdrh       assert( TK_LT==OP_Lt );
1970f2bc013cSdrh       assert( TK_LE==OP_Le );
1971f2bc013cSdrh       assert( TK_GT==OP_Gt );
1972f2bc013cSdrh       assert( TK_GE==OP_Ge );
1973f2bc013cSdrh       assert( TK_EQ==OP_Eq );
1974f2bc013cSdrh       assert( TK_NE==OP_Ne );
19754adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19764adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
1977be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
1978cce7d176Sdrh       break;
1979cce7d176Sdrh     }
1980cce7d176Sdrh     case TK_ISNULL:
1981cce7d176Sdrh     case TK_NOTNULL: {
1982f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
1983f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
19844adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
19854adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
1986cce7d176Sdrh       break;
1987cce7d176Sdrh     }
1988fef5208cSdrh     case TK_BETWEEN: {
19890202b29eSdanielk1977       /* The expression "x BETWEEN y AND z" is implemented as:
19900202b29eSdanielk1977       **
19910202b29eSdanielk1977       ** 1 IF (x < y) GOTO 3
19920202b29eSdanielk1977       ** 2 IF (x <= z) GOTO <dest>
19930202b29eSdanielk1977       ** 3 ...
19940202b29eSdanielk1977       */
1995f5905aa7Sdrh       int addr;
1996be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
1997be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
1998be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
19994adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2000be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2001be5c89acSdrh       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
20020202b29eSdanielk1977 
2003be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2004be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2005be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
20060202b29eSdanielk1977 
20074adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2008d654be80Sdrh       sqlite3VdbeJumpHere(v, addr);
20094adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2010fef5208cSdrh       break;
2011fef5208cSdrh     }
2012cce7d176Sdrh     default: {
20134adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
20144adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
2015cce7d176Sdrh       break;
2016cce7d176Sdrh     }
2017cce7d176Sdrh   }
2018ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2019cce7d176Sdrh }
2020cce7d176Sdrh 
2021cce7d176Sdrh /*
202266b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
2023cce7d176Sdrh ** to the label "dest" if the expression is false but execution
2024cce7d176Sdrh ** continues straight thru if the expression is true.
2025f5905aa7Sdrh **
2026f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
2027f5905aa7Sdrh ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
2028cce7d176Sdrh */
20294adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2030cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
2031cce7d176Sdrh   int op = 0;
2032ffe07b2dSdrh   int ckOffset = pParse->ckOffset;
2033daffd0e5Sdrh   if( v==0 || pExpr==0 ) return;
2034f2bc013cSdrh 
2035f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
2036f2bc013cSdrh   **
2037f2bc013cSdrh   **       pExpr->op            op
2038f2bc013cSdrh   **       ---------          ----------
2039f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
2040f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
2041f2bc013cSdrh   **       TK_NE              OP_Eq
2042f2bc013cSdrh   **       TK_EQ              OP_Ne
2043f2bc013cSdrh   **       TK_GT              OP_Le
2044f2bc013cSdrh   **       TK_LE              OP_Gt
2045f2bc013cSdrh   **       TK_GE              OP_Lt
2046f2bc013cSdrh   **       TK_LT              OP_Ge
2047f2bc013cSdrh   **
2048f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
2049f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
2050f2bc013cSdrh   ** can compute the mapping above using the following expression.
2051f2bc013cSdrh   ** Assert()s verify that the computation is correct.
2052f2bc013cSdrh   */
2053f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2054f2bc013cSdrh 
2055f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
2056f2bc013cSdrh   */
2057f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2058f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2059f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
2060f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
2061f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
2062f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
2063f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
2064f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
2065f2bc013cSdrh 
2066cce7d176Sdrh   switch( pExpr->op ){
2067cce7d176Sdrh     case TK_AND: {
20684adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
20694adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2070cce7d176Sdrh       break;
2071cce7d176Sdrh     }
2072cce7d176Sdrh     case TK_OR: {
20734adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
20744adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
20754adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
20764adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
2077cce7d176Sdrh       break;
2078cce7d176Sdrh     }
2079cce7d176Sdrh     case TK_NOT: {
20804adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2081cce7d176Sdrh       break;
2082cce7d176Sdrh     }
2083cce7d176Sdrh     case TK_LT:
2084cce7d176Sdrh     case TK_LE:
2085cce7d176Sdrh     case TK_GT:
2086cce7d176Sdrh     case TK_GE:
2087cce7d176Sdrh     case TK_NE:
2088cce7d176Sdrh     case TK_EQ: {
20894adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20904adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pRight);
2091be5c89acSdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2092cce7d176Sdrh       break;
2093cce7d176Sdrh     }
2094cce7d176Sdrh     case TK_ISNULL:
2095cce7d176Sdrh     case TK_NOTNULL: {
20964adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr->pLeft);
20974adee20fSdanielk1977       sqlite3VdbeAddOp(v, op, 1, dest);
2098cce7d176Sdrh       break;
2099cce7d176Sdrh     }
2100fef5208cSdrh     case TK_BETWEEN: {
21010202b29eSdanielk1977       /* The expression is "x BETWEEN y AND z". It is implemented as:
21020202b29eSdanielk1977       **
21030202b29eSdanielk1977       ** 1 IF (x >= y) GOTO 3
21040202b29eSdanielk1977       ** 2 GOTO <dest>
21050202b29eSdanielk1977       ** 3 IF (x > z) GOTO <dest>
21060202b29eSdanielk1977       */
2107fef5208cSdrh       int addr;
2108be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
2109be5c89acSdrh       Expr *pRight = pExpr->pList->a[0].pExpr;
2110be5c89acSdrh       sqlite3ExprCode(pParse, pLeft);
21114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2112be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
21134adee20fSdanielk1977       addr = sqlite3VdbeCurrentAddr(v);
2114be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2115be5c89acSdrh 
21164adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
21174adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2118be5c89acSdrh       pRight = pExpr->pList->a[1].pExpr;
2119be5c89acSdrh       sqlite3ExprCode(pParse, pRight);
2120be5c89acSdrh       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2121fef5208cSdrh       break;
2122fef5208cSdrh     }
2123cce7d176Sdrh     default: {
21244adee20fSdanielk1977       sqlite3ExprCode(pParse, pExpr);
21254adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2126cce7d176Sdrh       break;
2127cce7d176Sdrh     }
2128cce7d176Sdrh   }
2129ffe07b2dSdrh   pParse->ckOffset = ckOffset;
2130cce7d176Sdrh }
21312282792aSdrh 
21322282792aSdrh /*
21332282792aSdrh ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
21342282792aSdrh ** if they are identical and return FALSE if they differ in any way.
21352282792aSdrh */
21364adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
21372282792aSdrh   int i;
21384b202ae2Sdanielk1977   if( pA==0||pB==0 ){
21394b202ae2Sdanielk1977     return pB==pA;
21402282792aSdrh   }
21412282792aSdrh   if( pA->op!=pB->op ) return 0;
2142fd357974Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
21434adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
21444adee20fSdanielk1977   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
21452282792aSdrh   if( pA->pList ){
21462282792aSdrh     if( pB->pList==0 ) return 0;
21472282792aSdrh     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
21482282792aSdrh     for(i=0; i<pA->pList->nExpr; i++){
21494adee20fSdanielk1977       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
21502282792aSdrh         return 0;
21512282792aSdrh       }
21522282792aSdrh     }
21532282792aSdrh   }else if( pB->pList ){
21542282792aSdrh     return 0;
21552282792aSdrh   }
21562282792aSdrh   if( pA->pSelect || pB->pSelect ) return 0;
21572f2c01e5Sdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
21582282792aSdrh   if( pA->token.z ){
21592282792aSdrh     if( pB->token.z==0 ) return 0;
21606977fea8Sdrh     if( pB->token.n!=pA->token.n ) return 0;
21612646da7eSdrh     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
21622646da7eSdrh       return 0;
21632646da7eSdrh     }
21642282792aSdrh   }
21652282792aSdrh   return 1;
21662282792aSdrh }
21672282792aSdrh 
216813449892Sdrh 
21692282792aSdrh /*
217013449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
217113449892Sdrh ** the new element.  Return a negative number if malloc fails.
21722282792aSdrh */
217313449892Sdrh static int addAggInfoColumn(AggInfo *pInfo){
217413449892Sdrh   int i;
217513449892Sdrh   i = sqlite3ArrayAllocate((void**)&pInfo->aCol, sizeof(pInfo->aCol[0]), 3);
217613449892Sdrh   if( i<0 ){
21772282792aSdrh     return -1;
21782282792aSdrh   }
217913449892Sdrh   return i;
21802282792aSdrh }
218113449892Sdrh 
218213449892Sdrh /*
218313449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
218413449892Sdrh ** the new element.  Return a negative number if malloc fails.
218513449892Sdrh */
218613449892Sdrh static int addAggInfoFunc(AggInfo *pInfo){
218713449892Sdrh   int i;
218813449892Sdrh   i = sqlite3ArrayAllocate((void**)&pInfo->aFunc, sizeof(pInfo->aFunc[0]), 2);
218913449892Sdrh   if( i<0 ){
219013449892Sdrh     return -1;
219113449892Sdrh   }
219213449892Sdrh   return i;
21932282792aSdrh }
21942282792aSdrh 
21952282792aSdrh /*
2196626a879aSdrh ** This is an xFunc for walkExprTree() used to implement
2197626a879aSdrh ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
2198626a879aSdrh ** for additional information.
21992282792aSdrh **
2200626a879aSdrh ** This routine analyzes the aggregate function at pExpr.
22012282792aSdrh */
2202626a879aSdrh static int analyzeAggregate(void *pArg, Expr *pExpr){
22032282792aSdrh   int i;
2204a58fdfb1Sdanielk1977   NameContext *pNC = (NameContext *)pArg;
2205a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
2206a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
220713449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
220813449892Sdrh 
22092282792aSdrh 
22102282792aSdrh   switch( pExpr->op ){
221189c69d00Sdrh     case TK_AGG_COLUMN:
2212967e8b73Sdrh     case TK_COLUMN: {
221313449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
221413449892Sdrh       ** clause of the aggregate query */
221513449892Sdrh       if( pSrcList ){
221613449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
221713449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
221813449892Sdrh           struct AggInfo_col *pCol;
221913449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
222013449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
222113449892Sdrh             ** that is in the FROM clause of the aggregate query.
222213449892Sdrh             **
222313449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
222413449892Sdrh             ** is not an entry there already.
222513449892Sdrh             */
222613449892Sdrh             pCol = pAggInfo->aCol;
222713449892Sdrh             for(i=0; i<pAggInfo->nColumn; i++, pCol++){
222813449892Sdrh               if( pCol->iTable==pExpr->iTable &&
222913449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
22302282792aSdrh                 break;
22312282792aSdrh               }
22322282792aSdrh             }
223313449892Sdrh             if( i>=pAggInfo->nColumn && (i = addAggInfoColumn(pAggInfo))>=0 ){
223413449892Sdrh               pCol = &pAggInfo->aCol[i];
223513449892Sdrh               pCol->iTable = pExpr->iTable;
223613449892Sdrh               pCol->iColumn = pExpr->iColumn;
223713449892Sdrh               pCol->iMem = pParse->nMem++;
223813449892Sdrh               pCol->iSorterColumn = -1;
22395774b806Sdrh               pCol->pExpr = pExpr;
224013449892Sdrh               if( pAggInfo->pGroupBy ){
224113449892Sdrh                 int j, n;
224213449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
224313449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
224413449892Sdrh                 n = pGB->nExpr;
224513449892Sdrh                 for(j=0; j<n; j++, pTerm++){
224613449892Sdrh                   Expr *pE = pTerm->pExpr;
224713449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
224813449892Sdrh                       pE->iColumn==pExpr->iColumn ){
224913449892Sdrh                     pCol->iSorterColumn = j;
225013449892Sdrh                     break;
22512282792aSdrh                   }
225213449892Sdrh                 }
225313449892Sdrh               }
225413449892Sdrh               if( pCol->iSorterColumn<0 ){
225513449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
225613449892Sdrh               }
225713449892Sdrh             }
225813449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
225913449892Sdrh             ** because it was there before or because we just created it).
226013449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
226113449892Sdrh             ** pAggInfo->aCol[] entry.
226213449892Sdrh             */
226313449892Sdrh             pExpr->pAggInfo = pAggInfo;
226413449892Sdrh             pExpr->op = TK_AGG_COLUMN;
2265aaf88729Sdrh             pExpr->iAgg = i;
226613449892Sdrh             break;
226713449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
226813449892Sdrh         } /* end loop over pSrcList */
2269a58fdfb1Sdanielk1977       }
2270626a879aSdrh       return 1;
22712282792aSdrh     }
22722282792aSdrh     case TK_AGG_FUNCTION: {
227313449892Sdrh       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
227413449892Sdrh       ** to be ignored */
2275a58fdfb1Sdanielk1977       if( pNC->nDepth==0 ){
227613449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
227713449892Sdrh         ** function that is already in the pAggInfo structure
227813449892Sdrh         */
227913449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
228013449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
228113449892Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
22822282792aSdrh             break;
22832282792aSdrh           }
22842282792aSdrh         }
228513449892Sdrh         if( i>=pAggInfo->nFunc ){
228613449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
228713449892Sdrh           */
228814db2665Sdanielk1977           u8 enc = ENC(pParse->db);
228913449892Sdrh           i = addAggInfoFunc(pAggInfo);
229013449892Sdrh           if( i>=0 ){
229113449892Sdrh             pItem = &pAggInfo->aFunc[i];
229213449892Sdrh             pItem->pExpr = pExpr;
229313449892Sdrh             pItem->iMem = pParse->nMem++;
229413449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
22952646da7eSdrh                    (char*)pExpr->token.z, pExpr->token.n,
2296d8123366Sdanielk1977                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2297fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
2298fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
2299fd357974Sdrh             }else{
2300fd357974Sdrh               pItem->iDistinct = -1;
2301fd357974Sdrh             }
23022282792aSdrh           }
230313449892Sdrh         }
230413449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
230513449892Sdrh         */
23062282792aSdrh         pExpr->iAgg = i;
230713449892Sdrh         pExpr->pAggInfo = pAggInfo;
2308626a879aSdrh         return 1;
23092282792aSdrh       }
23102282792aSdrh     }
2311a58fdfb1Sdanielk1977   }
231213449892Sdrh 
231313449892Sdrh   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
231413449892Sdrh   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
231513449892Sdrh   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
231613449892Sdrh   */
2317a58fdfb1Sdanielk1977   if( pExpr->pSelect ){
2318a58fdfb1Sdanielk1977     pNC->nDepth++;
2319a58fdfb1Sdanielk1977     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2320a58fdfb1Sdanielk1977     pNC->nDepth--;
2321a58fdfb1Sdanielk1977   }
2322626a879aSdrh   return 0;
23232282792aSdrh }
2324626a879aSdrh 
2325626a879aSdrh /*
2326626a879aSdrh ** Analyze the given expression looking for aggregate functions and
2327626a879aSdrh ** for variables that need to be added to the pParse->aAgg[] array.
2328626a879aSdrh ** Make additional entries to the pParse->aAgg[] array as necessary.
2329626a879aSdrh **
2330626a879aSdrh ** This routine should only be called after the expression has been
2331626a879aSdrh ** analyzed by sqlite3ExprResolveNames().
2332626a879aSdrh **
2333626a879aSdrh ** If errors are seen, leave an error message in zErrMsg and return
2334626a879aSdrh ** the number of errors.
2335626a879aSdrh */
2336a58fdfb1Sdanielk1977 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2337a58fdfb1Sdanielk1977   int nErr = pNC->pParse->nErr;
2338a58fdfb1Sdanielk1977   walkExprTree(pExpr, analyzeAggregate, pNC);
2339a58fdfb1Sdanielk1977   return pNC->pParse->nErr - nErr;
23402282792aSdrh }
23415d9a4af9Sdrh 
23425d9a4af9Sdrh /*
23435d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
23445d9a4af9Sdrh ** expression list.  Return the number of errors.
23455d9a4af9Sdrh **
23465d9a4af9Sdrh ** If an error is found, the analysis is cut short.
23475d9a4af9Sdrh */
23485d9a4af9Sdrh int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
23495d9a4af9Sdrh   struct ExprList_item *pItem;
23505d9a4af9Sdrh   int i;
23515d9a4af9Sdrh   int nErr = 0;
23525d9a4af9Sdrh   if( pList ){
23535d9a4af9Sdrh     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
23545d9a4af9Sdrh       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
23555d9a4af9Sdrh     }
23565d9a4af9Sdrh   }
23575d9a4af9Sdrh   return nErr;
23585d9a4af9Sdrh }
2359