xref: /sqlite-3.40.0/src/expr.c (revision 0a8a406e)
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 */
15cce7d176Sdrh #include "sqliteInt.h"
16a2e00042Sdrh 
17e014a838Sdanielk1977 /*
18e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
19e014a838Sdanielk1977 **
20e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
21e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
22e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
23e014a838Sdanielk1977 ** indicating no affinity for the expression.
24e014a838Sdanielk1977 **
25e014a838Sdanielk1977 ** i.e. the WHERE clause expresssions in the following statements all
26e014a838Sdanielk1977 ** have an affinity:
27e014a838Sdanielk1977 **
28e014a838Sdanielk1977 ** CREATE TABLE t1(a);
29e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
30e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
31e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
32e014a838Sdanielk1977 */
33bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
34487e262fSdrh   int op = pExpr->op;
35487e262fSdrh   if( op==TK_SELECT ){
366ab3a2ecSdanielk1977     assert( pExpr->flags&EP_xIsSelect );
376ab3a2ecSdanielk1977     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
38a37cdde0Sdanielk1977   }
39487e262fSdrh #ifndef SQLITE_OMIT_CAST
40487e262fSdrh   if( op==TK_CAST ){
4133e619fcSdrh     assert( !ExprHasProperty(pExpr, EP_IntValue) );
4233e619fcSdrh     return sqlite3AffinityType(pExpr->u.zToken);
43487e262fSdrh   }
44487e262fSdrh #endif
45259a455fSdanielk1977   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
46259a455fSdanielk1977    && pExpr->pTab!=0
47259a455fSdanielk1977   ){
487d10d5a6Sdrh     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
497d10d5a6Sdrh     ** a TK_COLUMN but was previously evaluated and cached in a register */
507d10d5a6Sdrh     int j = pExpr->iColumn;
517d10d5a6Sdrh     if( j<0 ) return SQLITE_AFF_INTEGER;
527d10d5a6Sdrh     assert( pExpr->pTab && j<pExpr->pTab->nCol );
537d10d5a6Sdrh     return pExpr->pTab->aCol[j].affinity;
547d10d5a6Sdrh   }
55a37cdde0Sdanielk1977   return pExpr->affinity;
56a37cdde0Sdanielk1977 }
57a37cdde0Sdanielk1977 
5853db1458Sdrh /*
598b4c40d8Sdrh ** Set the collating sequence for expression pExpr to be the collating
60ae80ddeaSdrh ** sequence named by pToken.   Return a pointer to a new Expr node that
61ae80ddeaSdrh ** implements the COLLATE operator.
62*0a8a406eSdrh **
63*0a8a406eSdrh ** If a memory allocation error occurs, that fact is recorded in pParse->db
64*0a8a406eSdrh ** and the pExpr parameter is returned unchanged.
658b4c40d8Sdrh */
66*0a8a406eSdrh Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
67*0a8a406eSdrh   if( pCollName->n>0 ){
68ae80ddeaSdrh     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
69ae80ddeaSdrh     if( pNew ){
70ae80ddeaSdrh       pNew->pLeft = pExpr;
71ae80ddeaSdrh       pNew->flags |= EP_Collate;
72*0a8a406eSdrh       pExpr = pNew;
73ae80ddeaSdrh     }
74*0a8a406eSdrh   }
75*0a8a406eSdrh   return pExpr;
76*0a8a406eSdrh }
77*0a8a406eSdrh Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
78*0a8a406eSdrh   if( zC ){
79*0a8a406eSdrh     Token s;
80*0a8a406eSdrh     s.z = zC;
81*0a8a406eSdrh     s.n = sqlite3Strlen30(s.z);
82*0a8a406eSdrh     pExpr = sqlite3ExprAddCollateToken(pParse, pExpr, &s);
83*0a8a406eSdrh   }
84*0a8a406eSdrh   return pExpr;
85*0a8a406eSdrh }
86*0a8a406eSdrh 
87*0a8a406eSdrh /*
88*0a8a406eSdrh ** Skip over any TK_COLLATE operator in an expression.
89*0a8a406eSdrh */
90*0a8a406eSdrh Expr *sqlite3ExprSkipCollate(Expr *pExpr){
91*0a8a406eSdrh   if( pExpr && pExpr->op==TK_COLLATE ) pExpr = pExpr->pLeft;
92*0a8a406eSdrh   return pExpr;
938b4c40d8Sdrh }
948b4c40d8Sdrh 
958b4c40d8Sdrh /*
96ae80ddeaSdrh ** Return the collation sequence for the expression pExpr. If
97ae80ddeaSdrh ** there is no defined collating sequence, return NULL.
98ae80ddeaSdrh **
99ae80ddeaSdrh ** The collating sequence might be determined by a COLLATE operator
100ae80ddeaSdrh ** or by the presence of a column with a defined collating sequence.
101ae80ddeaSdrh ** COLLATE operators take first precedence.  Left operands take
102ae80ddeaSdrh ** precedence over right operands.
1030202b29eSdanielk1977 */
1047cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
105ae80ddeaSdrh   sqlite3 *db = pParse->db;
1067cedc8d4Sdanielk1977   CollSeq *pColl = 0;
1077d10d5a6Sdrh   Expr *p = pExpr;
108ae80ddeaSdrh   while( p && pColl==0 ){
109ae80ddeaSdrh     int op = p->op;
110ae80ddeaSdrh     if( op==TK_CAST || op==TK_UPLUS ){
111ae80ddeaSdrh       p = p->pLeft;
112ae80ddeaSdrh       continue;
113ae80ddeaSdrh     }
114ae80ddeaSdrh     if( op==TK_COLLATE ){
115ae80ddeaSdrh       pColl = sqlite3FindCollSeq(db, ENC(db), p->u.zToken, 0);
116ae80ddeaSdrh       break;
117ae80ddeaSdrh     }
118ae80ddeaSdrh     if( p->pTab!=0
119ae80ddeaSdrh      && (op==TK_AGG_COLUMN || op==TK_COLUMN
120ae80ddeaSdrh           || op==TK_REGISTER || op==TK_TRIGGER)
121ae80ddeaSdrh     ){
1227d10d5a6Sdrh       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
1237d10d5a6Sdrh       ** a TK_COLUMN but was previously evaluated and cached in a register */
1247d10d5a6Sdrh       int j = p->iColumn;
1257d10d5a6Sdrh       if( j>=0 ){
126ae80ddeaSdrh         const char *zColl = p->pTab->aCol[j].zColl;
127c4a64facSdrh         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
1280202b29eSdanielk1977       }
1297d10d5a6Sdrh       break;
1307d10d5a6Sdrh     }
131ae80ddeaSdrh     if( p->flags & EP_Collate ){
1324b17cf58Sdrh       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
1337d10d5a6Sdrh         p = p->pLeft;
134ae80ddeaSdrh       }else{
135ae80ddeaSdrh         p = p->pRight;
136ae80ddeaSdrh       }
137ae80ddeaSdrh     }else{
138ae80ddeaSdrh       break;
139ae80ddeaSdrh     }
1400202b29eSdanielk1977   }
1417cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
1427cedc8d4Sdanielk1977     pColl = 0;
1437cedc8d4Sdanielk1977   }
1447cedc8d4Sdanielk1977   return pColl;
1450202b29eSdanielk1977 }
1460202b29eSdanielk1977 
1470202b29eSdanielk1977 /*
148626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
149626a879aSdrh ** type affinity of the other operand.  This routine returns the
15053db1458Sdrh ** type affinity that should be used for the comparison operator.
15153db1458Sdrh */
152e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
153bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
154e014a838Sdanielk1977   if( aff1 && aff2 ){
1558df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
1568df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
157e014a838Sdanielk1977     */
1588a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
159e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
160e014a838Sdanielk1977     }else{
161e014a838Sdanielk1977       return SQLITE_AFF_NONE;
162e014a838Sdanielk1977     }
163e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
1645f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
1655f6a87b3Sdrh     ** results directly.
166e014a838Sdanielk1977     */
1675f6a87b3Sdrh     return SQLITE_AFF_NONE;
168e014a838Sdanielk1977   }else{
169e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
170fe05af87Sdrh     assert( aff1==0 || aff2==0 );
171e014a838Sdanielk1977     return (aff1 + aff2);
172e014a838Sdanielk1977   }
173e014a838Sdanielk1977 }
174e014a838Sdanielk1977 
17553db1458Sdrh /*
17653db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
17753db1458Sdrh ** be applied to both operands prior to doing the comparison.
17853db1458Sdrh */
179e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
180e014a838Sdanielk1977   char aff;
181e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
182e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
1836a2fe093Sdrh           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
184e014a838Sdanielk1977   assert( pExpr->pLeft );
185bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
186e014a838Sdanielk1977   if( pExpr->pRight ){
187e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
1886ab3a2ecSdanielk1977   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1896ab3a2ecSdanielk1977     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
1906ab3a2ecSdanielk1977   }else if( !aff ){
191de087bd5Sdrh     aff = SQLITE_AFF_NONE;
192e014a838Sdanielk1977   }
193e014a838Sdanielk1977   return aff;
194e014a838Sdanielk1977 }
195e014a838Sdanielk1977 
196e014a838Sdanielk1977 /*
197e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
198e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
199e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
200e014a838Sdanielk1977 ** the comparison in pExpr.
201e014a838Sdanielk1977 */
202e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
203e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
2048a51256cSdrh   switch( aff ){
2058a51256cSdrh     case SQLITE_AFF_NONE:
2068a51256cSdrh       return 1;
2078a51256cSdrh     case SQLITE_AFF_TEXT:
2088a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
2098a51256cSdrh     default:
2108a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
2118a51256cSdrh   }
212e014a838Sdanielk1977 }
213e014a838Sdanielk1977 
214a37cdde0Sdanielk1977 /*
21535573356Sdrh ** Return the P5 value that should be used for a binary comparison
216a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
217a37cdde0Sdanielk1977 */
21835573356Sdrh static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
21935573356Sdrh   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
2201bd10f8aSdrh   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
22135573356Sdrh   return aff;
222a37cdde0Sdanielk1977 }
223a37cdde0Sdanielk1977 
224a2e00042Sdrh /*
2250202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
2260202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
2270202b29eSdanielk1977 **
2280202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
2290202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
2300202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
2310202b29eSdanielk1977 ** type.
232bcbb04e5Sdanielk1977 **
233bcbb04e5Sdanielk1977 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
234bcbb04e5Sdanielk1977 ** it is not considered.
2350202b29eSdanielk1977 */
236bcbb04e5Sdanielk1977 CollSeq *sqlite3BinaryCompareCollSeq(
237bcbb04e5Sdanielk1977   Parse *pParse,
238bcbb04e5Sdanielk1977   Expr *pLeft,
239bcbb04e5Sdanielk1977   Expr *pRight
240bcbb04e5Sdanielk1977 ){
241ec41ddacSdrh   CollSeq *pColl;
242ec41ddacSdrh   assert( pLeft );
243ae80ddeaSdrh   if( pLeft->flags & EP_Collate ){
244ae80ddeaSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
245ae80ddeaSdrh   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
246ae80ddeaSdrh     pColl = sqlite3ExprCollSeq(pParse, pRight);
247ec41ddacSdrh   }else{
248ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
2490202b29eSdanielk1977     if( !pColl ){
2507cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
2510202b29eSdanielk1977     }
252ec41ddacSdrh   }
2530202b29eSdanielk1977   return pColl;
2540202b29eSdanielk1977 }
2550202b29eSdanielk1977 
2560202b29eSdanielk1977 /*
257be5c89acSdrh ** Generate code for a comparison operator.
258be5c89acSdrh */
259be5c89acSdrh static int codeCompare(
260be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
261be5c89acSdrh   Expr *pLeft,      /* The left operand */
262be5c89acSdrh   Expr *pRight,     /* The right operand */
263be5c89acSdrh   int opcode,       /* The comparison opcode */
26435573356Sdrh   int in1, int in2, /* Register holding operands */
265be5c89acSdrh   int dest,         /* Jump here if true.  */
266be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
267be5c89acSdrh ){
26835573356Sdrh   int p5;
26935573356Sdrh   int addr;
27035573356Sdrh   CollSeq *p4;
27135573356Sdrh 
27235573356Sdrh   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
27335573356Sdrh   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
27435573356Sdrh   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
27535573356Sdrh                            (void*)p4, P4_COLLSEQ);
2761bd10f8aSdrh   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
27735573356Sdrh   return addr;
278be5c89acSdrh }
279be5c89acSdrh 
2804b5255acSdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
2814b5255acSdanielk1977 /*
2824b5255acSdanielk1977 ** Check that argument nHeight is less than or equal to the maximum
2834b5255acSdanielk1977 ** expression depth allowed. If it is not, leave an error message in
2844b5255acSdanielk1977 ** pParse.
2854b5255acSdanielk1977 */
2867d10d5a6Sdrh int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
2874b5255acSdanielk1977   int rc = SQLITE_OK;
2884b5255acSdanielk1977   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
2894b5255acSdanielk1977   if( nHeight>mxHeight ){
2904b5255acSdanielk1977     sqlite3ErrorMsg(pParse,
2914b5255acSdanielk1977        "Expression tree is too large (maximum depth %d)", mxHeight
2924b5255acSdanielk1977     );
2934b5255acSdanielk1977     rc = SQLITE_ERROR;
2944b5255acSdanielk1977   }
2954b5255acSdanielk1977   return rc;
2964b5255acSdanielk1977 }
2974b5255acSdanielk1977 
2984b5255acSdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
2994b5255acSdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
3004b5255acSdanielk1977 ** of any expression tree referenced by the structure passed as the
3014b5255acSdanielk1977 ** first argument.
3024b5255acSdanielk1977 **
3034b5255acSdanielk1977 ** If this maximum height is greater than the current value pointed
3044b5255acSdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
3054b5255acSdanielk1977 ** value.
3064b5255acSdanielk1977 */
3074b5255acSdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
3084b5255acSdanielk1977   if( p ){
3094b5255acSdanielk1977     if( p->nHeight>*pnHeight ){
3104b5255acSdanielk1977       *pnHeight = p->nHeight;
3114b5255acSdanielk1977     }
3124b5255acSdanielk1977   }
3134b5255acSdanielk1977 }
3144b5255acSdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
3154b5255acSdanielk1977   if( p ){
3164b5255acSdanielk1977     int i;
3174b5255acSdanielk1977     for(i=0; i<p->nExpr; i++){
3184b5255acSdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
3194b5255acSdanielk1977     }
3204b5255acSdanielk1977   }
3214b5255acSdanielk1977 }
3224b5255acSdanielk1977 static void heightOfSelect(Select *p, int *pnHeight){
3234b5255acSdanielk1977   if( p ){
3244b5255acSdanielk1977     heightOfExpr(p->pWhere, pnHeight);
3254b5255acSdanielk1977     heightOfExpr(p->pHaving, pnHeight);
3264b5255acSdanielk1977     heightOfExpr(p->pLimit, pnHeight);
3274b5255acSdanielk1977     heightOfExpr(p->pOffset, pnHeight);
3284b5255acSdanielk1977     heightOfExprList(p->pEList, pnHeight);
3294b5255acSdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
3304b5255acSdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
3314b5255acSdanielk1977     heightOfSelect(p->pPrior, pnHeight);
3324b5255acSdanielk1977   }
3334b5255acSdanielk1977 }
3344b5255acSdanielk1977 
3354b5255acSdanielk1977 /*
3364b5255acSdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
3374b5255acSdanielk1977 ** argument. An expression with no children, Expr.pList or
3384b5255acSdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
3394b5255acSdanielk1977 ** has a height equal to the maximum height of any other
3404b5255acSdanielk1977 ** referenced Expr plus one.
3414b5255acSdanielk1977 */
3424b5255acSdanielk1977 static void exprSetHeight(Expr *p){
3434b5255acSdanielk1977   int nHeight = 0;
3444b5255acSdanielk1977   heightOfExpr(p->pLeft, &nHeight);
3454b5255acSdanielk1977   heightOfExpr(p->pRight, &nHeight);
3466ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_xIsSelect) ){
3476ab3a2ecSdanielk1977     heightOfSelect(p->x.pSelect, &nHeight);
3486ab3a2ecSdanielk1977   }else{
3496ab3a2ecSdanielk1977     heightOfExprList(p->x.pList, &nHeight);
3506ab3a2ecSdanielk1977   }
3514b5255acSdanielk1977   p->nHeight = nHeight + 1;
3524b5255acSdanielk1977 }
3534b5255acSdanielk1977 
3544b5255acSdanielk1977 /*
3554b5255acSdanielk1977 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
3564b5255acSdanielk1977 ** the height is greater than the maximum allowed expression depth,
3574b5255acSdanielk1977 ** leave an error in pParse.
3584b5255acSdanielk1977 */
3594b5255acSdanielk1977 void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
3604b5255acSdanielk1977   exprSetHeight(p);
3617d10d5a6Sdrh   sqlite3ExprCheckHeight(pParse, p->nHeight);
3624b5255acSdanielk1977 }
3634b5255acSdanielk1977 
3644b5255acSdanielk1977 /*
3654b5255acSdanielk1977 ** Return the maximum height of any expression tree referenced
3664b5255acSdanielk1977 ** by the select statement passed as an argument.
3674b5255acSdanielk1977 */
3684b5255acSdanielk1977 int sqlite3SelectExprHeight(Select *p){
3694b5255acSdanielk1977   int nHeight = 0;
3704b5255acSdanielk1977   heightOfSelect(p, &nHeight);
3714b5255acSdanielk1977   return nHeight;
3724b5255acSdanielk1977 }
3734b5255acSdanielk1977 #else
3744b5255acSdanielk1977   #define exprSetHeight(y)
3754b5255acSdanielk1977 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
3764b5255acSdanielk1977 
377be5c89acSdrh /*
378b7916a78Sdrh ** This routine is the core allocator for Expr nodes.
379b7916a78Sdrh **
380a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
381b7916a78Sdrh ** for this node and for the pToken argument is a single allocation
382b7916a78Sdrh ** obtained from sqlite3DbMalloc().  The calling function
383a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
384b7916a78Sdrh **
385b7916a78Sdrh ** If dequote is true, then the token (if it exists) is dequoted.
386b7916a78Sdrh ** If dequote is false, no dequoting is performance.  The deQuote
387b7916a78Sdrh ** parameter is ignored if pToken is NULL or if the token does not
388b7916a78Sdrh ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
389b7916a78Sdrh ** then the EP_DblQuoted flag is set on the expression node.
39033e619fcSdrh **
39133e619fcSdrh ** Special case:  If op==TK_INTEGER and pToken points to a string that
39233e619fcSdrh ** can be translated into a 32-bit integer, then the token is not
39333e619fcSdrh ** stored in u.zToken.  Instead, the integer values is written
39433e619fcSdrh ** into u.iValue and the EP_IntValue flag is set.  No extra storage
39533e619fcSdrh ** is allocated to hold the integer text and the dequote flag is ignored.
396a76b5dfcSdrh */
397b7916a78Sdrh Expr *sqlite3ExprAlloc(
398a1644fd8Sdanielk1977   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
39917435752Sdrh   int op,                 /* Expression opcode */
400b7916a78Sdrh   const Token *pToken,    /* Token argument.  Might be NULL */
401b7916a78Sdrh   int dequote             /* True to dequote */
40217435752Sdrh ){
403a76b5dfcSdrh   Expr *pNew;
40433e619fcSdrh   int nExtra = 0;
405cf697396Sshane   int iValue = 0;
406b7916a78Sdrh 
407b7916a78Sdrh   if( pToken ){
40833e619fcSdrh     if( op!=TK_INTEGER || pToken->z==0
40933e619fcSdrh           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
410b7916a78Sdrh       nExtra = pToken->n+1;
411d50ffc41Sdrh       assert( iValue>=0 );
41233e619fcSdrh     }
413a76b5dfcSdrh   }
414b7916a78Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
415b7916a78Sdrh   if( pNew ){
4161bd10f8aSdrh     pNew->op = (u8)op;
417a58fdfb1Sdanielk1977     pNew->iAgg = -1;
418a76b5dfcSdrh     if( pToken ){
41933e619fcSdrh       if( nExtra==0 ){
42033e619fcSdrh         pNew->flags |= EP_IntValue;
42133e619fcSdrh         pNew->u.iValue = iValue;
42233e619fcSdrh       }else{
423d9da78a2Sdrh         int c;
42433e619fcSdrh         pNew->u.zToken = (char*)&pNew[1];
425b07028f7Sdrh         assert( pToken->z!=0 || pToken->n==0 );
426b07028f7Sdrh         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
42733e619fcSdrh         pNew->u.zToken[pToken->n] = 0;
428b7916a78Sdrh         if( dequote && nExtra>=3
429d9da78a2Sdrh              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
43033e619fcSdrh           sqlite3Dequote(pNew->u.zToken);
43124fb627aSdrh           if( c=='"' ) pNew->flags |= EP_DblQuoted;
432a34001c9Sdrh         }
433a34001c9Sdrh       }
43433e619fcSdrh     }
435b7916a78Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
436b7916a78Sdrh     pNew->nHeight = 1;
437b7916a78Sdrh #endif
438a34001c9Sdrh   }
439a76b5dfcSdrh   return pNew;
440a76b5dfcSdrh }
441a76b5dfcSdrh 
442a76b5dfcSdrh /*
443b7916a78Sdrh ** Allocate a new expression node from a zero-terminated token that has
444b7916a78Sdrh ** already been dequoted.
445b7916a78Sdrh */
446b7916a78Sdrh Expr *sqlite3Expr(
447b7916a78Sdrh   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
448b7916a78Sdrh   int op,                 /* Expression opcode */
449b7916a78Sdrh   const char *zToken      /* Token argument.  Might be NULL */
450b7916a78Sdrh ){
451b7916a78Sdrh   Token x;
452b7916a78Sdrh   x.z = zToken;
453b7916a78Sdrh   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
454b7916a78Sdrh   return sqlite3ExprAlloc(db, op, &x, 0);
455b7916a78Sdrh }
456b7916a78Sdrh 
457b7916a78Sdrh /*
458b7916a78Sdrh ** Attach subtrees pLeft and pRight to the Expr node pRoot.
459b7916a78Sdrh **
460b7916a78Sdrh ** If pRoot==NULL that means that a memory allocation error has occurred.
461b7916a78Sdrh ** In that case, delete the subtrees pLeft and pRight.
462b7916a78Sdrh */
463b7916a78Sdrh void sqlite3ExprAttachSubtrees(
464b7916a78Sdrh   sqlite3 *db,
465b7916a78Sdrh   Expr *pRoot,
466b7916a78Sdrh   Expr *pLeft,
467b7916a78Sdrh   Expr *pRight
468b7916a78Sdrh ){
469b7916a78Sdrh   if( pRoot==0 ){
470b7916a78Sdrh     assert( db->mallocFailed );
471b7916a78Sdrh     sqlite3ExprDelete(db, pLeft);
472b7916a78Sdrh     sqlite3ExprDelete(db, pRight);
473b7916a78Sdrh   }else{
474b7916a78Sdrh     if( pRight ){
475b7916a78Sdrh       pRoot->pRight = pRight;
476ae80ddeaSdrh       pRoot->flags |= EP_Collate & pRight->flags;
477b7916a78Sdrh     }
478b7916a78Sdrh     if( pLeft ){
479b7916a78Sdrh       pRoot->pLeft = pLeft;
480ae80ddeaSdrh       pRoot->flags |= EP_Collate & pLeft->flags;
481b7916a78Sdrh     }
482b7916a78Sdrh     exprSetHeight(pRoot);
483b7916a78Sdrh   }
484b7916a78Sdrh }
485b7916a78Sdrh 
486b7916a78Sdrh /*
487bf664469Sdrh ** Allocate a Expr node which joins as many as two subtrees.
488b7916a78Sdrh **
489bf664469Sdrh ** One or both of the subtrees can be NULL.  Return a pointer to the new
490bf664469Sdrh ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
491bf664469Sdrh ** free the subtrees and return NULL.
492206f3d96Sdrh */
49317435752Sdrh Expr *sqlite3PExpr(
49417435752Sdrh   Parse *pParse,          /* Parsing context */
49517435752Sdrh   int op,                 /* Expression opcode */
49617435752Sdrh   Expr *pLeft,            /* Left operand */
49717435752Sdrh   Expr *pRight,           /* Right operand */
49817435752Sdrh   const Token *pToken     /* Argument token */
49917435752Sdrh ){
5005fb52caaSdrh   Expr *p;
5015fb52caaSdrh   if( op==TK_AND && pLeft && pRight ){
5025fb52caaSdrh     /* Take advantage of short-circuit false optimization for AND */
5035fb52caaSdrh     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
5045fb52caaSdrh   }else{
5055fb52caaSdrh     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
506b7916a78Sdrh     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
5075fb52caaSdrh   }
5082b359bdbSdan   if( p ) {
5092b359bdbSdan     sqlite3ExprCheckHeight(pParse, p->nHeight);
5102b359bdbSdan   }
5114e0cff60Sdrh   return p;
5124e0cff60Sdrh }
5134e0cff60Sdrh 
5144e0cff60Sdrh /*
5155fb52caaSdrh ** Return 1 if an expression must be FALSE in all cases and 0 if the
5165fb52caaSdrh ** expression might be true.  This is an optimization.  If is OK to
5175fb52caaSdrh ** return 0 here even if the expression really is always false (a
5185fb52caaSdrh ** false negative).  But it is a bug to return 1 if the expression
5195fb52caaSdrh ** might be true in some rare circumstances (a false positive.)
5205fb52caaSdrh **
5215fb52caaSdrh ** Note that if the expression is part of conditional for a
5225fb52caaSdrh ** LEFT JOIN, then we cannot determine at compile-time whether or not
5235fb52caaSdrh ** is it true or false, so always return 0.
5245fb52caaSdrh */
5255fb52caaSdrh static int exprAlwaysFalse(Expr *p){
5265fb52caaSdrh   int v = 0;
5275fb52caaSdrh   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
5285fb52caaSdrh   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
5295fb52caaSdrh   return v==0;
5305fb52caaSdrh }
5315fb52caaSdrh 
5325fb52caaSdrh /*
53391bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
53491bb0eedSdrh ** NULL, then just return the other expression.
5355fb52caaSdrh **
5365fb52caaSdrh ** If one side or the other of the AND is known to be false, then instead
5375fb52caaSdrh ** of returning an AND expression, just return a constant expression with
5385fb52caaSdrh ** a value of false.
53991bb0eedSdrh */
5401e536953Sdanielk1977 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
54191bb0eedSdrh   if( pLeft==0 ){
54291bb0eedSdrh     return pRight;
54391bb0eedSdrh   }else if( pRight==0 ){
54491bb0eedSdrh     return pLeft;
5455fb52caaSdrh   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
5465fb52caaSdrh     sqlite3ExprDelete(db, pLeft);
5475fb52caaSdrh     sqlite3ExprDelete(db, pRight);
5485fb52caaSdrh     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
54991bb0eedSdrh   }else{
550b7916a78Sdrh     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
551b7916a78Sdrh     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
552b7916a78Sdrh     return pNew;
553a76b5dfcSdrh   }
554a76b5dfcSdrh }
555a76b5dfcSdrh 
556a76b5dfcSdrh /*
557a76b5dfcSdrh ** Construct a new expression node for a function with multiple
558a76b5dfcSdrh ** arguments.
559a76b5dfcSdrh */
56017435752Sdrh Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
561a76b5dfcSdrh   Expr *pNew;
562633e6d57Sdrh   sqlite3 *db = pParse->db;
5634b202ae2Sdanielk1977   assert( pToken );
564b7916a78Sdrh   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
565a76b5dfcSdrh   if( pNew==0 ){
566d9da78a2Sdrh     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
567a76b5dfcSdrh     return 0;
568a76b5dfcSdrh   }
5696ab3a2ecSdanielk1977   pNew->x.pList = pList;
5706ab3a2ecSdanielk1977   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
5714b5255acSdanielk1977   sqlite3ExprSetHeight(pParse, pNew);
572a76b5dfcSdrh   return pNew;
573a76b5dfcSdrh }
574a76b5dfcSdrh 
575a76b5dfcSdrh /*
576fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
577fa6bc000Sdrh ** in the original SQL statement.
578fa6bc000Sdrh **
579fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
580fa6bc000Sdrh ** variable number.
581fa6bc000Sdrh **
582fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
583fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
584fa6bc000Sdrh ** the SQL statement comes from an external source.
585fa6bc000Sdrh **
58651f49f17Sdrh ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
587fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
588fa6bc000Sdrh ** instance of the wildcard, the next sequenial variable number is
589fa6bc000Sdrh ** assigned.
590fa6bc000Sdrh */
591fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
59217435752Sdrh   sqlite3 *db = pParse->db;
593b7916a78Sdrh   const char *z;
59417435752Sdrh 
595fa6bc000Sdrh   if( pExpr==0 ) return;
59633e619fcSdrh   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
59733e619fcSdrh   z = pExpr->u.zToken;
598b7916a78Sdrh   assert( z!=0 );
599b7916a78Sdrh   assert( z[0]!=0 );
600b7916a78Sdrh   if( z[1]==0 ){
601fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
602b7916a78Sdrh     assert( z[0]=='?' );
6038677d308Sdrh     pExpr->iColumn = (ynVar)(++pParse->nVar);
604124c0b49Sdrh   }else{
605124c0b49Sdrh     ynVar x = 0;
606124c0b49Sdrh     u32 n = sqlite3Strlen30(z);
607124c0b49Sdrh     if( z[0]=='?' ){
608fa6bc000Sdrh       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
609fa6bc000Sdrh       ** use it as the variable number */
610c8d735aeSdan       i64 i;
611124c0b49Sdrh       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
612124c0b49Sdrh       pExpr->iColumn = x = (ynVar)i;
613c5499befSdrh       testcase( i==0 );
614c5499befSdrh       testcase( i==1 );
615c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
616c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
617c8d735aeSdan       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
618fa6bc000Sdrh         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
619bb4957f8Sdrh             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
620124c0b49Sdrh         x = 0;
621fa6bc000Sdrh       }
622fa6bc000Sdrh       if( i>pParse->nVar ){
6231df2db7fSshaneh         pParse->nVar = (int)i;
624fa6bc000Sdrh       }
625fa6bc000Sdrh     }else{
62651f49f17Sdrh       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
627fa6bc000Sdrh       ** number as the prior appearance of the same name, or if the name
628fa6bc000Sdrh       ** has never appeared before, reuse the same variable number
629fa6bc000Sdrh       */
630124c0b49Sdrh       ynVar i;
631124c0b49Sdrh       for(i=0; i<pParse->nzVar; i++){
632124c0b49Sdrh         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
633124c0b49Sdrh           pExpr->iColumn = x = (ynVar)i+1;
634fa6bc000Sdrh           break;
635fa6bc000Sdrh         }
636fa6bc000Sdrh       }
637124c0b49Sdrh       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
638fa6bc000Sdrh     }
639124c0b49Sdrh     if( x>0 ){
640124c0b49Sdrh       if( x>pParse->nzVar ){
641124c0b49Sdrh         char **a;
642124c0b49Sdrh         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
643124c0b49Sdrh         if( a==0 ) return;  /* Error reported through db->mallocFailed */
644124c0b49Sdrh         pParse->azVar = a;
645124c0b49Sdrh         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
646124c0b49Sdrh         pParse->nzVar = x;
647124c0b49Sdrh       }
648124c0b49Sdrh       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
649124c0b49Sdrh         sqlite3DbFree(db, pParse->azVar[x-1]);
650124c0b49Sdrh         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
651fa6bc000Sdrh       }
652fa6bc000Sdrh     }
653fa6bc000Sdrh   }
654bb4957f8Sdrh   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
655832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
656832b2664Sdanielk1977   }
657fa6bc000Sdrh }
658fa6bc000Sdrh 
659fa6bc000Sdrh /*
660f6963f99Sdan ** Recursively delete an expression tree.
661a2e00042Sdrh */
662f6963f99Sdan void sqlite3ExprDelete(sqlite3 *db, Expr *p){
663f6963f99Sdan   if( p==0 ) return;
664d50ffc41Sdrh   /* Sanity check: Assert that the IntValue is non-negative if it exists */
665d50ffc41Sdrh   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
666b7916a78Sdrh   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
667633e6d57Sdrh     sqlite3ExprDelete(db, p->pLeft);
668633e6d57Sdrh     sqlite3ExprDelete(db, p->pRight);
66933e619fcSdrh     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
67033e619fcSdrh       sqlite3DbFree(db, p->u.zToken);
6716ab3a2ecSdanielk1977     }
6726ab3a2ecSdanielk1977     if( ExprHasProperty(p, EP_xIsSelect) ){
6736ab3a2ecSdanielk1977       sqlite3SelectDelete(db, p->x.pSelect);
6746ab3a2ecSdanielk1977     }else{
6756ab3a2ecSdanielk1977       sqlite3ExprListDelete(db, p->x.pList);
6766ab3a2ecSdanielk1977     }
6776ab3a2ecSdanielk1977   }
67833e619fcSdrh   if( !ExprHasProperty(p, EP_Static) ){
679633e6d57Sdrh     sqlite3DbFree(db, p);
680a2e00042Sdrh   }
68133e619fcSdrh }
682a2e00042Sdrh 
683d2687b77Sdrh /*
6846ab3a2ecSdanielk1977 ** Return the number of bytes allocated for the expression structure
6856ab3a2ecSdanielk1977 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
6866ab3a2ecSdanielk1977 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
6876ab3a2ecSdanielk1977 */
6886ab3a2ecSdanielk1977 static int exprStructSize(Expr *p){
6896ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
6906ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
6916ab3a2ecSdanielk1977   return EXPR_FULLSIZE;
6926ab3a2ecSdanielk1977 }
6936ab3a2ecSdanielk1977 
6946ab3a2ecSdanielk1977 /*
69533e619fcSdrh ** The dupedExpr*Size() routines each return the number of bytes required
69633e619fcSdrh ** to store a copy of an expression or expression tree.  They differ in
69733e619fcSdrh ** how much of the tree is measured.
69833e619fcSdrh **
69933e619fcSdrh **     dupedExprStructSize()     Size of only the Expr structure
70033e619fcSdrh **     dupedExprNodeSize()       Size of Expr + space for token
70133e619fcSdrh **     dupedExprSize()           Expr + token + subtree components
70233e619fcSdrh **
70333e619fcSdrh ***************************************************************************
70433e619fcSdrh **
70533e619fcSdrh ** The dupedExprStructSize() function returns two values OR-ed together:
70633e619fcSdrh ** (1) the space required for a copy of the Expr structure only and
70733e619fcSdrh ** (2) the EP_xxx flags that indicate what the structure size should be.
70833e619fcSdrh ** The return values is always one of:
70933e619fcSdrh **
71033e619fcSdrh **      EXPR_FULLSIZE
71133e619fcSdrh **      EXPR_REDUCEDSIZE   | EP_Reduced
71233e619fcSdrh **      EXPR_TOKENONLYSIZE | EP_TokenOnly
71333e619fcSdrh **
71433e619fcSdrh ** The size of the structure can be found by masking the return value
71533e619fcSdrh ** of this routine with 0xfff.  The flags can be found by masking the
71633e619fcSdrh ** return value with EP_Reduced|EP_TokenOnly.
71733e619fcSdrh **
71833e619fcSdrh ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
71933e619fcSdrh ** (unreduced) Expr objects as they or originally constructed by the parser.
72033e619fcSdrh ** During expression analysis, extra information is computed and moved into
72133e619fcSdrh ** later parts of teh Expr object and that extra information might get chopped
72233e619fcSdrh ** off if the expression is reduced.  Note also that it does not work to
72333e619fcSdrh ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
72433e619fcSdrh ** to reduce a pristine expression tree from the parser.  The implementation
72533e619fcSdrh ** of dupedExprStructSize() contain multiple assert() statements that attempt
72633e619fcSdrh ** to enforce this constraint.
7276ab3a2ecSdanielk1977 */
7286ab3a2ecSdanielk1977 static int dupedExprStructSize(Expr *p, int flags){
7296ab3a2ecSdanielk1977   int nSize;
73033e619fcSdrh   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
7316ab3a2ecSdanielk1977   if( 0==(flags&EXPRDUP_REDUCE) ){
7326ab3a2ecSdanielk1977     nSize = EXPR_FULLSIZE;
7336ab3a2ecSdanielk1977   }else{
73433e619fcSdrh     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
73533e619fcSdrh     assert( !ExprHasProperty(p, EP_FromJoin) );
73633e619fcSdrh     assert( (p->flags2 & EP2_MallocedToken)==0 );
73733e619fcSdrh     assert( (p->flags2 & EP2_Irreducible)==0 );
738ae80ddeaSdrh     if( p->pLeft || p->pRight || p->x.pList ){
73933e619fcSdrh       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
74033e619fcSdrh     }else{
74133e619fcSdrh       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
74233e619fcSdrh     }
7436ab3a2ecSdanielk1977   }
7446ab3a2ecSdanielk1977   return nSize;
7456ab3a2ecSdanielk1977 }
7466ab3a2ecSdanielk1977 
7476ab3a2ecSdanielk1977 /*
74833e619fcSdrh ** This function returns the space in bytes required to store the copy
74933e619fcSdrh ** of the Expr structure and a copy of the Expr.u.zToken string (if that
75033e619fcSdrh ** string is defined.)
7516ab3a2ecSdanielk1977 */
7526ab3a2ecSdanielk1977 static int dupedExprNodeSize(Expr *p, int flags){
75333e619fcSdrh   int nByte = dupedExprStructSize(p, flags) & 0xfff;
75433e619fcSdrh   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75533e619fcSdrh     nByte += sqlite3Strlen30(p->u.zToken)+1;
7566ab3a2ecSdanielk1977   }
757bc73971dSdanielk1977   return ROUND8(nByte);
7586ab3a2ecSdanielk1977 }
7596ab3a2ecSdanielk1977 
7606ab3a2ecSdanielk1977 /*
7616ab3a2ecSdanielk1977 ** Return the number of bytes required to create a duplicate of the
7626ab3a2ecSdanielk1977 ** expression passed as the first argument. The second argument is a
7636ab3a2ecSdanielk1977 ** mask containing EXPRDUP_XXX flags.
7646ab3a2ecSdanielk1977 **
7656ab3a2ecSdanielk1977 ** The value returned includes space to create a copy of the Expr struct
76633e619fcSdrh ** itself and the buffer referred to by Expr.u.zToken, if any.
7676ab3a2ecSdanielk1977 **
7686ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
7696ab3a2ecSdanielk1977 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
7706ab3a2ecSdanielk1977 ** and Expr.pRight variables (but not for any structures pointed to or
7716ab3a2ecSdanielk1977 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
7726ab3a2ecSdanielk1977 */
7736ab3a2ecSdanielk1977 static int dupedExprSize(Expr *p, int flags){
7746ab3a2ecSdanielk1977   int nByte = 0;
7756ab3a2ecSdanielk1977   if( p ){
7766ab3a2ecSdanielk1977     nByte = dupedExprNodeSize(p, flags);
7776ab3a2ecSdanielk1977     if( flags&EXPRDUP_REDUCE ){
778b7916a78Sdrh       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
7796ab3a2ecSdanielk1977     }
7806ab3a2ecSdanielk1977   }
7816ab3a2ecSdanielk1977   return nByte;
7826ab3a2ecSdanielk1977 }
7836ab3a2ecSdanielk1977 
7846ab3a2ecSdanielk1977 /*
7856ab3a2ecSdanielk1977 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
7866ab3a2ecSdanielk1977 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
78733e619fcSdrh ** to store the copy of expression p, the copies of p->u.zToken
7886ab3a2ecSdanielk1977 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
7896ab3a2ecSdanielk1977 ** if any. Before returning, *pzBuffer is set to the first byte passed the
7906ab3a2ecSdanielk1977 ** portion of the buffer copied into by this function.
7916ab3a2ecSdanielk1977 */
7926ab3a2ecSdanielk1977 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
7936ab3a2ecSdanielk1977   Expr *pNew = 0;                      /* Value to return */
7946ab3a2ecSdanielk1977   if( p ){
7956ab3a2ecSdanielk1977     const int isReduced = (flags&EXPRDUP_REDUCE);
7966ab3a2ecSdanielk1977     u8 *zAlloc;
79733e619fcSdrh     u32 staticFlag = 0;
7986ab3a2ecSdanielk1977 
7996ab3a2ecSdanielk1977     assert( pzBuffer==0 || isReduced );
8006ab3a2ecSdanielk1977 
8016ab3a2ecSdanielk1977     /* Figure out where to write the new Expr structure. */
8026ab3a2ecSdanielk1977     if( pzBuffer ){
8036ab3a2ecSdanielk1977       zAlloc = *pzBuffer;
80433e619fcSdrh       staticFlag = EP_Static;
8056ab3a2ecSdanielk1977     }else{
8066ab3a2ecSdanielk1977       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
8076ab3a2ecSdanielk1977     }
8086ab3a2ecSdanielk1977     pNew = (Expr *)zAlloc;
8096ab3a2ecSdanielk1977 
8106ab3a2ecSdanielk1977     if( pNew ){
8116ab3a2ecSdanielk1977       /* Set nNewSize to the size allocated for the structure pointed to
8126ab3a2ecSdanielk1977       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
8136ab3a2ecSdanielk1977       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
81433e619fcSdrh       ** by the copy of the p->u.zToken string (if any).
8156ab3a2ecSdanielk1977       */
81633e619fcSdrh       const unsigned nStructSize = dupedExprStructSize(p, flags);
81733e619fcSdrh       const int nNewSize = nStructSize & 0xfff;
81833e619fcSdrh       int nToken;
81933e619fcSdrh       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
82033e619fcSdrh         nToken = sqlite3Strlen30(p->u.zToken) + 1;
82133e619fcSdrh       }else{
82233e619fcSdrh         nToken = 0;
82333e619fcSdrh       }
8246ab3a2ecSdanielk1977       if( isReduced ){
8256ab3a2ecSdanielk1977         assert( ExprHasProperty(p, EP_Reduced)==0 );
8266ab3a2ecSdanielk1977         memcpy(zAlloc, p, nNewSize);
8276ab3a2ecSdanielk1977       }else{
8286ab3a2ecSdanielk1977         int nSize = exprStructSize(p);
8296ab3a2ecSdanielk1977         memcpy(zAlloc, p, nSize);
8306ab3a2ecSdanielk1977         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
8316ab3a2ecSdanielk1977       }
8326ab3a2ecSdanielk1977 
83333e619fcSdrh       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
83433e619fcSdrh       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
83533e619fcSdrh       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
83633e619fcSdrh       pNew->flags |= staticFlag;
8376ab3a2ecSdanielk1977 
83833e619fcSdrh       /* Copy the p->u.zToken string, if any. */
8396ab3a2ecSdanielk1977       if( nToken ){
84033e619fcSdrh         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
84133e619fcSdrh         memcpy(zToken, p->u.zToken, nToken);
8426ab3a2ecSdanielk1977       }
8436ab3a2ecSdanielk1977 
8446ab3a2ecSdanielk1977       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
8456ab3a2ecSdanielk1977         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
8466ab3a2ecSdanielk1977         if( ExprHasProperty(p, EP_xIsSelect) ){
8476ab3a2ecSdanielk1977           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
8486ab3a2ecSdanielk1977         }else{
8496ab3a2ecSdanielk1977           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
8506ab3a2ecSdanielk1977         }
8516ab3a2ecSdanielk1977       }
8526ab3a2ecSdanielk1977 
8536ab3a2ecSdanielk1977       /* Fill in pNew->pLeft and pNew->pRight. */
854b7916a78Sdrh       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
8556ab3a2ecSdanielk1977         zAlloc += dupedExprNodeSize(p, flags);
8566ab3a2ecSdanielk1977         if( ExprHasProperty(pNew, EP_Reduced) ){
8576ab3a2ecSdanielk1977           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
8586ab3a2ecSdanielk1977           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
8596ab3a2ecSdanielk1977         }
8606ab3a2ecSdanielk1977         if( pzBuffer ){
8616ab3a2ecSdanielk1977           *pzBuffer = zAlloc;
8626ab3a2ecSdanielk1977         }
863b7916a78Sdrh       }else{
864b7916a78Sdrh         pNew->flags2 = 0;
865b7916a78Sdrh         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
8666ab3a2ecSdanielk1977           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
8676ab3a2ecSdanielk1977           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
8686ab3a2ecSdanielk1977         }
8696ab3a2ecSdanielk1977       }
870b7916a78Sdrh 
871b7916a78Sdrh     }
8726ab3a2ecSdanielk1977   }
8736ab3a2ecSdanielk1977   return pNew;
8746ab3a2ecSdanielk1977 }
8756ab3a2ecSdanielk1977 
8766ab3a2ecSdanielk1977 /*
877ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
878ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
879ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
880ff78bd2fSdrh ** without effecting the originals.
881ff78bd2fSdrh **
8824adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
8834adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
884ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
885ff78bd2fSdrh **
886ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
8876ab3a2ecSdanielk1977 **
888b7916a78Sdrh ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
8896ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
8906ab3a2ecSdanielk1977 ** truncated version of the usual Expr structure that will be stored as
8916ab3a2ecSdanielk1977 ** part of the in-memory representation of the database schema.
892ff78bd2fSdrh */
8936ab3a2ecSdanielk1977 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
8946ab3a2ecSdanielk1977   return exprDup(db, p, flags, 0);
895ff78bd2fSdrh }
8966ab3a2ecSdanielk1977 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
897ff78bd2fSdrh   ExprList *pNew;
898145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
899ff78bd2fSdrh   int i;
900ff78bd2fSdrh   if( p==0 ) return 0;
90117435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
902ff78bd2fSdrh   if( pNew==0 ) return 0;
90331dad9daSdanielk1977   pNew->iECursor = 0;
904d872bb18Sdrh   pNew->nExpr = i = p->nExpr;
905d872bb18Sdrh   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
906d872bb18Sdrh   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
907e0048400Sdanielk1977   if( pItem==0 ){
908633e6d57Sdrh     sqlite3DbFree(db, pNew);
909e0048400Sdanielk1977     return 0;
910e0048400Sdanielk1977   }
911145716b3Sdrh   pOldItem = p->a;
912145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
9136ab3a2ecSdanielk1977     Expr *pOldExpr = pOldItem->pExpr;
914b5526ea6Sdrh     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
91517435752Sdrh     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
916b7916a78Sdrh     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
917145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
9183e7bc9caSdrh     pItem->done = 0;
9194b3ac73cSdrh     pItem->iOrderByCol = pOldItem->iOrderByCol;
9208b213899Sdrh     pItem->iAlias = pOldItem->iAlias;
921ff78bd2fSdrh   }
922ff78bd2fSdrh   return pNew;
923ff78bd2fSdrh }
92493758c8dSdanielk1977 
92593758c8dSdanielk1977 /*
92693758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
92793758c8dSdanielk1977 ** the build, then none of the following routines, except for
92893758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
92993758c8dSdanielk1977 ** called with a NULL argument.
93093758c8dSdanielk1977 */
9316a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
9326a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
9336ab3a2ecSdanielk1977 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
934ad3cab52Sdrh   SrcList *pNew;
935ad3cab52Sdrh   int i;
936113088ecSdrh   int nByte;
937ad3cab52Sdrh   if( p==0 ) return 0;
938113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
93917435752Sdrh   pNew = sqlite3DbMallocRaw(db, nByte );
940ad3cab52Sdrh   if( pNew==0 ) return 0;
9414305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
942ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
9434efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
9444efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
945ed8a3bb1Sdrh     Table *pTab;
94641fb5cd1Sdan     pNewItem->pSchema = pOldItem->pSchema;
94717435752Sdrh     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
94817435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
94917435752Sdrh     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
9504efc4754Sdrh     pNewItem->jointype = pOldItem->jointype;
9514efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
9525b6a9ed4Sdrh     pNewItem->addrFillSub = pOldItem->addrFillSub;
9535b6a9ed4Sdrh     pNewItem->regReturn = pOldItem->regReturn;
954da79cf0cSdan     pNewItem->isCorrelated = pOldItem->isCorrelated;
95521172c4cSdrh     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
95685574e31Sdanielk1977     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
95785574e31Sdanielk1977     pNewItem->notIndexed = pOldItem->notIndexed;
95885574e31Sdanielk1977     pNewItem->pIndex = pOldItem->pIndex;
959ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
960ed8a3bb1Sdrh     if( pTab ){
961ed8a3bb1Sdrh       pTab->nRef++;
962a1cb183dSdanielk1977     }
9636ab3a2ecSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
9646ab3a2ecSdanielk1977     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
96517435752Sdrh     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
9666c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
967ad3cab52Sdrh   }
968ad3cab52Sdrh   return pNew;
969ad3cab52Sdrh }
97017435752Sdrh IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
971ff78bd2fSdrh   IdList *pNew;
972ff78bd2fSdrh   int i;
973ff78bd2fSdrh   if( p==0 ) return 0;
97417435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
975ff78bd2fSdrh   if( pNew==0 ) return 0;
9766c535158Sdrh   pNew->nId = p->nId;
97717435752Sdrh   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
978d5d56523Sdanielk1977   if( pNew->a==0 ){
979633e6d57Sdrh     sqlite3DbFree(db, pNew);
980d5d56523Sdanielk1977     return 0;
981d5d56523Sdanielk1977   }
9826c535158Sdrh   /* Note that because the size of the allocation for p->a[] is not
9836c535158Sdrh   ** necessarily a power of two, sqlite3IdListAppend() may not be called
9846c535158Sdrh   ** on the duplicate created by this function. */
985ff78bd2fSdrh   for(i=0; i<p->nId; i++){
9864efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
9874efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
98817435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
9894efc4754Sdrh     pNewItem->idx = pOldItem->idx;
990ff78bd2fSdrh   }
991ff78bd2fSdrh   return pNew;
992ff78bd2fSdrh }
9936ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
99423b1b372Sdrh   Select *pNew, *pPrior;
995ff78bd2fSdrh   if( p==0 ) return 0;
99617435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
997ff78bd2fSdrh   if( pNew==0 ) return 0;
998b7916a78Sdrh   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
9996ab3a2ecSdanielk1977   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
10006ab3a2ecSdanielk1977   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
10016ab3a2ecSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
10026ab3a2ecSdanielk1977   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
10036ab3a2ecSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1004ff78bd2fSdrh   pNew->op = p->op;
100523b1b372Sdrh   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
100623b1b372Sdrh   if( pPrior ) pPrior->pNext = pNew;
100723b1b372Sdrh   pNew->pNext = 0;
10086ab3a2ecSdanielk1977   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
10096ab3a2ecSdanielk1977   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
101092b01d53Sdrh   pNew->iLimit = 0;
101192b01d53Sdrh   pNew->iOffset = 0;
10127d10d5a6Sdrh   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
10130342b1f5Sdrh   pNew->pRightmost = 0;
1014b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
1015b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
1016b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
1017ff78bd2fSdrh   return pNew;
1018ff78bd2fSdrh }
101993758c8dSdanielk1977 #else
10206ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
102193758c8dSdanielk1977   assert( p==0 );
102293758c8dSdanielk1977   return 0;
102393758c8dSdanielk1977 }
102493758c8dSdanielk1977 #endif
1025ff78bd2fSdrh 
1026ff78bd2fSdrh 
1027ff78bd2fSdrh /*
1028a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
1029a76b5dfcSdrh ** initially NULL, then create a new expression list.
1030b7916a78Sdrh **
1031b7916a78Sdrh ** If a memory allocation error occurs, the entire list is freed and
1032b7916a78Sdrh ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1033b7916a78Sdrh ** that the new entry was successfully appended.
1034a76b5dfcSdrh */
103517435752Sdrh ExprList *sqlite3ExprListAppend(
103617435752Sdrh   Parse *pParse,          /* Parsing context */
103717435752Sdrh   ExprList *pList,        /* List to which to append. Might be NULL */
1038b7916a78Sdrh   Expr *pExpr             /* Expression to be appended. Might be NULL */
103917435752Sdrh ){
104017435752Sdrh   sqlite3 *db = pParse->db;
1041a76b5dfcSdrh   if( pList==0 ){
104217435752Sdrh     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
1043a76b5dfcSdrh     if( pList==0 ){
1044d5d56523Sdanielk1977       goto no_mem;
1045a76b5dfcSdrh     }
1046d872bb18Sdrh     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
1047d872bb18Sdrh     if( pList->a==0 ) goto no_mem;
1048d872bb18Sdrh   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
1049d5d56523Sdanielk1977     struct ExprList_item *a;
1050d872bb18Sdrh     assert( pList->nExpr>0 );
1051d872bb18Sdrh     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
1052d5d56523Sdanielk1977     if( a==0 ){
1053d5d56523Sdanielk1977       goto no_mem;
1054a76b5dfcSdrh     }
1055d5d56523Sdanielk1977     pList->a = a;
1056a76b5dfcSdrh   }
10574efc4754Sdrh   assert( pList->a!=0 );
1058b7916a78Sdrh   if( 1 ){
10594efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
10604efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
1061e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
1062a76b5dfcSdrh   }
1063a76b5dfcSdrh   return pList;
1064d5d56523Sdanielk1977 
1065d5d56523Sdanielk1977 no_mem:
1066d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
1067633e6d57Sdrh   sqlite3ExprDelete(db, pExpr);
1068633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1069d5d56523Sdanielk1977   return 0;
1070a76b5dfcSdrh }
1071a76b5dfcSdrh 
1072a76b5dfcSdrh /*
1073b7916a78Sdrh ** Set the ExprList.a[].zName element of the most recently added item
1074b7916a78Sdrh ** on the expression list.
1075b7916a78Sdrh **
1076b7916a78Sdrh ** pList might be NULL following an OOM error.  But pName should never be
1077b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1078b7916a78Sdrh ** is set.
1079b7916a78Sdrh */
1080b7916a78Sdrh void sqlite3ExprListSetName(
1081b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1082b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1083b7916a78Sdrh   Token *pName,           /* Name to be added */
1084b7916a78Sdrh   int dequote             /* True to cause the name to be dequoted */
1085b7916a78Sdrh ){
1086b7916a78Sdrh   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1087b7916a78Sdrh   if( pList ){
1088b7916a78Sdrh     struct ExprList_item *pItem;
1089b7916a78Sdrh     assert( pList->nExpr>0 );
1090b7916a78Sdrh     pItem = &pList->a[pList->nExpr-1];
1091b7916a78Sdrh     assert( pItem->zName==0 );
1092b7916a78Sdrh     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1093b7916a78Sdrh     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
1094b7916a78Sdrh   }
1095b7916a78Sdrh }
1096b7916a78Sdrh 
1097b7916a78Sdrh /*
1098b7916a78Sdrh ** Set the ExprList.a[].zSpan element of the most recently added item
1099b7916a78Sdrh ** on the expression list.
1100b7916a78Sdrh **
1101b7916a78Sdrh ** pList might be NULL following an OOM error.  But pSpan should never be
1102b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1103b7916a78Sdrh ** is set.
1104b7916a78Sdrh */
1105b7916a78Sdrh void sqlite3ExprListSetSpan(
1106b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1107b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1108b7916a78Sdrh   ExprSpan *pSpan         /* The span to be added */
1109b7916a78Sdrh ){
1110b7916a78Sdrh   sqlite3 *db = pParse->db;
1111b7916a78Sdrh   assert( pList!=0 || db->mallocFailed!=0 );
1112b7916a78Sdrh   if( pList ){
1113b7916a78Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1114b7916a78Sdrh     assert( pList->nExpr>0 );
1115b7916a78Sdrh     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1116b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1117b7916a78Sdrh     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1118cf697396Sshane                                     (int)(pSpan->zEnd - pSpan->zStart));
1119b7916a78Sdrh   }
1120b7916a78Sdrh }
1121b7916a78Sdrh 
1122b7916a78Sdrh /*
11237a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
11247a15a4beSdanielk1977 ** leave an error message in pParse.
11257a15a4beSdanielk1977 */
11267a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
11277a15a4beSdanielk1977   Parse *pParse,
11287a15a4beSdanielk1977   ExprList *pEList,
11297a15a4beSdanielk1977   const char *zObject
11307a15a4beSdanielk1977 ){
1131b1a6c3c1Sdrh   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1132c5499befSdrh   testcase( pEList && pEList->nExpr==mx );
1133c5499befSdrh   testcase( pEList && pEList->nExpr==mx+1 );
1134b1a6c3c1Sdrh   if( pEList && pEList->nExpr>mx ){
11357a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
11367a15a4beSdanielk1977   }
11377a15a4beSdanielk1977 }
11387a15a4beSdanielk1977 
11397a15a4beSdanielk1977 /*
1140a76b5dfcSdrh ** Delete an entire expression list.
1141a76b5dfcSdrh */
1142633e6d57Sdrh void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1143a76b5dfcSdrh   int i;
1144be5c89acSdrh   struct ExprList_item *pItem;
1145a76b5dfcSdrh   if( pList==0 ) return;
1146d872bb18Sdrh   assert( pList->a!=0 || pList->nExpr==0 );
1147be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1148633e6d57Sdrh     sqlite3ExprDelete(db, pItem->pExpr);
1149633e6d57Sdrh     sqlite3DbFree(db, pItem->zName);
1150b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1151a76b5dfcSdrh   }
1152633e6d57Sdrh   sqlite3DbFree(db, pList->a);
1153633e6d57Sdrh   sqlite3DbFree(db, pList);
1154a76b5dfcSdrh }
1155a76b5dfcSdrh 
1156a76b5dfcSdrh /*
11577d10d5a6Sdrh ** These routines are Walker callbacks.  Walker.u.pi is a pointer
11587d10d5a6Sdrh ** to an integer.  These routines are checking an expression to see
11597d10d5a6Sdrh ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
11607d10d5a6Sdrh ** not constant.
116173b211abSdrh **
11627d10d5a6Sdrh ** These callback routines are used to implement the following:
1163626a879aSdrh **
11647d10d5a6Sdrh **     sqlite3ExprIsConstant()
11657d10d5a6Sdrh **     sqlite3ExprIsConstantNotJoin()
11667d10d5a6Sdrh **     sqlite3ExprIsConstantOrFunction()
116787abf5c0Sdrh **
1168626a879aSdrh */
11697d10d5a6Sdrh static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1170626a879aSdrh 
11717d10d5a6Sdrh   /* If pWalker->u.i is 3 then any term of the expression that comes from
11720a168377Sdrh   ** the ON or USING clauses of a join disqualifies the expression
11730a168377Sdrh   ** from being considered constant. */
11747d10d5a6Sdrh   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
11757d10d5a6Sdrh     pWalker->u.i = 0;
11767d10d5a6Sdrh     return WRC_Abort;
11770a168377Sdrh   }
11780a168377Sdrh 
1179626a879aSdrh   switch( pExpr->op ){
1180eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
11817d10d5a6Sdrh     ** and pWalker->u.i==2 */
1182eb55bd2fSdrh     case TK_FUNCTION:
11837d10d5a6Sdrh       if( pWalker->u.i==2 ) return 0;
1184eb55bd2fSdrh       /* Fall through */
1185626a879aSdrh     case TK_ID:
1186626a879aSdrh     case TK_COLUMN:
1187626a879aSdrh     case TK_AGG_FUNCTION:
118813449892Sdrh     case TK_AGG_COLUMN:
1189c5499befSdrh       testcase( pExpr->op==TK_ID );
1190c5499befSdrh       testcase( pExpr->op==TK_COLUMN );
1191c5499befSdrh       testcase( pExpr->op==TK_AGG_FUNCTION );
1192c5499befSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
11937d10d5a6Sdrh       pWalker->u.i = 0;
11947d10d5a6Sdrh       return WRC_Abort;
1195626a879aSdrh     default:
1196b74b1017Sdrh       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1197b74b1017Sdrh       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
11987d10d5a6Sdrh       return WRC_Continue;
1199626a879aSdrh   }
1200626a879aSdrh }
120162c14b34Sdanielk1977 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
120262c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
12037d10d5a6Sdrh   pWalker->u.i = 0;
12047d10d5a6Sdrh   return WRC_Abort;
12057d10d5a6Sdrh }
12067d10d5a6Sdrh static int exprIsConst(Expr *p, int initFlag){
12077d10d5a6Sdrh   Walker w;
12087d10d5a6Sdrh   w.u.i = initFlag;
12097d10d5a6Sdrh   w.xExprCallback = exprNodeIsConstant;
12107d10d5a6Sdrh   w.xSelectCallback = selectNodeIsConstant;
12117d10d5a6Sdrh   sqlite3WalkExpr(&w, p);
12127d10d5a6Sdrh   return w.u.i;
12137d10d5a6Sdrh }
1214626a879aSdrh 
1215626a879aSdrh /*
1216fef5208cSdrh ** Walk an expression tree.  Return 1 if the expression is constant
1217eb55bd2fSdrh ** and 0 if it involves variables or function calls.
12182398937bSdrh **
12192398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
12202398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
12212398937bSdrh ** a constant.
1222fef5208cSdrh */
12234adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
12247d10d5a6Sdrh   return exprIsConst(p, 1);
1225fef5208cSdrh }
1226fef5208cSdrh 
1227fef5208cSdrh /*
1228eb55bd2fSdrh ** Walk an expression tree.  Return 1 if the expression is constant
12290a168377Sdrh ** that does no originate from the ON or USING clauses of a join.
12300a168377Sdrh ** Return 0 if it involves variables or function calls or terms from
12310a168377Sdrh ** an ON or USING clause.
12320a168377Sdrh */
12330a168377Sdrh int sqlite3ExprIsConstantNotJoin(Expr *p){
12347d10d5a6Sdrh   return exprIsConst(p, 3);
12350a168377Sdrh }
12360a168377Sdrh 
12370a168377Sdrh /*
12380a168377Sdrh ** Walk an expression tree.  Return 1 if the expression is constant
1239eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
1240eb55bd2fSdrh ** are any variables.
1241eb55bd2fSdrh **
1242eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
1243eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
1244eb55bd2fSdrh ** a constant.
1245eb55bd2fSdrh */
1246eb55bd2fSdrh int sqlite3ExprIsConstantOrFunction(Expr *p){
12477d10d5a6Sdrh   return exprIsConst(p, 2);
1248eb55bd2fSdrh }
1249eb55bd2fSdrh 
1250eb55bd2fSdrh /*
125173b211abSdrh ** If the expression p codes a constant integer that is small enough
1252202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
1253202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
1254202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1255e4de1febSdrh */
12564adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
125792b01d53Sdrh   int rc = 0;
1258cd92e84dSdrh 
1259cd92e84dSdrh   /* If an expression is an integer literal that fits in a signed 32-bit
1260cd92e84dSdrh   ** integer, then the EP_IntValue flag will have already been set */
1261cd92e84dSdrh   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1262cd92e84dSdrh            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1263cd92e84dSdrh 
126492b01d53Sdrh   if( p->flags & EP_IntValue ){
126533e619fcSdrh     *pValue = p->u.iValue;
1266e4de1febSdrh     return 1;
1267e4de1febSdrh   }
126892b01d53Sdrh   switch( p->op ){
12694b59ab5eSdrh     case TK_UPLUS: {
127092b01d53Sdrh       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1271f6e369a1Sdrh       break;
12724b59ab5eSdrh     }
1273e4de1febSdrh     case TK_UMINUS: {
1274e4de1febSdrh       int v;
12754adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1276e4de1febSdrh         *pValue = -v;
127792b01d53Sdrh         rc = 1;
1278e4de1febSdrh       }
1279e4de1febSdrh       break;
1280e4de1febSdrh     }
1281e4de1febSdrh     default: break;
1282e4de1febSdrh   }
128392b01d53Sdrh   return rc;
1284e4de1febSdrh }
1285e4de1febSdrh 
1286e4de1febSdrh /*
1287039fc32eSdrh ** Return FALSE if there is no chance that the expression can be NULL.
1288039fc32eSdrh **
1289039fc32eSdrh ** If the expression might be NULL or if the expression is too complex
1290039fc32eSdrh ** to tell return TRUE.
1291039fc32eSdrh **
1292039fc32eSdrh ** This routine is used as an optimization, to skip OP_IsNull opcodes
1293039fc32eSdrh ** when we know that a value cannot be NULL.  Hence, a false positive
1294039fc32eSdrh ** (returning TRUE when in fact the expression can never be NULL) might
1295039fc32eSdrh ** be a small performance hit but is otherwise harmless.  On the other
1296039fc32eSdrh ** hand, a false negative (returning FALSE when the result could be NULL)
1297039fc32eSdrh ** will likely result in an incorrect answer.  So when in doubt, return
1298039fc32eSdrh ** TRUE.
1299039fc32eSdrh */
1300039fc32eSdrh int sqlite3ExprCanBeNull(const Expr *p){
1301039fc32eSdrh   u8 op;
1302cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1303039fc32eSdrh   op = p->op;
1304039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
1305039fc32eSdrh   switch( op ){
1306039fc32eSdrh     case TK_INTEGER:
1307039fc32eSdrh     case TK_STRING:
1308039fc32eSdrh     case TK_FLOAT:
1309039fc32eSdrh     case TK_BLOB:
1310039fc32eSdrh       return 0;
1311039fc32eSdrh     default:
1312039fc32eSdrh       return 1;
1313039fc32eSdrh   }
1314039fc32eSdrh }
1315039fc32eSdrh 
1316039fc32eSdrh /*
13172f2855b6Sdrh ** Generate an OP_IsNull instruction that tests register iReg and jumps
13182f2855b6Sdrh ** to location iDest if the value in iReg is NULL.  The value in iReg
13192f2855b6Sdrh ** was computed by pExpr.  If we can look at pExpr at compile-time and
13202f2855b6Sdrh ** determine that it can never generate a NULL, then the OP_IsNull operation
13212f2855b6Sdrh ** can be omitted.
13222f2855b6Sdrh */
13232f2855b6Sdrh void sqlite3ExprCodeIsNullJump(
13242f2855b6Sdrh   Vdbe *v,            /* The VDBE under construction */
13252f2855b6Sdrh   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
13262f2855b6Sdrh   int iReg,           /* Test the value in this register for NULL */
13272f2855b6Sdrh   int iDest           /* Jump here if the value is null */
13282f2855b6Sdrh ){
13292f2855b6Sdrh   if( sqlite3ExprCanBeNull(pExpr) ){
13302f2855b6Sdrh     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
13312f2855b6Sdrh   }
13322f2855b6Sdrh }
13332f2855b6Sdrh 
13342f2855b6Sdrh /*
1335039fc32eSdrh ** Return TRUE if the given expression is a constant which would be
1336039fc32eSdrh ** unchanged by OP_Affinity with the affinity given in the second
1337039fc32eSdrh ** argument.
1338039fc32eSdrh **
1339039fc32eSdrh ** This routine is used to determine if the OP_Affinity operation
1340039fc32eSdrh ** can be omitted.  When in doubt return FALSE.  A false negative
1341039fc32eSdrh ** is harmless.  A false positive, however, can result in the wrong
1342039fc32eSdrh ** answer.
1343039fc32eSdrh */
1344039fc32eSdrh int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1345039fc32eSdrh   u8 op;
1346039fc32eSdrh   if( aff==SQLITE_AFF_NONE ) return 1;
1347cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1348039fc32eSdrh   op = p->op;
1349039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
1350039fc32eSdrh   switch( op ){
1351039fc32eSdrh     case TK_INTEGER: {
1352039fc32eSdrh       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1353039fc32eSdrh     }
1354039fc32eSdrh     case TK_FLOAT: {
1355039fc32eSdrh       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1356039fc32eSdrh     }
1357039fc32eSdrh     case TK_STRING: {
1358039fc32eSdrh       return aff==SQLITE_AFF_TEXT;
1359039fc32eSdrh     }
1360039fc32eSdrh     case TK_BLOB: {
1361039fc32eSdrh       return 1;
1362039fc32eSdrh     }
13632f2855b6Sdrh     case TK_COLUMN: {
136488376ca7Sdrh       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
136588376ca7Sdrh       return p->iColumn<0
13662f2855b6Sdrh           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
13672f2855b6Sdrh     }
1368039fc32eSdrh     default: {
1369039fc32eSdrh       return 0;
1370039fc32eSdrh     }
1371039fc32eSdrh   }
1372039fc32eSdrh }
1373039fc32eSdrh 
1374039fc32eSdrh /*
1375c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
1376c4a3c779Sdrh */
13774adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
13784adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
13794adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
13804adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1381c4a3c779Sdrh   return 0;
1382c4a3c779Sdrh }
1383c4a3c779Sdrh 
13849a96b668Sdanielk1977 /*
1385b74b1017Sdrh ** Return true if we are able to the IN operator optimization on a
1386b74b1017Sdrh ** query of the form
1387b287f4b6Sdrh **
1388b74b1017Sdrh **       x IN (SELECT ...)
1389b287f4b6Sdrh **
1390b74b1017Sdrh ** Where the SELECT... clause is as specified by the parameter to this
1391b74b1017Sdrh ** routine.
1392b74b1017Sdrh **
1393b74b1017Sdrh ** The Select object passed in has already been preprocessed and no
1394b74b1017Sdrh ** errors have been found.
1395b287f4b6Sdrh */
1396b287f4b6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1397b287f4b6Sdrh static int isCandidateForInOpt(Select *p){
1398b287f4b6Sdrh   SrcList *pSrc;
1399b287f4b6Sdrh   ExprList *pEList;
1400b287f4b6Sdrh   Table *pTab;
1401b287f4b6Sdrh   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
1402b287f4b6Sdrh   if( p->pPrior ) return 0;              /* Not a compound SELECT */
14037d10d5a6Sdrh   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1404b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1405b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
14067d10d5a6Sdrh     return 0; /* No DISTINCT keyword and no aggregate functions */
14077d10d5a6Sdrh   }
1408b74b1017Sdrh   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
1409b287f4b6Sdrh   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
1410b74b1017Sdrh   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
1411b287f4b6Sdrh   if( p->pWhere ) return 0;              /* Has no WHERE clause */
1412b287f4b6Sdrh   pSrc = p->pSrc;
1413d1fa7bcaSdrh   assert( pSrc!=0 );
1414d1fa7bcaSdrh   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
1415b74b1017Sdrh   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
1416b287f4b6Sdrh   pTab = pSrc->a[0].pTab;
1417b74b1017Sdrh   if( NEVER(pTab==0) ) return 0;
1418b74b1017Sdrh   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
1419b287f4b6Sdrh   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
1420b287f4b6Sdrh   pEList = p->pEList;
1421b287f4b6Sdrh   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
1422b287f4b6Sdrh   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1423b287f4b6Sdrh   return 1;
1424b287f4b6Sdrh }
1425b287f4b6Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1426b287f4b6Sdrh 
1427b287f4b6Sdrh /*
14281d8cb21fSdan ** Code an OP_Once instruction and allocate space for its flag. Return the
14291d8cb21fSdan ** address of the new instruction.
14301d8cb21fSdan */
14311d8cb21fSdan int sqlite3CodeOnce(Parse *pParse){
14321d8cb21fSdan   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
14331d8cb21fSdan   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
14341d8cb21fSdan }
14351d8cb21fSdan 
14361d8cb21fSdan /*
14379a96b668Sdanielk1977 ** This function is used by the implementation of the IN (...) operator.
1438d4305ca6Sdrh ** The pX parameter is the expression on the RHS of the IN operator, which
1439d4305ca6Sdrh ** might be either a list of expressions or a subquery.
14409a96b668Sdanielk1977 **
1441d4305ca6Sdrh ** The job of this routine is to find or create a b-tree object that can
1442d4305ca6Sdrh ** be used either to test for membership in the RHS set or to iterate through
1443d4305ca6Sdrh ** all members of the RHS set, skipping duplicates.
1444d4305ca6Sdrh **
1445d4305ca6Sdrh ** A cursor is opened on the b-tree object that the RHS of the IN operator
1446d4305ca6Sdrh ** and pX->iTable is set to the index of that cursor.
1447d4305ca6Sdrh **
1448b74b1017Sdrh ** The returned value of this function indicates the b-tree type, as follows:
14499a96b668Sdanielk1977 **
14509a96b668Sdanielk1977 **   IN_INDEX_ROWID - The cursor was opened on a database table.
14512d401ab8Sdrh **   IN_INDEX_INDEX - The cursor was opened on a database index.
14529a96b668Sdanielk1977 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
14539a96b668Sdanielk1977 **                    populated epheremal table.
14549a96b668Sdanielk1977 **
1455d4305ca6Sdrh ** An existing b-tree might be used if the RHS expression pX is a simple
1456d4305ca6Sdrh ** subquery such as:
14579a96b668Sdanielk1977 **
14589a96b668Sdanielk1977 **     SELECT <column> FROM <table>
14599a96b668Sdanielk1977 **
1460d4305ca6Sdrh ** If the RHS of the IN operator is a list or a more complex subquery, then
1461d4305ca6Sdrh ** an ephemeral table might need to be generated from the RHS and then
1462d4305ca6Sdrh ** pX->iTable made to point to the ephermeral table instead of an
1463d4305ca6Sdrh ** existing table.
1464d4305ca6Sdrh **
1465b74b1017Sdrh ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
14669a96b668Sdanielk1977 ** through the set members, skipping any duplicates. In this case an
14679a96b668Sdanielk1977 ** epheremal table must be used unless the selected <column> is guaranteed
14689a96b668Sdanielk1977 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
1469b74b1017Sdrh ** has a UNIQUE constraint or UNIQUE index.
14700cdc022eSdanielk1977 **
1471b74b1017Sdrh ** If the prNotFound parameter is not 0, then the b-tree will be used
14720cdc022eSdanielk1977 ** for fast set membership tests. In this case an epheremal table must
14730cdc022eSdanielk1977 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
14740cdc022eSdanielk1977 ** be found with <column> as its left-most column.
14750cdc022eSdanielk1977 **
1476b74b1017Sdrh ** When the b-tree is being used for membership tests, the calling function
14770cdc022eSdanielk1977 ** needs to know whether or not the structure contains an SQL NULL
14780cdc022eSdanielk1977 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
1479e3365e6cSdrh ** If there is any chance that the (...) might contain a NULL value at
14800cdc022eSdanielk1977 ** runtime, then a register is allocated and the register number written
1481e3365e6cSdrh ** to *prNotFound. If there is no chance that the (...) contains a
14820cdc022eSdanielk1977 ** NULL value, then *prNotFound is left unchanged.
14830cdc022eSdanielk1977 **
14840cdc022eSdanielk1977 ** If a register is allocated and its location stored in *prNotFound, then
1485e3365e6cSdrh ** its initial value is NULL.  If the (...) does not remain constant
1486e3365e6cSdrh ** for the duration of the query (i.e. the SELECT within the (...)
1487b74b1017Sdrh ** is a correlated subquery) then the value of the allocated register is
1488e3365e6cSdrh ** reset to NULL each time the subquery is rerun. This allows the
1489b74b1017Sdrh ** caller to use vdbe code equivalent to the following:
14900cdc022eSdanielk1977 **
14910cdc022eSdanielk1977 **   if( register==NULL ){
14920cdc022eSdanielk1977 **     has_null = <test if data structure contains null>
14930cdc022eSdanielk1977 **     register = 1
14940cdc022eSdanielk1977 **   }
14950cdc022eSdanielk1977 **
14960cdc022eSdanielk1977 ** in order to avoid running the <test if data structure contains null>
14970cdc022eSdanielk1977 ** test more often than is necessary.
14989a96b668Sdanielk1977 */
1499284f4acaSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
15000cdc022eSdanielk1977 int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
1501b74b1017Sdrh   Select *p;                            /* SELECT to the right of IN operator */
1502b74b1017Sdrh   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
1503b74b1017Sdrh   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
1504b74b1017Sdrh   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
1505b8475df8Sdrh   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
15069a96b668Sdanielk1977 
15071450bc6eSdrh   assert( pX->op==TK_IN );
15081450bc6eSdrh 
1509b74b1017Sdrh   /* Check to see if an existing table or index can be used to
1510b74b1017Sdrh   ** satisfy the query.  This is preferable to generating a new
1511b74b1017Sdrh   ** ephemeral table.
15129a96b668Sdanielk1977   */
15136ab3a2ecSdanielk1977   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
1514fd773cf9Sdrh   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
1515e1fb65a0Sdanielk1977     sqlite3 *db = pParse->db;              /* Database connection */
1516b07028f7Sdrh     Table *pTab;                           /* Table <table>. */
1517b07028f7Sdrh     Expr *pExpr;                           /* Expression <column> */
1518b07028f7Sdrh     int iCol;                              /* Index of column <column> */
1519e1fb65a0Sdanielk1977     int iDb;                               /* Database idx for pTab */
1520e1fb65a0Sdanielk1977 
1521b07028f7Sdrh     assert( p );                        /* Because of isCandidateForInOpt(p) */
1522b07028f7Sdrh     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
1523b07028f7Sdrh     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
1524b07028f7Sdrh     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
1525b07028f7Sdrh     pTab = p->pSrc->a[0].pTab;
1526b07028f7Sdrh     pExpr = p->pEList->a[0].pExpr;
1527b07028f7Sdrh     iCol = pExpr->iColumn;
1528b07028f7Sdrh 
1529e1fb65a0Sdanielk1977     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
1530e1fb65a0Sdanielk1977     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1531e1fb65a0Sdanielk1977     sqlite3CodeVerifySchema(pParse, iDb);
1532e1fb65a0Sdanielk1977     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
15339a96b668Sdanielk1977 
15349a96b668Sdanielk1977     /* This function is only called from two places. In both cases the vdbe
15359a96b668Sdanielk1977     ** has already been allocated. So assume sqlite3GetVdbe() is always
15369a96b668Sdanielk1977     ** successful here.
15379a96b668Sdanielk1977     */
15389a96b668Sdanielk1977     assert(v);
15399a96b668Sdanielk1977     if( iCol<0 ){
15409a96b668Sdanielk1977       int iAddr;
15419a96b668Sdanielk1977 
15421d8cb21fSdan       iAddr = sqlite3CodeOnce(pParse);
15439a96b668Sdanielk1977 
15449a96b668Sdanielk1977       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
15459a96b668Sdanielk1977       eType = IN_INDEX_ROWID;
15469a96b668Sdanielk1977 
15479a96b668Sdanielk1977       sqlite3VdbeJumpHere(v, iAddr);
15489a96b668Sdanielk1977     }else{
1549e1fb65a0Sdanielk1977       Index *pIdx;                         /* Iterator variable */
1550e1fb65a0Sdanielk1977 
15519a96b668Sdanielk1977       /* The collation sequence used by the comparison. If an index is to
15529a96b668Sdanielk1977       ** be used in place of a temp-table, it must be ordered according
1553e1fb65a0Sdanielk1977       ** to this collation sequence.  */
15549a96b668Sdanielk1977       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
15559a96b668Sdanielk1977 
15569a96b668Sdanielk1977       /* Check that the affinity that will be used to perform the
15579a96b668Sdanielk1977       ** comparison is the same as the affinity of the column. If
15589a96b668Sdanielk1977       ** it is not, it is not possible to use any index.
15599a96b668Sdanielk1977       */
1560dbaee5e3Sdrh       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
15619a96b668Sdanielk1977 
15629a96b668Sdanielk1977       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
15639a96b668Sdanielk1977         if( (pIdx->aiColumn[0]==iCol)
1564b74b1017Sdrh          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
15659a96b668Sdanielk1977          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
15669a96b668Sdanielk1977         ){
15679a96b668Sdanielk1977           int iAddr;
15689a96b668Sdanielk1977           char *pKey;
15699a96b668Sdanielk1977 
15709a96b668Sdanielk1977           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
15711d8cb21fSdan           iAddr = sqlite3CodeOnce(pParse);
15729a96b668Sdanielk1977 
1573207872a4Sdanielk1977           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
157466a5167bSdrh                                pKey,P4_KEYINFO_HANDOFF);
1575207872a4Sdanielk1977           VdbeComment((v, "%s", pIdx->zName));
15769a96b668Sdanielk1977           eType = IN_INDEX_INDEX;
15779a96b668Sdanielk1977 
15789a96b668Sdanielk1977           sqlite3VdbeJumpHere(v, iAddr);
15790cdc022eSdanielk1977           if( prNotFound && !pTab->aCol[iCol].notNull ){
15800cdc022eSdanielk1977             *prNotFound = ++pParse->nMem;
1581b8475df8Sdrh             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
15820cdc022eSdanielk1977           }
15839a96b668Sdanielk1977         }
15849a96b668Sdanielk1977       }
15859a96b668Sdanielk1977     }
15869a96b668Sdanielk1977   }
15879a96b668Sdanielk1977 
15889a96b668Sdanielk1977   if( eType==0 ){
15891450bc6eSdrh     /* Could not found an existing table or index to use as the RHS b-tree.
1590b74b1017Sdrh     ** We will have to generate an ephemeral table to do the job.
1591b74b1017Sdrh     */
1592cf4d38aaSdrh     double savedNQueryLoop = pParse->nQueryLoop;
15930cdc022eSdanielk1977     int rMayHaveNull = 0;
159441a05b7bSdanielk1977     eType = IN_INDEX_EPH;
15950cdc022eSdanielk1977     if( prNotFound ){
15960cdc022eSdanielk1977       *prNotFound = rMayHaveNull = ++pParse->nMem;
1597b8475df8Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
1598cf4d38aaSdrh     }else{
1599cf4d38aaSdrh       testcase( pParse->nQueryLoop>(double)1 );
1600cf4d38aaSdrh       pParse->nQueryLoop = (double)1;
1601cf4d38aaSdrh       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
160241a05b7bSdanielk1977         eType = IN_INDEX_ROWID;
16030cdc022eSdanielk1977       }
1604cf4d38aaSdrh     }
160541a05b7bSdanielk1977     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
1606cf4d38aaSdrh     pParse->nQueryLoop = savedNQueryLoop;
16079a96b668Sdanielk1977   }else{
16089a96b668Sdanielk1977     pX->iTable = iTab;
16099a96b668Sdanielk1977   }
16109a96b668Sdanielk1977   return eType;
16119a96b668Sdanielk1977 }
1612284f4acaSdanielk1977 #endif
1613626a879aSdrh 
1614626a879aSdrh /*
1615d4187c71Sdrh ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
1616d4187c71Sdrh ** or IN operators.  Examples:
1617626a879aSdrh **
16189cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
16199cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
16209cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
16219cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1622fef5208cSdrh **
16239cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
16249cbe6352Sdrh ** operator or subquery.
162541a05b7bSdanielk1977 **
162641a05b7bSdanielk1977 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
162741a05b7bSdanielk1977 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
162841a05b7bSdanielk1977 ** to some integer key column of a table B-Tree. In this case, use an
162941a05b7bSdanielk1977 ** intkey B-Tree to store the set of IN(...) values instead of the usual
163041a05b7bSdanielk1977 ** (slower) variable length keys B-Tree.
1631fd773cf9Sdrh **
1632fd773cf9Sdrh ** If rMayHaveNull is non-zero, that means that the operation is an IN
1633fd773cf9Sdrh ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
1634fd773cf9Sdrh ** Furthermore, the IN is in a WHERE clause and that we really want
1635fd773cf9Sdrh ** to iterate over the RHS of the IN operator in order to quickly locate
1636fd773cf9Sdrh ** all corresponding LHS elements.  All this routine does is initialize
1637fd773cf9Sdrh ** the register given by rMayHaveNull to NULL.  Calling routines will take
1638fd773cf9Sdrh ** care of changing this register value to non-NULL if the RHS is NULL-free.
1639fd773cf9Sdrh **
1640fd773cf9Sdrh ** If rMayHaveNull is zero, that means that the subquery is being used
1641fd773cf9Sdrh ** for membership testing only.  There is no need to initialize any
1642fd773cf9Sdrh ** registers to indicate the presense or absence of NULLs on the RHS.
16431450bc6eSdrh **
16441450bc6eSdrh ** For a SELECT or EXISTS operator, return the register that holds the
16451450bc6eSdrh ** result.  For IN operators or if an error occurs, the return value is 0.
1646cce7d176Sdrh */
164751522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
16481450bc6eSdrh int sqlite3CodeSubselect(
1649fd773cf9Sdrh   Parse *pParse,          /* Parsing context */
1650fd773cf9Sdrh   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
1651fd773cf9Sdrh   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
1652fd773cf9Sdrh   int isRowid             /* If true, LHS of IN operator is a rowid */
165341a05b7bSdanielk1977 ){
1654dfd2d9f6Sdrh   int testAddr = -1;                      /* One-time test address */
16551450bc6eSdrh   int rReg = 0;                           /* Register storing resulting */
1656b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
16571450bc6eSdrh   if( NEVER(v==0) ) return 0;
1658ceea3321Sdrh   sqlite3ExprCachePush(pParse);
1659fc976065Sdanielk1977 
166057dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
166157dbd7b3Sdrh   ** if any of the following is true:
166257dbd7b3Sdrh   **
166357dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
166457dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
166557dbd7b3Sdrh   **    *  We are inside a trigger
166657dbd7b3Sdrh   **
166757dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
166857dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1669b3bce662Sdanielk1977   */
16701d8cb21fSdan   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
16711d8cb21fSdan     testAddr = sqlite3CodeOnce(pParse);
1672b3bce662Sdanielk1977   }
1673b3bce662Sdanielk1977 
16744a07e3dbSdan #ifndef SQLITE_OMIT_EXPLAIN
16754a07e3dbSdan   if( pParse->explain==2 ){
16764a07e3dbSdan     char *zMsg = sqlite3MPrintf(
1677dfd2d9f6Sdrh         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
16784a07e3dbSdan         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
16794a07e3dbSdan     );
16804a07e3dbSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
16814a07e3dbSdan   }
16824a07e3dbSdan #endif
16834a07e3dbSdan 
1684cce7d176Sdrh   switch( pExpr->op ){
1685fef5208cSdrh     case TK_IN: {
1686d4187c71Sdrh       char affinity;              /* Affinity of the LHS of the IN */
1687d4187c71Sdrh       KeyInfo keyInfo;            /* Keyinfo for the generated table */
1688e1a022e4Sdrh       static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
1689b9bb7c18Sdrh       int addr;                   /* Address of OP_OpenEphemeral instruction */
1690d4187c71Sdrh       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
1691d3d39e93Sdrh 
16920cdc022eSdanielk1977       if( rMayHaveNull ){
16930cdc022eSdanielk1977         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
16940cdc022eSdanielk1977       }
16950cdc022eSdanielk1977 
169641a05b7bSdanielk1977       affinity = sqlite3ExprAffinity(pLeft);
1697e014a838Sdanielk1977 
1698e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
16998cff69dfSdrh       ** expression it is handled the same way.  An ephemeral table is
1700e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1701e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1702fef5208cSdrh       **
1703e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1704e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1705e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1706e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1707e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1708e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1709e014a838Sdanielk1977       ** is used.
1710fef5208cSdrh       */
1711832508b7Sdrh       pExpr->iTable = pParse->nTab++;
171241a05b7bSdanielk1977       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
1713d4187c71Sdrh       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
1714d3d39e93Sdrh       memset(&keyInfo, 0, sizeof(keyInfo));
1715d3d39e93Sdrh       keyInfo.nField = 1;
1716e1a022e4Sdrh       keyInfo.aSortOrder = &sortOrder;
1717e014a838Sdanielk1977 
17186ab3a2ecSdanielk1977       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1719e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1720e014a838Sdanielk1977         **
1721e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1722e014a838Sdanielk1977         ** table allocated and opened above.
1723e014a838Sdanielk1977         */
17241013c932Sdrh         SelectDest dest;
1725be5c89acSdrh         ExprList *pEList;
17261013c932Sdrh 
172741a05b7bSdanielk1977         assert( !isRowid );
17281013c932Sdrh         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
17292b596da8Sdrh         dest.affSdst = (u8)affinity;
1730e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
173148b5b041Sdrh         pExpr->x.pSelect->iLimit = 0;
17326ab3a2ecSdanielk1977         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
17331450bc6eSdrh           return 0;
173494ccde58Sdrh         }
17356ab3a2ecSdanielk1977         pEList = pExpr->x.pSelect->pEList;
1736fd773cf9Sdrh         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
1737bcbb04e5Sdanielk1977           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1738be5c89acSdrh               pEList->a[0].pExpr);
17390202b29eSdanielk1977         }
1740a7d2db17Sdrh       }else if( ALWAYS(pExpr->x.pList!=0) ){
1741fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1742fef5208cSdrh         **
1743e014a838Sdanielk1977         ** For each expression, build an index key from the evaluation and
1744e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1745e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1746e014a838Sdanielk1977         ** a column, use numeric affinity.
1747fef5208cSdrh         */
1748e014a838Sdanielk1977         int i;
17496ab3a2ecSdanielk1977         ExprList *pList = pExpr->x.pList;
175057dbd7b3Sdrh         struct ExprList_item *pItem;
1751ecc31805Sdrh         int r1, r2, r3;
175257dbd7b3Sdrh 
1753e014a838Sdanielk1977         if( !affinity ){
17548159a35fSdrh           affinity = SQLITE_AFF_NONE;
1755e014a838Sdanielk1977         }
17567d10d5a6Sdrh         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
1757e1a022e4Sdrh         keyInfo.aSortOrder = &sortOrder;
1758e014a838Sdanielk1977 
1759e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
17602d401ab8Sdrh         r1 = sqlite3GetTempReg(pParse);
17612d401ab8Sdrh         r2 = sqlite3GetTempReg(pParse);
17624e7f36a2Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
176357dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
176457dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1765e05c929bSdrh           int iValToIns;
1766e014a838Sdanielk1977 
176757dbd7b3Sdrh           /* If the expression is not constant then we will need to
176857dbd7b3Sdrh           ** disable the test that was generated above that makes sure
176957dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
177057dbd7b3Sdrh           ** expression we need to rerun this code each time.
177157dbd7b3Sdrh           */
1772dfd2d9f6Sdrh           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
177348f2d3b1Sdrh             sqlite3VdbeChangeToNoop(v, testAddr);
1774dfd2d9f6Sdrh             testAddr = -1;
17754794b980Sdrh           }
1776e014a838Sdanielk1977 
1777e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
1778e05c929bSdrh           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
1779e05c929bSdrh             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
1780e05c929bSdrh           }else{
1781ecc31805Sdrh             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
178241a05b7bSdanielk1977             if( isRowid ){
1783e05c929bSdrh               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
1784e05c929bSdrh                                 sqlite3VdbeCurrentAddr(v)+2);
178541a05b7bSdanielk1977               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
178641a05b7bSdanielk1977             }else{
1787ecc31805Sdrh               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
17883c31fc23Sdrh               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
17892d401ab8Sdrh               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
1790fef5208cSdrh             }
179141a05b7bSdanielk1977           }
1792e05c929bSdrh         }
17932d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r1);
17942d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r2);
1795fef5208cSdrh       }
179641a05b7bSdanielk1977       if( !isRowid ){
179766a5167bSdrh         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
179841a05b7bSdanielk1977       }
1799b3bce662Sdanielk1977       break;
1800fef5208cSdrh     }
1801fef5208cSdrh 
180251522cd3Sdrh     case TK_EXISTS:
1803fd773cf9Sdrh     case TK_SELECT:
1804fd773cf9Sdrh     default: {
1805fd773cf9Sdrh       /* If this has to be a scalar SELECT.  Generate code to put the
1806fef5208cSdrh       ** value of this select in a memory cell and record the number
1807fd773cf9Sdrh       ** of the memory cell in iColumn.  If this is an EXISTS, write
1808fd773cf9Sdrh       ** an integer 0 (not exists) or 1 (exists) into a memory cell
1809fd773cf9Sdrh       ** and record that memory cell in iColumn.
1810fef5208cSdrh       */
1811fd773cf9Sdrh       Select *pSel;                         /* SELECT statement to encode */
1812fd773cf9Sdrh       SelectDest dest;                      /* How to deal with SELECt result */
18131398ad36Sdrh 
1814cf697396Sshane       testcase( pExpr->op==TK_EXISTS );
1815cf697396Sshane       testcase( pExpr->op==TK_SELECT );
1816cf697396Sshane       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
1817cf697396Sshane 
18186ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
18196ab3a2ecSdanielk1977       pSel = pExpr->x.pSelect;
18201013c932Sdrh       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
182151522cd3Sdrh       if( pExpr->op==TK_SELECT ){
18226c8c8ce0Sdanielk1977         dest.eDest = SRT_Mem;
18232b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
1824d4e70ebdSdrh         VdbeComment((v, "Init subquery result"));
182551522cd3Sdrh       }else{
18266c8c8ce0Sdanielk1977         dest.eDest = SRT_Exists;
18272b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
1828d4e70ebdSdrh         VdbeComment((v, "Init EXISTS result"));
182951522cd3Sdrh       }
1830633e6d57Sdrh       sqlite3ExprDelete(pParse->db, pSel->pLimit);
1831094430ebSdrh       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
1832094430ebSdrh                                   &sqlite3IntTokens[1]);
183348b5b041Sdrh       pSel->iLimit = 0;
18347d10d5a6Sdrh       if( sqlite3Select(pParse, pSel, &dest) ){
18351450bc6eSdrh         return 0;
183694ccde58Sdrh       }
18372b596da8Sdrh       rReg = dest.iSDParm;
183833e619fcSdrh       ExprSetIrreducible(pExpr);
1839b3bce662Sdanielk1977       break;
184019a775c2Sdrh     }
1841cce7d176Sdrh   }
1842b3bce662Sdanielk1977 
1843dfd2d9f6Sdrh   if( testAddr>=0 ){
184448f2d3b1Sdrh     sqlite3VdbeJumpHere(v, testAddr);
1845b3bce662Sdanielk1977   }
1846ceea3321Sdrh   sqlite3ExprCachePop(pParse, 1);
1847fc976065Sdanielk1977 
18481450bc6eSdrh   return rReg;
1849cce7d176Sdrh }
185051522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1851cce7d176Sdrh 
1852e3365e6cSdrh #ifndef SQLITE_OMIT_SUBQUERY
1853e3365e6cSdrh /*
1854e3365e6cSdrh ** Generate code for an IN expression.
1855e3365e6cSdrh **
1856e3365e6cSdrh **      x IN (SELECT ...)
1857e3365e6cSdrh **      x IN (value, value, ...)
1858e3365e6cSdrh **
1859e3365e6cSdrh ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
1860e3365e6cSdrh ** is an array of zero or more values.  The expression is true if the LHS is
1861e3365e6cSdrh ** contained within the RHS.  The value of the expression is unknown (NULL)
1862e3365e6cSdrh ** if the LHS is NULL or if the LHS is not contained within the RHS and the
1863e3365e6cSdrh ** RHS contains one or more NULL values.
1864e3365e6cSdrh **
1865e3365e6cSdrh ** This routine generates code will jump to destIfFalse if the LHS is not
1866e3365e6cSdrh ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
1867e3365e6cSdrh ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
1868e3365e6cSdrh ** within the RHS then fall through.
1869e3365e6cSdrh */
1870e3365e6cSdrh static void sqlite3ExprCodeIN(
1871e3365e6cSdrh   Parse *pParse,        /* Parsing and code generating context */
1872e3365e6cSdrh   Expr *pExpr,          /* The IN expression */
1873e3365e6cSdrh   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
1874e3365e6cSdrh   int destIfNull        /* Jump here if the results are unknown due to NULLs */
1875e3365e6cSdrh ){
1876e3365e6cSdrh   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
1877e3365e6cSdrh   char affinity;        /* Comparison affinity to use */
1878e3365e6cSdrh   int eType;            /* Type of the RHS */
1879e3365e6cSdrh   int r1;               /* Temporary use register */
1880e3365e6cSdrh   Vdbe *v;              /* Statement under construction */
1881e3365e6cSdrh 
1882e3365e6cSdrh   /* Compute the RHS.   After this step, the table with cursor
1883e3365e6cSdrh   ** pExpr->iTable will contains the values that make up the RHS.
1884e3365e6cSdrh   */
1885e3365e6cSdrh   v = pParse->pVdbe;
1886e3365e6cSdrh   assert( v!=0 );       /* OOM detected prior to this routine */
1887e3365e6cSdrh   VdbeNoopComment((v, "begin IN expr"));
1888e3365e6cSdrh   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
1889e3365e6cSdrh 
1890e3365e6cSdrh   /* Figure out the affinity to use to create a key from the results
1891e3365e6cSdrh   ** of the expression. affinityStr stores a static string suitable for
1892e3365e6cSdrh   ** P4 of OP_MakeRecord.
1893e3365e6cSdrh   */
1894e3365e6cSdrh   affinity = comparisonAffinity(pExpr);
1895e3365e6cSdrh 
1896e3365e6cSdrh   /* Code the LHS, the <expr> from "<expr> IN (...)".
1897e3365e6cSdrh   */
1898e3365e6cSdrh   sqlite3ExprCachePush(pParse);
1899e3365e6cSdrh   r1 = sqlite3GetTempReg(pParse);
1900e3365e6cSdrh   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
1901e3365e6cSdrh 
1902094430ebSdrh   /* If the LHS is NULL, then the result is either false or NULL depending
1903094430ebSdrh   ** on whether the RHS is empty or not, respectively.
1904094430ebSdrh   */
1905094430ebSdrh   if( destIfNull==destIfFalse ){
1906094430ebSdrh     /* Shortcut for the common case where the false and NULL outcomes are
1907094430ebSdrh     ** the same. */
1908094430ebSdrh     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
1909094430ebSdrh   }else{
1910094430ebSdrh     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
1911094430ebSdrh     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
1912094430ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
1913094430ebSdrh     sqlite3VdbeJumpHere(v, addr1);
1914094430ebSdrh   }
1915e3365e6cSdrh 
1916e3365e6cSdrh   if( eType==IN_INDEX_ROWID ){
1917e3365e6cSdrh     /* In this case, the RHS is the ROWID of table b-tree
1918e3365e6cSdrh     */
1919e3365e6cSdrh     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
1920e3365e6cSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
1921e3365e6cSdrh   }else{
1922e3365e6cSdrh     /* In this case, the RHS is an index b-tree.
1923e3365e6cSdrh     */
19248cff69dfSdrh     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
1925e3365e6cSdrh 
1926e3365e6cSdrh     /* If the set membership test fails, then the result of the
1927e3365e6cSdrh     ** "x IN (...)" expression must be either 0 or NULL. If the set
1928e3365e6cSdrh     ** contains no NULL values, then the result is 0. If the set
1929e3365e6cSdrh     ** contains one or more NULL values, then the result of the
1930e3365e6cSdrh     ** expression is also NULL.
1931e3365e6cSdrh     */
1932e3365e6cSdrh     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
1933e3365e6cSdrh       /* This branch runs if it is known at compile time that the RHS
1934e3365e6cSdrh       ** cannot contain NULL values. This happens as the result
1935e3365e6cSdrh       ** of a "NOT NULL" constraint in the database schema.
1936e3365e6cSdrh       **
1937e3365e6cSdrh       ** Also run this branch if NULL is equivalent to FALSE
1938e3365e6cSdrh       ** for this particular IN operator.
1939e3365e6cSdrh       */
19408cff69dfSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
1941e3365e6cSdrh 
1942e3365e6cSdrh     }else{
1943e3365e6cSdrh       /* In this branch, the RHS of the IN might contain a NULL and
1944e3365e6cSdrh       ** the presence of a NULL on the RHS makes a difference in the
1945e3365e6cSdrh       ** outcome.
1946e3365e6cSdrh       */
1947e3365e6cSdrh       int j1, j2, j3;
1948e3365e6cSdrh 
1949e3365e6cSdrh       /* First check to see if the LHS is contained in the RHS.  If so,
1950e3365e6cSdrh       ** then the presence of NULLs in the RHS does not matter, so jump
1951e3365e6cSdrh       ** over all of the code that follows.
1952e3365e6cSdrh       */
19538cff69dfSdrh       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
1954e3365e6cSdrh 
1955e3365e6cSdrh       /* Here we begin generating code that runs if the LHS is not
1956e3365e6cSdrh       ** contained within the RHS.  Generate additional code that
1957e3365e6cSdrh       ** tests the RHS for NULLs.  If the RHS contains a NULL then
1958e3365e6cSdrh       ** jump to destIfNull.  If there are no NULLs in the RHS then
1959e3365e6cSdrh       ** jump to destIfFalse.
1960e3365e6cSdrh       */
1961e3365e6cSdrh       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
19628cff69dfSdrh       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
1963e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
1964e3365e6cSdrh       sqlite3VdbeJumpHere(v, j3);
1965e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
1966e3365e6cSdrh       sqlite3VdbeJumpHere(v, j2);
1967e3365e6cSdrh 
1968e3365e6cSdrh       /* Jump to the appropriate target depending on whether or not
1969e3365e6cSdrh       ** the RHS contains a NULL
1970e3365e6cSdrh       */
1971e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
1972e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
1973e3365e6cSdrh 
1974e3365e6cSdrh       /* The OP_Found at the top of this branch jumps here when true,
1975e3365e6cSdrh       ** causing the overall IN expression evaluation to fall through.
1976e3365e6cSdrh       */
1977e3365e6cSdrh       sqlite3VdbeJumpHere(v, j1);
1978e3365e6cSdrh     }
1979e3365e6cSdrh   }
1980e3365e6cSdrh   sqlite3ReleaseTempReg(pParse, r1);
1981e3365e6cSdrh   sqlite3ExprCachePop(pParse, 1);
1982e3365e6cSdrh   VdbeComment((v, "end IN expr"));
1983e3365e6cSdrh }
1984e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
1985e3365e6cSdrh 
1986cce7d176Sdrh /*
1987598f1340Sdrh ** Duplicate an 8-byte value
1988598f1340Sdrh */
1989598f1340Sdrh static char *dup8bytes(Vdbe *v, const char *in){
1990598f1340Sdrh   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
1991598f1340Sdrh   if( out ){
1992598f1340Sdrh     memcpy(out, in, 8);
1993598f1340Sdrh   }
1994598f1340Sdrh   return out;
1995598f1340Sdrh }
1996598f1340Sdrh 
199713573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
1998598f1340Sdrh /*
1999598f1340Sdrh ** Generate an instruction that will put the floating point
20009cbf3425Sdrh ** value described by z[0..n-1] into register iMem.
20010cf19ed8Sdrh **
20020cf19ed8Sdrh ** The z[] string will probably not be zero-terminated.  But the
20030cf19ed8Sdrh ** z[n] character is guaranteed to be something that does not look
20040cf19ed8Sdrh ** like the continuation of the number.
2005598f1340Sdrh */
2006b7916a78Sdrh static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
2007fd773cf9Sdrh   if( ALWAYS(z!=0) ){
2008598f1340Sdrh     double value;
2009598f1340Sdrh     char *zV;
20109339da1fSdrh     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
2011d0015161Sdrh     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2012598f1340Sdrh     if( negateFlag ) value = -value;
2013598f1340Sdrh     zV = dup8bytes(v, (char*)&value);
20149de221dfSdrh     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
2015598f1340Sdrh   }
2016598f1340Sdrh }
201713573c71Sdrh #endif
2018598f1340Sdrh 
2019598f1340Sdrh 
2020598f1340Sdrh /*
2021fec19aadSdrh ** Generate an instruction that will put the integer describe by
20229cbf3425Sdrh ** text z[0..n-1] into register iMem.
20230cf19ed8Sdrh **
20245f1d6b61Sshaneh ** Expr.u.zToken is always UTF8 and zero-terminated.
2025fec19aadSdrh */
202613573c71Sdrh static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
202713573c71Sdrh   Vdbe *v = pParse->pVdbe;
202892b01d53Sdrh   if( pExpr->flags & EP_IntValue ){
202933e619fcSdrh     int i = pExpr->u.iValue;
2030d50ffc41Sdrh     assert( i>=0 );
203192b01d53Sdrh     if( negFlag ) i = -i;
203292b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
2033fd773cf9Sdrh   }else{
20345f1d6b61Sshaneh     int c;
20355f1d6b61Sshaneh     i64 value;
2036fd773cf9Sdrh     const char *z = pExpr->u.zToken;
2037fd773cf9Sdrh     assert( z!=0 );
20385f1d6b61Sshaneh     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
20395f1d6b61Sshaneh     if( c==0 || (c==2 && negFlag) ){
2040598f1340Sdrh       char *zV;
2041158b9cb9Sdrh       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
2042598f1340Sdrh       zV = dup8bytes(v, (char*)&value);
20439de221dfSdrh       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
2044fec19aadSdrh     }else{
204513573c71Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
204613573c71Sdrh       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
204713573c71Sdrh #else
2048b7916a78Sdrh       codeReal(v, z, negFlag, iMem);
204913573c71Sdrh #endif
2050fec19aadSdrh     }
2051fec19aadSdrh   }
2052c9cf901dSdanielk1977 }
2053fec19aadSdrh 
2054ceea3321Sdrh /*
2055ceea3321Sdrh ** Clear a cache entry.
2056ceea3321Sdrh */
2057ceea3321Sdrh static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2058ceea3321Sdrh   if( p->tempReg ){
2059ceea3321Sdrh     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2060ceea3321Sdrh       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2061ceea3321Sdrh     }
2062ceea3321Sdrh     p->tempReg = 0;
2063ceea3321Sdrh   }
2064ceea3321Sdrh }
2065ceea3321Sdrh 
2066ceea3321Sdrh 
2067ceea3321Sdrh /*
2068ceea3321Sdrh ** Record in the column cache that a particular column from a
2069ceea3321Sdrh ** particular table is stored in a particular register.
2070ceea3321Sdrh */
2071ceea3321Sdrh void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2072ceea3321Sdrh   int i;
2073ceea3321Sdrh   int minLru;
2074ceea3321Sdrh   int idxLru;
2075ceea3321Sdrh   struct yColCache *p;
2076ceea3321Sdrh 
207720411ea7Sdrh   assert( iReg>0 );  /* Register numbers are always positive */
207820411ea7Sdrh   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
207920411ea7Sdrh 
2080b6da74ebSdrh   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
2081b6da74ebSdrh   ** for testing only - to verify that SQLite always gets the same answer
2082b6da74ebSdrh   ** with and without the column cache.
2083b6da74ebSdrh   */
20847e5418e4Sdrh   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
2085b6da74ebSdrh 
208627ee406eSdrh   /* First replace any existing entry.
208727ee406eSdrh   **
208827ee406eSdrh   ** Actually, the way the column cache is currently used, we are guaranteed
208927ee406eSdrh   ** that the object will never already be in cache.  Verify this guarantee.
209027ee406eSdrh   */
209127ee406eSdrh #ifndef NDEBUG
2092ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
209327ee406eSdrh     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
2094ceea3321Sdrh   }
209527ee406eSdrh #endif
2096ceea3321Sdrh 
2097ceea3321Sdrh   /* Find an empty slot and replace it */
2098ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2099ceea3321Sdrh     if( p->iReg==0 ){
2100ceea3321Sdrh       p->iLevel = pParse->iCacheLevel;
2101ceea3321Sdrh       p->iTable = iTab;
2102ceea3321Sdrh       p->iColumn = iCol;
2103ceea3321Sdrh       p->iReg = iReg;
2104ceea3321Sdrh       p->tempReg = 0;
2105ceea3321Sdrh       p->lru = pParse->iCacheCnt++;
2106ceea3321Sdrh       return;
2107ceea3321Sdrh     }
2108ceea3321Sdrh   }
2109ceea3321Sdrh 
2110ceea3321Sdrh   /* Replace the last recently used */
2111ceea3321Sdrh   minLru = 0x7fffffff;
2112ceea3321Sdrh   idxLru = -1;
2113ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2114ceea3321Sdrh     if( p->lru<minLru ){
2115ceea3321Sdrh       idxLru = i;
2116ceea3321Sdrh       minLru = p->lru;
2117ceea3321Sdrh     }
2118ceea3321Sdrh   }
211920411ea7Sdrh   if( ALWAYS(idxLru>=0) ){
2120ceea3321Sdrh     p = &pParse->aColCache[idxLru];
2121ceea3321Sdrh     p->iLevel = pParse->iCacheLevel;
2122ceea3321Sdrh     p->iTable = iTab;
2123ceea3321Sdrh     p->iColumn = iCol;
2124ceea3321Sdrh     p->iReg = iReg;
2125ceea3321Sdrh     p->tempReg = 0;
2126ceea3321Sdrh     p->lru = pParse->iCacheCnt++;
2127ceea3321Sdrh     return;
2128ceea3321Sdrh   }
2129ceea3321Sdrh }
2130ceea3321Sdrh 
2131ceea3321Sdrh /*
2132f49f3523Sdrh ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2133f49f3523Sdrh ** Purge the range of registers from the column cache.
2134ceea3321Sdrh */
2135f49f3523Sdrh void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
2136ceea3321Sdrh   int i;
2137f49f3523Sdrh   int iLast = iReg + nReg - 1;
2138ceea3321Sdrh   struct yColCache *p;
2139ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2140f49f3523Sdrh     int r = p->iReg;
2141f49f3523Sdrh     if( r>=iReg && r<=iLast ){
2142ceea3321Sdrh       cacheEntryClear(pParse, p);
2143ceea3321Sdrh       p->iReg = 0;
2144ceea3321Sdrh     }
2145ceea3321Sdrh   }
2146ceea3321Sdrh }
2147ceea3321Sdrh 
2148ceea3321Sdrh /*
2149ceea3321Sdrh ** Remember the current column cache context.  Any new entries added
2150ceea3321Sdrh ** added to the column cache after this call are removed when the
2151ceea3321Sdrh ** corresponding pop occurs.
2152ceea3321Sdrh */
2153ceea3321Sdrh void sqlite3ExprCachePush(Parse *pParse){
2154ceea3321Sdrh   pParse->iCacheLevel++;
2155ceea3321Sdrh }
2156ceea3321Sdrh 
2157ceea3321Sdrh /*
2158ceea3321Sdrh ** Remove from the column cache any entries that were added since the
2159ceea3321Sdrh ** the previous N Push operations.  In other words, restore the cache
2160ceea3321Sdrh ** to the state it was in N Pushes ago.
2161ceea3321Sdrh */
2162ceea3321Sdrh void sqlite3ExprCachePop(Parse *pParse, int N){
2163ceea3321Sdrh   int i;
2164ceea3321Sdrh   struct yColCache *p;
2165ceea3321Sdrh   assert( N>0 );
2166ceea3321Sdrh   assert( pParse->iCacheLevel>=N );
2167ceea3321Sdrh   pParse->iCacheLevel -= N;
2168ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2169ceea3321Sdrh     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2170ceea3321Sdrh       cacheEntryClear(pParse, p);
2171ceea3321Sdrh       p->iReg = 0;
2172ceea3321Sdrh     }
2173ceea3321Sdrh   }
2174ceea3321Sdrh }
2175945498f3Sdrh 
2176945498f3Sdrh /*
21775cd79239Sdrh ** When a cached column is reused, make sure that its register is
21785cd79239Sdrh ** no longer available as a temp register.  ticket #3879:  that same
21795cd79239Sdrh ** register might be in the cache in multiple places, so be sure to
21805cd79239Sdrh ** get them all.
21815cd79239Sdrh */
21825cd79239Sdrh static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
21835cd79239Sdrh   int i;
21845cd79239Sdrh   struct yColCache *p;
21855cd79239Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
21865cd79239Sdrh     if( p->iReg==iReg ){
21875cd79239Sdrh       p->tempReg = 0;
21885cd79239Sdrh     }
21895cd79239Sdrh   }
21905cd79239Sdrh }
21915cd79239Sdrh 
21925cd79239Sdrh /*
21935c092e8aSdrh ** Generate code to extract the value of the iCol-th column of a table.
21945c092e8aSdrh */
21955c092e8aSdrh void sqlite3ExprCodeGetColumnOfTable(
21965c092e8aSdrh   Vdbe *v,        /* The VDBE under construction */
21975c092e8aSdrh   Table *pTab,    /* The table containing the value */
21985c092e8aSdrh   int iTabCur,    /* The cursor for this table */
21995c092e8aSdrh   int iCol,       /* Index of the column to extract */
22005c092e8aSdrh   int regOut      /* Extract the valud into this register */
22015c092e8aSdrh ){
22025c092e8aSdrh   if( iCol<0 || iCol==pTab->iPKey ){
22035c092e8aSdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
22045c092e8aSdrh   }else{
22055c092e8aSdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
22065c092e8aSdrh     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
22075c092e8aSdrh   }
22085c092e8aSdrh   if( iCol>=0 ){
22095c092e8aSdrh     sqlite3ColumnDefault(v, pTab, iCol, regOut);
22105c092e8aSdrh   }
22115c092e8aSdrh }
22125c092e8aSdrh 
22135c092e8aSdrh /*
2214945498f3Sdrh ** Generate code that will extract the iColumn-th column from
2215e55cbd72Sdrh ** table pTab and store the column value in a register.  An effort
2216e55cbd72Sdrh ** is made to store the column value in register iReg, but this is
2217e55cbd72Sdrh ** not guaranteed.  The location of the column value is returned.
2218e55cbd72Sdrh **
2219e55cbd72Sdrh ** There must be an open cursor to pTab in iTable when this routine
2220e55cbd72Sdrh ** is called.  If iColumn<0 then code is generated that extracts the rowid.
2221945498f3Sdrh */
2222e55cbd72Sdrh int sqlite3ExprCodeGetColumn(
2223e55cbd72Sdrh   Parse *pParse,   /* Parsing and code generating context */
22242133d822Sdrh   Table *pTab,     /* Description of the table we are reading from */
22252133d822Sdrh   int iColumn,     /* Index of the table column */
22262133d822Sdrh   int iTable,      /* The cursor pointing to the table */
2227a748fdccSdrh   int iReg,        /* Store results here */
2228a748fdccSdrh   u8 p5            /* P5 value for OP_Column */
22292133d822Sdrh ){
2230e55cbd72Sdrh   Vdbe *v = pParse->pVdbe;
2231e55cbd72Sdrh   int i;
2232da250ea5Sdrh   struct yColCache *p;
2233e55cbd72Sdrh 
2234ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2235b6da74ebSdrh     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
2236ceea3321Sdrh       p->lru = pParse->iCacheCnt++;
22375cd79239Sdrh       sqlite3ExprCachePinRegister(pParse, p->iReg);
2238da250ea5Sdrh       return p->iReg;
2239e55cbd72Sdrh     }
2240e55cbd72Sdrh   }
2241e55cbd72Sdrh   assert( v!=0 );
22425c092e8aSdrh   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
2243a748fdccSdrh   if( p5 ){
2244a748fdccSdrh     sqlite3VdbeChangeP5(v, p5);
2245a748fdccSdrh   }else{
2246ceea3321Sdrh     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2247a748fdccSdrh   }
2248e55cbd72Sdrh   return iReg;
2249e55cbd72Sdrh }
2250e55cbd72Sdrh 
2251e55cbd72Sdrh /*
2252ceea3321Sdrh ** Clear all column cache entries.
2253e55cbd72Sdrh */
2254ceea3321Sdrh void sqlite3ExprCacheClear(Parse *pParse){
2255e55cbd72Sdrh   int i;
2256ceea3321Sdrh   struct yColCache *p;
2257ceea3321Sdrh 
2258ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2259ceea3321Sdrh     if( p->iReg ){
2260ceea3321Sdrh       cacheEntryClear(pParse, p);
2261ceea3321Sdrh       p->iReg = 0;
2262e55cbd72Sdrh     }
2263da250ea5Sdrh   }
2264da250ea5Sdrh }
2265e55cbd72Sdrh 
2266e55cbd72Sdrh /*
2267da250ea5Sdrh ** Record the fact that an affinity change has occurred on iCount
2268da250ea5Sdrh ** registers starting with iStart.
2269e55cbd72Sdrh */
2270da250ea5Sdrh void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2271f49f3523Sdrh   sqlite3ExprCacheRemove(pParse, iStart, iCount);
2272e55cbd72Sdrh }
2273e55cbd72Sdrh 
2274e55cbd72Sdrh /*
2275b21e7c70Sdrh ** Generate code to move content from registers iFrom...iFrom+nReg-1
2276b21e7c70Sdrh ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
2277e55cbd72Sdrh */
2278b21e7c70Sdrh void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
2279e55cbd72Sdrh   int i;
2280ceea3321Sdrh   struct yColCache *p;
2281e8e4af76Sdrh   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
2282e8e4af76Sdrh   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
2283ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2284ceea3321Sdrh     int x = p->iReg;
2285b21e7c70Sdrh     if( x>=iFrom && x<iFrom+nReg ){
2286ceea3321Sdrh       p->iReg += iTo-iFrom;
2287e55cbd72Sdrh     }
2288e55cbd72Sdrh   }
2289945498f3Sdrh }
2290945498f3Sdrh 
2291f49f3523Sdrh #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
229292b01d53Sdrh /*
2293652fbf55Sdrh ** Return true if any register in the range iFrom..iTo (inclusive)
2294652fbf55Sdrh ** is used as part of the column cache.
2295f49f3523Sdrh **
2296f49f3523Sdrh ** This routine is used within assert() and testcase() macros only
2297f49f3523Sdrh ** and does not appear in a normal build.
2298652fbf55Sdrh */
2299652fbf55Sdrh static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2300652fbf55Sdrh   int i;
2301ceea3321Sdrh   struct yColCache *p;
2302ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2303ceea3321Sdrh     int r = p->iReg;
2304f49f3523Sdrh     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
2305652fbf55Sdrh   }
2306652fbf55Sdrh   return 0;
2307652fbf55Sdrh }
2308f49f3523Sdrh #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
2309652fbf55Sdrh 
2310652fbf55Sdrh /*
2311cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
23122dcef11bSdrh ** expression.  Attempt to store the results in register "target".
23132dcef11bSdrh ** Return the register where results are stored.
2314389a1adbSdrh **
23158b213899Sdrh ** With this routine, there is no guarantee that results will
23162dcef11bSdrh ** be stored in target.  The result might be stored in some other
23172dcef11bSdrh ** register if it is convenient to do so.  The calling function
23182dcef11bSdrh ** must check the return code and move the results to the desired
23192dcef11bSdrh ** register.
2320cce7d176Sdrh */
2321678ccce8Sdrh int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
23222dcef11bSdrh   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
23232dcef11bSdrh   int op;                   /* The opcode being coded */
23242dcef11bSdrh   int inReg = target;       /* Results stored in register inReg */
23252dcef11bSdrh   int regFree1 = 0;         /* If non-zero free this temporary register */
23262dcef11bSdrh   int regFree2 = 0;         /* If non-zero free this temporary register */
2327678ccce8Sdrh   int r1, r2, r3, r4;       /* Various register numbers */
232820411ea7Sdrh   sqlite3 *db = pParse->db; /* The database connection */
2329ffe07b2dSdrh 
23309cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
233120411ea7Sdrh   if( v==0 ){
233220411ea7Sdrh     assert( pParse->db->mallocFailed );
233320411ea7Sdrh     return 0;
233420411ea7Sdrh   }
2335389a1adbSdrh 
2336389a1adbSdrh   if( pExpr==0 ){
2337389a1adbSdrh     op = TK_NULL;
2338389a1adbSdrh   }else{
2339f2bc013cSdrh     op = pExpr->op;
2340389a1adbSdrh   }
2341f2bc013cSdrh   switch( op ){
234213449892Sdrh     case TK_AGG_COLUMN: {
234313449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
234413449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
234513449892Sdrh       if( !pAggInfo->directMode ){
23469de221dfSdrh         assert( pCol->iMem>0 );
23479de221dfSdrh         inReg = pCol->iMem;
234813449892Sdrh         break;
234913449892Sdrh       }else if( pAggInfo->useSortingIdx ){
23505134d135Sdan         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
2351389a1adbSdrh                               pCol->iSorterColumn, target);
235213449892Sdrh         break;
235313449892Sdrh       }
235413449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
235513449892Sdrh     }
2356967e8b73Sdrh     case TK_COLUMN: {
2357ffe07b2dSdrh       if( pExpr->iTable<0 ){
2358ffe07b2dSdrh         /* This only happens when coding check constraints */
2359aa9b8963Sdrh         assert( pParse->ckBase>0 );
2360aa9b8963Sdrh         inReg = pExpr->iColumn + pParse->ckBase;
2361c4a3c779Sdrh       }else{
2362e55cbd72Sdrh         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2363a748fdccSdrh                                  pExpr->iColumn, pExpr->iTable, target,
2364a748fdccSdrh                                  pExpr->op2);
23652282792aSdrh       }
2366cce7d176Sdrh       break;
2367cce7d176Sdrh     }
2368cce7d176Sdrh     case TK_INTEGER: {
236913573c71Sdrh       codeInteger(pParse, pExpr, 0, target);
2370fec19aadSdrh       break;
237151e9a445Sdrh     }
237213573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2373598f1340Sdrh     case TK_FLOAT: {
237433e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
237533e619fcSdrh       codeReal(v, pExpr->u.zToken, 0, target);
2376598f1340Sdrh       break;
2377598f1340Sdrh     }
237813573c71Sdrh #endif
2379fec19aadSdrh     case TK_STRING: {
238033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
238133e619fcSdrh       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
2382cce7d176Sdrh       break;
2383cce7d176Sdrh     }
2384f0863fe5Sdrh     case TK_NULL: {
23859de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2386f0863fe5Sdrh       break;
2387f0863fe5Sdrh     }
23885338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
2389c572ef7fSdanielk1977     case TK_BLOB: {
23906c8c6cecSdrh       int n;
23916c8c6cecSdrh       const char *z;
2392ca48c90fSdrh       char *zBlob;
239333e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
239433e619fcSdrh       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
239533e619fcSdrh       assert( pExpr->u.zToken[1]=='\'' );
239633e619fcSdrh       z = &pExpr->u.zToken[2];
2397b7916a78Sdrh       n = sqlite3Strlen30(z) - 1;
2398b7916a78Sdrh       assert( z[n]=='\'' );
2399ca48c90fSdrh       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2400ca48c90fSdrh       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2401c572ef7fSdanielk1977       break;
2402c572ef7fSdanielk1977     }
24035338a5f7Sdanielk1977 #endif
240450457896Sdrh     case TK_VARIABLE: {
240533e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
240633e619fcSdrh       assert( pExpr->u.zToken!=0 );
240733e619fcSdrh       assert( pExpr->u.zToken[0]!=0 );
2408eaf52d88Sdrh       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
240933e619fcSdrh       if( pExpr->u.zToken[1]!=0 ){
241004e9eeadSdrh         assert( pExpr->u.zToken[0]=='?'
241104e9eeadSdrh              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
241204e9eeadSdrh         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
2413895d7472Sdrh       }
241450457896Sdrh       break;
241550457896Sdrh     }
24164e0cff60Sdrh     case TK_REGISTER: {
24179de221dfSdrh       inReg = pExpr->iTable;
24184e0cff60Sdrh       break;
24194e0cff60Sdrh     }
24208b213899Sdrh     case TK_AS: {
24217445ffe2Sdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
24228b213899Sdrh       break;
24238b213899Sdrh     }
2424487e262fSdrh #ifndef SQLITE_OMIT_CAST
2425487e262fSdrh     case TK_CAST: {
2426487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
2427f0113000Sdanielk1977       int aff, to_op;
24282dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
242933e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
243033e619fcSdrh       aff = sqlite3AffinityType(pExpr->u.zToken);
2431f0113000Sdanielk1977       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
2432f0113000Sdanielk1977       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
2433f0113000Sdanielk1977       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
2434f0113000Sdanielk1977       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
2435f0113000Sdanielk1977       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
2436f0113000Sdanielk1977       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
2437c5499befSdrh       testcase( to_op==OP_ToText );
2438c5499befSdrh       testcase( to_op==OP_ToBlob );
2439c5499befSdrh       testcase( to_op==OP_ToNumeric );
2440c5499befSdrh       testcase( to_op==OP_ToInt );
2441c5499befSdrh       testcase( to_op==OP_ToReal );
24421735fa88Sdrh       if( inReg!=target ){
24431735fa88Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
24441735fa88Sdrh         inReg = target;
24451735fa88Sdrh       }
24462dcef11bSdrh       sqlite3VdbeAddOp1(v, to_op, inReg);
2447c5499befSdrh       testcase( usedAsColumnCache(pParse, inReg, inReg) );
2448b3843a82Sdrh       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
2449487e262fSdrh       break;
2450487e262fSdrh     }
2451487e262fSdrh #endif /* SQLITE_OMIT_CAST */
2452c9b84a1fSdrh     case TK_LT:
2453c9b84a1fSdrh     case TK_LE:
2454c9b84a1fSdrh     case TK_GT:
2455c9b84a1fSdrh     case TK_GE:
2456c9b84a1fSdrh     case TK_NE:
2457c9b84a1fSdrh     case TK_EQ: {
2458f2bc013cSdrh       assert( TK_LT==OP_Lt );
2459f2bc013cSdrh       assert( TK_LE==OP_Le );
2460f2bc013cSdrh       assert( TK_GT==OP_Gt );
2461f2bc013cSdrh       assert( TK_GE==OP_Ge );
2462f2bc013cSdrh       assert( TK_EQ==OP_Eq );
2463f2bc013cSdrh       assert( TK_NE==OP_Ne );
2464c5499befSdrh       testcase( op==TK_LT );
2465c5499befSdrh       testcase( op==TK_LE );
2466c5499befSdrh       testcase( op==TK_GT );
2467c5499befSdrh       testcase( op==TK_GE );
2468c5499befSdrh       testcase( op==TK_EQ );
2469c5499befSdrh       testcase( op==TK_NE );
2470b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2471b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
247235573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
247335573356Sdrh                   r1, r2, inReg, SQLITE_STOREP2);
2474c5499befSdrh       testcase( regFree1==0 );
2475c5499befSdrh       testcase( regFree2==0 );
2476a37cdde0Sdanielk1977       break;
2477c9b84a1fSdrh     }
24786a2fe093Sdrh     case TK_IS:
24796a2fe093Sdrh     case TK_ISNOT: {
24806a2fe093Sdrh       testcase( op==TK_IS );
24816a2fe093Sdrh       testcase( op==TK_ISNOT );
2482b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2483b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
24846a2fe093Sdrh       op = (op==TK_IS) ? TK_EQ : TK_NE;
24856a2fe093Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
24866a2fe093Sdrh                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
24876a2fe093Sdrh       testcase( regFree1==0 );
24886a2fe093Sdrh       testcase( regFree2==0 );
24896a2fe093Sdrh       break;
24906a2fe093Sdrh     }
2491cce7d176Sdrh     case TK_AND:
2492cce7d176Sdrh     case TK_OR:
2493cce7d176Sdrh     case TK_PLUS:
2494cce7d176Sdrh     case TK_STAR:
2495cce7d176Sdrh     case TK_MINUS:
2496bf4133cbSdrh     case TK_REM:
2497bf4133cbSdrh     case TK_BITAND:
2498bf4133cbSdrh     case TK_BITOR:
249917c40294Sdrh     case TK_SLASH:
2500bf4133cbSdrh     case TK_LSHIFT:
2501855eb1cfSdrh     case TK_RSHIFT:
25020040077dSdrh     case TK_CONCAT: {
2503f2bc013cSdrh       assert( TK_AND==OP_And );
2504f2bc013cSdrh       assert( TK_OR==OP_Or );
2505f2bc013cSdrh       assert( TK_PLUS==OP_Add );
2506f2bc013cSdrh       assert( TK_MINUS==OP_Subtract );
2507f2bc013cSdrh       assert( TK_REM==OP_Remainder );
2508f2bc013cSdrh       assert( TK_BITAND==OP_BitAnd );
2509f2bc013cSdrh       assert( TK_BITOR==OP_BitOr );
2510f2bc013cSdrh       assert( TK_SLASH==OP_Divide );
2511f2bc013cSdrh       assert( TK_LSHIFT==OP_ShiftLeft );
2512f2bc013cSdrh       assert( TK_RSHIFT==OP_ShiftRight );
2513f2bc013cSdrh       assert( TK_CONCAT==OP_Concat );
2514c5499befSdrh       testcase( op==TK_AND );
2515c5499befSdrh       testcase( op==TK_OR );
2516c5499befSdrh       testcase( op==TK_PLUS );
2517c5499befSdrh       testcase( op==TK_MINUS );
2518c5499befSdrh       testcase( op==TK_REM );
2519c5499befSdrh       testcase( op==TK_BITAND );
2520c5499befSdrh       testcase( op==TK_BITOR );
2521c5499befSdrh       testcase( op==TK_SLASH );
2522c5499befSdrh       testcase( op==TK_LSHIFT );
2523c5499befSdrh       testcase( op==TK_RSHIFT );
2524c5499befSdrh       testcase( op==TK_CONCAT );
25252dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
25262dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
25275b6afba9Sdrh       sqlite3VdbeAddOp3(v, op, r2, r1, target);
2528c5499befSdrh       testcase( regFree1==0 );
2529c5499befSdrh       testcase( regFree2==0 );
25300040077dSdrh       break;
25310040077dSdrh     }
2532cce7d176Sdrh     case TK_UMINUS: {
2533fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
2534fec19aadSdrh       assert( pLeft );
253513573c71Sdrh       if( pLeft->op==TK_INTEGER ){
253613573c71Sdrh         codeInteger(pParse, pLeft, 1, target);
253713573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
253813573c71Sdrh       }else if( pLeft->op==TK_FLOAT ){
253933e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
254033e619fcSdrh         codeReal(v, pLeft->u.zToken, 1, target);
254113573c71Sdrh #endif
25423c84ddffSdrh       }else{
25432dcef11bSdrh         regFree1 = r1 = sqlite3GetTempReg(pParse);
25443c84ddffSdrh         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
2545e55cbd72Sdrh         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
25462dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
2547c5499befSdrh         testcase( regFree2==0 );
25483c84ddffSdrh       }
25499de221dfSdrh       inReg = target;
25506e142f54Sdrh       break;
25516e142f54Sdrh     }
2552bf4133cbSdrh     case TK_BITNOT:
25536e142f54Sdrh     case TK_NOT: {
2554f2bc013cSdrh       assert( TK_BITNOT==OP_BitNot );
2555f2bc013cSdrh       assert( TK_NOT==OP_Not );
2556c5499befSdrh       testcase( op==TK_BITNOT );
2557c5499befSdrh       testcase( op==TK_NOT );
2558e99fa2afSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2559e99fa2afSdrh       testcase( regFree1==0 );
2560e99fa2afSdrh       inReg = target;
2561e99fa2afSdrh       sqlite3VdbeAddOp2(v, op, r1, inReg);
2562cce7d176Sdrh       break;
2563cce7d176Sdrh     }
2564cce7d176Sdrh     case TK_ISNULL:
2565cce7d176Sdrh     case TK_NOTNULL: {
25666a288a33Sdrh       int addr;
2567f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
2568f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
2569c5499befSdrh       testcase( op==TK_ISNULL );
2570c5499befSdrh       testcase( op==TK_NOTNULL );
25719de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
25722dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2573c5499befSdrh       testcase( regFree1==0 );
25742dcef11bSdrh       addr = sqlite3VdbeAddOp1(v, op, r1);
25759de221dfSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
25766a288a33Sdrh       sqlite3VdbeJumpHere(v, addr);
2577a37cdde0Sdanielk1977       break;
2578f2bc013cSdrh     }
25792282792aSdrh     case TK_AGG_FUNCTION: {
258013449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
25817e56e711Sdrh       if( pInfo==0 ){
258233e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
258333e619fcSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
25847e56e711Sdrh       }else{
25859de221dfSdrh         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
25867e56e711Sdrh       }
25872282792aSdrh       break;
25882282792aSdrh     }
2589b71090fdSdrh     case TK_CONST_FUNC:
2590cce7d176Sdrh     case TK_FUNCTION: {
259112ffee8cSdrh       ExprList *pFarg;       /* List of function arguments */
259212ffee8cSdrh       int nFarg;             /* Number of function arguments */
259312ffee8cSdrh       FuncDef *pDef;         /* The function definition object */
259412ffee8cSdrh       int nId;               /* Length of the function name in bytes */
259512ffee8cSdrh       const char *zId;       /* The function name */
259612ffee8cSdrh       int constMask = 0;     /* Mask of function arguments that are constant */
259712ffee8cSdrh       int i;                 /* Loop counter */
259812ffee8cSdrh       u8 enc = ENC(db);      /* The text encoding used by this database */
259912ffee8cSdrh       CollSeq *pColl = 0;    /* A collating sequence */
260017435752Sdrh 
26016ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2602c5499befSdrh       testcase( op==TK_CONST_FUNC );
2603c5499befSdrh       testcase( op==TK_FUNCTION );
2604b7916a78Sdrh       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
260512ffee8cSdrh         pFarg = 0;
260612ffee8cSdrh       }else{
260712ffee8cSdrh         pFarg = pExpr->x.pList;
260812ffee8cSdrh       }
260912ffee8cSdrh       nFarg = pFarg ? pFarg->nExpr : 0;
261033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
261133e619fcSdrh       zId = pExpr->u.zToken;
2612b7916a78Sdrh       nId = sqlite3Strlen30(zId);
261312ffee8cSdrh       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
2614feb306f5Sdrh       if( pDef==0 ){
2615feb306f5Sdrh         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
2616feb306f5Sdrh         break;
2617feb306f5Sdrh       }
2618ae6bb957Sdrh 
2619ae6bb957Sdrh       /* Attempt a direct implementation of the built-in COALESCE() and
2620ae6bb957Sdrh       ** IFNULL() functions.  This avoids unnecessary evalation of
2621ae6bb957Sdrh       ** arguments past the first non-NULL argument.
2622ae6bb957Sdrh       */
2623ae6bb957Sdrh       if( pDef->flags & SQLITE_FUNC_COALESCE ){
2624ae6bb957Sdrh         int endCoalesce = sqlite3VdbeMakeLabel(v);
2625ae6bb957Sdrh         assert( nFarg>=2 );
2626ae6bb957Sdrh         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
2627ae6bb957Sdrh         for(i=1; i<nFarg; i++){
2628ae6bb957Sdrh           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
2629f49f3523Sdrh           sqlite3ExprCacheRemove(pParse, target, 1);
2630ae6bb957Sdrh           sqlite3ExprCachePush(pParse);
2631ae6bb957Sdrh           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
2632ae6bb957Sdrh           sqlite3ExprCachePop(pParse, 1);
2633ae6bb957Sdrh         }
2634ae6bb957Sdrh         sqlite3VdbeResolveLabel(v, endCoalesce);
2635ae6bb957Sdrh         break;
2636ae6bb957Sdrh       }
2637ae6bb957Sdrh 
2638ae6bb957Sdrh 
263912ffee8cSdrh       if( pFarg ){
264012ffee8cSdrh         r1 = sqlite3GetTempRange(pParse, nFarg);
2641a748fdccSdrh 
2642a748fdccSdrh         /* For length() and typeof() functions with a column argument,
2643a748fdccSdrh         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
2644a748fdccSdrh         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
2645a748fdccSdrh         ** loading.
2646a748fdccSdrh         */
2647a748fdccSdrh         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
26484e245a4cSdrh           u8 exprOp;
2649a748fdccSdrh           assert( nFarg==1 );
2650a748fdccSdrh           assert( pFarg->a[0].pExpr!=0 );
26514e245a4cSdrh           exprOp = pFarg->a[0].pExpr->op;
26524e245a4cSdrh           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
2653a748fdccSdrh             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
2654a748fdccSdrh             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
2655a748fdccSdrh             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
2656a748fdccSdrh             pFarg->a[0].pExpr->op2 = pDef->flags;
2657a748fdccSdrh           }
2658a748fdccSdrh         }
2659a748fdccSdrh 
2660d7d385ddSdrh         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
266112ffee8cSdrh         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
2662d7d385ddSdrh         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
2663892d3179Sdrh       }else{
266412ffee8cSdrh         r1 = 0;
2665892d3179Sdrh       }
2666b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
2667a43fa227Sdrh       /* Possibly overload the function if the first argument is
2668a43fa227Sdrh       ** a virtual table column.
2669a43fa227Sdrh       **
2670a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2671a43fa227Sdrh       ** second argument, not the first, as the argument to test to
2672a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
2673a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
2674a43fa227Sdrh       ** control overloading) ends up as the second argument to the
2675a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
2676a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
2677a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
2678a43fa227Sdrh       */
267912ffee8cSdrh       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
268012ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
268112ffee8cSdrh       }else if( nFarg>0 ){
268212ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
2683b7f6f68fSdrh       }
2684b7f6f68fSdrh #endif
2685f7bca574Sdrh       for(i=0; i<nFarg; i++){
2686f7bca574Sdrh         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
268713449892Sdrh           constMask |= (1<<i);
2688d02eb1fdSdanielk1977         }
2689e82f5d04Sdrh         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
269012ffee8cSdrh           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
2691dc1bdc4fSdanielk1977         }
2692dc1bdc4fSdanielk1977       }
2693e82f5d04Sdrh       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
26948b213899Sdrh         if( !pColl ) pColl = db->pDfltColl;
269566a5167bSdrh         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
2696682f68b0Sdanielk1977       }
26972dcef11bSdrh       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
269866a5167bSdrh                         (char*)pDef, P4_FUNCDEF);
269912ffee8cSdrh       sqlite3VdbeChangeP5(v, (u8)nFarg);
270012ffee8cSdrh       if( nFarg ){
270112ffee8cSdrh         sqlite3ReleaseTempRange(pParse, r1, nFarg);
27022dcef11bSdrh       }
27036ec2733bSdrh       break;
27046ec2733bSdrh     }
2705fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
2706fe2093d7Sdrh     case TK_EXISTS:
270719a775c2Sdrh     case TK_SELECT: {
2708c5499befSdrh       testcase( op==TK_EXISTS );
2709c5499befSdrh       testcase( op==TK_SELECT );
27101450bc6eSdrh       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
271119a775c2Sdrh       break;
271219a775c2Sdrh     }
2713fef5208cSdrh     case TK_IN: {
2714e3365e6cSdrh       int destIfFalse = sqlite3VdbeMakeLabel(v);
2715e3365e6cSdrh       int destIfNull = sqlite3VdbeMakeLabel(v);
2716e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2717e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
271866ba23ceSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2719e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
2720e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
2721e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfNull);
2722fef5208cSdrh       break;
2723fef5208cSdrh     }
2724e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
2725e3365e6cSdrh 
2726e3365e6cSdrh 
27272dcef11bSdrh     /*
27282dcef11bSdrh     **    x BETWEEN y AND z
27292dcef11bSdrh     **
27302dcef11bSdrh     ** This is equivalent to
27312dcef11bSdrh     **
27322dcef11bSdrh     **    x>=y AND x<=z
27332dcef11bSdrh     **
27342dcef11bSdrh     ** X is stored in pExpr->pLeft.
27352dcef11bSdrh     ** Y is stored in pExpr->pList->a[0].pExpr.
27362dcef11bSdrh     ** Z is stored in pExpr->pList->a[1].pExpr.
27372dcef11bSdrh     */
2738fef5208cSdrh     case TK_BETWEEN: {
2739be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
27406ab3a2ecSdanielk1977       struct ExprList_item *pLItem = pExpr->x.pList->a;
2741be5c89acSdrh       Expr *pRight = pLItem->pExpr;
274235573356Sdrh 
2743b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
2744b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
2745c5499befSdrh       testcase( regFree1==0 );
2746c5499befSdrh       testcase( regFree2==0 );
27472dcef11bSdrh       r3 = sqlite3GetTempReg(pParse);
2748678ccce8Sdrh       r4 = sqlite3GetTempReg(pParse);
274935573356Sdrh       codeCompare(pParse, pLeft, pRight, OP_Ge,
275035573356Sdrh                   r1, r2, r3, SQLITE_STOREP2);
2751be5c89acSdrh       pLItem++;
2752be5c89acSdrh       pRight = pLItem->pExpr;
27532dcef11bSdrh       sqlite3ReleaseTempReg(pParse, regFree2);
27542dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
2755c5499befSdrh       testcase( regFree2==0 );
2756678ccce8Sdrh       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
2757678ccce8Sdrh       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
27582dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r3);
2759678ccce8Sdrh       sqlite3ReleaseTempReg(pParse, r4);
2760fef5208cSdrh       break;
2761fef5208cSdrh     }
2762ae80ddeaSdrh     case TK_COLLATE:
27634f07e5fbSdrh     case TK_UPLUS: {
27642dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2765a2e00042Sdrh       break;
2766a2e00042Sdrh     }
27672dcef11bSdrh 
2768165921a7Sdan     case TK_TRIGGER: {
276965a7cd16Sdan       /* If the opcode is TK_TRIGGER, then the expression is a reference
277065a7cd16Sdan       ** to a column in the new.* or old.* pseudo-tables available to
277165a7cd16Sdan       ** trigger programs. In this case Expr.iTable is set to 1 for the
277265a7cd16Sdan       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
277365a7cd16Sdan       ** is set to the column of the pseudo-table to read, or to -1 to
277465a7cd16Sdan       ** read the rowid field.
277565a7cd16Sdan       **
277665a7cd16Sdan       ** The expression is implemented using an OP_Param opcode. The p1
277765a7cd16Sdan       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
277865a7cd16Sdan       ** to reference another column of the old.* pseudo-table, where
277965a7cd16Sdan       ** i is the index of the column. For a new.rowid reference, p1 is
278065a7cd16Sdan       ** set to (n+1), where n is the number of columns in each pseudo-table.
278165a7cd16Sdan       ** For a reference to any other column in the new.* pseudo-table, p1
278265a7cd16Sdan       ** is set to (n+2+i), where n and i are as defined previously. For
278365a7cd16Sdan       ** example, if the table on which triggers are being fired is
278465a7cd16Sdan       ** declared as:
278565a7cd16Sdan       **
278665a7cd16Sdan       **   CREATE TABLE t1(a, b);
278765a7cd16Sdan       **
278865a7cd16Sdan       ** Then p1 is interpreted as follows:
278965a7cd16Sdan       **
279065a7cd16Sdan       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
279165a7cd16Sdan       **   p1==1   ->    old.a         p1==4   ->    new.a
279265a7cd16Sdan       **   p1==2   ->    old.b         p1==5   ->    new.b
279365a7cd16Sdan       */
27942832ad42Sdan       Table *pTab = pExpr->pTab;
279565a7cd16Sdan       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
279665a7cd16Sdan 
279765a7cd16Sdan       assert( pExpr->iTable==0 || pExpr->iTable==1 );
279865a7cd16Sdan       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
279965a7cd16Sdan       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
280065a7cd16Sdan       assert( p1>=0 && p1<(pTab->nCol*2+2) );
280165a7cd16Sdan 
280265a7cd16Sdan       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
280376d462eeSdan       VdbeComment((v, "%s.%s -> $%d",
2804165921a7Sdan         (pExpr->iTable ? "new" : "old"),
280576d462eeSdan         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
280676d462eeSdan         target
2807165921a7Sdan       ));
280865a7cd16Sdan 
280944dbca83Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
281065a7cd16Sdan       /* If the column has REAL affinity, it may currently be stored as an
281165a7cd16Sdan       ** integer. Use OP_RealAffinity to make sure it is really real.  */
28122832ad42Sdan       if( pExpr->iColumn>=0
28132832ad42Sdan        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
28142832ad42Sdan       ){
28152832ad42Sdan         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
28162832ad42Sdan       }
281744dbca83Sdrh #endif
2818165921a7Sdan       break;
2819165921a7Sdan     }
2820165921a7Sdan 
2821165921a7Sdan 
28222dcef11bSdrh     /*
28232dcef11bSdrh     ** Form A:
28242dcef11bSdrh     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
28252dcef11bSdrh     **
28262dcef11bSdrh     ** Form B:
28272dcef11bSdrh     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
28282dcef11bSdrh     **
28292dcef11bSdrh     ** Form A is can be transformed into the equivalent form B as follows:
28302dcef11bSdrh     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
28312dcef11bSdrh     **        WHEN x=eN THEN rN ELSE y END
28322dcef11bSdrh     **
28332dcef11bSdrh     ** X (if it exists) is in pExpr->pLeft.
28342dcef11bSdrh     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
28352dcef11bSdrh     ** ELSE clause and no other term matches, then the result of the
28362dcef11bSdrh     ** exprssion is NULL.
28372dcef11bSdrh     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
28382dcef11bSdrh     **
28392dcef11bSdrh     ** The result of the expression is the Ri for the first matching Ei,
28402dcef11bSdrh     ** or if there is no matching Ei, the ELSE term Y, or if there is
28412dcef11bSdrh     ** no ELSE term, NULL.
28422dcef11bSdrh     */
284333cd4909Sdrh     default: assert( op==TK_CASE ); {
28442dcef11bSdrh       int endLabel;                     /* GOTO label for end of CASE stmt */
28452dcef11bSdrh       int nextCase;                     /* GOTO label for next WHEN clause */
28462dcef11bSdrh       int nExpr;                        /* 2x number of WHEN terms */
28472dcef11bSdrh       int i;                            /* Loop counter */
28482dcef11bSdrh       ExprList *pEList;                 /* List of WHEN terms */
28492dcef11bSdrh       struct ExprList_item *aListelem;  /* Array of WHEN terms */
28502dcef11bSdrh       Expr opCompare;                   /* The X==Ei expression */
28512dcef11bSdrh       Expr cacheX;                      /* Cached expression X */
28522dcef11bSdrh       Expr *pX;                         /* The X expression */
28531bd10f8aSdrh       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
2854ceea3321Sdrh       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
285517a7f8ddSdrh 
28566ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
28576ab3a2ecSdanielk1977       assert((pExpr->x.pList->nExpr % 2) == 0);
28586ab3a2ecSdanielk1977       assert(pExpr->x.pList->nExpr > 0);
28596ab3a2ecSdanielk1977       pEList = pExpr->x.pList;
2860be5c89acSdrh       aListelem = pEList->a;
2861be5c89acSdrh       nExpr = pEList->nExpr;
28622dcef11bSdrh       endLabel = sqlite3VdbeMakeLabel(v);
28632dcef11bSdrh       if( (pX = pExpr->pLeft)!=0 ){
28642dcef11bSdrh         cacheX = *pX;
286533cd4909Sdrh         testcase( pX->op==TK_COLUMN );
286633cd4909Sdrh         testcase( pX->op==TK_REGISTER );
28672dcef11bSdrh         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
2868c5499befSdrh         testcase( regFree1==0 );
28692dcef11bSdrh         cacheX.op = TK_REGISTER;
28702dcef11bSdrh         opCompare.op = TK_EQ;
28712dcef11bSdrh         opCompare.pLeft = &cacheX;
28722dcef11bSdrh         pTest = &opCompare;
28738b1db07fSdrh         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
28748b1db07fSdrh         ** The value in regFree1 might get SCopy-ed into the file result.
28758b1db07fSdrh         ** So make sure that the regFree1 register is not reused for other
28768b1db07fSdrh         ** purposes and possibly overwritten.  */
28778b1db07fSdrh         regFree1 = 0;
2878cce7d176Sdrh       }
2879f5905aa7Sdrh       for(i=0; i<nExpr; i=i+2){
2880ceea3321Sdrh         sqlite3ExprCachePush(pParse);
28812dcef11bSdrh         if( pX ){
28821bd10f8aSdrh           assert( pTest!=0 );
28832dcef11bSdrh           opCompare.pRight = aListelem[i].pExpr;
2884f5905aa7Sdrh         }else{
28852dcef11bSdrh           pTest = aListelem[i].pExpr;
288617a7f8ddSdrh         }
28872dcef11bSdrh         nextCase = sqlite3VdbeMakeLabel(v);
288833cd4909Sdrh         testcase( pTest->op==TK_COLUMN );
28892dcef11bSdrh         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
2890c5499befSdrh         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
2891c5499befSdrh         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
28929de221dfSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
28932dcef11bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
2894ceea3321Sdrh         sqlite3ExprCachePop(pParse, 1);
28952dcef11bSdrh         sqlite3VdbeResolveLabel(v, nextCase);
2896f570f011Sdrh       }
289717a7f8ddSdrh       if( pExpr->pRight ){
2898ceea3321Sdrh         sqlite3ExprCachePush(pParse);
28999de221dfSdrh         sqlite3ExprCode(pParse, pExpr->pRight, target);
2900ceea3321Sdrh         sqlite3ExprCachePop(pParse, 1);
290117a7f8ddSdrh       }else{
29029de221dfSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
290317a7f8ddSdrh       }
2904c1f4a19bSdanielk1977       assert( db->mallocFailed || pParse->nErr>0
2905c1f4a19bSdanielk1977            || pParse->iCacheLevel==iCacheLevel );
29062dcef11bSdrh       sqlite3VdbeResolveLabel(v, endLabel);
29076f34903eSdanielk1977       break;
29086f34903eSdanielk1977     }
29095338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
29106f34903eSdanielk1977     case TK_RAISE: {
2911165921a7Sdan       assert( pExpr->affinity==OE_Rollback
2912165921a7Sdan            || pExpr->affinity==OE_Abort
2913165921a7Sdan            || pExpr->affinity==OE_Fail
2914165921a7Sdan            || pExpr->affinity==OE_Ignore
2915165921a7Sdan       );
2916e0af83acSdan       if( !pParse->pTriggerTab ){
2917e0af83acSdan         sqlite3ErrorMsg(pParse,
2918e0af83acSdan                        "RAISE() may only be used within a trigger-program");
2919e0af83acSdan         return 0;
2920e0af83acSdan       }
2921e0af83acSdan       if( pExpr->affinity==OE_Abort ){
2922e0af83acSdan         sqlite3MayAbort(pParse);
2923e0af83acSdan       }
292433e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2925e0af83acSdan       if( pExpr->affinity==OE_Ignore ){
2926e0af83acSdan         sqlite3VdbeAddOp4(
2927e0af83acSdan             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
2928e0af83acSdan       }else{
2929e0af83acSdan         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
2930e0af83acSdan       }
2931e0af83acSdan 
2932ffe07b2dSdrh       break;
293317a7f8ddSdrh     }
29345338a5f7Sdanielk1977 #endif
2935ffe07b2dSdrh   }
29362dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
29372dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
29382dcef11bSdrh   return inReg;
29395b6afba9Sdrh }
29402dcef11bSdrh 
29412dcef11bSdrh /*
29422dcef11bSdrh ** Generate code to evaluate an expression and store the results
29432dcef11bSdrh ** into a register.  Return the register number where the results
29442dcef11bSdrh ** are stored.
29452dcef11bSdrh **
29462dcef11bSdrh ** If the register is a temporary register that can be deallocated,
2947678ccce8Sdrh ** then write its number into *pReg.  If the result register is not
29482dcef11bSdrh ** a temporary, then set *pReg to zero.
29492dcef11bSdrh */
29502dcef11bSdrh int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
29512dcef11bSdrh   int r1 = sqlite3GetTempReg(pParse);
29522dcef11bSdrh   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
29532dcef11bSdrh   if( r2==r1 ){
29542dcef11bSdrh     *pReg = r1;
29552dcef11bSdrh   }else{
29562dcef11bSdrh     sqlite3ReleaseTempReg(pParse, r1);
29572dcef11bSdrh     *pReg = 0;
29582dcef11bSdrh   }
29592dcef11bSdrh   return r2;
29602dcef11bSdrh }
29612dcef11bSdrh 
29622dcef11bSdrh /*
29632dcef11bSdrh ** Generate code that will evaluate expression pExpr and store the
29642dcef11bSdrh ** results in register target.  The results are guaranteed to appear
29652dcef11bSdrh ** in register target.
29662dcef11bSdrh */
29672dcef11bSdrh int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
29689cbf3425Sdrh   int inReg;
29699cbf3425Sdrh 
29709cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
2971ebc16717Sdrh   if( pExpr && pExpr->op==TK_REGISTER ){
2972ebc16717Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
2973ebc16717Sdrh   }else{
29749cbf3425Sdrh     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
29750e359b30Sdrh     assert( pParse->pVdbe || pParse->db->mallocFailed );
29760e359b30Sdrh     if( inReg!=target && pParse->pVdbe ){
29779cbf3425Sdrh       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
297817a7f8ddSdrh     }
2979ebc16717Sdrh   }
2980389a1adbSdrh   return target;
2981cce7d176Sdrh }
2982cce7d176Sdrh 
2983cce7d176Sdrh /*
29842dcef11bSdrh ** Generate code that evalutes the given expression and puts the result
2985de4fcfddSdrh ** in register target.
298625303780Sdrh **
29872dcef11bSdrh ** Also make a copy of the expression results into another "cache" register
29882dcef11bSdrh ** and modify the expression so that the next time it is evaluated,
29892dcef11bSdrh ** the result is a copy of the cache register.
29902dcef11bSdrh **
29912dcef11bSdrh ** This routine is used for expressions that are used multiple
29922dcef11bSdrh ** times.  They are evaluated once and the results of the expression
29932dcef11bSdrh ** are reused.
299425303780Sdrh */
29952dcef11bSdrh int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
299625303780Sdrh   Vdbe *v = pParse->pVdbe;
29972dcef11bSdrh   int inReg;
29982dcef11bSdrh   inReg = sqlite3ExprCode(pParse, pExpr, target);
2999de4fcfddSdrh   assert( target>0 );
300020bc393cSdrh   /* This routine is called for terms to INSERT or UPDATE.  And the only
300120bc393cSdrh   ** other place where expressions can be converted into TK_REGISTER is
300220bc393cSdrh   ** in WHERE clause processing.  So as currently implemented, there is
300320bc393cSdrh   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
300420bc393cSdrh   ** keep the ALWAYS() in case the conditions above change with future
300520bc393cSdrh   ** modifications or enhancements. */
300620bc393cSdrh   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
300725303780Sdrh     int iMem;
30082dcef11bSdrh     iMem = ++pParse->nMem;
30092dcef11bSdrh     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
30102dcef11bSdrh     pExpr->iTable = iMem;
3011937d0deaSdan     pExpr->op2 = pExpr->op;
301225303780Sdrh     pExpr->op = TK_REGISTER;
301325303780Sdrh   }
30142dcef11bSdrh   return inReg;
301525303780Sdrh }
30162dcef11bSdrh 
3017678a9aa7Sdrh #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
30187e02e5e6Sdrh /*
30197e02e5e6Sdrh ** Generate a human-readable explanation of an expression tree.
30207e02e5e6Sdrh */
3021a84203a0Sdrh void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
3022a84203a0Sdrh   int op;                   /* The opcode being coded */
3023a84203a0Sdrh   const char *zBinOp = 0;   /* Binary operator */
3024a84203a0Sdrh   const char *zUniOp = 0;   /* Unary operator */
3025a84203a0Sdrh   if( pExpr==0 ){
3026a84203a0Sdrh     op = TK_NULL;
30277e02e5e6Sdrh   }else{
3028a84203a0Sdrh     op = pExpr->op;
30297e02e5e6Sdrh   }
3030a84203a0Sdrh   switch( op ){
3031a84203a0Sdrh     case TK_AGG_COLUMN: {
303204b8342bSdrh       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
303304b8342bSdrh             pExpr->iTable, pExpr->iColumn);
3034a84203a0Sdrh       break;
30357e02e5e6Sdrh     }
3036a84203a0Sdrh     case TK_COLUMN: {
3037a84203a0Sdrh       if( pExpr->iTable<0 ){
3038a84203a0Sdrh         /* This only happens when coding check constraints */
3039a84203a0Sdrh         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
3040a84203a0Sdrh       }else{
304104b8342bSdrh         sqlite3ExplainPrintf(pOut, "{%d:%d}",
304204b8342bSdrh                              pExpr->iTable, pExpr->iColumn);
3043a84203a0Sdrh       }
3044a84203a0Sdrh       break;
3045a84203a0Sdrh     }
3046a84203a0Sdrh     case TK_INTEGER: {
3047a84203a0Sdrh       if( pExpr->flags & EP_IntValue ){
304804b8342bSdrh         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
3049a84203a0Sdrh       }else{
305004b8342bSdrh         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
3051a84203a0Sdrh       }
3052a84203a0Sdrh       break;
3053a84203a0Sdrh     }
3054a84203a0Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
3055a84203a0Sdrh     case TK_FLOAT: {
305604b8342bSdrh       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
3057a84203a0Sdrh       break;
3058a84203a0Sdrh     }
3059a84203a0Sdrh #endif
3060a84203a0Sdrh     case TK_STRING: {
306104b8342bSdrh       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
3062a84203a0Sdrh       break;
3063a84203a0Sdrh     }
3064a84203a0Sdrh     case TK_NULL: {
3065a84203a0Sdrh       sqlite3ExplainPrintf(pOut,"NULL");
3066a84203a0Sdrh       break;
3067a84203a0Sdrh     }
3068a84203a0Sdrh #ifndef SQLITE_OMIT_BLOB_LITERAL
3069a84203a0Sdrh     case TK_BLOB: {
307004b8342bSdrh       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
3071a84203a0Sdrh       break;
3072a84203a0Sdrh     }
3073a84203a0Sdrh #endif
3074a84203a0Sdrh     case TK_VARIABLE: {
3075a84203a0Sdrh       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
3076a84203a0Sdrh                            pExpr->u.zToken, pExpr->iColumn);
3077a84203a0Sdrh       break;
3078a84203a0Sdrh     }
3079a84203a0Sdrh     case TK_REGISTER: {
3080a84203a0Sdrh       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
3081a84203a0Sdrh       break;
3082a84203a0Sdrh     }
3083a84203a0Sdrh     case TK_AS: {
3084a84203a0Sdrh       sqlite3ExplainExpr(pOut, pExpr->pLeft);
3085a84203a0Sdrh       break;
3086a84203a0Sdrh     }
3087a84203a0Sdrh #ifndef SQLITE_OMIT_CAST
3088a84203a0Sdrh     case TK_CAST: {
3089a84203a0Sdrh       /* Expressions of the form:   CAST(pLeft AS token) */
3090a84203a0Sdrh       const char *zAff = "unk";
3091a84203a0Sdrh       switch( sqlite3AffinityType(pExpr->u.zToken) ){
3092a84203a0Sdrh         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
3093a84203a0Sdrh         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
3094a84203a0Sdrh         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
3095a84203a0Sdrh         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
3096a84203a0Sdrh         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
3097a84203a0Sdrh       }
3098a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
3099a84203a0Sdrh       sqlite3ExplainExpr(pOut, pExpr->pLeft);
3100a84203a0Sdrh       sqlite3ExplainPrintf(pOut, ")");
3101a84203a0Sdrh       break;
3102a84203a0Sdrh     }
3103a84203a0Sdrh #endif /* SQLITE_OMIT_CAST */
3104a84203a0Sdrh     case TK_LT:      zBinOp = "LT";     break;
3105a84203a0Sdrh     case TK_LE:      zBinOp = "LE";     break;
3106a84203a0Sdrh     case TK_GT:      zBinOp = "GT";     break;
3107a84203a0Sdrh     case TK_GE:      zBinOp = "GE";     break;
3108a84203a0Sdrh     case TK_NE:      zBinOp = "NE";     break;
3109a84203a0Sdrh     case TK_EQ:      zBinOp = "EQ";     break;
3110a84203a0Sdrh     case TK_IS:      zBinOp = "IS";     break;
3111a84203a0Sdrh     case TK_ISNOT:   zBinOp = "ISNOT";  break;
3112a84203a0Sdrh     case TK_AND:     zBinOp = "AND";    break;
3113a84203a0Sdrh     case TK_OR:      zBinOp = "OR";     break;
3114a84203a0Sdrh     case TK_PLUS:    zBinOp = "ADD";    break;
3115a84203a0Sdrh     case TK_STAR:    zBinOp = "MUL";    break;
3116a84203a0Sdrh     case TK_MINUS:   zBinOp = "SUB";    break;
3117a84203a0Sdrh     case TK_REM:     zBinOp = "REM";    break;
3118a84203a0Sdrh     case TK_BITAND:  zBinOp = "BITAND"; break;
3119a84203a0Sdrh     case TK_BITOR:   zBinOp = "BITOR";  break;
3120a84203a0Sdrh     case TK_SLASH:   zBinOp = "DIV";    break;
3121a84203a0Sdrh     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
3122a84203a0Sdrh     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
3123a84203a0Sdrh     case TK_CONCAT:  zBinOp = "CONCAT"; break;
3124a84203a0Sdrh 
3125a84203a0Sdrh     case TK_UMINUS:  zUniOp = "UMINUS"; break;
3126a84203a0Sdrh     case TK_UPLUS:   zUniOp = "UPLUS";  break;
3127a84203a0Sdrh     case TK_BITNOT:  zUniOp = "BITNOT"; break;
3128a84203a0Sdrh     case TK_NOT:     zUniOp = "NOT";    break;
3129a84203a0Sdrh     case TK_ISNULL:  zUniOp = "ISNULL"; break;
3130a84203a0Sdrh     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
3131a84203a0Sdrh 
3132a84203a0Sdrh     case TK_AGG_FUNCTION:
3133a84203a0Sdrh     case TK_CONST_FUNC:
3134a84203a0Sdrh     case TK_FUNCTION: {
3135a84203a0Sdrh       ExprList *pFarg;       /* List of function arguments */
3136a84203a0Sdrh       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
3137a84203a0Sdrh         pFarg = 0;
3138a84203a0Sdrh       }else{
3139a84203a0Sdrh         pFarg = pExpr->x.pList;
3140a84203a0Sdrh       }
3141ed551b95Sdrh       if( op==TK_AGG_FUNCTION ){
3142ed551b95Sdrh         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
3143ed551b95Sdrh                              pExpr->op2, pExpr->u.zToken);
3144ed551b95Sdrh       }else{
3145ed551b95Sdrh         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
3146ed551b95Sdrh       }
3147a84203a0Sdrh       if( pFarg ){
3148a84203a0Sdrh         sqlite3ExplainExprList(pOut, pFarg);
31497e02e5e6Sdrh       }
31507e02e5e6Sdrh       sqlite3ExplainPrintf(pOut, ")");
3151a84203a0Sdrh       break;
3152a84203a0Sdrh     }
3153a84203a0Sdrh #ifndef SQLITE_OMIT_SUBQUERY
3154a84203a0Sdrh     case TK_EXISTS: {
3155a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "EXISTS(");
3156a84203a0Sdrh       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
3157a84203a0Sdrh       sqlite3ExplainPrintf(pOut,")");
3158a84203a0Sdrh       break;
3159a84203a0Sdrh     }
3160a84203a0Sdrh     case TK_SELECT: {
3161a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "(");
3162a84203a0Sdrh       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
3163a84203a0Sdrh       sqlite3ExplainPrintf(pOut, ")");
3164a84203a0Sdrh       break;
3165a84203a0Sdrh     }
3166a84203a0Sdrh     case TK_IN: {
3167a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "IN(");
3168a84203a0Sdrh       sqlite3ExplainExpr(pOut, pExpr->pLeft);
3169a84203a0Sdrh       sqlite3ExplainPrintf(pOut, ",");
3170a84203a0Sdrh       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3171a84203a0Sdrh         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
3172a84203a0Sdrh       }else{
3173a84203a0Sdrh         sqlite3ExplainExprList(pOut, pExpr->x.pList);
3174a84203a0Sdrh       }
3175a84203a0Sdrh       sqlite3ExplainPrintf(pOut, ")");
3176a84203a0Sdrh       break;
3177a84203a0Sdrh     }
3178a84203a0Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
3179a84203a0Sdrh 
3180a84203a0Sdrh     /*
3181a84203a0Sdrh     **    x BETWEEN y AND z
3182a84203a0Sdrh     **
3183a84203a0Sdrh     ** This is equivalent to
3184a84203a0Sdrh     **
3185a84203a0Sdrh     **    x>=y AND x<=z
3186a84203a0Sdrh     **
3187a84203a0Sdrh     ** X is stored in pExpr->pLeft.
3188a84203a0Sdrh     ** Y is stored in pExpr->pList->a[0].pExpr.
3189a84203a0Sdrh     ** Z is stored in pExpr->pList->a[1].pExpr.
3190a84203a0Sdrh     */
3191a84203a0Sdrh     case TK_BETWEEN: {
3192a84203a0Sdrh       Expr *pX = pExpr->pLeft;
3193a84203a0Sdrh       Expr *pY = pExpr->x.pList->a[0].pExpr;
3194a84203a0Sdrh       Expr *pZ = pExpr->x.pList->a[1].pExpr;
3195a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "BETWEEN(");
3196a84203a0Sdrh       sqlite3ExplainExpr(pOut, pX);
3197a84203a0Sdrh       sqlite3ExplainPrintf(pOut, ",");
3198a84203a0Sdrh       sqlite3ExplainExpr(pOut, pY);
3199a84203a0Sdrh       sqlite3ExplainPrintf(pOut, ",");
3200a84203a0Sdrh       sqlite3ExplainExpr(pOut, pZ);
3201a84203a0Sdrh       sqlite3ExplainPrintf(pOut, ")");
3202a84203a0Sdrh       break;
3203a84203a0Sdrh     }
3204a84203a0Sdrh     case TK_TRIGGER: {
3205a84203a0Sdrh       /* If the opcode is TK_TRIGGER, then the expression is a reference
3206a84203a0Sdrh       ** to a column in the new.* or old.* pseudo-tables available to
3207a84203a0Sdrh       ** trigger programs. In this case Expr.iTable is set to 1 for the
3208a84203a0Sdrh       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3209a84203a0Sdrh       ** is set to the column of the pseudo-table to read, or to -1 to
3210a84203a0Sdrh       ** read the rowid field.
3211a84203a0Sdrh       */
3212a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "%s(%d)",
3213a84203a0Sdrh           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
3214a84203a0Sdrh       break;
3215a84203a0Sdrh     }
3216a84203a0Sdrh     case TK_CASE: {
3217a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "CASE(");
3218a84203a0Sdrh       sqlite3ExplainExpr(pOut, pExpr->pLeft);
3219a84203a0Sdrh       sqlite3ExplainPrintf(pOut, ",");
3220a84203a0Sdrh       sqlite3ExplainExprList(pOut, pExpr->x.pList);
3221a84203a0Sdrh       break;
3222a84203a0Sdrh     }
3223a84203a0Sdrh #ifndef SQLITE_OMIT_TRIGGER
3224a84203a0Sdrh     case TK_RAISE: {
3225a84203a0Sdrh       const char *zType = "unk";
3226a84203a0Sdrh       switch( pExpr->affinity ){
3227a84203a0Sdrh         case OE_Rollback:   zType = "rollback";  break;
3228a84203a0Sdrh         case OE_Abort:      zType = "abort";     break;
3229a84203a0Sdrh         case OE_Fail:       zType = "fail";      break;
3230a84203a0Sdrh         case OE_Ignore:     zType = "ignore";    break;
3231a84203a0Sdrh       }
3232a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
3233a84203a0Sdrh       break;
3234a84203a0Sdrh     }
3235a84203a0Sdrh #endif
3236a84203a0Sdrh   }
3237a84203a0Sdrh   if( zBinOp ){
3238a84203a0Sdrh     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
3239a84203a0Sdrh     sqlite3ExplainExpr(pOut, pExpr->pLeft);
3240a84203a0Sdrh     sqlite3ExplainPrintf(pOut,",");
3241a84203a0Sdrh     sqlite3ExplainExpr(pOut, pExpr->pRight);
3242a84203a0Sdrh     sqlite3ExplainPrintf(pOut,")");
3243a84203a0Sdrh   }else if( zUniOp ){
3244a84203a0Sdrh     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
3245a84203a0Sdrh     sqlite3ExplainExpr(pOut, pExpr->pLeft);
3246a84203a0Sdrh     sqlite3ExplainPrintf(pOut,")");
3247a84203a0Sdrh   }
32487e02e5e6Sdrh }
3249678a9aa7Sdrh #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
32507e02e5e6Sdrh 
3251678a9aa7Sdrh #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
32527e02e5e6Sdrh /*
32537e02e5e6Sdrh ** Generate a human-readable explanation of an expression list.
32547e02e5e6Sdrh */
32557e02e5e6Sdrh void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
32567e02e5e6Sdrh   int i;
3257a84203a0Sdrh   if( pList==0 || pList->nExpr==0 ){
32587e02e5e6Sdrh     sqlite3ExplainPrintf(pOut, "(empty-list)");
32597e02e5e6Sdrh     return;
3260a84203a0Sdrh   }else if( pList->nExpr==1 ){
3261a84203a0Sdrh     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
3262a84203a0Sdrh   }else{
32637e02e5e6Sdrh     sqlite3ExplainPush(pOut);
32647e02e5e6Sdrh     for(i=0; i<pList->nExpr; i++){
3265a84203a0Sdrh       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
32667e02e5e6Sdrh       sqlite3ExplainPush(pOut);
32677e02e5e6Sdrh       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
32687e02e5e6Sdrh       sqlite3ExplainPop(pOut);
32697e02e5e6Sdrh       if( i<pList->nExpr-1 ){
32707e02e5e6Sdrh         sqlite3ExplainNL(pOut);
32717e02e5e6Sdrh       }
32727e02e5e6Sdrh     }
32737e02e5e6Sdrh     sqlite3ExplainPop(pOut);
32747e02e5e6Sdrh   }
3275a84203a0Sdrh }
32767e02e5e6Sdrh #endif /* SQLITE_DEBUG */
32777e02e5e6Sdrh 
3278678ccce8Sdrh /*
327947de955eSdrh ** Return TRUE if pExpr is an constant expression that is appropriate
328047de955eSdrh ** for factoring out of a loop.  Appropriate expressions are:
328147de955eSdrh **
328247de955eSdrh **    *  Any expression that evaluates to two or more opcodes.
328347de955eSdrh **
328447de955eSdrh **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
328547de955eSdrh **       or OP_Variable that does not need to be placed in a
328647de955eSdrh **       specific register.
328747de955eSdrh **
328847de955eSdrh ** There is no point in factoring out single-instruction constant
328947de955eSdrh ** expressions that need to be placed in a particular register.
329047de955eSdrh ** We could factor them out, but then we would end up adding an
329147de955eSdrh ** OP_SCopy instruction to move the value into the correct register
329247de955eSdrh ** later.  We might as well just use the original instruction and
329347de955eSdrh ** avoid the OP_SCopy.
329447de955eSdrh */
329547de955eSdrh static int isAppropriateForFactoring(Expr *p){
329647de955eSdrh   if( !sqlite3ExprIsConstantNotJoin(p) ){
329747de955eSdrh     return 0;  /* Only constant expressions are appropriate for factoring */
329847de955eSdrh   }
329947de955eSdrh   if( (p->flags & EP_FixedDest)==0 ){
330047de955eSdrh     return 1;  /* Any constant without a fixed destination is appropriate */
330147de955eSdrh   }
330247de955eSdrh   while( p->op==TK_UPLUS ) p = p->pLeft;
330347de955eSdrh   switch( p->op ){
330447de955eSdrh #ifndef SQLITE_OMIT_BLOB_LITERAL
330547de955eSdrh     case TK_BLOB:
330647de955eSdrh #endif
330747de955eSdrh     case TK_VARIABLE:
330847de955eSdrh     case TK_INTEGER:
330947de955eSdrh     case TK_FLOAT:
331047de955eSdrh     case TK_NULL:
331147de955eSdrh     case TK_STRING: {
331247de955eSdrh       testcase( p->op==TK_BLOB );
331347de955eSdrh       testcase( p->op==TK_VARIABLE );
331447de955eSdrh       testcase( p->op==TK_INTEGER );
331547de955eSdrh       testcase( p->op==TK_FLOAT );
331647de955eSdrh       testcase( p->op==TK_NULL );
331747de955eSdrh       testcase( p->op==TK_STRING );
331847de955eSdrh       /* Single-instruction constants with a fixed destination are
331947de955eSdrh       ** better done in-line.  If we factor them, they will just end
332047de955eSdrh       ** up generating an OP_SCopy to move the value to the destination
332147de955eSdrh       ** register. */
332247de955eSdrh       return 0;
332347de955eSdrh     }
332447de955eSdrh     case TK_UMINUS: {
332547de955eSdrh       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
332647de955eSdrh         return 0;
332747de955eSdrh       }
332847de955eSdrh       break;
332947de955eSdrh     }
333047de955eSdrh     default: {
333147de955eSdrh       break;
333247de955eSdrh     }
333347de955eSdrh   }
333447de955eSdrh   return 1;
333547de955eSdrh }
333647de955eSdrh 
333747de955eSdrh /*
333847de955eSdrh ** If pExpr is a constant expression that is appropriate for
333947de955eSdrh ** factoring out of a loop, then evaluate the expression
3340678ccce8Sdrh ** into a register and convert the expression into a TK_REGISTER
3341678ccce8Sdrh ** expression.
3342678ccce8Sdrh */
33437d10d5a6Sdrh static int evalConstExpr(Walker *pWalker, Expr *pExpr){
33447d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
334547de955eSdrh   switch( pExpr->op ){
3346e05c929bSdrh     case TK_IN:
334747de955eSdrh     case TK_REGISTER: {
334833cd4909Sdrh       return WRC_Prune;
3349678ccce8Sdrh     }
335047de955eSdrh     case TK_FUNCTION:
335147de955eSdrh     case TK_AGG_FUNCTION:
335247de955eSdrh     case TK_CONST_FUNC: {
335347de955eSdrh       /* The arguments to a function have a fixed destination.
335447de955eSdrh       ** Mark them this way to avoid generated unneeded OP_SCopy
335547de955eSdrh       ** instructions.
335647de955eSdrh       */
33576ab3a2ecSdanielk1977       ExprList *pList = pExpr->x.pList;
33586ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
335947de955eSdrh       if( pList ){
336047de955eSdrh         int i = pList->nExpr;
336147de955eSdrh         struct ExprList_item *pItem = pList->a;
336247de955eSdrh         for(; i>0; i--, pItem++){
336333cd4909Sdrh           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
336447de955eSdrh         }
336547de955eSdrh       }
336647de955eSdrh       break;
336747de955eSdrh     }
336847de955eSdrh   }
336947de955eSdrh   if( isAppropriateForFactoring(pExpr) ){
3370678ccce8Sdrh     int r1 = ++pParse->nMem;
3371678ccce8Sdrh     int r2;
3372678ccce8Sdrh     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
33734b17cf58Sdrh     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
3374fcd4a150Sdan     pExpr->op2 = pExpr->op;
3375678ccce8Sdrh     pExpr->op = TK_REGISTER;
3376678ccce8Sdrh     pExpr->iTable = r2;
33777d10d5a6Sdrh     return WRC_Prune;
3378678ccce8Sdrh   }
33797d10d5a6Sdrh   return WRC_Continue;
3380678ccce8Sdrh }
3381678ccce8Sdrh 
3382678ccce8Sdrh /*
3383678ccce8Sdrh ** Preevaluate constant subexpressions within pExpr and store the
3384678ccce8Sdrh ** results in registers.  Modify pExpr so that the constant subexpresions
3385678ccce8Sdrh ** are TK_REGISTER opcodes that refer to the precomputed values.
3386f58ee7f1Sdrh **
3387f58ee7f1Sdrh ** This routine is a no-op if the jump to the cookie-check code has
3388f58ee7f1Sdrh ** already occur.  Since the cookie-check jump is generated prior to
3389f58ee7f1Sdrh ** any other serious processing, this check ensures that there is no
3390f58ee7f1Sdrh ** way to accidently bypass the constant initializations.
3391f58ee7f1Sdrh **
3392f58ee7f1Sdrh ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
3393f58ee7f1Sdrh ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
3394f58ee7f1Sdrh ** interface.  This allows test logic to verify that the same answer is
3395f58ee7f1Sdrh ** obtained for queries regardless of whether or not constants are
3396f58ee7f1Sdrh ** precomputed into registers or if they are inserted in-line.
3397678ccce8Sdrh */
3398678ccce8Sdrh void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
33997d10d5a6Sdrh   Walker w;
340048b5b041Sdrh   if( pParse->cookieGoto ) return;
34017e5418e4Sdrh   if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
34027d10d5a6Sdrh   w.xExprCallback = evalConstExpr;
3403ef4c0598Sdrh   w.xSelectCallback = 0;
34047d10d5a6Sdrh   w.pParse = pParse;
34057d10d5a6Sdrh   sqlite3WalkExpr(&w, pExpr);
3406678ccce8Sdrh }
3407678ccce8Sdrh 
340825303780Sdrh 
340925303780Sdrh /*
3410268380caSdrh ** Generate code that pushes the value of every element of the given
34119cbf3425Sdrh ** expression list into a sequence of registers beginning at target.
3412268380caSdrh **
3413892d3179Sdrh ** Return the number of elements evaluated.
3414268380caSdrh */
34154adee20fSdanielk1977 int sqlite3ExprCodeExprList(
3416268380caSdrh   Parse *pParse,     /* Parsing context */
3417389a1adbSdrh   ExprList *pList,   /* The expression list to be coded */
3418191b54cbSdrh   int target,        /* Where to write results */
3419d176611bSdrh   int doHardCopy     /* Make a hard copy of every element */
3420268380caSdrh ){
3421268380caSdrh   struct ExprList_item *pItem;
34229cbf3425Sdrh   int i, n;
34239d8b3072Sdrh   assert( pList!=0 );
34249cbf3425Sdrh   assert( target>0 );
3425d81a142bSdrh   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
3426268380caSdrh   n = pList->nExpr;
3427191b54cbSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
34287445ffe2Sdrh     Expr *pExpr = pItem->pExpr;
34297445ffe2Sdrh     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
3430746fd9ccSdrh     if( inReg!=target+i ){
34317445ffe2Sdrh       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
34327445ffe2Sdrh                         inReg, target+i);
3433d176611bSdrh     }
3434268380caSdrh   }
3435f9b596ebSdrh   return n;
3436268380caSdrh }
3437268380caSdrh 
3438268380caSdrh /*
343936c563a2Sdrh ** Generate code for a BETWEEN operator.
344036c563a2Sdrh **
344136c563a2Sdrh **    x BETWEEN y AND z
344236c563a2Sdrh **
344336c563a2Sdrh ** The above is equivalent to
344436c563a2Sdrh **
344536c563a2Sdrh **    x>=y AND x<=z
344636c563a2Sdrh **
344736c563a2Sdrh ** Code it as such, taking care to do the common subexpression
344836c563a2Sdrh ** elementation of x.
344936c563a2Sdrh */
345036c563a2Sdrh static void exprCodeBetween(
345136c563a2Sdrh   Parse *pParse,    /* Parsing and code generating context */
345236c563a2Sdrh   Expr *pExpr,      /* The BETWEEN expression */
345336c563a2Sdrh   int dest,         /* Jump here if the jump is taken */
345436c563a2Sdrh   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
345536c563a2Sdrh   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
345636c563a2Sdrh ){
345736c563a2Sdrh   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
345836c563a2Sdrh   Expr compLeft;    /* The  x>=y  term */
345936c563a2Sdrh   Expr compRight;   /* The  x<=z  term */
346036c563a2Sdrh   Expr exprX;       /* The  x  subexpression */
346136c563a2Sdrh   int regFree1 = 0; /* Temporary use register */
346236c563a2Sdrh 
346336c563a2Sdrh   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
346436c563a2Sdrh   exprX = *pExpr->pLeft;
346536c563a2Sdrh   exprAnd.op = TK_AND;
346636c563a2Sdrh   exprAnd.pLeft = &compLeft;
346736c563a2Sdrh   exprAnd.pRight = &compRight;
346836c563a2Sdrh   compLeft.op = TK_GE;
346936c563a2Sdrh   compLeft.pLeft = &exprX;
347036c563a2Sdrh   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
347136c563a2Sdrh   compRight.op = TK_LE;
347236c563a2Sdrh   compRight.pLeft = &exprX;
347336c563a2Sdrh   compRight.pRight = pExpr->x.pList->a[1].pExpr;
347436c563a2Sdrh   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
347536c563a2Sdrh   exprX.op = TK_REGISTER;
347636c563a2Sdrh   if( jumpIfTrue ){
347736c563a2Sdrh     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
347836c563a2Sdrh   }else{
347936c563a2Sdrh     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
348036c563a2Sdrh   }
348136c563a2Sdrh   sqlite3ReleaseTempReg(pParse, regFree1);
348236c563a2Sdrh 
348336c563a2Sdrh   /* Ensure adequate test coverage */
348436c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
348536c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
348636c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
348736c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
348836c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
348936c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
349036c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
349136c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
349236c563a2Sdrh }
349336c563a2Sdrh 
349436c563a2Sdrh /*
3495cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
3496cce7d176Sdrh ** to the label "dest" if the expression is true but execution
3497cce7d176Sdrh ** continues straight thru if the expression is false.
3498f5905aa7Sdrh **
3499f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
350035573356Sdrh ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
3501f2bc013cSdrh **
3502f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
3503f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3504f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
3505f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
3506f2bc013cSdrh ** below verify that the numbers are aligned correctly.
3507cce7d176Sdrh */
35084adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3509cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3510cce7d176Sdrh   int op = 0;
35112dcef11bSdrh   int regFree1 = 0;
35122dcef11bSdrh   int regFree2 = 0;
35132dcef11bSdrh   int r1, r2;
35142dcef11bSdrh 
351535573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
351633cd4909Sdrh   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
351733cd4909Sdrh   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
3518f2bc013cSdrh   op = pExpr->op;
3519f2bc013cSdrh   switch( op ){
3520cce7d176Sdrh     case TK_AND: {
35214adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3522c5499befSdrh       testcase( jumpIfNull==0 );
3523ceea3321Sdrh       sqlite3ExprCachePush(pParse);
352435573356Sdrh       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
35254adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
35264adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3527ceea3321Sdrh       sqlite3ExprCachePop(pParse, 1);
3528cce7d176Sdrh       break;
3529cce7d176Sdrh     }
3530cce7d176Sdrh     case TK_OR: {
3531c5499befSdrh       testcase( jumpIfNull==0 );
35324adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
35334adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3534cce7d176Sdrh       break;
3535cce7d176Sdrh     }
3536cce7d176Sdrh     case TK_NOT: {
3537c5499befSdrh       testcase( jumpIfNull==0 );
35384adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3539cce7d176Sdrh       break;
3540cce7d176Sdrh     }
3541cce7d176Sdrh     case TK_LT:
3542cce7d176Sdrh     case TK_LE:
3543cce7d176Sdrh     case TK_GT:
3544cce7d176Sdrh     case TK_GE:
3545cce7d176Sdrh     case TK_NE:
35460ac65892Sdrh     case TK_EQ: {
3547f2bc013cSdrh       assert( TK_LT==OP_Lt );
3548f2bc013cSdrh       assert( TK_LE==OP_Le );
3549f2bc013cSdrh       assert( TK_GT==OP_Gt );
3550f2bc013cSdrh       assert( TK_GE==OP_Ge );
3551f2bc013cSdrh       assert( TK_EQ==OP_Eq );
3552f2bc013cSdrh       assert( TK_NE==OP_Ne );
3553c5499befSdrh       testcase( op==TK_LT );
3554c5499befSdrh       testcase( op==TK_LE );
3555c5499befSdrh       testcase( op==TK_GT );
3556c5499befSdrh       testcase( op==TK_GE );
3557c5499befSdrh       testcase( op==TK_EQ );
3558c5499befSdrh       testcase( op==TK_NE );
3559c5499befSdrh       testcase( jumpIfNull==0 );
3560b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3561b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
356235573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
35632dcef11bSdrh                   r1, r2, dest, jumpIfNull);
3564c5499befSdrh       testcase( regFree1==0 );
3565c5499befSdrh       testcase( regFree2==0 );
3566cce7d176Sdrh       break;
3567cce7d176Sdrh     }
35686a2fe093Sdrh     case TK_IS:
35696a2fe093Sdrh     case TK_ISNOT: {
35706a2fe093Sdrh       testcase( op==TK_IS );
35716a2fe093Sdrh       testcase( op==TK_ISNOT );
3572b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3573b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
35746a2fe093Sdrh       op = (op==TK_IS) ? TK_EQ : TK_NE;
35756a2fe093Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
35766a2fe093Sdrh                   r1, r2, dest, SQLITE_NULLEQ);
35776a2fe093Sdrh       testcase( regFree1==0 );
35786a2fe093Sdrh       testcase( regFree2==0 );
35796a2fe093Sdrh       break;
35806a2fe093Sdrh     }
3581cce7d176Sdrh     case TK_ISNULL:
3582cce7d176Sdrh     case TK_NOTNULL: {
3583f2bc013cSdrh       assert( TK_ISNULL==OP_IsNull );
3584f2bc013cSdrh       assert( TK_NOTNULL==OP_NotNull );
3585c5499befSdrh       testcase( op==TK_ISNULL );
3586c5499befSdrh       testcase( op==TK_NOTNULL );
35872dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
35882dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
3589c5499befSdrh       testcase( regFree1==0 );
3590cce7d176Sdrh       break;
3591cce7d176Sdrh     }
3592fef5208cSdrh     case TK_BETWEEN: {
35935c03f30aSdrh       testcase( jumpIfNull==0 );
359436c563a2Sdrh       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
3595fef5208cSdrh       break;
3596fef5208cSdrh     }
3597bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
3598e3365e6cSdrh     case TK_IN: {
3599e3365e6cSdrh       int destIfFalse = sqlite3VdbeMakeLabel(v);
3600e3365e6cSdrh       int destIfNull = jumpIfNull ? dest : destIfFalse;
3601e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3602e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
3603e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
3604e3365e6cSdrh       break;
3605e3365e6cSdrh     }
3606bb201344Sshaneh #endif
3607cce7d176Sdrh     default: {
36082dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
36092dcef11bSdrh       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
3610c5499befSdrh       testcase( regFree1==0 );
3611c5499befSdrh       testcase( jumpIfNull==0 );
3612cce7d176Sdrh       break;
3613cce7d176Sdrh     }
3614cce7d176Sdrh   }
36152dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
36162dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3617cce7d176Sdrh }
3618cce7d176Sdrh 
3619cce7d176Sdrh /*
362066b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
3621cce7d176Sdrh ** to the label "dest" if the expression is false but execution
3622cce7d176Sdrh ** continues straight thru if the expression is true.
3623f5905aa7Sdrh **
3624f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
362535573356Sdrh ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
362635573356Sdrh ** is 0.
3627cce7d176Sdrh */
36284adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3629cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3630cce7d176Sdrh   int op = 0;
36312dcef11bSdrh   int regFree1 = 0;
36322dcef11bSdrh   int regFree2 = 0;
36332dcef11bSdrh   int r1, r2;
36342dcef11bSdrh 
363535573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
363633cd4909Sdrh   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
363733cd4909Sdrh   if( pExpr==0 )    return;
3638f2bc013cSdrh 
3639f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
3640f2bc013cSdrh   **
3641f2bc013cSdrh   **       pExpr->op            op
3642f2bc013cSdrh   **       ---------          ----------
3643f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
3644f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
3645f2bc013cSdrh   **       TK_NE              OP_Eq
3646f2bc013cSdrh   **       TK_EQ              OP_Ne
3647f2bc013cSdrh   **       TK_GT              OP_Le
3648f2bc013cSdrh   **       TK_LE              OP_Gt
3649f2bc013cSdrh   **       TK_GE              OP_Lt
3650f2bc013cSdrh   **       TK_LT              OP_Ge
3651f2bc013cSdrh   **
3652f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
3653f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
3654f2bc013cSdrh   ** can compute the mapping above using the following expression.
3655f2bc013cSdrh   ** Assert()s verify that the computation is correct.
3656f2bc013cSdrh   */
3657f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3658f2bc013cSdrh 
3659f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
3660f2bc013cSdrh   */
3661f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3662f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3663f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
3664f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
3665f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
3666f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
3667f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
3668f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
3669f2bc013cSdrh 
3670cce7d176Sdrh   switch( pExpr->op ){
3671cce7d176Sdrh     case TK_AND: {
3672c5499befSdrh       testcase( jumpIfNull==0 );
36734adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
36744adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3675cce7d176Sdrh       break;
3676cce7d176Sdrh     }
3677cce7d176Sdrh     case TK_OR: {
36784adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3679c5499befSdrh       testcase( jumpIfNull==0 );
3680ceea3321Sdrh       sqlite3ExprCachePush(pParse);
368135573356Sdrh       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
36824adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
36834adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3684ceea3321Sdrh       sqlite3ExprCachePop(pParse, 1);
3685cce7d176Sdrh       break;
3686cce7d176Sdrh     }
3687cce7d176Sdrh     case TK_NOT: {
36885c03f30aSdrh       testcase( jumpIfNull==0 );
36894adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3690cce7d176Sdrh       break;
3691cce7d176Sdrh     }
3692cce7d176Sdrh     case TK_LT:
3693cce7d176Sdrh     case TK_LE:
3694cce7d176Sdrh     case TK_GT:
3695cce7d176Sdrh     case TK_GE:
3696cce7d176Sdrh     case TK_NE:
3697cce7d176Sdrh     case TK_EQ: {
3698c5499befSdrh       testcase( op==TK_LT );
3699c5499befSdrh       testcase( op==TK_LE );
3700c5499befSdrh       testcase( op==TK_GT );
3701c5499befSdrh       testcase( op==TK_GE );
3702c5499befSdrh       testcase( op==TK_EQ );
3703c5499befSdrh       testcase( op==TK_NE );
3704c5499befSdrh       testcase( jumpIfNull==0 );
3705b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3706b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
370735573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
37082dcef11bSdrh                   r1, r2, dest, jumpIfNull);
3709c5499befSdrh       testcase( regFree1==0 );
3710c5499befSdrh       testcase( regFree2==0 );
3711cce7d176Sdrh       break;
3712cce7d176Sdrh     }
37136a2fe093Sdrh     case TK_IS:
37146a2fe093Sdrh     case TK_ISNOT: {
37156d4486aeSdrh       testcase( pExpr->op==TK_IS );
37166d4486aeSdrh       testcase( pExpr->op==TK_ISNOT );
3717b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3718b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
37196a2fe093Sdrh       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
37206a2fe093Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
37216a2fe093Sdrh                   r1, r2, dest, SQLITE_NULLEQ);
37226a2fe093Sdrh       testcase( regFree1==0 );
37236a2fe093Sdrh       testcase( regFree2==0 );
37246a2fe093Sdrh       break;
37256a2fe093Sdrh     }
3726cce7d176Sdrh     case TK_ISNULL:
3727cce7d176Sdrh     case TK_NOTNULL: {
3728c5499befSdrh       testcase( op==TK_ISNULL );
3729c5499befSdrh       testcase( op==TK_NOTNULL );
37302dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
37312dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
3732c5499befSdrh       testcase( regFree1==0 );
3733cce7d176Sdrh       break;
3734cce7d176Sdrh     }
3735fef5208cSdrh     case TK_BETWEEN: {
37365c03f30aSdrh       testcase( jumpIfNull==0 );
373736c563a2Sdrh       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
3738fef5208cSdrh       break;
3739fef5208cSdrh     }
3740bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
3741e3365e6cSdrh     case TK_IN: {
3742e3365e6cSdrh       if( jumpIfNull ){
3743e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
3744e3365e6cSdrh       }else{
3745e3365e6cSdrh         int destIfNull = sqlite3VdbeMakeLabel(v);
3746e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
3747e3365e6cSdrh         sqlite3VdbeResolveLabel(v, destIfNull);
3748e3365e6cSdrh       }
3749e3365e6cSdrh       break;
3750e3365e6cSdrh     }
3751bb201344Sshaneh #endif
3752cce7d176Sdrh     default: {
37532dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
37542dcef11bSdrh       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
3755c5499befSdrh       testcase( regFree1==0 );
3756c5499befSdrh       testcase( jumpIfNull==0 );
3757cce7d176Sdrh       break;
3758cce7d176Sdrh     }
3759cce7d176Sdrh   }
37602dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
37612dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3762cce7d176Sdrh }
37632282792aSdrh 
37642282792aSdrh /*
37651d9da70aSdrh ** Do a deep comparison of two expression trees.  Return 0 if the two
37661d9da70aSdrh ** expressions are completely identical.  Return 1 if they differ only
37671d9da70aSdrh ** by a COLLATE operator at the top level.  Return 2 if there are differences
37681d9da70aSdrh ** other than the top-level COLLATE operator.
3769d40aab0eSdrh **
37701d9da70aSdrh ** Sometimes this routine will return 2 even if the two expressions
3771d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
37721d9da70aSdrh ** identical, we return 2 just to be safe.  So if this routine
37731d9da70aSdrh ** returns 2, then you do not really know for certain if the two
37741d9da70aSdrh ** expressions are the same.  But if you get a 0 or 1 return, then you
3775d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
37761d9da70aSdrh ** this routine is used, it does not hurt to get an extra 2 - that
3777d40aab0eSdrh ** just might result in some slightly slower code.  But returning
37781d9da70aSdrh ** an incorrect 0 or 1 could lead to a malfunction.
37792282792aSdrh */
37804adee20fSdanielk1977 int sqlite3ExprCompare(Expr *pA, Expr *pB){
37814b202ae2Sdanielk1977   if( pA==0||pB==0 ){
37821d9da70aSdrh     return pB==pA ? 0 : 2;
37832282792aSdrh   }
378433e619fcSdrh   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
378533e619fcSdrh   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
37866ab3a2ecSdanielk1977   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
37871d9da70aSdrh     return 2;
37886ab3a2ecSdanielk1977   }
37891d9da70aSdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
3790ae80ddeaSdrh   if( pA->op!=pB->op ){
3791ae80ddeaSdrh     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
3792ae80ddeaSdrh       return 1;
3793ae80ddeaSdrh     }
3794ae80ddeaSdrh     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
3795ae80ddeaSdrh       return 1;
3796ae80ddeaSdrh     }
3797ae80ddeaSdrh     return 2;
3798ae80ddeaSdrh   }
37991d9da70aSdrh   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
38001d9da70aSdrh   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
38018c6f666bSdrh   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
38021d9da70aSdrh   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
380333e619fcSdrh   if( ExprHasProperty(pA, EP_IntValue) ){
380433e619fcSdrh     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
38051d9da70aSdrh       return 2;
380633e619fcSdrh     }
3807bbabe197Sdrh   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
38081d9da70aSdrh     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
38096b93c9aeSdrh     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
3810ae80ddeaSdrh       return pA->op==TK_COLLATE ? 1 : 2;
38111d9da70aSdrh     }
38121d9da70aSdrh   }
38134b17cf58Sdrh   if( (pA->flags&EP_Collate)!=(pB->flags&EP_Collate) ) return 1;
38142646da7eSdrh   return 0;
38152646da7eSdrh }
38162282792aSdrh 
38178c6f666bSdrh /*
38188c6f666bSdrh ** Compare two ExprList objects.  Return 0 if they are identical and
38198c6f666bSdrh ** non-zero if they differ in any way.
38208c6f666bSdrh **
38218c6f666bSdrh ** This routine might return non-zero for equivalent ExprLists.  The
38228c6f666bSdrh ** only consequence will be disabled optimizations.  But this routine
38238c6f666bSdrh ** must never return 0 if the two ExprList objects are different, or
38248c6f666bSdrh ** a malfunction will result.
38258c6f666bSdrh **
38268c6f666bSdrh ** Two NULL pointers are considered to be the same.  But a NULL pointer
38278c6f666bSdrh ** always differs from a non-NULL pointer.
38288c6f666bSdrh */
38298c6f666bSdrh int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
38308c6f666bSdrh   int i;
38318c6f666bSdrh   if( pA==0 && pB==0 ) return 0;
38328c6f666bSdrh   if( pA==0 || pB==0 ) return 1;
38338c6f666bSdrh   if( pA->nExpr!=pB->nExpr ) return 1;
38348c6f666bSdrh   for(i=0; i<pA->nExpr; i++){
38358c6f666bSdrh     Expr *pExprA = pA->a[i].pExpr;
38368c6f666bSdrh     Expr *pExprB = pB->a[i].pExpr;
38378c6f666bSdrh     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
38388c6f666bSdrh     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
38398c6f666bSdrh   }
38408c6f666bSdrh   return 0;
38418c6f666bSdrh }
384213449892Sdrh 
38432282792aSdrh /*
3844030796dfSdrh ** An instance of the following structure is used by the tree walker
3845030796dfSdrh ** to count references to table columns in the arguments of an
3846ed551b95Sdrh ** aggregate function, in order to implement the
3847ed551b95Sdrh ** sqlite3FunctionThisSrc() routine.
3848374fdce4Sdrh */
3849030796dfSdrh struct SrcCount {
3850030796dfSdrh   SrcList *pSrc;   /* One particular FROM clause in a nested query */
3851030796dfSdrh   int nThis;       /* Number of references to columns in pSrcList */
3852030796dfSdrh   int nOther;      /* Number of references to columns in other FROM clauses */
3853030796dfSdrh };
3854030796dfSdrh 
3855030796dfSdrh /*
3856030796dfSdrh ** Count the number of references to columns.
3857030796dfSdrh */
3858030796dfSdrh static int exprSrcCount(Walker *pWalker, Expr *pExpr){
3859fb0a6081Sdrh   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
3860fb0a6081Sdrh   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
3861fb0a6081Sdrh   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
3862fb0a6081Sdrh   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
3863fb0a6081Sdrh   ** NEVER() will need to be removed. */
3864fb0a6081Sdrh   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
3865374fdce4Sdrh     int i;
3866030796dfSdrh     struct SrcCount *p = pWalker->u.pSrcCount;
3867030796dfSdrh     SrcList *pSrc = p->pSrc;
3868374fdce4Sdrh     for(i=0; i<pSrc->nSrc; i++){
3869030796dfSdrh       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
3870374fdce4Sdrh     }
3871030796dfSdrh     if( i<pSrc->nSrc ){
3872030796dfSdrh       p->nThis++;
3873374fdce4Sdrh     }else{
3874030796dfSdrh       p->nOther++;
3875374fdce4Sdrh     }
3876374fdce4Sdrh   }
3877030796dfSdrh   return WRC_Continue;
3878030796dfSdrh }
3879374fdce4Sdrh 
3880374fdce4Sdrh /*
3881030796dfSdrh ** Determine if any of the arguments to the pExpr Function reference
3882030796dfSdrh ** pSrcList.  Return true if they do.  Also return true if the function
3883030796dfSdrh ** has no arguments or has only constant arguments.  Return false if pExpr
3884030796dfSdrh ** references columns but not columns of tables found in pSrcList.
3885374fdce4Sdrh */
3886030796dfSdrh int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
3887374fdce4Sdrh   Walker w;
3888030796dfSdrh   struct SrcCount cnt;
3889374fdce4Sdrh   assert( pExpr->op==TK_AGG_FUNCTION );
3890374fdce4Sdrh   memset(&w, 0, sizeof(w));
3891030796dfSdrh   w.xExprCallback = exprSrcCount;
3892030796dfSdrh   w.u.pSrcCount = &cnt;
3893030796dfSdrh   cnt.pSrc = pSrcList;
3894030796dfSdrh   cnt.nThis = 0;
3895030796dfSdrh   cnt.nOther = 0;
3896030796dfSdrh   sqlite3WalkExprList(&w, pExpr->x.pList);
3897030796dfSdrh   return cnt.nThis>0 || cnt.nOther==0;
3898374fdce4Sdrh }
3899374fdce4Sdrh 
3900374fdce4Sdrh /*
390113449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
390213449892Sdrh ** the new element.  Return a negative number if malloc fails.
39032282792aSdrh */
390417435752Sdrh static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
390513449892Sdrh   int i;
3906cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
390717435752Sdrh        db,
3908cf643729Sdrh        pInfo->aCol,
3909cf643729Sdrh        sizeof(pInfo->aCol[0]),
3910cf643729Sdrh        &pInfo->nColumn,
3911cf643729Sdrh        &i
3912cf643729Sdrh   );
391313449892Sdrh   return i;
39142282792aSdrh }
391513449892Sdrh 
391613449892Sdrh /*
391713449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
391813449892Sdrh ** the new element.  Return a negative number if malloc fails.
391913449892Sdrh */
392017435752Sdrh static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
392113449892Sdrh   int i;
3922cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
392317435752Sdrh        db,
3924cf643729Sdrh        pInfo->aFunc,
3925cf643729Sdrh        sizeof(pInfo->aFunc[0]),
3926cf643729Sdrh        &pInfo->nFunc,
3927cf643729Sdrh        &i
3928cf643729Sdrh   );
392913449892Sdrh   return i;
39302282792aSdrh }
39312282792aSdrh 
39322282792aSdrh /*
39337d10d5a6Sdrh ** This is the xExprCallback for a tree walker.  It is used to
39347d10d5a6Sdrh ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
3935626a879aSdrh ** for additional information.
39362282792aSdrh */
39377d10d5a6Sdrh static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
39382282792aSdrh   int i;
39397d10d5a6Sdrh   NameContext *pNC = pWalker->u.pNC;
3940a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
3941a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
394213449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
394313449892Sdrh 
39442282792aSdrh   switch( pExpr->op ){
394589c69d00Sdrh     case TK_AGG_COLUMN:
3946967e8b73Sdrh     case TK_COLUMN: {
39478b213899Sdrh       testcase( pExpr->op==TK_AGG_COLUMN );
39488b213899Sdrh       testcase( pExpr->op==TK_COLUMN );
394913449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
395013449892Sdrh       ** clause of the aggregate query */
395120bc393cSdrh       if( ALWAYS(pSrcList!=0) ){
395213449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
395313449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
395413449892Sdrh           struct AggInfo_col *pCol;
395533e619fcSdrh           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
395613449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
395713449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
395813449892Sdrh             ** that is in the FROM clause of the aggregate query.
395913449892Sdrh             **
396013449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
396113449892Sdrh             ** is not an entry there already.
396213449892Sdrh             */
39637f906d63Sdrh             int k;
396413449892Sdrh             pCol = pAggInfo->aCol;
39657f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
396613449892Sdrh               if( pCol->iTable==pExpr->iTable &&
396713449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
39682282792aSdrh                 break;
39692282792aSdrh               }
39702282792aSdrh             }
39711e536953Sdanielk1977             if( (k>=pAggInfo->nColumn)
39721e536953Sdanielk1977              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
39731e536953Sdanielk1977             ){
39747f906d63Sdrh               pCol = &pAggInfo->aCol[k];
39750817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
397613449892Sdrh               pCol->iTable = pExpr->iTable;
397713449892Sdrh               pCol->iColumn = pExpr->iColumn;
39780a07c107Sdrh               pCol->iMem = ++pParse->nMem;
397913449892Sdrh               pCol->iSorterColumn = -1;
39805774b806Sdrh               pCol->pExpr = pExpr;
398113449892Sdrh               if( pAggInfo->pGroupBy ){
398213449892Sdrh                 int j, n;
398313449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
398413449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
398513449892Sdrh                 n = pGB->nExpr;
398613449892Sdrh                 for(j=0; j<n; j++, pTerm++){
398713449892Sdrh                   Expr *pE = pTerm->pExpr;
398813449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
398913449892Sdrh                       pE->iColumn==pExpr->iColumn ){
399013449892Sdrh                     pCol->iSorterColumn = j;
399113449892Sdrh                     break;
39922282792aSdrh                   }
399313449892Sdrh                 }
399413449892Sdrh               }
399513449892Sdrh               if( pCol->iSorterColumn<0 ){
399613449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
399713449892Sdrh               }
399813449892Sdrh             }
399913449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
400013449892Sdrh             ** because it was there before or because we just created it).
400113449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
400213449892Sdrh             ** pAggInfo->aCol[] entry.
400313449892Sdrh             */
400433e619fcSdrh             ExprSetIrreducible(pExpr);
400513449892Sdrh             pExpr->pAggInfo = pAggInfo;
400613449892Sdrh             pExpr->op = TK_AGG_COLUMN;
4007cf697396Sshane             pExpr->iAgg = (i16)k;
400813449892Sdrh             break;
400913449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
401013449892Sdrh         } /* end loop over pSrcList */
4011a58fdfb1Sdanielk1977       }
40127d10d5a6Sdrh       return WRC_Prune;
40132282792aSdrh     }
40142282792aSdrh     case TK_AGG_FUNCTION: {
40153a8c4be7Sdrh       if( (pNC->ncFlags & NC_InAggFunc)==0
4016ed551b95Sdrh        && pWalker->walkerDepth==pExpr->op2
40173a8c4be7Sdrh       ){
401813449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
401913449892Sdrh         ** function that is already in the pAggInfo structure
402013449892Sdrh         */
402113449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
402213449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
40231d9da70aSdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
40242282792aSdrh             break;
40252282792aSdrh           }
40262282792aSdrh         }
402713449892Sdrh         if( i>=pAggInfo->nFunc ){
402813449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
402913449892Sdrh           */
403014db2665Sdanielk1977           u8 enc = ENC(pParse->db);
40311e536953Sdanielk1977           i = addAggInfoFunc(pParse->db, pAggInfo);
403213449892Sdrh           if( i>=0 ){
40336ab3a2ecSdanielk1977             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
403413449892Sdrh             pItem = &pAggInfo->aFunc[i];
403513449892Sdrh             pItem->pExpr = pExpr;
40360a07c107Sdrh             pItem->iMem = ++pParse->nMem;
403733e619fcSdrh             assert( !ExprHasProperty(pExpr, EP_IntValue) );
403813449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
403933e619fcSdrh                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
40406ab3a2ecSdanielk1977                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
4041fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
4042fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
4043fd357974Sdrh             }else{
4044fd357974Sdrh               pItem->iDistinct = -1;
4045fd357974Sdrh             }
40462282792aSdrh           }
404713449892Sdrh         }
404813449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
404913449892Sdrh         */
405033e619fcSdrh         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
405133e619fcSdrh         ExprSetIrreducible(pExpr);
4052cf697396Sshane         pExpr->iAgg = (i16)i;
405313449892Sdrh         pExpr->pAggInfo = pAggInfo;
40543a8c4be7Sdrh         return WRC_Prune;
40556e83a57fSdrh       }else{
40566e83a57fSdrh         return WRC_Continue;
40576e83a57fSdrh       }
40582282792aSdrh     }
4059a58fdfb1Sdanielk1977   }
40607d10d5a6Sdrh   return WRC_Continue;
40617d10d5a6Sdrh }
40627d10d5a6Sdrh static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
4063d5a336efSdrh   UNUSED_PARAMETER(pWalker);
4064d5a336efSdrh   UNUSED_PARAMETER(pSelect);
40657d10d5a6Sdrh   return WRC_Continue;
4066a58fdfb1Sdanielk1977 }
4067626a879aSdrh 
4068626a879aSdrh /*
4069e8abb4caSdrh ** Analyze the pExpr expression looking for aggregate functions and
4070e8abb4caSdrh ** for variables that need to be added to AggInfo object that pNC->pAggInfo
4071e8abb4caSdrh ** points to.  Additional entries are made on the AggInfo object as
4072e8abb4caSdrh ** necessary.
4073626a879aSdrh **
4074626a879aSdrh ** This routine should only be called after the expression has been
40757d10d5a6Sdrh ** analyzed by sqlite3ResolveExprNames().
4076626a879aSdrh */
4077d2b3e23bSdrh void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
40787d10d5a6Sdrh   Walker w;
4079374fdce4Sdrh   memset(&w, 0, sizeof(w));
40807d10d5a6Sdrh   w.xExprCallback = analyzeAggregate;
40817d10d5a6Sdrh   w.xSelectCallback = analyzeAggregatesInSelect;
40827d10d5a6Sdrh   w.u.pNC = pNC;
408320bc393cSdrh   assert( pNC->pSrcList!=0 );
40847d10d5a6Sdrh   sqlite3WalkExpr(&w, pExpr);
40852282792aSdrh }
40865d9a4af9Sdrh 
40875d9a4af9Sdrh /*
40885d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
40895d9a4af9Sdrh ** expression list.  Return the number of errors.
40905d9a4af9Sdrh **
40915d9a4af9Sdrh ** If an error is found, the analysis is cut short.
40925d9a4af9Sdrh */
4093d2b3e23bSdrh void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
40945d9a4af9Sdrh   struct ExprList_item *pItem;
40955d9a4af9Sdrh   int i;
40965d9a4af9Sdrh   if( pList ){
4097d2b3e23bSdrh     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4098d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
40995d9a4af9Sdrh     }
41005d9a4af9Sdrh   }
41015d9a4af9Sdrh }
4102892d3179Sdrh 
4103892d3179Sdrh /*
4104ceea3321Sdrh ** Allocate a single new register for use to hold some intermediate result.
4105892d3179Sdrh */
4106892d3179Sdrh int sqlite3GetTempReg(Parse *pParse){
4107e55cbd72Sdrh   if( pParse->nTempReg==0 ){
4108892d3179Sdrh     return ++pParse->nMem;
4109892d3179Sdrh   }
41102f425f6bSdanielk1977   return pParse->aTempReg[--pParse->nTempReg];
4111892d3179Sdrh }
4112ceea3321Sdrh 
4113ceea3321Sdrh /*
4114ceea3321Sdrh ** Deallocate a register, making available for reuse for some other
4115ceea3321Sdrh ** purpose.
4116ceea3321Sdrh **
4117ceea3321Sdrh ** If a register is currently being used by the column cache, then
4118ceea3321Sdrh ** the dallocation is deferred until the column cache line that uses
4119ceea3321Sdrh ** the register becomes stale.
4120ceea3321Sdrh */
4121892d3179Sdrh void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
41222dcef11bSdrh   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
4123ceea3321Sdrh     int i;
4124ceea3321Sdrh     struct yColCache *p;
4125ceea3321Sdrh     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4126ceea3321Sdrh       if( p->iReg==iReg ){
4127ceea3321Sdrh         p->tempReg = 1;
4128ceea3321Sdrh         return;
4129ceea3321Sdrh       }
4130ceea3321Sdrh     }
4131892d3179Sdrh     pParse->aTempReg[pParse->nTempReg++] = iReg;
4132892d3179Sdrh   }
4133892d3179Sdrh }
4134892d3179Sdrh 
4135892d3179Sdrh /*
4136892d3179Sdrh ** Allocate or deallocate a block of nReg consecutive registers
4137892d3179Sdrh */
4138892d3179Sdrh int sqlite3GetTempRange(Parse *pParse, int nReg){
4139e55cbd72Sdrh   int i, n;
4140892d3179Sdrh   i = pParse->iRangeReg;
4141e55cbd72Sdrh   n = pParse->nRangeReg;
4142f49f3523Sdrh   if( nReg<=n ){
4143f49f3523Sdrh     assert( !usedAsColumnCache(pParse, i, i+n-1) );
4144892d3179Sdrh     pParse->iRangeReg += nReg;
4145892d3179Sdrh     pParse->nRangeReg -= nReg;
4146892d3179Sdrh   }else{
4147892d3179Sdrh     i = pParse->nMem+1;
4148892d3179Sdrh     pParse->nMem += nReg;
4149892d3179Sdrh   }
4150892d3179Sdrh   return i;
4151892d3179Sdrh }
4152892d3179Sdrh void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
4153f49f3523Sdrh   sqlite3ExprCacheRemove(pParse, iReg, nReg);
4154892d3179Sdrh   if( nReg>pParse->nRangeReg ){
4155892d3179Sdrh     pParse->nRangeReg = nReg;
4156892d3179Sdrh     pParse->iRangeReg = iReg;
4157892d3179Sdrh   }
4158892d3179Sdrh }
4159cdc69557Sdrh 
4160cdc69557Sdrh /*
4161cdc69557Sdrh ** Mark all temporary registers as being unavailable for reuse.
4162cdc69557Sdrh */
4163cdc69557Sdrh void sqlite3ClearTempRegCache(Parse *pParse){
4164cdc69557Sdrh   pParse->nTempReg = 0;
4165cdc69557Sdrh   pParse->nRangeReg = 0;
4166cdc69557Sdrh }
4167