xref: /sqlite-3.40.0/src/expr.c (revision 2edc5fd7)
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 **
2560ec914cSpeter.d.reid ** i.e. the WHERE clause expressions 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){
34580c8c18Sdrh   int op;
35580c8c18Sdrh   pExpr = sqlite3ExprSkipCollate(pExpr);
369bec6fb3Smistachkin   if( pExpr->flags & EP_Generic ) return 0;
37580c8c18Sdrh   op = pExpr->op;
38487e262fSdrh   if( op==TK_SELECT ){
396ab3a2ecSdanielk1977     assert( pExpr->flags&EP_xIsSelect );
406ab3a2ecSdanielk1977     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
41a37cdde0Sdanielk1977   }
42487e262fSdrh #ifndef SQLITE_OMIT_CAST
43487e262fSdrh   if( op==TK_CAST ){
4433e619fcSdrh     assert( !ExprHasProperty(pExpr, EP_IntValue) );
45fdaac671Sdrh     return sqlite3AffinityType(pExpr->u.zToken, 0);
46487e262fSdrh   }
47487e262fSdrh #endif
48259a455fSdanielk1977   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
49259a455fSdanielk1977    && pExpr->pTab!=0
50259a455fSdanielk1977   ){
517d10d5a6Sdrh     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
527d10d5a6Sdrh     ** a TK_COLUMN but was previously evaluated and cached in a register */
537d10d5a6Sdrh     int j = pExpr->iColumn;
547d10d5a6Sdrh     if( j<0 ) return SQLITE_AFF_INTEGER;
557d10d5a6Sdrh     assert( pExpr->pTab && j<pExpr->pTab->nCol );
567d10d5a6Sdrh     return pExpr->pTab->aCol[j].affinity;
577d10d5a6Sdrh   }
58a37cdde0Sdanielk1977   return pExpr->affinity;
59a37cdde0Sdanielk1977 }
60a37cdde0Sdanielk1977 
6153db1458Sdrh /*
628b4c40d8Sdrh ** Set the collating sequence for expression pExpr to be the collating
63ae80ddeaSdrh ** sequence named by pToken.   Return a pointer to a new Expr node that
64ae80ddeaSdrh ** implements the COLLATE operator.
650a8a406eSdrh **
660a8a406eSdrh ** If a memory allocation error occurs, that fact is recorded in pParse->db
670a8a406eSdrh ** and the pExpr parameter is returned unchanged.
688b4c40d8Sdrh */
694ef7efadSdrh Expr *sqlite3ExprAddCollateToken(
704ef7efadSdrh   Parse *pParse,           /* Parsing context */
714ef7efadSdrh   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
7280103fc6Sdan   const Token *pCollName,  /* Name of collating sequence */
7380103fc6Sdan   int dequote              /* True to dequote pCollName */
744ef7efadSdrh ){
750a8a406eSdrh   if( pCollName->n>0 ){
7680103fc6Sdan     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
77ae80ddeaSdrh     if( pNew ){
78ae80ddeaSdrh       pNew->pLeft = pExpr;
79a4c3c87eSdrh       pNew->flags |= EP_Collate|EP_Skip;
800a8a406eSdrh       pExpr = pNew;
81ae80ddeaSdrh     }
820a8a406eSdrh   }
830a8a406eSdrh   return pExpr;
840a8a406eSdrh }
850a8a406eSdrh Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
860a8a406eSdrh   Token s;
87261d8a51Sdrh   assert( zC!=0 );
880a8a406eSdrh   s.z = zC;
890a8a406eSdrh   s.n = sqlite3Strlen30(s.z);
9080103fc6Sdan   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
910a8a406eSdrh }
920a8a406eSdrh 
930a8a406eSdrh /*
940b8d255cSdrh ** Skip over any TK_COLLATE operators and any unlikely()
95a4c3c87eSdrh ** or likelihood() function at the root of an expression.
960a8a406eSdrh */
970a8a406eSdrh Expr *sqlite3ExprSkipCollate(Expr *pExpr){
98a4c3c87eSdrh   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
99a4c3c87eSdrh     if( ExprHasProperty(pExpr, EP_Unlikely) ){
100cca9f3d2Sdrh       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
101cca9f3d2Sdrh       assert( pExpr->x.pList->nExpr>0 );
102a4c3c87eSdrh       assert( pExpr->op==TK_FUNCTION );
103cca9f3d2Sdrh       pExpr = pExpr->x.pList->a[0].pExpr;
104cca9f3d2Sdrh     }else{
1050b8d255cSdrh       assert( pExpr->op==TK_COLLATE );
106d91eba96Sdrh       pExpr = pExpr->pLeft;
107cca9f3d2Sdrh     }
108d91eba96Sdrh   }
1090a8a406eSdrh   return pExpr;
1108b4c40d8Sdrh }
1118b4c40d8Sdrh 
1128b4c40d8Sdrh /*
113ae80ddeaSdrh ** Return the collation sequence for the expression pExpr. If
114ae80ddeaSdrh ** there is no defined collating sequence, return NULL.
115ae80ddeaSdrh **
116ae80ddeaSdrh ** The collating sequence might be determined by a COLLATE operator
117ae80ddeaSdrh ** or by the presence of a column with a defined collating sequence.
118ae80ddeaSdrh ** COLLATE operators take first precedence.  Left operands take
119ae80ddeaSdrh ** precedence over right operands.
1200202b29eSdanielk1977 */
1217cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
122ae80ddeaSdrh   sqlite3 *db = pParse->db;
1237cedc8d4Sdanielk1977   CollSeq *pColl = 0;
1247d10d5a6Sdrh   Expr *p = pExpr;
125261d8a51Sdrh   while( p ){
126ae80ddeaSdrh     int op = p->op;
127fbb24d10Sdrh     if( p->flags & EP_Generic ) break;
128ae80ddeaSdrh     if( op==TK_CAST || op==TK_UPLUS ){
129ae80ddeaSdrh       p = p->pLeft;
130ae80ddeaSdrh       continue;
131ae80ddeaSdrh     }
13236e78309Sdan     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
1337a66da13Sdrh       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
134ae80ddeaSdrh       break;
135ae80ddeaSdrh     }
136a58d4a96Sdrh     if( (op==TK_AGG_COLUMN || op==TK_COLUMN
137ae80ddeaSdrh           || op==TK_REGISTER || op==TK_TRIGGER)
138a58d4a96Sdrh      && p->pTab!=0
139ae80ddeaSdrh     ){
1407d10d5a6Sdrh       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
1417d10d5a6Sdrh       ** a TK_COLUMN but was previously evaluated and cached in a register */
1427d10d5a6Sdrh       int j = p->iColumn;
1437d10d5a6Sdrh       if( j>=0 ){
144ae80ddeaSdrh         const char *zColl = p->pTab->aCol[j].zColl;
145c4a64facSdrh         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
1460202b29eSdanielk1977       }
1477d10d5a6Sdrh       break;
1487d10d5a6Sdrh     }
149ae80ddeaSdrh     if( p->flags & EP_Collate ){
1502308ed38Sdrh       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
1517d10d5a6Sdrh         p = p->pLeft;
152ae80ddeaSdrh       }else{
1532308ed38Sdrh         Expr *pNext  = p->pRight;
1546728cd91Sdrh         /* The Expr.x union is never used at the same time as Expr.pRight */
1556728cd91Sdrh         assert( p->x.pList==0 || p->pRight==0 );
1566728cd91Sdrh         /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
1576728cd91Sdrh         ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
1586728cd91Sdrh         ** least one EP_Collate. Thus the following two ALWAYS. */
1596728cd91Sdrh         if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
1602308ed38Sdrh           int i;
1616728cd91Sdrh           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
1622308ed38Sdrh             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
1632308ed38Sdrh               pNext = p->x.pList->a[i].pExpr;
1642308ed38Sdrh               break;
1652308ed38Sdrh             }
1662308ed38Sdrh           }
1672308ed38Sdrh         }
1682308ed38Sdrh         p = pNext;
169ae80ddeaSdrh       }
170ae80ddeaSdrh     }else{
171ae80ddeaSdrh       break;
172ae80ddeaSdrh     }
1730202b29eSdanielk1977   }
1747cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
1757cedc8d4Sdanielk1977     pColl = 0;
1767cedc8d4Sdanielk1977   }
1777cedc8d4Sdanielk1977   return pColl;
1780202b29eSdanielk1977 }
1790202b29eSdanielk1977 
1800202b29eSdanielk1977 /*
181626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
182626a879aSdrh ** type affinity of the other operand.  This routine returns the
18353db1458Sdrh ** type affinity that should be used for the comparison operator.
18453db1458Sdrh */
185e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
186bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
187e014a838Sdanielk1977   if( aff1 && aff2 ){
1888df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
1898df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
190e014a838Sdanielk1977     */
1918a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
192e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
193e014a838Sdanielk1977     }else{
19405883a34Sdrh       return SQLITE_AFF_BLOB;
195e014a838Sdanielk1977     }
196e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
1975f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
1985f6a87b3Sdrh     ** results directly.
199e014a838Sdanielk1977     */
20005883a34Sdrh     return SQLITE_AFF_BLOB;
201e014a838Sdanielk1977   }else{
202e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
203fe05af87Sdrh     assert( aff1==0 || aff2==0 );
204e014a838Sdanielk1977     return (aff1 + aff2);
205e014a838Sdanielk1977   }
206e014a838Sdanielk1977 }
207e014a838Sdanielk1977 
20853db1458Sdrh /*
20953db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
21053db1458Sdrh ** be applied to both operands prior to doing the comparison.
21153db1458Sdrh */
212e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
213e014a838Sdanielk1977   char aff;
214e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
215e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
2166a2fe093Sdrh           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
217e014a838Sdanielk1977   assert( pExpr->pLeft );
218bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
219e014a838Sdanielk1977   if( pExpr->pRight ){
220e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
2216ab3a2ecSdanielk1977   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2226ab3a2ecSdanielk1977     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
2236ab3a2ecSdanielk1977   }else if( !aff ){
22405883a34Sdrh     aff = SQLITE_AFF_BLOB;
225e014a838Sdanielk1977   }
226e014a838Sdanielk1977   return aff;
227e014a838Sdanielk1977 }
228e014a838Sdanielk1977 
229e014a838Sdanielk1977 /*
230e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
231e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
232e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
233e014a838Sdanielk1977 ** the comparison in pExpr.
234e014a838Sdanielk1977 */
235e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
236e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
2378a51256cSdrh   switch( aff ){
23805883a34Sdrh     case SQLITE_AFF_BLOB:
2398a51256cSdrh       return 1;
2408a51256cSdrh     case SQLITE_AFF_TEXT:
2418a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
2428a51256cSdrh     default:
2438a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
2448a51256cSdrh   }
245e014a838Sdanielk1977 }
246e014a838Sdanielk1977 
247a37cdde0Sdanielk1977 /*
24835573356Sdrh ** Return the P5 value that should be used for a binary comparison
249a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
250a37cdde0Sdanielk1977 */
25135573356Sdrh static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
25235573356Sdrh   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
2531bd10f8aSdrh   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
25435573356Sdrh   return aff;
255a37cdde0Sdanielk1977 }
256a37cdde0Sdanielk1977 
257a2e00042Sdrh /*
2580202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
2590202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
2600202b29eSdanielk1977 **
2610202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
2620202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
2630202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
2640202b29eSdanielk1977 ** type.
265bcbb04e5Sdanielk1977 **
266bcbb04e5Sdanielk1977 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
267bcbb04e5Sdanielk1977 ** it is not considered.
2680202b29eSdanielk1977 */
269bcbb04e5Sdanielk1977 CollSeq *sqlite3BinaryCompareCollSeq(
270bcbb04e5Sdanielk1977   Parse *pParse,
271bcbb04e5Sdanielk1977   Expr *pLeft,
272bcbb04e5Sdanielk1977   Expr *pRight
273bcbb04e5Sdanielk1977 ){
274ec41ddacSdrh   CollSeq *pColl;
275ec41ddacSdrh   assert( pLeft );
276ae80ddeaSdrh   if( pLeft->flags & EP_Collate ){
277ae80ddeaSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
278ae80ddeaSdrh   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
279ae80ddeaSdrh     pColl = sqlite3ExprCollSeq(pParse, pRight);
280ec41ddacSdrh   }else{
281ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
2820202b29eSdanielk1977     if( !pColl ){
2837cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
2840202b29eSdanielk1977     }
285ec41ddacSdrh   }
2860202b29eSdanielk1977   return pColl;
2870202b29eSdanielk1977 }
2880202b29eSdanielk1977 
2890202b29eSdanielk1977 /*
290be5c89acSdrh ** Generate code for a comparison operator.
291be5c89acSdrh */
292be5c89acSdrh static int codeCompare(
293be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
294be5c89acSdrh   Expr *pLeft,      /* The left operand */
295be5c89acSdrh   Expr *pRight,     /* The right operand */
296be5c89acSdrh   int opcode,       /* The comparison opcode */
29735573356Sdrh   int in1, int in2, /* Register holding operands */
298be5c89acSdrh   int dest,         /* Jump here if true.  */
299be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
300be5c89acSdrh ){
30135573356Sdrh   int p5;
30235573356Sdrh   int addr;
30335573356Sdrh   CollSeq *p4;
30435573356Sdrh 
30535573356Sdrh   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
30635573356Sdrh   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
30735573356Sdrh   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
30835573356Sdrh                            (void*)p4, P4_COLLSEQ);
3091bd10f8aSdrh   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
31035573356Sdrh   return addr;
311be5c89acSdrh }
312be5c89acSdrh 
3134b5255acSdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
3144b5255acSdanielk1977 /*
3154b5255acSdanielk1977 ** Check that argument nHeight is less than or equal to the maximum
3164b5255acSdanielk1977 ** expression depth allowed. If it is not, leave an error message in
3174b5255acSdanielk1977 ** pParse.
3184b5255acSdanielk1977 */
3197d10d5a6Sdrh int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
3204b5255acSdanielk1977   int rc = SQLITE_OK;
3214b5255acSdanielk1977   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
3224b5255acSdanielk1977   if( nHeight>mxHeight ){
3234b5255acSdanielk1977     sqlite3ErrorMsg(pParse,
3244b5255acSdanielk1977        "Expression tree is too large (maximum depth %d)", mxHeight
3254b5255acSdanielk1977     );
3264b5255acSdanielk1977     rc = SQLITE_ERROR;
3274b5255acSdanielk1977   }
3284b5255acSdanielk1977   return rc;
3294b5255acSdanielk1977 }
3304b5255acSdanielk1977 
3314b5255acSdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
3324b5255acSdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
3334b5255acSdanielk1977 ** of any expression tree referenced by the structure passed as the
3344b5255acSdanielk1977 ** first argument.
3354b5255acSdanielk1977 **
3364b5255acSdanielk1977 ** If this maximum height is greater than the current value pointed
3374b5255acSdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
3384b5255acSdanielk1977 ** value.
3394b5255acSdanielk1977 */
3404b5255acSdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
3414b5255acSdanielk1977   if( p ){
3424b5255acSdanielk1977     if( p->nHeight>*pnHeight ){
3434b5255acSdanielk1977       *pnHeight = p->nHeight;
3444b5255acSdanielk1977     }
3454b5255acSdanielk1977   }
3464b5255acSdanielk1977 }
3474b5255acSdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
3484b5255acSdanielk1977   if( p ){
3494b5255acSdanielk1977     int i;
3504b5255acSdanielk1977     for(i=0; i<p->nExpr; i++){
3514b5255acSdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
3524b5255acSdanielk1977     }
3534b5255acSdanielk1977   }
3544b5255acSdanielk1977 }
3554b5255acSdanielk1977 static void heightOfSelect(Select *p, int *pnHeight){
3564b5255acSdanielk1977   if( p ){
3574b5255acSdanielk1977     heightOfExpr(p->pWhere, pnHeight);
3584b5255acSdanielk1977     heightOfExpr(p->pHaving, pnHeight);
3594b5255acSdanielk1977     heightOfExpr(p->pLimit, pnHeight);
3604b5255acSdanielk1977     heightOfExpr(p->pOffset, pnHeight);
3614b5255acSdanielk1977     heightOfExprList(p->pEList, pnHeight);
3624b5255acSdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
3634b5255acSdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
3644b5255acSdanielk1977     heightOfSelect(p->pPrior, pnHeight);
3654b5255acSdanielk1977   }
3664b5255acSdanielk1977 }
3674b5255acSdanielk1977 
3684b5255acSdanielk1977 /*
3694b5255acSdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
3704b5255acSdanielk1977 ** argument. An expression with no children, Expr.pList or
3714b5255acSdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
3724b5255acSdanielk1977 ** has a height equal to the maximum height of any other
3734b5255acSdanielk1977 ** referenced Expr plus one.
3742308ed38Sdrh **
3752308ed38Sdrh ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
3762308ed38Sdrh ** if appropriate.
3774b5255acSdanielk1977 */
3784b5255acSdanielk1977 static void exprSetHeight(Expr *p){
3794b5255acSdanielk1977   int nHeight = 0;
3804b5255acSdanielk1977   heightOfExpr(p->pLeft, &nHeight);
3814b5255acSdanielk1977   heightOfExpr(p->pRight, &nHeight);
3826ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_xIsSelect) ){
3836ab3a2ecSdanielk1977     heightOfSelect(p->x.pSelect, &nHeight);
3842308ed38Sdrh   }else if( p->x.pList ){
3856ab3a2ecSdanielk1977     heightOfExprList(p->x.pList, &nHeight);
3862308ed38Sdrh     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
3876ab3a2ecSdanielk1977   }
3884b5255acSdanielk1977   p->nHeight = nHeight + 1;
3894b5255acSdanielk1977 }
3904b5255acSdanielk1977 
3914b5255acSdanielk1977 /*
3924b5255acSdanielk1977 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
3934b5255acSdanielk1977 ** the height is greater than the maximum allowed expression depth,
3944b5255acSdanielk1977 ** leave an error in pParse.
3952308ed38Sdrh **
3962308ed38Sdrh ** Also propagate all EP_Propagate flags from the Expr.x.pList into
3972308ed38Sdrh ** Expr.flags.
3984b5255acSdanielk1977 */
3992308ed38Sdrh void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
40074893a4cSdrh   if( pParse->nErr ) return;
4014b5255acSdanielk1977   exprSetHeight(p);
4027d10d5a6Sdrh   sqlite3ExprCheckHeight(pParse, p->nHeight);
4034b5255acSdanielk1977 }
4044b5255acSdanielk1977 
4054b5255acSdanielk1977 /*
4064b5255acSdanielk1977 ** Return the maximum height of any expression tree referenced
4074b5255acSdanielk1977 ** by the select statement passed as an argument.
4084b5255acSdanielk1977 */
4094b5255acSdanielk1977 int sqlite3SelectExprHeight(Select *p){
4104b5255acSdanielk1977   int nHeight = 0;
4114b5255acSdanielk1977   heightOfSelect(p, &nHeight);
4124b5255acSdanielk1977   return nHeight;
4134b5255acSdanielk1977 }
4142308ed38Sdrh #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
4152308ed38Sdrh /*
4162308ed38Sdrh ** Propagate all EP_Propagate flags from the Expr.x.pList into
4172308ed38Sdrh ** Expr.flags.
4182308ed38Sdrh */
4192308ed38Sdrh void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
4202308ed38Sdrh   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
4212308ed38Sdrh     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
4222308ed38Sdrh   }
4232308ed38Sdrh }
4244b5255acSdanielk1977 #define exprSetHeight(y)
4254b5255acSdanielk1977 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
4264b5255acSdanielk1977 
427be5c89acSdrh /*
428b7916a78Sdrh ** This routine is the core allocator for Expr nodes.
429b7916a78Sdrh **
430a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
431b7916a78Sdrh ** for this node and for the pToken argument is a single allocation
432b7916a78Sdrh ** obtained from sqlite3DbMalloc().  The calling function
433a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
434b7916a78Sdrh **
435b7916a78Sdrh ** If dequote is true, then the token (if it exists) is dequoted.
436e792b5b4Sdrh ** If dequote is false, no dequoting is performed.  The deQuote
437b7916a78Sdrh ** parameter is ignored if pToken is NULL or if the token does not
438b7916a78Sdrh ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
439b7916a78Sdrh ** then the EP_DblQuoted flag is set on the expression node.
44033e619fcSdrh **
44133e619fcSdrh ** Special case:  If op==TK_INTEGER and pToken points to a string that
44233e619fcSdrh ** can be translated into a 32-bit integer, then the token is not
44333e619fcSdrh ** stored in u.zToken.  Instead, the integer values is written
44433e619fcSdrh ** into u.iValue and the EP_IntValue flag is set.  No extra storage
44533e619fcSdrh ** is allocated to hold the integer text and the dequote flag is ignored.
446a76b5dfcSdrh */
447b7916a78Sdrh Expr *sqlite3ExprAlloc(
448a1644fd8Sdanielk1977   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
44917435752Sdrh   int op,                 /* Expression opcode */
450b7916a78Sdrh   const Token *pToken,    /* Token argument.  Might be NULL */
451b7916a78Sdrh   int dequote             /* True to dequote */
45217435752Sdrh ){
453a76b5dfcSdrh   Expr *pNew;
45433e619fcSdrh   int nExtra = 0;
455cf697396Sshane   int iValue = 0;
456b7916a78Sdrh 
457b7916a78Sdrh   if( pToken ){
45833e619fcSdrh     if( op!=TK_INTEGER || pToken->z==0
45933e619fcSdrh           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
460b7916a78Sdrh       nExtra = pToken->n+1;
461d50ffc41Sdrh       assert( iValue>=0 );
46233e619fcSdrh     }
463a76b5dfcSdrh   }
464b7916a78Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
465b7916a78Sdrh   if( pNew ){
4661bd10f8aSdrh     pNew->op = (u8)op;
467a58fdfb1Sdanielk1977     pNew->iAgg = -1;
468a76b5dfcSdrh     if( pToken ){
46933e619fcSdrh       if( nExtra==0 ){
47033e619fcSdrh         pNew->flags |= EP_IntValue;
47133e619fcSdrh         pNew->u.iValue = iValue;
47233e619fcSdrh       }else{
473d9da78a2Sdrh         int c;
47433e619fcSdrh         pNew->u.zToken = (char*)&pNew[1];
475b07028f7Sdrh         assert( pToken->z!=0 || pToken->n==0 );
476b07028f7Sdrh         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
47733e619fcSdrh         pNew->u.zToken[pToken->n] = 0;
478b7916a78Sdrh         if( dequote && nExtra>=3
479d9da78a2Sdrh              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
48033e619fcSdrh           sqlite3Dequote(pNew->u.zToken);
48124fb627aSdrh           if( c=='"' ) pNew->flags |= EP_DblQuoted;
482a34001c9Sdrh         }
483a34001c9Sdrh       }
48433e619fcSdrh     }
485b7916a78Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
486b7916a78Sdrh     pNew->nHeight = 1;
487b7916a78Sdrh #endif
488a34001c9Sdrh   }
489a76b5dfcSdrh   return pNew;
490a76b5dfcSdrh }
491a76b5dfcSdrh 
492a76b5dfcSdrh /*
493b7916a78Sdrh ** Allocate a new expression node from a zero-terminated token that has
494b7916a78Sdrh ** already been dequoted.
495b7916a78Sdrh */
496b7916a78Sdrh Expr *sqlite3Expr(
497b7916a78Sdrh   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
498b7916a78Sdrh   int op,                 /* Expression opcode */
499b7916a78Sdrh   const char *zToken      /* Token argument.  Might be NULL */
500b7916a78Sdrh ){
501b7916a78Sdrh   Token x;
502b7916a78Sdrh   x.z = zToken;
503b7916a78Sdrh   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
504b7916a78Sdrh   return sqlite3ExprAlloc(db, op, &x, 0);
505b7916a78Sdrh }
506b7916a78Sdrh 
507b7916a78Sdrh /*
508b7916a78Sdrh ** Attach subtrees pLeft and pRight to the Expr node pRoot.
509b7916a78Sdrh **
510b7916a78Sdrh ** If pRoot==NULL that means that a memory allocation error has occurred.
511b7916a78Sdrh ** In that case, delete the subtrees pLeft and pRight.
512b7916a78Sdrh */
513b7916a78Sdrh void sqlite3ExprAttachSubtrees(
514b7916a78Sdrh   sqlite3 *db,
515b7916a78Sdrh   Expr *pRoot,
516b7916a78Sdrh   Expr *pLeft,
517b7916a78Sdrh   Expr *pRight
518b7916a78Sdrh ){
519b7916a78Sdrh   if( pRoot==0 ){
520b7916a78Sdrh     assert( db->mallocFailed );
521b7916a78Sdrh     sqlite3ExprDelete(db, pLeft);
522b7916a78Sdrh     sqlite3ExprDelete(db, pRight);
523b7916a78Sdrh   }else{
524b7916a78Sdrh     if( pRight ){
525b7916a78Sdrh       pRoot->pRight = pRight;
526885a5b03Sdrh       pRoot->flags |= EP_Propagate & pRight->flags;
527b7916a78Sdrh     }
528b7916a78Sdrh     if( pLeft ){
529b7916a78Sdrh       pRoot->pLeft = pLeft;
530885a5b03Sdrh       pRoot->flags |= EP_Propagate & pLeft->flags;
531b7916a78Sdrh     }
532b7916a78Sdrh     exprSetHeight(pRoot);
533b7916a78Sdrh   }
534b7916a78Sdrh }
535b7916a78Sdrh 
536b7916a78Sdrh /*
53760ec914cSpeter.d.reid ** Allocate an Expr node which joins as many as two subtrees.
538b7916a78Sdrh **
539bf664469Sdrh ** One or both of the subtrees can be NULL.  Return a pointer to the new
540bf664469Sdrh ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
541bf664469Sdrh ** free the subtrees and return NULL.
542206f3d96Sdrh */
54317435752Sdrh Expr *sqlite3PExpr(
54417435752Sdrh   Parse *pParse,          /* Parsing context */
54517435752Sdrh   int op,                 /* Expression opcode */
54617435752Sdrh   Expr *pLeft,            /* Left operand */
54717435752Sdrh   Expr *pRight,           /* Right operand */
54817435752Sdrh   const Token *pToken     /* Argument token */
54917435752Sdrh ){
5505fb52caaSdrh   Expr *p;
5511167d327Sdrh   if( op==TK_AND && pParse->nErr==0 ){
5525fb52caaSdrh     /* Take advantage of short-circuit false optimization for AND */
5535fb52caaSdrh     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
5545fb52caaSdrh   }else{
5551167d327Sdrh     p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
556b7916a78Sdrh     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
5575fb52caaSdrh   }
5582b359bdbSdan   if( p ) {
5592b359bdbSdan     sqlite3ExprCheckHeight(pParse, p->nHeight);
5602b359bdbSdan   }
5614e0cff60Sdrh   return p;
5624e0cff60Sdrh }
5634e0cff60Sdrh 
5644e0cff60Sdrh /*
565991a1985Sdrh ** If the expression is always either TRUE or FALSE (respectively),
566991a1985Sdrh ** then return 1.  If one cannot determine the truth value of the
567991a1985Sdrh ** expression at compile-time return 0.
568991a1985Sdrh **
569991a1985Sdrh ** This is an optimization.  If is OK to return 0 here even if
570991a1985Sdrh ** the expression really is always false or false (a false negative).
571991a1985Sdrh ** But it is a bug to return 1 if the expression might have different
572991a1985Sdrh ** boolean values in different circumstances (a false positive.)
5735fb52caaSdrh **
5745fb52caaSdrh ** Note that if the expression is part of conditional for a
5755fb52caaSdrh ** LEFT JOIN, then we cannot determine at compile-time whether or not
5765fb52caaSdrh ** is it true or false, so always return 0.
5775fb52caaSdrh */
578991a1985Sdrh static int exprAlwaysTrue(Expr *p){
579991a1985Sdrh   int v = 0;
580991a1985Sdrh   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
581991a1985Sdrh   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
582991a1985Sdrh   return v!=0;
583991a1985Sdrh }
5845fb52caaSdrh static int exprAlwaysFalse(Expr *p){
5855fb52caaSdrh   int v = 0;
5865fb52caaSdrh   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
5875fb52caaSdrh   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
5885fb52caaSdrh   return v==0;
5895fb52caaSdrh }
5905fb52caaSdrh 
5915fb52caaSdrh /*
59291bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
59391bb0eedSdrh ** NULL, then just return the other expression.
5945fb52caaSdrh **
5955fb52caaSdrh ** If one side or the other of the AND is known to be false, then instead
5965fb52caaSdrh ** of returning an AND expression, just return a constant expression with
5975fb52caaSdrh ** a value of false.
59891bb0eedSdrh */
5991e536953Sdanielk1977 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
60091bb0eedSdrh   if( pLeft==0 ){
60191bb0eedSdrh     return pRight;
60291bb0eedSdrh   }else if( pRight==0 ){
60391bb0eedSdrh     return pLeft;
6045fb52caaSdrh   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
6055fb52caaSdrh     sqlite3ExprDelete(db, pLeft);
6065fb52caaSdrh     sqlite3ExprDelete(db, pRight);
6075fb52caaSdrh     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
60891bb0eedSdrh   }else{
609b7916a78Sdrh     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
610b7916a78Sdrh     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
611b7916a78Sdrh     return pNew;
612a76b5dfcSdrh   }
613a76b5dfcSdrh }
614a76b5dfcSdrh 
615a76b5dfcSdrh /*
616a76b5dfcSdrh ** Construct a new expression node for a function with multiple
617a76b5dfcSdrh ** arguments.
618a76b5dfcSdrh */
61917435752Sdrh Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
620a76b5dfcSdrh   Expr *pNew;
621633e6d57Sdrh   sqlite3 *db = pParse->db;
6224b202ae2Sdanielk1977   assert( pToken );
623b7916a78Sdrh   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
624a76b5dfcSdrh   if( pNew==0 ){
625d9da78a2Sdrh     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
626a76b5dfcSdrh     return 0;
627a76b5dfcSdrh   }
6286ab3a2ecSdanielk1977   pNew->x.pList = pList;
6296ab3a2ecSdanielk1977   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
6302308ed38Sdrh   sqlite3ExprSetHeightAndFlags(pParse, pNew);
631a76b5dfcSdrh   return pNew;
632a76b5dfcSdrh }
633a76b5dfcSdrh 
634a76b5dfcSdrh /*
635fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
636fa6bc000Sdrh ** in the original SQL statement.
637fa6bc000Sdrh **
638fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
639fa6bc000Sdrh ** variable number.
640fa6bc000Sdrh **
641fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
642fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
643fa6bc000Sdrh ** the SQL statement comes from an external source.
644fa6bc000Sdrh **
64551f49f17Sdrh ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
646fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
64760ec914cSpeter.d.reid ** instance of the wildcard, the next sequential variable number is
648fa6bc000Sdrh ** assigned.
649fa6bc000Sdrh */
650fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
65117435752Sdrh   sqlite3 *db = pParse->db;
652b7916a78Sdrh   const char *z;
65317435752Sdrh 
654fa6bc000Sdrh   if( pExpr==0 ) return;
655c5cd1249Sdrh   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
65633e619fcSdrh   z = pExpr->u.zToken;
657b7916a78Sdrh   assert( z!=0 );
658b7916a78Sdrh   assert( z[0]!=0 );
659b7916a78Sdrh   if( z[1]==0 ){
660fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
661b7916a78Sdrh     assert( z[0]=='?' );
6628677d308Sdrh     pExpr->iColumn = (ynVar)(++pParse->nVar);
663124c0b49Sdrh   }else{
664124c0b49Sdrh     ynVar x = 0;
665124c0b49Sdrh     u32 n = sqlite3Strlen30(z);
666124c0b49Sdrh     if( z[0]=='?' ){
667fa6bc000Sdrh       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
668fa6bc000Sdrh       ** use it as the variable number */
669c8d735aeSdan       i64 i;
670124c0b49Sdrh       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
671124c0b49Sdrh       pExpr->iColumn = x = (ynVar)i;
672c5499befSdrh       testcase( i==0 );
673c5499befSdrh       testcase( i==1 );
674c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
675c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
676c8d735aeSdan       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
677fa6bc000Sdrh         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
678bb4957f8Sdrh             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
679124c0b49Sdrh         x = 0;
680fa6bc000Sdrh       }
681fa6bc000Sdrh       if( i>pParse->nVar ){
6821df2db7fSshaneh         pParse->nVar = (int)i;
683fa6bc000Sdrh       }
684fa6bc000Sdrh     }else{
68551f49f17Sdrh       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
686fa6bc000Sdrh       ** number as the prior appearance of the same name, or if the name
687fa6bc000Sdrh       ** has never appeared before, reuse the same variable number
688fa6bc000Sdrh       */
689124c0b49Sdrh       ynVar i;
690124c0b49Sdrh       for(i=0; i<pParse->nzVar; i++){
691503a686eSdrh         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
692124c0b49Sdrh           pExpr->iColumn = x = (ynVar)i+1;
693fa6bc000Sdrh           break;
694fa6bc000Sdrh         }
695fa6bc000Sdrh       }
696124c0b49Sdrh       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
697fa6bc000Sdrh     }
698124c0b49Sdrh     if( x>0 ){
699124c0b49Sdrh       if( x>pParse->nzVar ){
700124c0b49Sdrh         char **a;
701124c0b49Sdrh         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
702124c0b49Sdrh         if( a==0 ) return;  /* Error reported through db->mallocFailed */
703124c0b49Sdrh         pParse->azVar = a;
704124c0b49Sdrh         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
705124c0b49Sdrh         pParse->nzVar = x;
706124c0b49Sdrh       }
707124c0b49Sdrh       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
708124c0b49Sdrh         sqlite3DbFree(db, pParse->azVar[x-1]);
709124c0b49Sdrh         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
710fa6bc000Sdrh       }
711fa6bc000Sdrh     }
712fa6bc000Sdrh   }
713bb4957f8Sdrh   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
714832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
715832b2664Sdanielk1977   }
716fa6bc000Sdrh }
717fa6bc000Sdrh 
718fa6bc000Sdrh /*
719f6963f99Sdan ** Recursively delete an expression tree.
720a2e00042Sdrh */
721f6963f99Sdan void sqlite3ExprDelete(sqlite3 *db, Expr *p){
722f6963f99Sdan   if( p==0 ) return;
723d50ffc41Sdrh   /* Sanity check: Assert that the IntValue is non-negative if it exists */
724d50ffc41Sdrh   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
725c5cd1249Sdrh   if( !ExprHasProperty(p, EP_TokenOnly) ){
726c5cd1249Sdrh     /* The Expr.x union is never used at the same time as Expr.pRight */
727c5cd1249Sdrh     assert( p->x.pList==0 || p->pRight==0 );
728633e6d57Sdrh     sqlite3ExprDelete(db, p->pLeft);
729633e6d57Sdrh     sqlite3ExprDelete(db, p->pRight);
730c5cd1249Sdrh     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
7316ab3a2ecSdanielk1977     if( ExprHasProperty(p, EP_xIsSelect) ){
7326ab3a2ecSdanielk1977       sqlite3SelectDelete(db, p->x.pSelect);
7336ab3a2ecSdanielk1977     }else{
7346ab3a2ecSdanielk1977       sqlite3ExprListDelete(db, p->x.pList);
7356ab3a2ecSdanielk1977     }
7366ab3a2ecSdanielk1977   }
73733e619fcSdrh   if( !ExprHasProperty(p, EP_Static) ){
738633e6d57Sdrh     sqlite3DbFree(db, p);
739a2e00042Sdrh   }
74033e619fcSdrh }
741a2e00042Sdrh 
742d2687b77Sdrh /*
7436ab3a2ecSdanielk1977 ** Return the number of bytes allocated for the expression structure
7446ab3a2ecSdanielk1977 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
7456ab3a2ecSdanielk1977 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
7466ab3a2ecSdanielk1977 */
7476ab3a2ecSdanielk1977 static int exprStructSize(Expr *p){
7486ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
7496ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
7506ab3a2ecSdanielk1977   return EXPR_FULLSIZE;
7516ab3a2ecSdanielk1977 }
7526ab3a2ecSdanielk1977 
7536ab3a2ecSdanielk1977 /*
75433e619fcSdrh ** The dupedExpr*Size() routines each return the number of bytes required
75533e619fcSdrh ** to store a copy of an expression or expression tree.  They differ in
75633e619fcSdrh ** how much of the tree is measured.
75733e619fcSdrh **
75833e619fcSdrh **     dupedExprStructSize()     Size of only the Expr structure
75933e619fcSdrh **     dupedExprNodeSize()       Size of Expr + space for token
76033e619fcSdrh **     dupedExprSize()           Expr + token + subtree components
76133e619fcSdrh **
76233e619fcSdrh ***************************************************************************
76333e619fcSdrh **
76433e619fcSdrh ** The dupedExprStructSize() function returns two values OR-ed together:
76533e619fcSdrh ** (1) the space required for a copy of the Expr structure only and
76633e619fcSdrh ** (2) the EP_xxx flags that indicate what the structure size should be.
76733e619fcSdrh ** The return values is always one of:
76833e619fcSdrh **
76933e619fcSdrh **      EXPR_FULLSIZE
77033e619fcSdrh **      EXPR_REDUCEDSIZE   | EP_Reduced
77133e619fcSdrh **      EXPR_TOKENONLYSIZE | EP_TokenOnly
77233e619fcSdrh **
77333e619fcSdrh ** The size of the structure can be found by masking the return value
77433e619fcSdrh ** of this routine with 0xfff.  The flags can be found by masking the
77533e619fcSdrh ** return value with EP_Reduced|EP_TokenOnly.
77633e619fcSdrh **
77733e619fcSdrh ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
77833e619fcSdrh ** (unreduced) Expr objects as they or originally constructed by the parser.
77933e619fcSdrh ** During expression analysis, extra information is computed and moved into
78033e619fcSdrh ** later parts of teh Expr object and that extra information might get chopped
78133e619fcSdrh ** off if the expression is reduced.  Note also that it does not work to
78260ec914cSpeter.d.reid ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
78333e619fcSdrh ** to reduce a pristine expression tree from the parser.  The implementation
78433e619fcSdrh ** of dupedExprStructSize() contain multiple assert() statements that attempt
78533e619fcSdrh ** to enforce this constraint.
7866ab3a2ecSdanielk1977 */
7876ab3a2ecSdanielk1977 static int dupedExprStructSize(Expr *p, int flags){
7886ab3a2ecSdanielk1977   int nSize;
78933e619fcSdrh   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
790aecd8021Sdrh   assert( EXPR_FULLSIZE<=0xfff );
791aecd8021Sdrh   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
7926ab3a2ecSdanielk1977   if( 0==(flags&EXPRDUP_REDUCE) ){
7936ab3a2ecSdanielk1977     nSize = EXPR_FULLSIZE;
7946ab3a2ecSdanielk1977   }else{
795c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
79633e619fcSdrh     assert( !ExprHasProperty(p, EP_FromJoin) );
797c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_MemToken) );
798ebb6a65dSdrh     assert( !ExprHasProperty(p, EP_NoReduce) );
799aecd8021Sdrh     if( p->pLeft || p->x.pList ){
80033e619fcSdrh       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
80133e619fcSdrh     }else{
802aecd8021Sdrh       assert( p->pRight==0 );
80333e619fcSdrh       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
80433e619fcSdrh     }
8056ab3a2ecSdanielk1977   }
8066ab3a2ecSdanielk1977   return nSize;
8076ab3a2ecSdanielk1977 }
8086ab3a2ecSdanielk1977 
8096ab3a2ecSdanielk1977 /*
81033e619fcSdrh ** This function returns the space in bytes required to store the copy
81133e619fcSdrh ** of the Expr structure and a copy of the Expr.u.zToken string (if that
81233e619fcSdrh ** string is defined.)
8136ab3a2ecSdanielk1977 */
8146ab3a2ecSdanielk1977 static int dupedExprNodeSize(Expr *p, int flags){
81533e619fcSdrh   int nByte = dupedExprStructSize(p, flags) & 0xfff;
81633e619fcSdrh   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
81733e619fcSdrh     nByte += sqlite3Strlen30(p->u.zToken)+1;
8186ab3a2ecSdanielk1977   }
819bc73971dSdanielk1977   return ROUND8(nByte);
8206ab3a2ecSdanielk1977 }
8216ab3a2ecSdanielk1977 
8226ab3a2ecSdanielk1977 /*
8236ab3a2ecSdanielk1977 ** Return the number of bytes required to create a duplicate of the
8246ab3a2ecSdanielk1977 ** expression passed as the first argument. The second argument is a
8256ab3a2ecSdanielk1977 ** mask containing EXPRDUP_XXX flags.
8266ab3a2ecSdanielk1977 **
8276ab3a2ecSdanielk1977 ** The value returned includes space to create a copy of the Expr struct
82833e619fcSdrh ** itself and the buffer referred to by Expr.u.zToken, if any.
8296ab3a2ecSdanielk1977 **
8306ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
8316ab3a2ecSdanielk1977 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
8326ab3a2ecSdanielk1977 ** and Expr.pRight variables (but not for any structures pointed to or
8336ab3a2ecSdanielk1977 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
8346ab3a2ecSdanielk1977 */
8356ab3a2ecSdanielk1977 static int dupedExprSize(Expr *p, int flags){
8366ab3a2ecSdanielk1977   int nByte = 0;
8376ab3a2ecSdanielk1977   if( p ){
8386ab3a2ecSdanielk1977     nByte = dupedExprNodeSize(p, flags);
8396ab3a2ecSdanielk1977     if( flags&EXPRDUP_REDUCE ){
840b7916a78Sdrh       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
8416ab3a2ecSdanielk1977     }
8426ab3a2ecSdanielk1977   }
8436ab3a2ecSdanielk1977   return nByte;
8446ab3a2ecSdanielk1977 }
8456ab3a2ecSdanielk1977 
8466ab3a2ecSdanielk1977 /*
8476ab3a2ecSdanielk1977 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
8486ab3a2ecSdanielk1977 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
84933e619fcSdrh ** to store the copy of expression p, the copies of p->u.zToken
8506ab3a2ecSdanielk1977 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
85160ec914cSpeter.d.reid ** if any. Before returning, *pzBuffer is set to the first byte past the
8526ab3a2ecSdanielk1977 ** portion of the buffer copied into by this function.
8536ab3a2ecSdanielk1977 */
8546ab3a2ecSdanielk1977 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
8556ab3a2ecSdanielk1977   Expr *pNew = 0;                      /* Value to return */
8566ab3a2ecSdanielk1977   if( p ){
8576ab3a2ecSdanielk1977     const int isReduced = (flags&EXPRDUP_REDUCE);
8586ab3a2ecSdanielk1977     u8 *zAlloc;
85933e619fcSdrh     u32 staticFlag = 0;
8606ab3a2ecSdanielk1977 
8616ab3a2ecSdanielk1977     assert( pzBuffer==0 || isReduced );
8626ab3a2ecSdanielk1977 
8636ab3a2ecSdanielk1977     /* Figure out where to write the new Expr structure. */
8646ab3a2ecSdanielk1977     if( pzBuffer ){
8656ab3a2ecSdanielk1977       zAlloc = *pzBuffer;
86633e619fcSdrh       staticFlag = EP_Static;
8676ab3a2ecSdanielk1977     }else{
8686ab3a2ecSdanielk1977       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
8696ab3a2ecSdanielk1977     }
8706ab3a2ecSdanielk1977     pNew = (Expr *)zAlloc;
8716ab3a2ecSdanielk1977 
8726ab3a2ecSdanielk1977     if( pNew ){
8736ab3a2ecSdanielk1977       /* Set nNewSize to the size allocated for the structure pointed to
8746ab3a2ecSdanielk1977       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
8756ab3a2ecSdanielk1977       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
87633e619fcSdrh       ** by the copy of the p->u.zToken string (if any).
8776ab3a2ecSdanielk1977       */
87833e619fcSdrh       const unsigned nStructSize = dupedExprStructSize(p, flags);
87933e619fcSdrh       const int nNewSize = nStructSize & 0xfff;
88033e619fcSdrh       int nToken;
88133e619fcSdrh       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
88233e619fcSdrh         nToken = sqlite3Strlen30(p->u.zToken) + 1;
88333e619fcSdrh       }else{
88433e619fcSdrh         nToken = 0;
88533e619fcSdrh       }
8866ab3a2ecSdanielk1977       if( isReduced ){
8876ab3a2ecSdanielk1977         assert( ExprHasProperty(p, EP_Reduced)==0 );
8886ab3a2ecSdanielk1977         memcpy(zAlloc, p, nNewSize);
8896ab3a2ecSdanielk1977       }else{
8906ab3a2ecSdanielk1977         int nSize = exprStructSize(p);
8916ab3a2ecSdanielk1977         memcpy(zAlloc, p, nSize);
8926ab3a2ecSdanielk1977         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
8936ab3a2ecSdanielk1977       }
8946ab3a2ecSdanielk1977 
89533e619fcSdrh       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
896c5cd1249Sdrh       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
89733e619fcSdrh       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
89833e619fcSdrh       pNew->flags |= staticFlag;
8996ab3a2ecSdanielk1977 
90033e619fcSdrh       /* Copy the p->u.zToken string, if any. */
9016ab3a2ecSdanielk1977       if( nToken ){
90233e619fcSdrh         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
90333e619fcSdrh         memcpy(zToken, p->u.zToken, nToken);
9046ab3a2ecSdanielk1977       }
9056ab3a2ecSdanielk1977 
9066ab3a2ecSdanielk1977       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
9076ab3a2ecSdanielk1977         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
9086ab3a2ecSdanielk1977         if( ExprHasProperty(p, EP_xIsSelect) ){
9096ab3a2ecSdanielk1977           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
9106ab3a2ecSdanielk1977         }else{
9116ab3a2ecSdanielk1977           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
9126ab3a2ecSdanielk1977         }
9136ab3a2ecSdanielk1977       }
9146ab3a2ecSdanielk1977 
9156ab3a2ecSdanielk1977       /* Fill in pNew->pLeft and pNew->pRight. */
916c5cd1249Sdrh       if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
9176ab3a2ecSdanielk1977         zAlloc += dupedExprNodeSize(p, flags);
9186ab3a2ecSdanielk1977         if( ExprHasProperty(pNew, EP_Reduced) ){
9196ab3a2ecSdanielk1977           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
9206ab3a2ecSdanielk1977           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
9216ab3a2ecSdanielk1977         }
9226ab3a2ecSdanielk1977         if( pzBuffer ){
9236ab3a2ecSdanielk1977           *pzBuffer = zAlloc;
9246ab3a2ecSdanielk1977         }
925b7916a78Sdrh       }else{
926c5cd1249Sdrh         if( !ExprHasProperty(p, EP_TokenOnly) ){
9276ab3a2ecSdanielk1977           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
9286ab3a2ecSdanielk1977           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
9296ab3a2ecSdanielk1977         }
9306ab3a2ecSdanielk1977       }
931b7916a78Sdrh 
932b7916a78Sdrh     }
9336ab3a2ecSdanielk1977   }
9346ab3a2ecSdanielk1977   return pNew;
9356ab3a2ecSdanielk1977 }
9366ab3a2ecSdanielk1977 
9376ab3a2ecSdanielk1977 /*
938bfe31e7fSdan ** Create and return a deep copy of the object passed as the second
939bfe31e7fSdan ** argument. If an OOM condition is encountered, NULL is returned
940bfe31e7fSdan ** and the db->mallocFailed flag set.
941bfe31e7fSdan */
942eede6a53Sdan #ifndef SQLITE_OMIT_CTE
943bfe31e7fSdan static With *withDup(sqlite3 *db, With *p){
9444e9119d9Sdan   With *pRet = 0;
9454e9119d9Sdan   if( p ){
9464e9119d9Sdan     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
9474e9119d9Sdan     pRet = sqlite3DbMallocZero(db, nByte);
9484e9119d9Sdan     if( pRet ){
9494e9119d9Sdan       int i;
9504e9119d9Sdan       pRet->nCte = p->nCte;
9514e9119d9Sdan       for(i=0; i<p->nCte; i++){
9524e9119d9Sdan         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
9534e9119d9Sdan         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
9544e9119d9Sdan         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
9554e9119d9Sdan       }
9564e9119d9Sdan     }
9574e9119d9Sdan   }
9584e9119d9Sdan   return pRet;
9594e9119d9Sdan }
960eede6a53Sdan #else
961eede6a53Sdan # define withDup(x,y) 0
962eede6a53Sdan #endif
9634e9119d9Sdan 
964a76b5dfcSdrh /*
965ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
966ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
967ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
968ff78bd2fSdrh ** without effecting the originals.
969ff78bd2fSdrh **
9704adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
9714adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
972ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
973ff78bd2fSdrh **
974ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
9756ab3a2ecSdanielk1977 **
976b7916a78Sdrh ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
9776ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
9786ab3a2ecSdanielk1977 ** truncated version of the usual Expr structure that will be stored as
9796ab3a2ecSdanielk1977 ** part of the in-memory representation of the database schema.
980ff78bd2fSdrh */
9816ab3a2ecSdanielk1977 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
9826ab3a2ecSdanielk1977   return exprDup(db, p, flags, 0);
983ff78bd2fSdrh }
9846ab3a2ecSdanielk1977 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
985ff78bd2fSdrh   ExprList *pNew;
986145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
987ff78bd2fSdrh   int i;
988ff78bd2fSdrh   if( p==0 ) return 0;
98917435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
990ff78bd2fSdrh   if( pNew==0 ) return 0;
991d872bb18Sdrh   pNew->nExpr = i = p->nExpr;
992d872bb18Sdrh   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
993d872bb18Sdrh   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
994e0048400Sdanielk1977   if( pItem==0 ){
995633e6d57Sdrh     sqlite3DbFree(db, pNew);
996e0048400Sdanielk1977     return 0;
997e0048400Sdanielk1977   }
998145716b3Sdrh   pOldItem = p->a;
999145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
10006ab3a2ecSdanielk1977     Expr *pOldExpr = pOldItem->pExpr;
1001b5526ea6Sdrh     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
100217435752Sdrh     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1003b7916a78Sdrh     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
1004145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
10053e7bc9caSdrh     pItem->done = 0;
10062c036cffSdrh     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
1007c2acc4e4Sdrh     pItem->u = pOldItem->u;
1008ff78bd2fSdrh   }
1009ff78bd2fSdrh   return pNew;
1010ff78bd2fSdrh }
101193758c8dSdanielk1977 
101293758c8dSdanielk1977 /*
101393758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
101493758c8dSdanielk1977 ** the build, then none of the following routines, except for
101593758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
101693758c8dSdanielk1977 ** called with a NULL argument.
101793758c8dSdanielk1977 */
10186a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
10196a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
10206ab3a2ecSdanielk1977 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1021ad3cab52Sdrh   SrcList *pNew;
1022ad3cab52Sdrh   int i;
1023113088ecSdrh   int nByte;
1024ad3cab52Sdrh   if( p==0 ) return 0;
1025113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
102617435752Sdrh   pNew = sqlite3DbMallocRaw(db, nByte );
1027ad3cab52Sdrh   if( pNew==0 ) return 0;
10284305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
1029ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
10304efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
10314efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
1032ed8a3bb1Sdrh     Table *pTab;
103341fb5cd1Sdan     pNewItem->pSchema = pOldItem->pSchema;
103417435752Sdrh     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
103517435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
103617435752Sdrh     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
10378a48b9c0Sdrh     pNewItem->fg = pOldItem->fg;
10384efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
10395b6a9ed4Sdrh     pNewItem->addrFillSub = pOldItem->addrFillSub;
10405b6a9ed4Sdrh     pNewItem->regReturn = pOldItem->regReturn;
10418a48b9c0Sdrh     if( pNewItem->fg.isIndexedBy ){
10428a48b9c0Sdrh       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
10438a48b9c0Sdrh     }
10448a48b9c0Sdrh     pNewItem->pIBIndex = pOldItem->pIBIndex;
10458a48b9c0Sdrh     if( pNewItem->fg.isTabFunc ){
10468a48b9c0Sdrh       pNewItem->u1.pFuncArg =
10478a48b9c0Sdrh           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
10488a48b9c0Sdrh     }
1049ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
1050ed8a3bb1Sdrh     if( pTab ){
1051ed8a3bb1Sdrh       pTab->nRef++;
1052a1cb183dSdanielk1977     }
10536ab3a2ecSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
10546ab3a2ecSdanielk1977     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
105517435752Sdrh     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
10566c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
1057ad3cab52Sdrh   }
1058ad3cab52Sdrh   return pNew;
1059ad3cab52Sdrh }
106017435752Sdrh IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1061ff78bd2fSdrh   IdList *pNew;
1062ff78bd2fSdrh   int i;
1063ff78bd2fSdrh   if( p==0 ) return 0;
106417435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
1065ff78bd2fSdrh   if( pNew==0 ) return 0;
10666c535158Sdrh   pNew->nId = p->nId;
106717435752Sdrh   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
1068d5d56523Sdanielk1977   if( pNew->a==0 ){
1069633e6d57Sdrh     sqlite3DbFree(db, pNew);
1070d5d56523Sdanielk1977     return 0;
1071d5d56523Sdanielk1977   }
10726c535158Sdrh   /* Note that because the size of the allocation for p->a[] is not
10736c535158Sdrh   ** necessarily a power of two, sqlite3IdListAppend() may not be called
10746c535158Sdrh   ** on the duplicate created by this function. */
1075ff78bd2fSdrh   for(i=0; i<p->nId; i++){
10764efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
10774efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
107817435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
10794efc4754Sdrh     pNewItem->idx = pOldItem->idx;
1080ff78bd2fSdrh   }
1081ff78bd2fSdrh   return pNew;
1082ff78bd2fSdrh }
10836ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
108423b1b372Sdrh   Select *pNew, *pPrior;
1085ff78bd2fSdrh   if( p==0 ) return 0;
108617435752Sdrh   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
1087ff78bd2fSdrh   if( pNew==0 ) return 0;
1088b7916a78Sdrh   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
10896ab3a2ecSdanielk1977   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
10906ab3a2ecSdanielk1977   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
10916ab3a2ecSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
10926ab3a2ecSdanielk1977   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
10936ab3a2ecSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1094ff78bd2fSdrh   pNew->op = p->op;
109523b1b372Sdrh   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
109623b1b372Sdrh   if( pPrior ) pPrior->pNext = pNew;
109723b1b372Sdrh   pNew->pNext = 0;
10986ab3a2ecSdanielk1977   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
10996ab3a2ecSdanielk1977   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
110092b01d53Sdrh   pNew->iLimit = 0;
110192b01d53Sdrh   pNew->iOffset = 0;
11027d10d5a6Sdrh   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1103b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
1104b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
1105ec2da854Sdrh   pNew->nSelectRow = p->nSelectRow;
11064e9119d9Sdan   pNew->pWith = withDup(db, p->pWith);
1107eb9b884cSdrh   sqlite3SelectSetName(pNew, p->zSelName);
1108ff78bd2fSdrh   return pNew;
1109ff78bd2fSdrh }
111093758c8dSdanielk1977 #else
11116ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
111293758c8dSdanielk1977   assert( p==0 );
111393758c8dSdanielk1977   return 0;
111493758c8dSdanielk1977 }
111593758c8dSdanielk1977 #endif
1116ff78bd2fSdrh 
1117ff78bd2fSdrh 
1118ff78bd2fSdrh /*
1119a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
1120a76b5dfcSdrh ** initially NULL, then create a new expression list.
1121b7916a78Sdrh **
1122b7916a78Sdrh ** If a memory allocation error occurs, the entire list is freed and
1123b7916a78Sdrh ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1124b7916a78Sdrh ** that the new entry was successfully appended.
1125a76b5dfcSdrh */
112617435752Sdrh ExprList *sqlite3ExprListAppend(
112717435752Sdrh   Parse *pParse,          /* Parsing context */
112817435752Sdrh   ExprList *pList,        /* List to which to append. Might be NULL */
1129b7916a78Sdrh   Expr *pExpr             /* Expression to be appended. Might be NULL */
113017435752Sdrh ){
113117435752Sdrh   sqlite3 *db = pParse->db;
1132a76b5dfcSdrh   if( pList==0 ){
113317435752Sdrh     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
1134a76b5dfcSdrh     if( pList==0 ){
1135d5d56523Sdanielk1977       goto no_mem;
1136a76b5dfcSdrh     }
1137d872bb18Sdrh     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
1138d872bb18Sdrh     if( pList->a==0 ) goto no_mem;
1139d872bb18Sdrh   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
1140d5d56523Sdanielk1977     struct ExprList_item *a;
1141d872bb18Sdrh     assert( pList->nExpr>0 );
1142d872bb18Sdrh     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
1143d5d56523Sdanielk1977     if( a==0 ){
1144d5d56523Sdanielk1977       goto no_mem;
1145a76b5dfcSdrh     }
1146d5d56523Sdanielk1977     pList->a = a;
1147a76b5dfcSdrh   }
11484efc4754Sdrh   assert( pList->a!=0 );
1149b7916a78Sdrh   if( 1 ){
11504efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
11514efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
1152e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
1153a76b5dfcSdrh   }
1154a76b5dfcSdrh   return pList;
1155d5d56523Sdanielk1977 
1156d5d56523Sdanielk1977 no_mem:
1157d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
1158633e6d57Sdrh   sqlite3ExprDelete(db, pExpr);
1159633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1160d5d56523Sdanielk1977   return 0;
1161a76b5dfcSdrh }
1162a76b5dfcSdrh 
1163a76b5dfcSdrh /*
1164bc622bc0Sdrh ** Set the sort order for the last element on the given ExprList.
1165bc622bc0Sdrh */
1166bc622bc0Sdrh void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1167bc622bc0Sdrh   if( p==0 ) return;
1168bc622bc0Sdrh   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1169bc622bc0Sdrh   assert( p->nExpr>0 );
1170bc622bc0Sdrh   if( iSortOrder<0 ){
1171bc622bc0Sdrh     assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1172bc622bc0Sdrh     return;
1173bc622bc0Sdrh   }
1174bc622bc0Sdrh   p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
1175bc622bc0Sdrh }
1176bc622bc0Sdrh 
1177bc622bc0Sdrh /*
1178b7916a78Sdrh ** Set the ExprList.a[].zName element of the most recently added item
1179b7916a78Sdrh ** on the expression list.
1180b7916a78Sdrh **
1181b7916a78Sdrh ** pList might be NULL following an OOM error.  But pName should never be
1182b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1183b7916a78Sdrh ** is set.
1184b7916a78Sdrh */
1185b7916a78Sdrh void sqlite3ExprListSetName(
1186b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1187b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1188b7916a78Sdrh   Token *pName,           /* Name to be added */
1189b7916a78Sdrh   int dequote             /* True to cause the name to be dequoted */
1190b7916a78Sdrh ){
1191b7916a78Sdrh   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1192b7916a78Sdrh   if( pList ){
1193b7916a78Sdrh     struct ExprList_item *pItem;
1194b7916a78Sdrh     assert( pList->nExpr>0 );
1195b7916a78Sdrh     pItem = &pList->a[pList->nExpr-1];
1196b7916a78Sdrh     assert( pItem->zName==0 );
1197b7916a78Sdrh     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1198b7916a78Sdrh     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
1199b7916a78Sdrh   }
1200b7916a78Sdrh }
1201b7916a78Sdrh 
1202b7916a78Sdrh /*
1203b7916a78Sdrh ** Set the ExprList.a[].zSpan element of the most recently added item
1204b7916a78Sdrh ** on the expression list.
1205b7916a78Sdrh **
1206b7916a78Sdrh ** pList might be NULL following an OOM error.  But pSpan should never be
1207b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1208b7916a78Sdrh ** is set.
1209b7916a78Sdrh */
1210b7916a78Sdrh void sqlite3ExprListSetSpan(
1211b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1212b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1213b7916a78Sdrh   ExprSpan *pSpan         /* The span to be added */
1214b7916a78Sdrh ){
1215b7916a78Sdrh   sqlite3 *db = pParse->db;
1216b7916a78Sdrh   assert( pList!=0 || db->mallocFailed!=0 );
1217b7916a78Sdrh   if( pList ){
1218b7916a78Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1219b7916a78Sdrh     assert( pList->nExpr>0 );
1220b7916a78Sdrh     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1221b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1222b7916a78Sdrh     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1223cf697396Sshane                                     (int)(pSpan->zEnd - pSpan->zStart));
1224b7916a78Sdrh   }
1225b7916a78Sdrh }
1226b7916a78Sdrh 
1227b7916a78Sdrh /*
12287a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
12297a15a4beSdanielk1977 ** leave an error message in pParse.
12307a15a4beSdanielk1977 */
12317a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
12327a15a4beSdanielk1977   Parse *pParse,
12337a15a4beSdanielk1977   ExprList *pEList,
12347a15a4beSdanielk1977   const char *zObject
12357a15a4beSdanielk1977 ){
1236b1a6c3c1Sdrh   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1237c5499befSdrh   testcase( pEList && pEList->nExpr==mx );
1238c5499befSdrh   testcase( pEList && pEList->nExpr==mx+1 );
1239b1a6c3c1Sdrh   if( pEList && pEList->nExpr>mx ){
12407a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
12417a15a4beSdanielk1977   }
12427a15a4beSdanielk1977 }
12437a15a4beSdanielk1977 
12447a15a4beSdanielk1977 /*
1245a76b5dfcSdrh ** Delete an entire expression list.
1246a76b5dfcSdrh */
1247633e6d57Sdrh void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1248a76b5dfcSdrh   int i;
1249be5c89acSdrh   struct ExprList_item *pItem;
1250a76b5dfcSdrh   if( pList==0 ) return;
1251d872bb18Sdrh   assert( pList->a!=0 || pList->nExpr==0 );
1252be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1253633e6d57Sdrh     sqlite3ExprDelete(db, pItem->pExpr);
1254633e6d57Sdrh     sqlite3DbFree(db, pItem->zName);
1255b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1256a76b5dfcSdrh   }
1257633e6d57Sdrh   sqlite3DbFree(db, pList->a);
1258633e6d57Sdrh   sqlite3DbFree(db, pList);
1259a76b5dfcSdrh }
1260a76b5dfcSdrh 
1261a76b5dfcSdrh /*
12622308ed38Sdrh ** Return the bitwise-OR of all Expr.flags fields in the given
12632308ed38Sdrh ** ExprList.
1264885a5b03Sdrh */
12652308ed38Sdrh u32 sqlite3ExprListFlags(const ExprList *pList){
1266885a5b03Sdrh   int i;
12672308ed38Sdrh   u32 m = 0;
12682308ed38Sdrh   if( pList ){
1269885a5b03Sdrh     for(i=0; i<pList->nExpr; i++){
1270d0c73053Sdrh        Expr *pExpr = pList->a[i].pExpr;
12710a96931bSdrh        if( ALWAYS(pExpr) ) m |= pExpr->flags;
1272885a5b03Sdrh     }
12732308ed38Sdrh   }
12742308ed38Sdrh   return m;
1275885a5b03Sdrh }
1276885a5b03Sdrh 
1277885a5b03Sdrh /*
1278059b2d50Sdrh ** These routines are Walker callbacks used to check expressions to
1279059b2d50Sdrh ** see if they are "constant" for some definition of constant.  The
1280059b2d50Sdrh ** Walker.eCode value determines the type of "constant" we are looking
1281059b2d50Sdrh ** for.
128273b211abSdrh **
12837d10d5a6Sdrh ** These callback routines are used to implement the following:
1284626a879aSdrh **
1285059b2d50Sdrh **     sqlite3ExprIsConstant()                  pWalker->eCode==1
1286059b2d50Sdrh **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
1287fcb9f4f3Sdrh **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
1288059b2d50Sdrh **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
128987abf5c0Sdrh **
1290059b2d50Sdrh ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1291059b2d50Sdrh ** is found to not be a constant.
129287abf5c0Sdrh **
1293feada2dfSdrh ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
1294059b2d50Sdrh ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
1295059b2d50Sdrh ** an existing schema and 4 when processing a new statement.  A bound
1296feada2dfSdrh ** parameter raises an error for new statements, but is silently converted
1297feada2dfSdrh ** to NULL for existing schemas.  This allows sqlite_master tables that
1298feada2dfSdrh ** contain a bound parameter because they were generated by older versions
1299feada2dfSdrh ** of SQLite to be parsed by newer versions of SQLite without raising a
1300feada2dfSdrh ** malformed schema error.
1301626a879aSdrh */
13027d10d5a6Sdrh static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1303626a879aSdrh 
1304059b2d50Sdrh   /* If pWalker->eCode is 2 then any term of the expression that comes from
1305059b2d50Sdrh   ** the ON or USING clauses of a left join disqualifies the expression
13060a168377Sdrh   ** from being considered constant. */
1307059b2d50Sdrh   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1308059b2d50Sdrh     pWalker->eCode = 0;
13097d10d5a6Sdrh     return WRC_Abort;
13100a168377Sdrh   }
13110a168377Sdrh 
1312626a879aSdrh   switch( pExpr->op ){
1313eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
1314059b2d50Sdrh     ** and either pWalker->eCode==4 or 5 or the function has the
1315059b2d50Sdrh     ** SQLITE_FUNC_CONST flag. */
1316eb55bd2fSdrh     case TK_FUNCTION:
131763f84573Sdrh       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
1318b1fba286Sdrh         return WRC_Continue;
1319059b2d50Sdrh       }else{
1320059b2d50Sdrh         pWalker->eCode = 0;
1321059b2d50Sdrh         return WRC_Abort;
1322b1fba286Sdrh       }
1323626a879aSdrh     case TK_ID:
1324626a879aSdrh     case TK_COLUMN:
1325626a879aSdrh     case TK_AGG_FUNCTION:
132613449892Sdrh     case TK_AGG_COLUMN:
1327c5499befSdrh       testcase( pExpr->op==TK_ID );
1328c5499befSdrh       testcase( pExpr->op==TK_COLUMN );
1329c5499befSdrh       testcase( pExpr->op==TK_AGG_FUNCTION );
1330c5499befSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1331059b2d50Sdrh       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1332059b2d50Sdrh         return WRC_Continue;
1333059b2d50Sdrh       }else{
1334059b2d50Sdrh         pWalker->eCode = 0;
13357d10d5a6Sdrh         return WRC_Abort;
1336059b2d50Sdrh       }
1337feada2dfSdrh     case TK_VARIABLE:
1338059b2d50Sdrh       if( pWalker->eCode==5 ){
1339feada2dfSdrh         /* Silently convert bound parameters that appear inside of CREATE
1340feada2dfSdrh         ** statements into a NULL when parsing the CREATE statement text out
1341feada2dfSdrh         ** of the sqlite_master table */
1342feada2dfSdrh         pExpr->op = TK_NULL;
1343059b2d50Sdrh       }else if( pWalker->eCode==4 ){
1344feada2dfSdrh         /* A bound parameter in a CREATE statement that originates from
1345feada2dfSdrh         ** sqlite3_prepare() causes an error */
1346059b2d50Sdrh         pWalker->eCode = 0;
1347feada2dfSdrh         return WRC_Abort;
1348feada2dfSdrh       }
1349feada2dfSdrh       /* Fall through */
1350626a879aSdrh     default:
1351b74b1017Sdrh       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1352b74b1017Sdrh       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
13537d10d5a6Sdrh       return WRC_Continue;
1354626a879aSdrh   }
1355626a879aSdrh }
135662c14b34Sdanielk1977 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
135762c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
1358059b2d50Sdrh   pWalker->eCode = 0;
13597d10d5a6Sdrh   return WRC_Abort;
13607d10d5a6Sdrh }
1361059b2d50Sdrh static int exprIsConst(Expr *p, int initFlag, int iCur){
13627d10d5a6Sdrh   Walker w;
1363aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
1364059b2d50Sdrh   w.eCode = initFlag;
13657d10d5a6Sdrh   w.xExprCallback = exprNodeIsConstant;
13667d10d5a6Sdrh   w.xSelectCallback = selectNodeIsConstant;
1367059b2d50Sdrh   w.u.iCur = iCur;
13687d10d5a6Sdrh   sqlite3WalkExpr(&w, p);
1369059b2d50Sdrh   return w.eCode;
13707d10d5a6Sdrh }
1371626a879aSdrh 
1372626a879aSdrh /*
1373059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1374eb55bd2fSdrh ** and 0 if it involves variables or function calls.
13752398937bSdrh **
13762398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
13772398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
13782398937bSdrh ** a constant.
1379fef5208cSdrh */
13804adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
1381059b2d50Sdrh   return exprIsConst(p, 1, 0);
1382fef5208cSdrh }
1383fef5208cSdrh 
1384fef5208cSdrh /*
1385059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
13860a168377Sdrh ** that does no originate from the ON or USING clauses of a join.
13870a168377Sdrh ** Return 0 if it involves variables or function calls or terms from
13880a168377Sdrh ** an ON or USING clause.
13890a168377Sdrh */
13900a168377Sdrh int sqlite3ExprIsConstantNotJoin(Expr *p){
1391059b2d50Sdrh   return exprIsConst(p, 2, 0);
13920a168377Sdrh }
13930a168377Sdrh 
13940a168377Sdrh /*
1395fcb9f4f3Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1396059b2d50Sdrh ** for any single row of the table with cursor iCur.  In other words, the
1397059b2d50Sdrh ** expression must not refer to any non-deterministic function nor any
1398059b2d50Sdrh ** table other than iCur.
1399059b2d50Sdrh */
1400059b2d50Sdrh int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1401059b2d50Sdrh   return exprIsConst(p, 3, iCur);
1402059b2d50Sdrh }
1403059b2d50Sdrh 
1404059b2d50Sdrh /*
1405059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1406eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
1407eb55bd2fSdrh ** are any variables.
1408eb55bd2fSdrh **
1409eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
1410eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
1411eb55bd2fSdrh ** a constant.
1412eb55bd2fSdrh */
1413feada2dfSdrh int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1414feada2dfSdrh   assert( isInit==0 || isInit==1 );
1415059b2d50Sdrh   return exprIsConst(p, 4+isInit, 0);
1416eb55bd2fSdrh }
1417eb55bd2fSdrh 
14185b88bc4bSdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS
14195b88bc4bSdrh /*
14205b88bc4bSdrh ** Walk an expression tree.  Return 1 if the expression contains a
14215b88bc4bSdrh ** subquery of some kind.  Return 0 if there are no subqueries.
14225b88bc4bSdrh */
14235b88bc4bSdrh int sqlite3ExprContainsSubquery(Expr *p){
14245b88bc4bSdrh   Walker w;
14255b88bc4bSdrh   memset(&w, 0, sizeof(w));
1426bec2476aSdrh   w.eCode = 1;
14275b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
14285b88bc4bSdrh   w.xSelectCallback = selectNodeIsConstant;
14295b88bc4bSdrh   sqlite3WalkExpr(&w, p);
143007194bffSdrh   return w.eCode==0;
14315b88bc4bSdrh }
14325b88bc4bSdrh #endif
14335b88bc4bSdrh 
1434eb55bd2fSdrh /*
143573b211abSdrh ** If the expression p codes a constant integer that is small enough
1436202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
1437202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
1438202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1439e4de1febSdrh */
14404adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
144192b01d53Sdrh   int rc = 0;
1442cd92e84dSdrh 
1443cd92e84dSdrh   /* If an expression is an integer literal that fits in a signed 32-bit
1444cd92e84dSdrh   ** integer, then the EP_IntValue flag will have already been set */
1445cd92e84dSdrh   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1446cd92e84dSdrh            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1447cd92e84dSdrh 
144892b01d53Sdrh   if( p->flags & EP_IntValue ){
144933e619fcSdrh     *pValue = p->u.iValue;
1450e4de1febSdrh     return 1;
1451e4de1febSdrh   }
145292b01d53Sdrh   switch( p->op ){
14534b59ab5eSdrh     case TK_UPLUS: {
145492b01d53Sdrh       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1455f6e369a1Sdrh       break;
14564b59ab5eSdrh     }
1457e4de1febSdrh     case TK_UMINUS: {
1458e4de1febSdrh       int v;
14594adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1460f6418891Smistachkin         assert( v!=(-2147483647-1) );
1461e4de1febSdrh         *pValue = -v;
146292b01d53Sdrh         rc = 1;
1463e4de1febSdrh       }
1464e4de1febSdrh       break;
1465e4de1febSdrh     }
1466e4de1febSdrh     default: break;
1467e4de1febSdrh   }
146892b01d53Sdrh   return rc;
1469e4de1febSdrh }
1470e4de1febSdrh 
1471e4de1febSdrh /*
1472039fc32eSdrh ** Return FALSE if there is no chance that the expression can be NULL.
1473039fc32eSdrh **
1474039fc32eSdrh ** If the expression might be NULL or if the expression is too complex
1475039fc32eSdrh ** to tell return TRUE.
1476039fc32eSdrh **
1477039fc32eSdrh ** This routine is used as an optimization, to skip OP_IsNull opcodes
1478039fc32eSdrh ** when we know that a value cannot be NULL.  Hence, a false positive
1479039fc32eSdrh ** (returning TRUE when in fact the expression can never be NULL) might
1480039fc32eSdrh ** be a small performance hit but is otherwise harmless.  On the other
1481039fc32eSdrh ** hand, a false negative (returning FALSE when the result could be NULL)
1482039fc32eSdrh ** will likely result in an incorrect answer.  So when in doubt, return
1483039fc32eSdrh ** TRUE.
1484039fc32eSdrh */
1485039fc32eSdrh int sqlite3ExprCanBeNull(const Expr *p){
1486039fc32eSdrh   u8 op;
1487cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1488039fc32eSdrh   op = p->op;
1489039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
1490039fc32eSdrh   switch( op ){
1491039fc32eSdrh     case TK_INTEGER:
1492039fc32eSdrh     case TK_STRING:
1493039fc32eSdrh     case TK_FLOAT:
1494039fc32eSdrh     case TK_BLOB:
1495039fc32eSdrh       return 0;
14967248a8b2Sdrh     case TK_COLUMN:
14977248a8b2Sdrh       assert( p->pTab!=0 );
149872673a24Sdrh       return ExprHasProperty(p, EP_CanBeNull) ||
149972673a24Sdrh              (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
1500039fc32eSdrh     default:
1501039fc32eSdrh       return 1;
1502039fc32eSdrh   }
1503039fc32eSdrh }
1504039fc32eSdrh 
1505039fc32eSdrh /*
1506039fc32eSdrh ** Return TRUE if the given expression is a constant which would be
1507039fc32eSdrh ** unchanged by OP_Affinity with the affinity given in the second
1508039fc32eSdrh ** argument.
1509039fc32eSdrh **
1510039fc32eSdrh ** This routine is used to determine if the OP_Affinity operation
1511039fc32eSdrh ** can be omitted.  When in doubt return FALSE.  A false negative
1512039fc32eSdrh ** is harmless.  A false positive, however, can result in the wrong
1513039fc32eSdrh ** answer.
1514039fc32eSdrh */
1515039fc32eSdrh int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1516039fc32eSdrh   u8 op;
151705883a34Sdrh   if( aff==SQLITE_AFF_BLOB ) return 1;
1518cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1519039fc32eSdrh   op = p->op;
1520039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
1521039fc32eSdrh   switch( op ){
1522039fc32eSdrh     case TK_INTEGER: {
1523039fc32eSdrh       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1524039fc32eSdrh     }
1525039fc32eSdrh     case TK_FLOAT: {
1526039fc32eSdrh       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1527039fc32eSdrh     }
1528039fc32eSdrh     case TK_STRING: {
1529039fc32eSdrh       return aff==SQLITE_AFF_TEXT;
1530039fc32eSdrh     }
1531039fc32eSdrh     case TK_BLOB: {
1532039fc32eSdrh       return 1;
1533039fc32eSdrh     }
15342f2855b6Sdrh     case TK_COLUMN: {
153588376ca7Sdrh       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
153688376ca7Sdrh       return p->iColumn<0
15372f2855b6Sdrh           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
15382f2855b6Sdrh     }
1539039fc32eSdrh     default: {
1540039fc32eSdrh       return 0;
1541039fc32eSdrh     }
1542039fc32eSdrh   }
1543039fc32eSdrh }
1544039fc32eSdrh 
1545039fc32eSdrh /*
1546c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
1547c4a3c779Sdrh */
15484adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
15494adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
15504adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
15514adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1552c4a3c779Sdrh   return 0;
1553c4a3c779Sdrh }
1554c4a3c779Sdrh 
15559a96b668Sdanielk1977 /*
1556b74b1017Sdrh ** Return true if we are able to the IN operator optimization on a
1557b74b1017Sdrh ** query of the form
1558b287f4b6Sdrh **
1559b74b1017Sdrh **       x IN (SELECT ...)
1560b287f4b6Sdrh **
1561b74b1017Sdrh ** Where the SELECT... clause is as specified by the parameter to this
1562b74b1017Sdrh ** routine.
1563b74b1017Sdrh **
1564b74b1017Sdrh ** The Select object passed in has already been preprocessed and no
1565b74b1017Sdrh ** errors have been found.
1566b287f4b6Sdrh */
1567b287f4b6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1568b287f4b6Sdrh static int isCandidateForInOpt(Select *p){
1569b287f4b6Sdrh   SrcList *pSrc;
1570b287f4b6Sdrh   ExprList *pEList;
1571b287f4b6Sdrh   Table *pTab;
1572b287f4b6Sdrh   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
1573b287f4b6Sdrh   if( p->pPrior ) return 0;              /* Not a compound SELECT */
15747d10d5a6Sdrh   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1575b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1576b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
15777d10d5a6Sdrh     return 0; /* No DISTINCT keyword and no aggregate functions */
15787d10d5a6Sdrh   }
1579b74b1017Sdrh   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
1580b287f4b6Sdrh   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
1581b74b1017Sdrh   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
1582b287f4b6Sdrh   if( p->pWhere ) return 0;              /* Has no WHERE clause */
1583b287f4b6Sdrh   pSrc = p->pSrc;
1584d1fa7bcaSdrh   assert( pSrc!=0 );
1585d1fa7bcaSdrh   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
1586b74b1017Sdrh   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
1587b287f4b6Sdrh   pTab = pSrc->a[0].pTab;
1588b74b1017Sdrh   if( NEVER(pTab==0) ) return 0;
1589b74b1017Sdrh   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
1590b287f4b6Sdrh   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
1591b287f4b6Sdrh   pEList = p->pEList;
1592b287f4b6Sdrh   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
1593b287f4b6Sdrh   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1594b287f4b6Sdrh   return 1;
1595b287f4b6Sdrh }
1596b287f4b6Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1597b287f4b6Sdrh 
1598b287f4b6Sdrh /*
15991d8cb21fSdan ** Code an OP_Once instruction and allocate space for its flag. Return the
16001d8cb21fSdan ** address of the new instruction.
16011d8cb21fSdan */
16021d8cb21fSdan int sqlite3CodeOnce(Parse *pParse){
16031d8cb21fSdan   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
16041d8cb21fSdan   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
16051d8cb21fSdan }
16061d8cb21fSdan 
16071d8cb21fSdan /*
16084c259e9fSdrh ** Generate code that checks the left-most column of index table iCur to see if
16094c259e9fSdrh ** it contains any NULL entries.  Cause the register at regHasNull to be set
16106be515ebSdrh ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
16116be515ebSdrh ** to be set to NULL if iCur contains one or more NULL values.
16126be515ebSdrh */
16136be515ebSdrh static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
1614728e0f91Sdrh   int addr1;
16156be515ebSdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
1616728e0f91Sdrh   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
16176be515ebSdrh   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
16186be515ebSdrh   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
16194c259e9fSdrh   VdbeComment((v, "first_entry_in(%d)", iCur));
1620728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
16216be515ebSdrh }
16226be515ebSdrh 
1623bb53ecb1Sdrh 
1624bb53ecb1Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1625bb53ecb1Sdrh /*
1626bb53ecb1Sdrh ** The argument is an IN operator with a list (not a subquery) on the
1627bb53ecb1Sdrh ** right-hand side.  Return TRUE if that list is constant.
1628bb53ecb1Sdrh */
1629bb53ecb1Sdrh static int sqlite3InRhsIsConstant(Expr *pIn){
1630bb53ecb1Sdrh   Expr *pLHS;
1631bb53ecb1Sdrh   int res;
1632bb53ecb1Sdrh   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
1633bb53ecb1Sdrh   pLHS = pIn->pLeft;
1634bb53ecb1Sdrh   pIn->pLeft = 0;
1635bb53ecb1Sdrh   res = sqlite3ExprIsConstant(pIn);
1636bb53ecb1Sdrh   pIn->pLeft = pLHS;
1637bb53ecb1Sdrh   return res;
1638bb53ecb1Sdrh }
1639bb53ecb1Sdrh #endif
1640bb53ecb1Sdrh 
16416be515ebSdrh /*
16429a96b668Sdanielk1977 ** This function is used by the implementation of the IN (...) operator.
1643d4305ca6Sdrh ** The pX parameter is the expression on the RHS of the IN operator, which
1644d4305ca6Sdrh ** might be either a list of expressions or a subquery.
16459a96b668Sdanielk1977 **
1646d4305ca6Sdrh ** The job of this routine is to find or create a b-tree object that can
1647d4305ca6Sdrh ** be used either to test for membership in the RHS set or to iterate through
1648d4305ca6Sdrh ** all members of the RHS set, skipping duplicates.
1649d4305ca6Sdrh **
16503a85625dSdrh ** A cursor is opened on the b-tree object that is the RHS of the IN operator
1651d4305ca6Sdrh ** and pX->iTable is set to the index of that cursor.
1652d4305ca6Sdrh **
1653b74b1017Sdrh ** The returned value of this function indicates the b-tree type, as follows:
16549a96b668Sdanielk1977 **
16559a96b668Sdanielk1977 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
16561ccce449Sdrh **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
16571ccce449Sdrh **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
16589a96b668Sdanielk1977 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
16599a96b668Sdanielk1977 **                         populated epheremal table.
1660bb53ecb1Sdrh **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
1661bb53ecb1Sdrh **                         implemented as a sequence of comparisons.
16629a96b668Sdanielk1977 **
1663d4305ca6Sdrh ** An existing b-tree might be used if the RHS expression pX is a simple
1664d4305ca6Sdrh ** subquery such as:
16659a96b668Sdanielk1977 **
16669a96b668Sdanielk1977 **     SELECT <column> FROM <table>
16679a96b668Sdanielk1977 **
1668d4305ca6Sdrh ** If the RHS of the IN operator is a list or a more complex subquery, then
1669d4305ca6Sdrh ** an ephemeral table might need to be generated from the RHS and then
167060ec914cSpeter.d.reid ** pX->iTable made to point to the ephemeral table instead of an
1671d4305ca6Sdrh ** existing table.
1672d4305ca6Sdrh **
16733a85625dSdrh ** The inFlags parameter must contain exactly one of the bits
16743a85625dSdrh ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
16753a85625dSdrh ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
16763a85625dSdrh ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
16773a85625dSdrh ** IN index will be used to loop over all values of the RHS of the
16783a85625dSdrh ** IN operator.
16793a85625dSdrh **
16803a85625dSdrh ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
16813a85625dSdrh ** through the set members) then the b-tree must not contain duplicates.
16823a85625dSdrh ** An epheremal table must be used unless the selected <column> is guaranteed
16839a96b668Sdanielk1977 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
1684b74b1017Sdrh ** has a UNIQUE constraint or UNIQUE index.
16850cdc022eSdanielk1977 **
16863a85625dSdrh ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
16873a85625dSdrh ** for fast set membership tests) then an epheremal table must
16880cdc022eSdanielk1977 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
16890cdc022eSdanielk1977 ** be found with <column> as its left-most column.
16900cdc022eSdanielk1977 **
1691bb53ecb1Sdrh ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
1692bb53ecb1Sdrh ** if the RHS of the IN operator is a list (not a subquery) then this
1693bb53ecb1Sdrh ** routine might decide that creating an ephemeral b-tree for membership
1694bb53ecb1Sdrh ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
1695bb53ecb1Sdrh ** calling routine should implement the IN operator using a sequence
1696bb53ecb1Sdrh ** of Eq or Ne comparison operations.
1697bb53ecb1Sdrh **
1698b74b1017Sdrh ** When the b-tree is being used for membership tests, the calling function
16993a85625dSdrh ** might need to know whether or not the RHS side of the IN operator
1700e21a6e1dSdrh ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
17013a85625dSdrh ** if there is any chance that the (...) might contain a NULL value at
17020cdc022eSdanielk1977 ** runtime, then a register is allocated and the register number written
1703e21a6e1dSdrh ** to *prRhsHasNull. If there is no chance that the (...) contains a
1704e21a6e1dSdrh ** NULL value, then *prRhsHasNull is left unchanged.
17050cdc022eSdanielk1977 **
1706e21a6e1dSdrh ** If a register is allocated and its location stored in *prRhsHasNull, then
17076be515ebSdrh ** the value in that register will be NULL if the b-tree contains one or more
17086be515ebSdrh ** NULL values, and it will be some non-NULL value if the b-tree contains no
17096be515ebSdrh ** NULL values.
17109a96b668Sdanielk1977 */
1711284f4acaSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1712e21a6e1dSdrh int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
1713b74b1017Sdrh   Select *p;                            /* SELECT to the right of IN operator */
1714b74b1017Sdrh   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
1715b74b1017Sdrh   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
17163a85625dSdrh   int mustBeUnique;                     /* True if RHS must be unique */
1717b8475df8Sdrh   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
17189a96b668Sdanielk1977 
17191450bc6eSdrh   assert( pX->op==TK_IN );
17203a85625dSdrh   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
17211450bc6eSdrh 
1722b74b1017Sdrh   /* Check to see if an existing table or index can be used to
1723b74b1017Sdrh   ** satisfy the query.  This is preferable to generating a new
1724b74b1017Sdrh   ** ephemeral table.
17259a96b668Sdanielk1977   */
17266ab3a2ecSdanielk1977   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
1727311efc70Sdrh   if( pParse->nErr==0 && isCandidateForInOpt(p) ){
1728e1fb65a0Sdanielk1977     sqlite3 *db = pParse->db;              /* Database connection */
1729b07028f7Sdrh     Table *pTab;                           /* Table <table>. */
1730b07028f7Sdrh     Expr *pExpr;                           /* Expression <column> */
1731bbbdc83bSdrh     i16 iCol;                              /* Index of column <column> */
1732bbbdc83bSdrh     i16 iDb;                               /* Database idx for pTab */
1733e1fb65a0Sdanielk1977 
1734b07028f7Sdrh     assert( p );                        /* Because of isCandidateForInOpt(p) */
1735b07028f7Sdrh     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
1736b07028f7Sdrh     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
1737b07028f7Sdrh     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
1738b07028f7Sdrh     pTab = p->pSrc->a[0].pTab;
1739b07028f7Sdrh     pExpr = p->pEList->a[0].pExpr;
1740bbbdc83bSdrh     iCol = (i16)pExpr->iColumn;
1741b07028f7Sdrh 
1742b22f7c83Sdrh     /* Code an OP_Transaction and OP_TableLock for <table>. */
1743e1fb65a0Sdanielk1977     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1744e1fb65a0Sdanielk1977     sqlite3CodeVerifySchema(pParse, iDb);
1745e1fb65a0Sdanielk1977     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
17469a96b668Sdanielk1977 
17479a96b668Sdanielk1977     /* This function is only called from two places. In both cases the vdbe
17489a96b668Sdanielk1977     ** has already been allocated. So assume sqlite3GetVdbe() is always
17499a96b668Sdanielk1977     ** successful here.
17509a96b668Sdanielk1977     */
17519a96b668Sdanielk1977     assert(v);
17529a96b668Sdanielk1977     if( iCol<0 ){
17537d176105Sdrh       int iAddr = sqlite3CodeOnce(pParse);
17547d176105Sdrh       VdbeCoverage(v);
17559a96b668Sdanielk1977 
17569a96b668Sdanielk1977       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
17579a96b668Sdanielk1977       eType = IN_INDEX_ROWID;
17589a96b668Sdanielk1977 
17599a96b668Sdanielk1977       sqlite3VdbeJumpHere(v, iAddr);
17609a96b668Sdanielk1977     }else{
1761e1fb65a0Sdanielk1977       Index *pIdx;                         /* Iterator variable */
1762e1fb65a0Sdanielk1977 
17639a96b668Sdanielk1977       /* The collation sequence used by the comparison. If an index is to
17649a96b668Sdanielk1977       ** be used in place of a temp-table, it must be ordered according
1765e1fb65a0Sdanielk1977       ** to this collation sequence.  */
17669a96b668Sdanielk1977       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
17679a96b668Sdanielk1977 
17689a96b668Sdanielk1977       /* Check that the affinity that will be used to perform the
17699a96b668Sdanielk1977       ** comparison is the same as the affinity of the column. If
17709a96b668Sdanielk1977       ** it is not, it is not possible to use any index.
17719a96b668Sdanielk1977       */
1772dbaee5e3Sdrh       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
17739a96b668Sdanielk1977 
17749a96b668Sdanielk1977       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
17759a96b668Sdanielk1977         if( (pIdx->aiColumn[0]==iCol)
1776b74b1017Sdrh          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
17775f1d1d9cSdrh          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
17789a96b668Sdanielk1977         ){
17797d176105Sdrh           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
17802ec2fb22Sdrh           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
17812ec2fb22Sdrh           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1782207872a4Sdanielk1977           VdbeComment((v, "%s", pIdx->zName));
17831ccce449Sdrh           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
17841ccce449Sdrh           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
17859a96b668Sdanielk1977 
1786e21a6e1dSdrh           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
1787e21a6e1dSdrh             *prRhsHasNull = ++pParse->nMem;
17886be515ebSdrh             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
17890cdc022eSdanielk1977           }
1790552fd454Sdrh           sqlite3VdbeJumpHere(v, iAddr);
17919a96b668Sdanielk1977         }
17929a96b668Sdanielk1977       }
17939a96b668Sdanielk1977     }
17949a96b668Sdanielk1977   }
17959a96b668Sdanielk1977 
1796bb53ecb1Sdrh   /* If no preexisting index is available for the IN clause
1797bb53ecb1Sdrh   ** and IN_INDEX_NOOP is an allowed reply
1798bb53ecb1Sdrh   ** and the RHS of the IN operator is a list, not a subquery
1799bb53ecb1Sdrh   ** and the RHS is not contant or has two or fewer terms,
180060ec914cSpeter.d.reid   ** then it is not worth creating an ephemeral table to evaluate
1801bb53ecb1Sdrh   ** the IN operator so return IN_INDEX_NOOP.
1802bb53ecb1Sdrh   */
1803bb53ecb1Sdrh   if( eType==0
1804bb53ecb1Sdrh    && (inFlags & IN_INDEX_NOOP_OK)
1805bb53ecb1Sdrh    && !ExprHasProperty(pX, EP_xIsSelect)
1806bb53ecb1Sdrh    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
1807bb53ecb1Sdrh   ){
1808bb53ecb1Sdrh     eType = IN_INDEX_NOOP;
1809bb53ecb1Sdrh   }
1810bb53ecb1Sdrh 
1811bb53ecb1Sdrh 
18129a96b668Sdanielk1977   if( eType==0 ){
18134387006cSdrh     /* Could not find an existing table or index to use as the RHS b-tree.
1814b74b1017Sdrh     ** We will have to generate an ephemeral table to do the job.
1815b74b1017Sdrh     */
18168e23daf3Sdrh     u32 savedNQueryLoop = pParse->nQueryLoop;
18170cdc022eSdanielk1977     int rMayHaveNull = 0;
181841a05b7bSdanielk1977     eType = IN_INDEX_EPH;
18193a85625dSdrh     if( inFlags & IN_INDEX_LOOP ){
18204a5acf8eSdrh       pParse->nQueryLoop = 0;
1821c5cd1249Sdrh       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
182241a05b7bSdanielk1977         eType = IN_INDEX_ROWID;
18230cdc022eSdanielk1977       }
1824e21a6e1dSdrh     }else if( prRhsHasNull ){
1825e21a6e1dSdrh       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
1826cf4d38aaSdrh     }
182741a05b7bSdanielk1977     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
1828cf4d38aaSdrh     pParse->nQueryLoop = savedNQueryLoop;
18299a96b668Sdanielk1977   }else{
18309a96b668Sdanielk1977     pX->iTable = iTab;
18319a96b668Sdanielk1977   }
18329a96b668Sdanielk1977   return eType;
18339a96b668Sdanielk1977 }
1834284f4acaSdanielk1977 #endif
1835626a879aSdrh 
1836626a879aSdrh /*
1837d4187c71Sdrh ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
1838d4187c71Sdrh ** or IN operators.  Examples:
1839626a879aSdrh **
18409cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
18419cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
18429cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
18439cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1844fef5208cSdrh **
18459cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
18469cbe6352Sdrh ** operator or subquery.
184741a05b7bSdanielk1977 **
184841a05b7bSdanielk1977 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
184941a05b7bSdanielk1977 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
185041a05b7bSdanielk1977 ** to some integer key column of a table B-Tree. In this case, use an
185141a05b7bSdanielk1977 ** intkey B-Tree to store the set of IN(...) values instead of the usual
185241a05b7bSdanielk1977 ** (slower) variable length keys B-Tree.
1853fd773cf9Sdrh **
1854fd773cf9Sdrh ** If rMayHaveNull is non-zero, that means that the operation is an IN
1855fd773cf9Sdrh ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
18563a85625dSdrh ** All this routine does is initialize the register given by rMayHaveNull
18573a85625dSdrh ** to NULL.  Calling routines will take care of changing this register
18583a85625dSdrh ** value to non-NULL if the RHS is NULL-free.
18591450bc6eSdrh **
18601450bc6eSdrh ** For a SELECT or EXISTS operator, return the register that holds the
18611450bc6eSdrh ** result.  For IN operators or if an error occurs, the return value is 0.
1862cce7d176Sdrh */
186351522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
18641450bc6eSdrh int sqlite3CodeSubselect(
1865fd773cf9Sdrh   Parse *pParse,          /* Parsing context */
1866fd773cf9Sdrh   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
18676be515ebSdrh   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
1868fd773cf9Sdrh   int isRowid             /* If true, LHS of IN operator is a rowid */
186941a05b7bSdanielk1977 ){
18706be515ebSdrh   int jmpIfDynamic = -1;                      /* One-time test address */
18711450bc6eSdrh   int rReg = 0;                           /* Register storing resulting */
1872b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
18731450bc6eSdrh   if( NEVER(v==0) ) return 0;
1874ceea3321Sdrh   sqlite3ExprCachePush(pParse);
1875fc976065Sdanielk1977 
187657dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
187757dbd7b3Sdrh   ** if any of the following is true:
187857dbd7b3Sdrh   **
187957dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
188057dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
188157dbd7b3Sdrh   **    *  We are inside a trigger
188257dbd7b3Sdrh   **
188357dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
188457dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1885b3bce662Sdanielk1977   */
1886c5cd1249Sdrh   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
18876be515ebSdrh     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
1888b3bce662Sdanielk1977   }
1889b3bce662Sdanielk1977 
18904a07e3dbSdan #ifndef SQLITE_OMIT_EXPLAIN
18914a07e3dbSdan   if( pParse->explain==2 ){
189262aaa6caSdrh     char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
189362aaa6caSdrh         jmpIfDynamic>=0?"":"CORRELATED ",
189462aaa6caSdrh         pExpr->op==TK_IN?"LIST":"SCALAR",
189562aaa6caSdrh         pParse->iNextSelectId
18964a07e3dbSdan     );
18974a07e3dbSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
18984a07e3dbSdan   }
18994a07e3dbSdan #endif
19004a07e3dbSdan 
1901cce7d176Sdrh   switch( pExpr->op ){
1902fef5208cSdrh     case TK_IN: {
1903d4187c71Sdrh       char affinity;              /* Affinity of the LHS of the IN */
1904b9bb7c18Sdrh       int addr;                   /* Address of OP_OpenEphemeral instruction */
1905d4187c71Sdrh       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
1906323df790Sdrh       KeyInfo *pKeyInfo = 0;      /* Key information */
1907d3d39e93Sdrh 
190841a05b7bSdanielk1977       affinity = sqlite3ExprAffinity(pLeft);
1909e014a838Sdanielk1977 
1910e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
19118cff69dfSdrh       ** expression it is handled the same way.  An ephemeral table is
1912e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1913e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1914fef5208cSdrh       **
1915e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1916e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1917e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1918e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1919e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1920e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1921e014a838Sdanielk1977       ** is used.
1922fef5208cSdrh       */
1923832508b7Sdrh       pExpr->iTable = pParse->nTab++;
192441a05b7bSdanielk1977       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
1925ad124329Sdrh       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
1926e014a838Sdanielk1977 
19276ab3a2ecSdanielk1977       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1928e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1929e014a838Sdanielk1977         **
1930e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1931e014a838Sdanielk1977         ** table allocated and opened above.
1932e014a838Sdanielk1977         */
19334387006cSdrh         Select *pSelect = pExpr->x.pSelect;
19341013c932Sdrh         SelectDest dest;
1935be5c89acSdrh         ExprList *pEList;
19361013c932Sdrh 
193741a05b7bSdanielk1977         assert( !isRowid );
19381013c932Sdrh         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
19392b596da8Sdrh         dest.affSdst = (u8)affinity;
1940e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
19414387006cSdrh         pSelect->iLimit = 0;
19424387006cSdrh         testcase( pSelect->selFlags & SF_Distinct );
1943812ea833Sdrh         testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
19444387006cSdrh         if( sqlite3Select(pParse, pSelect, &dest) ){
19452ec2fb22Sdrh           sqlite3KeyInfoUnref(pKeyInfo);
19461450bc6eSdrh           return 0;
194794ccde58Sdrh         }
19484387006cSdrh         pEList = pSelect->pEList;
1949812ea833Sdrh         assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
19503535ec3eSdrh         assert( pEList!=0 );
19513535ec3eSdrh         assert( pEList->nExpr>0 );
19522ec2fb22Sdrh         assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
1953323df790Sdrh         pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1954be5c89acSdrh                                                          pEList->a[0].pExpr);
1955a7d2db17Sdrh       }else if( ALWAYS(pExpr->x.pList!=0) ){
1956fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1957fef5208cSdrh         **
1958e014a838Sdanielk1977         ** For each expression, build an index key from the evaluation and
1959e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1960e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1961e014a838Sdanielk1977         ** a column, use numeric affinity.
1962fef5208cSdrh         */
1963e014a838Sdanielk1977         int i;
19646ab3a2ecSdanielk1977         ExprList *pList = pExpr->x.pList;
196557dbd7b3Sdrh         struct ExprList_item *pItem;
1966ecc31805Sdrh         int r1, r2, r3;
196757dbd7b3Sdrh 
1968e014a838Sdanielk1977         if( !affinity ){
196905883a34Sdrh           affinity = SQLITE_AFF_BLOB;
1970e014a838Sdanielk1977         }
1971323df790Sdrh         if( pKeyInfo ){
19722ec2fb22Sdrh           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
1973323df790Sdrh           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
1974323df790Sdrh         }
1975e014a838Sdanielk1977 
1976e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
19772d401ab8Sdrh         r1 = sqlite3GetTempReg(pParse);
19782d401ab8Sdrh         r2 = sqlite3GetTempReg(pParse);
197937e08081Sdrh         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
198057dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
198157dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
1982e05c929bSdrh           int iValToIns;
1983e014a838Sdanielk1977 
198457dbd7b3Sdrh           /* If the expression is not constant then we will need to
198557dbd7b3Sdrh           ** disable the test that was generated above that makes sure
198657dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
198757dbd7b3Sdrh           ** expression we need to rerun this code each time.
198857dbd7b3Sdrh           */
19896be515ebSdrh           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
19906be515ebSdrh             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
19916be515ebSdrh             jmpIfDynamic = -1;
19924794b980Sdrh           }
1993e014a838Sdanielk1977 
1994e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
1995e05c929bSdrh           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
1996e05c929bSdrh             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
1997e05c929bSdrh           }else{
1998ecc31805Sdrh             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
199941a05b7bSdanielk1977             if( isRowid ){
2000e05c929bSdrh               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2001e05c929bSdrh                                 sqlite3VdbeCurrentAddr(v)+2);
2002688852abSdrh               VdbeCoverage(v);
200341a05b7bSdanielk1977               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
200441a05b7bSdanielk1977             }else{
2005ecc31805Sdrh               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
20063c31fc23Sdrh               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
20072d401ab8Sdrh               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2008fef5208cSdrh             }
200941a05b7bSdanielk1977           }
2010e05c929bSdrh         }
20112d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r1);
20122d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r2);
2013fef5208cSdrh       }
2014323df790Sdrh       if( pKeyInfo ){
20152ec2fb22Sdrh         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
201641a05b7bSdanielk1977       }
2017b3bce662Sdanielk1977       break;
2018fef5208cSdrh     }
2019fef5208cSdrh 
202051522cd3Sdrh     case TK_EXISTS:
2021fd773cf9Sdrh     case TK_SELECT:
2022fd773cf9Sdrh     default: {
2023fd773cf9Sdrh       /* If this has to be a scalar SELECT.  Generate code to put the
2024fef5208cSdrh       ** value of this select in a memory cell and record the number
2025fd773cf9Sdrh       ** of the memory cell in iColumn.  If this is an EXISTS, write
2026fd773cf9Sdrh       ** an integer 0 (not exists) or 1 (exists) into a memory cell
2027fd773cf9Sdrh       ** and record that memory cell in iColumn.
2028fef5208cSdrh       */
2029fd773cf9Sdrh       Select *pSel;                         /* SELECT statement to encode */
2030fd773cf9Sdrh       SelectDest dest;                      /* How to deal with SELECt result */
20311398ad36Sdrh 
2032cf697396Sshane       testcase( pExpr->op==TK_EXISTS );
2033cf697396Sshane       testcase( pExpr->op==TK_SELECT );
2034cf697396Sshane       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
2035cf697396Sshane 
20366ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
20376ab3a2ecSdanielk1977       pSel = pExpr->x.pSelect;
20381013c932Sdrh       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
203951522cd3Sdrh       if( pExpr->op==TK_SELECT ){
20406c8c8ce0Sdanielk1977         dest.eDest = SRT_Mem;
204153932ce8Sdrh         dest.iSdst = dest.iSDParm;
20422b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
2043d4e70ebdSdrh         VdbeComment((v, "Init subquery result"));
204451522cd3Sdrh       }else{
20456c8c8ce0Sdanielk1977         dest.eDest = SRT_Exists;
20462b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
2047d4e70ebdSdrh         VdbeComment((v, "Init EXISTS result"));
204851522cd3Sdrh       }
2049633e6d57Sdrh       sqlite3ExprDelete(pParse->db, pSel->pLimit);
2050094430ebSdrh       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2051094430ebSdrh                                   &sqlite3IntTokens[1]);
205248b5b041Sdrh       pSel->iLimit = 0;
2053772460fdSdrh       pSel->selFlags &= ~SF_MultiValue;
20547d10d5a6Sdrh       if( sqlite3Select(pParse, pSel, &dest) ){
20551450bc6eSdrh         return 0;
205694ccde58Sdrh       }
20572b596da8Sdrh       rReg = dest.iSDParm;
2058ebb6a65dSdrh       ExprSetVVAProperty(pExpr, EP_NoReduce);
2059b3bce662Sdanielk1977       break;
206019a775c2Sdrh     }
2061cce7d176Sdrh   }
2062b3bce662Sdanielk1977 
20636be515ebSdrh   if( rHasNullFlag ){
20646be515ebSdrh     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
2065b3bce662Sdanielk1977   }
20666be515ebSdrh 
20676be515ebSdrh   if( jmpIfDynamic>=0 ){
20686be515ebSdrh     sqlite3VdbeJumpHere(v, jmpIfDynamic);
2069b3bce662Sdanielk1977   }
2070d2490904Sdrh   sqlite3ExprCachePop(pParse);
2071fc976065Sdanielk1977 
20721450bc6eSdrh   return rReg;
2073cce7d176Sdrh }
207451522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
2075cce7d176Sdrh 
2076e3365e6cSdrh #ifndef SQLITE_OMIT_SUBQUERY
2077e3365e6cSdrh /*
2078e3365e6cSdrh ** Generate code for an IN expression.
2079e3365e6cSdrh **
2080e3365e6cSdrh **      x IN (SELECT ...)
2081e3365e6cSdrh **      x IN (value, value, ...)
2082e3365e6cSdrh **
2083e3365e6cSdrh ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
2084e3365e6cSdrh ** is an array of zero or more values.  The expression is true if the LHS is
2085e3365e6cSdrh ** contained within the RHS.  The value of the expression is unknown (NULL)
2086e3365e6cSdrh ** if the LHS is NULL or if the LHS is not contained within the RHS and the
2087e3365e6cSdrh ** RHS contains one or more NULL values.
2088e3365e6cSdrh **
20896be515ebSdrh ** This routine generates code that jumps to destIfFalse if the LHS is not
2090e3365e6cSdrh ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
2091e3365e6cSdrh ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
2092e3365e6cSdrh ** within the RHS then fall through.
2093e3365e6cSdrh */
2094e3365e6cSdrh static void sqlite3ExprCodeIN(
2095e3365e6cSdrh   Parse *pParse,        /* Parsing and code generating context */
2096e3365e6cSdrh   Expr *pExpr,          /* The IN expression */
2097e3365e6cSdrh   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
2098e3365e6cSdrh   int destIfNull        /* Jump here if the results are unknown due to NULLs */
2099e3365e6cSdrh ){
2100e3365e6cSdrh   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
2101e3365e6cSdrh   char affinity;        /* Comparison affinity to use */
2102e3365e6cSdrh   int eType;            /* Type of the RHS */
2103e3365e6cSdrh   int r1;               /* Temporary use register */
2104e3365e6cSdrh   Vdbe *v;              /* Statement under construction */
2105e3365e6cSdrh 
2106e3365e6cSdrh   /* Compute the RHS.   After this step, the table with cursor
2107e3365e6cSdrh   ** pExpr->iTable will contains the values that make up the RHS.
2108e3365e6cSdrh   */
2109e3365e6cSdrh   v = pParse->pVdbe;
2110e3365e6cSdrh   assert( v!=0 );       /* OOM detected prior to this routine */
2111e3365e6cSdrh   VdbeNoopComment((v, "begin IN expr"));
2112bb53ecb1Sdrh   eType = sqlite3FindInIndex(pParse, pExpr,
2113bb53ecb1Sdrh                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
21143a85625dSdrh                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
2115e3365e6cSdrh 
2116e3365e6cSdrh   /* Figure out the affinity to use to create a key from the results
2117e3365e6cSdrh   ** of the expression. affinityStr stores a static string suitable for
2118e3365e6cSdrh   ** P4 of OP_MakeRecord.
2119e3365e6cSdrh   */
2120e3365e6cSdrh   affinity = comparisonAffinity(pExpr);
2121e3365e6cSdrh 
2122e3365e6cSdrh   /* Code the LHS, the <expr> from "<expr> IN (...)".
2123e3365e6cSdrh   */
2124e3365e6cSdrh   sqlite3ExprCachePush(pParse);
2125e3365e6cSdrh   r1 = sqlite3GetTempReg(pParse);
2126e3365e6cSdrh   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
2127e3365e6cSdrh 
2128bb53ecb1Sdrh   /* If sqlite3FindInIndex() did not find or create an index that is
2129bb53ecb1Sdrh   ** suitable for evaluating the IN operator, then evaluate using a
2130bb53ecb1Sdrh   ** sequence of comparisons.
2131bb53ecb1Sdrh   */
2132bb53ecb1Sdrh   if( eType==IN_INDEX_NOOP ){
2133bb53ecb1Sdrh     ExprList *pList = pExpr->x.pList;
2134bb53ecb1Sdrh     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2135bb53ecb1Sdrh     int labelOk = sqlite3VdbeMakeLabel(v);
2136bb53ecb1Sdrh     int r2, regToFree;
2137bb53ecb1Sdrh     int regCkNull = 0;
2138bb53ecb1Sdrh     int ii;
2139bb53ecb1Sdrh     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2140bb53ecb1Sdrh     if( destIfNull!=destIfFalse ){
2141bb53ecb1Sdrh       regCkNull = sqlite3GetTempReg(pParse);
2142a976979bSdrh       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
2143bb53ecb1Sdrh     }
2144bb53ecb1Sdrh     for(ii=0; ii<pList->nExpr; ii++){
2145bb53ecb1Sdrh       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
2146a976979bSdrh       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
2147bb53ecb1Sdrh         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2148bb53ecb1Sdrh       }
2149bb53ecb1Sdrh       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2150bb53ecb1Sdrh         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
21514336b0e6Sdrh                           (void*)pColl, P4_COLLSEQ);
21524336b0e6Sdrh         VdbeCoverageIf(v, ii<pList->nExpr-1);
21534336b0e6Sdrh         VdbeCoverageIf(v, ii==pList->nExpr-1);
2154bb53ecb1Sdrh         sqlite3VdbeChangeP5(v, affinity);
2155bb53ecb1Sdrh       }else{
2156bb53ecb1Sdrh         assert( destIfNull==destIfFalse );
2157bb53ecb1Sdrh         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2158bb53ecb1Sdrh                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
2159bb53ecb1Sdrh         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
2160bb53ecb1Sdrh       }
2161bb53ecb1Sdrh       sqlite3ReleaseTempReg(pParse, regToFree);
2162bb53ecb1Sdrh     }
2163bb53ecb1Sdrh     if( regCkNull ){
2164bb53ecb1Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
2165076e85f5Sdrh       sqlite3VdbeGoto(v, destIfFalse);
2166bb53ecb1Sdrh     }
2167bb53ecb1Sdrh     sqlite3VdbeResolveLabel(v, labelOk);
2168bb53ecb1Sdrh     sqlite3ReleaseTempReg(pParse, regCkNull);
2169bb53ecb1Sdrh   }else{
2170bb53ecb1Sdrh 
2171094430ebSdrh     /* If the LHS is NULL, then the result is either false or NULL depending
2172094430ebSdrh     ** on whether the RHS is empty or not, respectively.
2173094430ebSdrh     */
21747248a8b2Sdrh     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
2175094430ebSdrh       if( destIfNull==destIfFalse ){
2176094430ebSdrh         /* Shortcut for the common case where the false and NULL outcomes are
2177094430ebSdrh         ** the same. */
2178688852abSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
2179094430ebSdrh       }else{
2180688852abSdrh         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2181094430ebSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2182688852abSdrh         VdbeCoverage(v);
2183076e85f5Sdrh         sqlite3VdbeGoto(v, destIfNull);
2184094430ebSdrh         sqlite3VdbeJumpHere(v, addr1);
2185094430ebSdrh       }
21867248a8b2Sdrh     }
2187e3365e6cSdrh 
2188e3365e6cSdrh     if( eType==IN_INDEX_ROWID ){
2189e3365e6cSdrh       /* In this case, the RHS is the ROWID of table b-tree
2190e3365e6cSdrh       */
2191688852abSdrh       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
2192e3365e6cSdrh       sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
2193688852abSdrh       VdbeCoverage(v);
2194e3365e6cSdrh     }else{
2195e3365e6cSdrh       /* In this case, the RHS is an index b-tree.
2196e3365e6cSdrh       */
21978cff69dfSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
2198e3365e6cSdrh 
2199e3365e6cSdrh       /* If the set membership test fails, then the result of the
2200e3365e6cSdrh       ** "x IN (...)" expression must be either 0 or NULL. If the set
2201e3365e6cSdrh       ** contains no NULL values, then the result is 0. If the set
2202e3365e6cSdrh       ** contains one or more NULL values, then the result of the
2203e3365e6cSdrh       ** expression is also NULL.
2204e3365e6cSdrh       */
2205e80c9b9aSdrh       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
2206e80c9b9aSdrh       if( rRhsHasNull==0 ){
2207e3365e6cSdrh         /* This branch runs if it is known at compile time that the RHS
2208e3365e6cSdrh         ** cannot contain NULL values. This happens as the result
2209e3365e6cSdrh         ** of a "NOT NULL" constraint in the database schema.
2210e3365e6cSdrh         **
2211e3365e6cSdrh         ** Also run this branch if NULL is equivalent to FALSE
2212e3365e6cSdrh         ** for this particular IN operator.
2213e3365e6cSdrh         */
22148cff69dfSdrh         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
2215688852abSdrh         VdbeCoverage(v);
2216e3365e6cSdrh       }else{
2217e3365e6cSdrh         /* In this branch, the RHS of the IN might contain a NULL and
2218e3365e6cSdrh         ** the presence of a NULL on the RHS makes a difference in the
2219e3365e6cSdrh         ** outcome.
2220e3365e6cSdrh         */
2221728e0f91Sdrh         int addr1;
2222e3365e6cSdrh 
2223e3365e6cSdrh         /* First check to see if the LHS is contained in the RHS.  If so,
22246be515ebSdrh         ** then the answer is TRUE the presence of NULLs in the RHS does
22256be515ebSdrh         ** not matter.  If the LHS is not contained in the RHS, then the
22266be515ebSdrh         ** answer is NULL if the RHS contains NULLs and the answer is
22276be515ebSdrh         ** FALSE if the RHS is NULL-free.
2228e3365e6cSdrh         */
2229728e0f91Sdrh         addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
2230688852abSdrh         VdbeCoverage(v);
22316be515ebSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2232552fd454Sdrh         VdbeCoverage(v);
2233076e85f5Sdrh         sqlite3VdbeGoto(v, destIfFalse);
2234728e0f91Sdrh         sqlite3VdbeJumpHere(v, addr1);
2235e3365e6cSdrh       }
2236e3365e6cSdrh     }
2237bb53ecb1Sdrh   }
2238e3365e6cSdrh   sqlite3ReleaseTempReg(pParse, r1);
2239d2490904Sdrh   sqlite3ExprCachePop(pParse);
2240e3365e6cSdrh   VdbeComment((v, "end IN expr"));
2241e3365e6cSdrh }
2242e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
2243e3365e6cSdrh 
224413573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2245598f1340Sdrh /*
2246598f1340Sdrh ** Generate an instruction that will put the floating point
22479cbf3425Sdrh ** value described by z[0..n-1] into register iMem.
22480cf19ed8Sdrh **
22490cf19ed8Sdrh ** The z[] string will probably not be zero-terminated.  But the
22500cf19ed8Sdrh ** z[n] character is guaranteed to be something that does not look
22510cf19ed8Sdrh ** like the continuation of the number.
2252598f1340Sdrh */
2253b7916a78Sdrh static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
2254fd773cf9Sdrh   if( ALWAYS(z!=0) ){
2255598f1340Sdrh     double value;
22569339da1fSdrh     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
2257d0015161Sdrh     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2258598f1340Sdrh     if( negateFlag ) value = -value;
225997bae794Sdrh     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
2260598f1340Sdrh   }
2261598f1340Sdrh }
226213573c71Sdrh #endif
2263598f1340Sdrh 
2264598f1340Sdrh 
2265598f1340Sdrh /*
2266fec19aadSdrh ** Generate an instruction that will put the integer describe by
22679cbf3425Sdrh ** text z[0..n-1] into register iMem.
22680cf19ed8Sdrh **
22695f1d6b61Sshaneh ** Expr.u.zToken is always UTF8 and zero-terminated.
2270fec19aadSdrh */
227113573c71Sdrh static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
227213573c71Sdrh   Vdbe *v = pParse->pVdbe;
227392b01d53Sdrh   if( pExpr->flags & EP_IntValue ){
227433e619fcSdrh     int i = pExpr->u.iValue;
2275d50ffc41Sdrh     assert( i>=0 );
227692b01d53Sdrh     if( negFlag ) i = -i;
227792b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
2278fd773cf9Sdrh   }else{
22795f1d6b61Sshaneh     int c;
22805f1d6b61Sshaneh     i64 value;
2281fd773cf9Sdrh     const char *z = pExpr->u.zToken;
2282fd773cf9Sdrh     assert( z!=0 );
22839296c18aSdrh     c = sqlite3DecOrHexToI64(z, &value);
22845f1d6b61Sshaneh     if( c==0 || (c==2 && negFlag) ){
2285158b9cb9Sdrh       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
228697bae794Sdrh       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
2287fec19aadSdrh     }else{
228813573c71Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
228913573c71Sdrh       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
229013573c71Sdrh #else
22911b7ddc59Sdrh #ifndef SQLITE_OMIT_HEX_INTEGER
22929296c18aSdrh       if( sqlite3_strnicmp(z,"0x",2)==0 ){
22939296c18aSdrh         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
22941b7ddc59Sdrh       }else
22951b7ddc59Sdrh #endif
22961b7ddc59Sdrh       {
2297b7916a78Sdrh         codeReal(v, z, negFlag, iMem);
22989296c18aSdrh       }
229913573c71Sdrh #endif
2300fec19aadSdrh     }
2301fec19aadSdrh   }
2302c9cf901dSdanielk1977 }
2303fec19aadSdrh 
2304ceea3321Sdrh /*
2305ceea3321Sdrh ** Clear a cache entry.
2306ceea3321Sdrh */
2307ceea3321Sdrh static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2308ceea3321Sdrh   if( p->tempReg ){
2309ceea3321Sdrh     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2310ceea3321Sdrh       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2311ceea3321Sdrh     }
2312ceea3321Sdrh     p->tempReg = 0;
2313ceea3321Sdrh   }
2314ceea3321Sdrh }
2315ceea3321Sdrh 
2316ceea3321Sdrh 
2317ceea3321Sdrh /*
2318ceea3321Sdrh ** Record in the column cache that a particular column from a
2319ceea3321Sdrh ** particular table is stored in a particular register.
2320ceea3321Sdrh */
2321ceea3321Sdrh void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2322ceea3321Sdrh   int i;
2323ceea3321Sdrh   int minLru;
2324ceea3321Sdrh   int idxLru;
2325ceea3321Sdrh   struct yColCache *p;
2326ceea3321Sdrh 
2327ce8f53d4Sdan   /* Unless an error has occurred, register numbers are always positive. */
2328ce8f53d4Sdan   assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
232920411ea7Sdrh   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
233020411ea7Sdrh 
2331b6da74ebSdrh   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
2332b6da74ebSdrh   ** for testing only - to verify that SQLite always gets the same answer
2333b6da74ebSdrh   ** with and without the column cache.
2334b6da74ebSdrh   */
23357e5418e4Sdrh   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
2336b6da74ebSdrh 
233727ee406eSdrh   /* First replace any existing entry.
233827ee406eSdrh   **
233927ee406eSdrh   ** Actually, the way the column cache is currently used, we are guaranteed
234027ee406eSdrh   ** that the object will never already be in cache.  Verify this guarantee.
234127ee406eSdrh   */
234227ee406eSdrh #ifndef NDEBUG
2343ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
234427ee406eSdrh     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
2345ceea3321Sdrh   }
234627ee406eSdrh #endif
2347ceea3321Sdrh 
2348ceea3321Sdrh   /* Find an empty slot and replace it */
2349ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2350ceea3321Sdrh     if( p->iReg==0 ){
2351ceea3321Sdrh       p->iLevel = pParse->iCacheLevel;
2352ceea3321Sdrh       p->iTable = iTab;
2353ceea3321Sdrh       p->iColumn = iCol;
2354ceea3321Sdrh       p->iReg = iReg;
2355ceea3321Sdrh       p->tempReg = 0;
2356ceea3321Sdrh       p->lru = pParse->iCacheCnt++;
2357ceea3321Sdrh       return;
2358ceea3321Sdrh     }
2359ceea3321Sdrh   }
2360ceea3321Sdrh 
2361ceea3321Sdrh   /* Replace the last recently used */
2362ceea3321Sdrh   minLru = 0x7fffffff;
2363ceea3321Sdrh   idxLru = -1;
2364ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2365ceea3321Sdrh     if( p->lru<minLru ){
2366ceea3321Sdrh       idxLru = i;
2367ceea3321Sdrh       minLru = p->lru;
2368ceea3321Sdrh     }
2369ceea3321Sdrh   }
237020411ea7Sdrh   if( ALWAYS(idxLru>=0) ){
2371ceea3321Sdrh     p = &pParse->aColCache[idxLru];
2372ceea3321Sdrh     p->iLevel = pParse->iCacheLevel;
2373ceea3321Sdrh     p->iTable = iTab;
2374ceea3321Sdrh     p->iColumn = iCol;
2375ceea3321Sdrh     p->iReg = iReg;
2376ceea3321Sdrh     p->tempReg = 0;
2377ceea3321Sdrh     p->lru = pParse->iCacheCnt++;
2378ceea3321Sdrh     return;
2379ceea3321Sdrh   }
2380ceea3321Sdrh }
2381ceea3321Sdrh 
2382ceea3321Sdrh /*
2383f49f3523Sdrh ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2384f49f3523Sdrh ** Purge the range of registers from the column cache.
2385ceea3321Sdrh */
2386f49f3523Sdrh void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
2387ceea3321Sdrh   int i;
2388f49f3523Sdrh   int iLast = iReg + nReg - 1;
2389ceea3321Sdrh   struct yColCache *p;
2390ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2391f49f3523Sdrh     int r = p->iReg;
2392f49f3523Sdrh     if( r>=iReg && r<=iLast ){
2393ceea3321Sdrh       cacheEntryClear(pParse, p);
2394ceea3321Sdrh       p->iReg = 0;
2395ceea3321Sdrh     }
2396ceea3321Sdrh   }
2397ceea3321Sdrh }
2398ceea3321Sdrh 
2399ceea3321Sdrh /*
2400ceea3321Sdrh ** Remember the current column cache context.  Any new entries added
2401ceea3321Sdrh ** added to the column cache after this call are removed when the
2402ceea3321Sdrh ** corresponding pop occurs.
2403ceea3321Sdrh */
2404ceea3321Sdrh void sqlite3ExprCachePush(Parse *pParse){
2405ceea3321Sdrh   pParse->iCacheLevel++;
24069ac7962aSdrh #ifdef SQLITE_DEBUG
24079ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
24089ac7962aSdrh     printf("PUSH to %d\n", pParse->iCacheLevel);
24099ac7962aSdrh   }
24109ac7962aSdrh #endif
2411ceea3321Sdrh }
2412ceea3321Sdrh 
2413ceea3321Sdrh /*
2414ceea3321Sdrh ** Remove from the column cache any entries that were added since the
2415d2490904Sdrh ** the previous sqlite3ExprCachePush operation.  In other words, restore
2416d2490904Sdrh ** the cache to the state it was in prior the most recent Push.
2417ceea3321Sdrh */
2418d2490904Sdrh void sqlite3ExprCachePop(Parse *pParse){
2419ceea3321Sdrh   int i;
2420ceea3321Sdrh   struct yColCache *p;
2421d2490904Sdrh   assert( pParse->iCacheLevel>=1 );
2422d2490904Sdrh   pParse->iCacheLevel--;
24239ac7962aSdrh #ifdef SQLITE_DEBUG
24249ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
24259ac7962aSdrh     printf("POP  to %d\n", pParse->iCacheLevel);
24269ac7962aSdrh   }
24279ac7962aSdrh #endif
2428ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2429ceea3321Sdrh     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2430ceea3321Sdrh       cacheEntryClear(pParse, p);
2431ceea3321Sdrh       p->iReg = 0;
2432ceea3321Sdrh     }
2433ceea3321Sdrh   }
2434ceea3321Sdrh }
2435945498f3Sdrh 
2436945498f3Sdrh /*
24375cd79239Sdrh ** When a cached column is reused, make sure that its register is
24385cd79239Sdrh ** no longer available as a temp register.  ticket #3879:  that same
24395cd79239Sdrh ** register might be in the cache in multiple places, so be sure to
24405cd79239Sdrh ** get them all.
24415cd79239Sdrh */
24425cd79239Sdrh static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
24435cd79239Sdrh   int i;
24445cd79239Sdrh   struct yColCache *p;
24455cd79239Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
24465cd79239Sdrh     if( p->iReg==iReg ){
24475cd79239Sdrh       p->tempReg = 0;
24485cd79239Sdrh     }
24495cd79239Sdrh   }
24505cd79239Sdrh }
24515cd79239Sdrh 
24521f9ca2c8Sdrh /* Generate code that will load into register regOut a value that is
24531f9ca2c8Sdrh ** appropriate for the iIdxCol-th column of index pIdx.
24541f9ca2c8Sdrh */
24551f9ca2c8Sdrh void sqlite3ExprCodeLoadIndexColumn(
24561f9ca2c8Sdrh   Parse *pParse,  /* The parsing context */
24571f9ca2c8Sdrh   Index *pIdx,    /* The index whose column is to be loaded */
24581f9ca2c8Sdrh   int iTabCur,    /* Cursor pointing to a table row */
24591f9ca2c8Sdrh   int iIdxCol,    /* The column of the index to be loaded */
24601f9ca2c8Sdrh   int regOut      /* Store the index column value in this register */
24611f9ca2c8Sdrh ){
24621f9ca2c8Sdrh   i16 iTabCol = pIdx->aiColumn[iIdxCol];
24634b92f98cSdrh   if( iTabCol==XN_EXPR ){
24641f9ca2c8Sdrh     assert( pIdx->aColExpr );
24651f9ca2c8Sdrh     assert( pIdx->aColExpr->nExpr>iIdxCol );
24661f9ca2c8Sdrh     pParse->iSelfTab = iTabCur;
24671f9ca2c8Sdrh     sqlite3ExprCode(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
24684b92f98cSdrh   }else{
24694b92f98cSdrh     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
24704b92f98cSdrh                                     iTabCol, regOut);
24714b92f98cSdrh   }
24721f9ca2c8Sdrh }
24731f9ca2c8Sdrh 
24745cd79239Sdrh /*
24755c092e8aSdrh ** Generate code to extract the value of the iCol-th column of a table.
24765c092e8aSdrh */
24775c092e8aSdrh void sqlite3ExprCodeGetColumnOfTable(
24785c092e8aSdrh   Vdbe *v,        /* The VDBE under construction */
24795c092e8aSdrh   Table *pTab,    /* The table containing the value */
2480313619f5Sdrh   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
24815c092e8aSdrh   int iCol,       /* Index of the column to extract */
2482313619f5Sdrh   int regOut      /* Extract the value into this register */
24835c092e8aSdrh ){
24845c092e8aSdrh   if( iCol<0 || iCol==pTab->iPKey ){
24855c092e8aSdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
24865c092e8aSdrh   }else{
24875c092e8aSdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
2488ee0ec8e1Sdrh     int x = iCol;
2489ee0ec8e1Sdrh     if( !HasRowid(pTab) ){
2490ee0ec8e1Sdrh       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
2491ee0ec8e1Sdrh     }
2492ee0ec8e1Sdrh     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
24935c092e8aSdrh   }
24945c092e8aSdrh   if( iCol>=0 ){
24955c092e8aSdrh     sqlite3ColumnDefault(v, pTab, iCol, regOut);
24965c092e8aSdrh   }
24975c092e8aSdrh }
24985c092e8aSdrh 
24995c092e8aSdrh /*
2500945498f3Sdrh ** Generate code that will extract the iColumn-th column from
2501ce78bc6eSdrh ** table pTab and store the column value in a register.
2502ce78bc6eSdrh **
2503ce78bc6eSdrh ** An effort is made to store the column value in register iReg.  This
2504ce78bc6eSdrh ** is not garanteeed for GetColumn() - the result can be stored in
2505ce78bc6eSdrh ** any register.  But the result is guaranteed to land in register iReg
2506ce78bc6eSdrh ** for GetColumnToReg().
2507e55cbd72Sdrh **
2508e55cbd72Sdrh ** There must be an open cursor to pTab in iTable when this routine
2509e55cbd72Sdrh ** is called.  If iColumn<0 then code is generated that extracts the rowid.
2510945498f3Sdrh */
2511e55cbd72Sdrh int sqlite3ExprCodeGetColumn(
2512e55cbd72Sdrh   Parse *pParse,   /* Parsing and code generating context */
25132133d822Sdrh   Table *pTab,     /* Description of the table we are reading from */
25142133d822Sdrh   int iColumn,     /* Index of the table column */
25152133d822Sdrh   int iTable,      /* The cursor pointing to the table */
2516a748fdccSdrh   int iReg,        /* Store results here */
2517ce78bc6eSdrh   u8 p5            /* P5 value for OP_Column + FLAGS */
25182133d822Sdrh ){
2519e55cbd72Sdrh   Vdbe *v = pParse->pVdbe;
2520e55cbd72Sdrh   int i;
2521da250ea5Sdrh   struct yColCache *p;
2522e55cbd72Sdrh 
2523ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2524b6da74ebSdrh     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
2525ceea3321Sdrh       p->lru = pParse->iCacheCnt++;
25265cd79239Sdrh       sqlite3ExprCachePinRegister(pParse, p->iReg);
2527da250ea5Sdrh       return p->iReg;
2528e55cbd72Sdrh     }
2529e55cbd72Sdrh   }
2530e55cbd72Sdrh   assert( v!=0 );
25315c092e8aSdrh   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
2532a748fdccSdrh   if( p5 ){
2533a748fdccSdrh     sqlite3VdbeChangeP5(v, p5);
2534a748fdccSdrh   }else{
2535ceea3321Sdrh     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2536a748fdccSdrh   }
2537e55cbd72Sdrh   return iReg;
2538e55cbd72Sdrh }
2539ce78bc6eSdrh void sqlite3ExprCodeGetColumnToReg(
2540ce78bc6eSdrh   Parse *pParse,   /* Parsing and code generating context */
2541ce78bc6eSdrh   Table *pTab,     /* Description of the table we are reading from */
2542ce78bc6eSdrh   int iColumn,     /* Index of the table column */
2543ce78bc6eSdrh   int iTable,      /* The cursor pointing to the table */
2544ce78bc6eSdrh   int iReg         /* Store results here */
2545ce78bc6eSdrh ){
2546ce78bc6eSdrh   int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
2547ce78bc6eSdrh   if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
2548ce78bc6eSdrh }
2549ce78bc6eSdrh 
2550e55cbd72Sdrh 
2551e55cbd72Sdrh /*
2552ceea3321Sdrh ** Clear all column cache entries.
2553e55cbd72Sdrh */
2554ceea3321Sdrh void sqlite3ExprCacheClear(Parse *pParse){
2555e55cbd72Sdrh   int i;
2556ceea3321Sdrh   struct yColCache *p;
2557ceea3321Sdrh 
25589ac7962aSdrh #if SQLITE_DEBUG
25599ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
25609ac7962aSdrh     printf("CLEAR\n");
25619ac7962aSdrh   }
25629ac7962aSdrh #endif
2563ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2564ceea3321Sdrh     if( p->iReg ){
2565ceea3321Sdrh       cacheEntryClear(pParse, p);
2566ceea3321Sdrh       p->iReg = 0;
2567e55cbd72Sdrh     }
2568da250ea5Sdrh   }
2569da250ea5Sdrh }
2570e55cbd72Sdrh 
2571e55cbd72Sdrh /*
2572da250ea5Sdrh ** Record the fact that an affinity change has occurred on iCount
2573da250ea5Sdrh ** registers starting with iStart.
2574e55cbd72Sdrh */
2575da250ea5Sdrh void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2576f49f3523Sdrh   sqlite3ExprCacheRemove(pParse, iStart, iCount);
2577e55cbd72Sdrh }
2578e55cbd72Sdrh 
2579e55cbd72Sdrh /*
2580b21e7c70Sdrh ** Generate code to move content from registers iFrom...iFrom+nReg-1
2581b21e7c70Sdrh ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
2582e55cbd72Sdrh */
2583b21e7c70Sdrh void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
2584e8e4af76Sdrh   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
2585079a3072Sdrh   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
2586236241aeSdrh   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
2587945498f3Sdrh }
2588945498f3Sdrh 
2589f49f3523Sdrh #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
259092b01d53Sdrh /*
2591652fbf55Sdrh ** Return true if any register in the range iFrom..iTo (inclusive)
2592652fbf55Sdrh ** is used as part of the column cache.
2593f49f3523Sdrh **
2594f49f3523Sdrh ** This routine is used within assert() and testcase() macros only
2595f49f3523Sdrh ** and does not appear in a normal build.
2596652fbf55Sdrh */
2597652fbf55Sdrh static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2598652fbf55Sdrh   int i;
2599ceea3321Sdrh   struct yColCache *p;
2600ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2601ceea3321Sdrh     int r = p->iReg;
2602f49f3523Sdrh     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
2603652fbf55Sdrh   }
2604652fbf55Sdrh   return 0;
2605652fbf55Sdrh }
2606f49f3523Sdrh #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
2607652fbf55Sdrh 
2608652fbf55Sdrh /*
2609a4c3c87eSdrh ** Convert an expression node to a TK_REGISTER
2610a4c3c87eSdrh */
2611a4c3c87eSdrh static void exprToRegister(Expr *p, int iReg){
2612a4c3c87eSdrh   p->op2 = p->op;
2613a4c3c87eSdrh   p->op = TK_REGISTER;
2614a4c3c87eSdrh   p->iTable = iReg;
2615a4c3c87eSdrh   ExprClearProperty(p, EP_Skip);
2616a4c3c87eSdrh }
2617a4c3c87eSdrh 
2618a4c3c87eSdrh /*
2619cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
26202dcef11bSdrh ** expression.  Attempt to store the results in register "target".
26212dcef11bSdrh ** Return the register where results are stored.
2622389a1adbSdrh **
26238b213899Sdrh ** With this routine, there is no guarantee that results will
26242dcef11bSdrh ** be stored in target.  The result might be stored in some other
26252dcef11bSdrh ** register if it is convenient to do so.  The calling function
26262dcef11bSdrh ** must check the return code and move the results to the desired
26272dcef11bSdrh ** register.
2628cce7d176Sdrh */
2629678ccce8Sdrh int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
26302dcef11bSdrh   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
26312dcef11bSdrh   int op;                   /* The opcode being coded */
26322dcef11bSdrh   int inReg = target;       /* Results stored in register inReg */
26332dcef11bSdrh   int regFree1 = 0;         /* If non-zero free this temporary register */
26342dcef11bSdrh   int regFree2 = 0;         /* If non-zero free this temporary register */
2635678ccce8Sdrh   int r1, r2, r3, r4;       /* Various register numbers */
263620411ea7Sdrh   sqlite3 *db = pParse->db; /* The database connection */
263710d1edf0Sdrh   Expr tempX;               /* Temporary expression node */
2638ffe07b2dSdrh 
26399cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
264020411ea7Sdrh   if( v==0 ){
264120411ea7Sdrh     assert( pParse->db->mallocFailed );
264220411ea7Sdrh     return 0;
264320411ea7Sdrh   }
2644389a1adbSdrh 
2645389a1adbSdrh   if( pExpr==0 ){
2646389a1adbSdrh     op = TK_NULL;
2647389a1adbSdrh   }else{
2648f2bc013cSdrh     op = pExpr->op;
2649389a1adbSdrh   }
2650f2bc013cSdrh   switch( op ){
265113449892Sdrh     case TK_AGG_COLUMN: {
265213449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
265313449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
265413449892Sdrh       if( !pAggInfo->directMode ){
26559de221dfSdrh         assert( pCol->iMem>0 );
26569de221dfSdrh         inReg = pCol->iMem;
265713449892Sdrh         break;
265813449892Sdrh       }else if( pAggInfo->useSortingIdx ){
26595134d135Sdan         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
2660389a1adbSdrh                               pCol->iSorterColumn, target);
266113449892Sdrh         break;
266213449892Sdrh       }
266313449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
266413449892Sdrh     }
2665967e8b73Sdrh     case TK_COLUMN: {
2666b2b9d3d7Sdrh       int iTab = pExpr->iTable;
2667b2b9d3d7Sdrh       if( iTab<0 ){
2668b2b9d3d7Sdrh         if( pParse->ckBase>0 ){
2669b2b9d3d7Sdrh           /* Generating CHECK constraints or inserting into partial index */
2670aa9b8963Sdrh           inReg = pExpr->iColumn + pParse->ckBase;
2671b2b9d3d7Sdrh           break;
2672c4a3c779Sdrh         }else{
26731f9ca2c8Sdrh           /* Coding an expression that is part of an index where column names
26741f9ca2c8Sdrh           ** in the index refer to the table to which the index belongs */
26751f9ca2c8Sdrh           iTab = pParse->iSelfTab;
26762282792aSdrh         }
2677b2b9d3d7Sdrh       }
2678b2b9d3d7Sdrh       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2679b2b9d3d7Sdrh                                pExpr->iColumn, iTab, target,
2680b2b9d3d7Sdrh                                pExpr->op2);
2681cce7d176Sdrh       break;
2682cce7d176Sdrh     }
2683cce7d176Sdrh     case TK_INTEGER: {
268413573c71Sdrh       codeInteger(pParse, pExpr, 0, target);
2685fec19aadSdrh       break;
268651e9a445Sdrh     }
268713573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2688598f1340Sdrh     case TK_FLOAT: {
268933e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
269033e619fcSdrh       codeReal(v, pExpr->u.zToken, 0, target);
2691598f1340Sdrh       break;
2692598f1340Sdrh     }
269313573c71Sdrh #endif
2694fec19aadSdrh     case TK_STRING: {
269533e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2696076e85f5Sdrh       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
2697cce7d176Sdrh       break;
2698cce7d176Sdrh     }
2699f0863fe5Sdrh     case TK_NULL: {
27009de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2701f0863fe5Sdrh       break;
2702f0863fe5Sdrh     }
27035338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
2704c572ef7fSdanielk1977     case TK_BLOB: {
27056c8c6cecSdrh       int n;
27066c8c6cecSdrh       const char *z;
2707ca48c90fSdrh       char *zBlob;
270833e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
270933e619fcSdrh       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
271033e619fcSdrh       assert( pExpr->u.zToken[1]=='\'' );
271133e619fcSdrh       z = &pExpr->u.zToken[2];
2712b7916a78Sdrh       n = sqlite3Strlen30(z) - 1;
2713b7916a78Sdrh       assert( z[n]=='\'' );
2714ca48c90fSdrh       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2715ca48c90fSdrh       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2716c572ef7fSdanielk1977       break;
2717c572ef7fSdanielk1977     }
27185338a5f7Sdanielk1977 #endif
271950457896Sdrh     case TK_VARIABLE: {
272033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
272133e619fcSdrh       assert( pExpr->u.zToken!=0 );
272233e619fcSdrh       assert( pExpr->u.zToken[0]!=0 );
2723eaf52d88Sdrh       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
272433e619fcSdrh       if( pExpr->u.zToken[1]!=0 ){
272504e9eeadSdrh         assert( pExpr->u.zToken[0]=='?'
272604e9eeadSdrh              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
272704e9eeadSdrh         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
2728895d7472Sdrh       }
272950457896Sdrh       break;
273050457896Sdrh     }
27314e0cff60Sdrh     case TK_REGISTER: {
27329de221dfSdrh       inReg = pExpr->iTable;
27334e0cff60Sdrh       break;
27344e0cff60Sdrh     }
2735487e262fSdrh #ifndef SQLITE_OMIT_CAST
2736487e262fSdrh     case TK_CAST: {
2737487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
27382dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
27391735fa88Sdrh       if( inReg!=target ){
27401735fa88Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
27411735fa88Sdrh         inReg = target;
27421735fa88Sdrh       }
27434169e430Sdrh       sqlite3VdbeAddOp2(v, OP_Cast, target,
27444169e430Sdrh                         sqlite3AffinityType(pExpr->u.zToken, 0));
2745c5499befSdrh       testcase( usedAsColumnCache(pParse, inReg, inReg) );
2746b3843a82Sdrh       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
2747487e262fSdrh       break;
2748487e262fSdrh     }
2749487e262fSdrh #endif /* SQLITE_OMIT_CAST */
2750c9b84a1fSdrh     case TK_LT:
2751c9b84a1fSdrh     case TK_LE:
2752c9b84a1fSdrh     case TK_GT:
2753c9b84a1fSdrh     case TK_GE:
2754c9b84a1fSdrh     case TK_NE:
2755c9b84a1fSdrh     case TK_EQ: {
2756b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2757b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
275835573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
275935573356Sdrh                   r1, r2, inReg, SQLITE_STOREP2);
27607d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
27617d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
27627d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
27637d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
27647d176105Sdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
27657d176105Sdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
2766c5499befSdrh       testcase( regFree1==0 );
2767c5499befSdrh       testcase( regFree2==0 );
2768a37cdde0Sdanielk1977       break;
2769c9b84a1fSdrh     }
27706a2fe093Sdrh     case TK_IS:
27716a2fe093Sdrh     case TK_ISNOT: {
27726a2fe093Sdrh       testcase( op==TK_IS );
27736a2fe093Sdrh       testcase( op==TK_ISNOT );
2774b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2775b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
27766a2fe093Sdrh       op = (op==TK_IS) ? TK_EQ : TK_NE;
27776a2fe093Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
27786a2fe093Sdrh                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
27797d176105Sdrh       VdbeCoverageIf(v, op==TK_EQ);
27807d176105Sdrh       VdbeCoverageIf(v, op==TK_NE);
27816a2fe093Sdrh       testcase( regFree1==0 );
27826a2fe093Sdrh       testcase( regFree2==0 );
27836a2fe093Sdrh       break;
27846a2fe093Sdrh     }
2785cce7d176Sdrh     case TK_AND:
2786cce7d176Sdrh     case TK_OR:
2787cce7d176Sdrh     case TK_PLUS:
2788cce7d176Sdrh     case TK_STAR:
2789cce7d176Sdrh     case TK_MINUS:
2790bf4133cbSdrh     case TK_REM:
2791bf4133cbSdrh     case TK_BITAND:
2792bf4133cbSdrh     case TK_BITOR:
279317c40294Sdrh     case TK_SLASH:
2794bf4133cbSdrh     case TK_LSHIFT:
2795855eb1cfSdrh     case TK_RSHIFT:
27960040077dSdrh     case TK_CONCAT: {
27977d176105Sdrh       assert( TK_AND==OP_And );            testcase( op==TK_AND );
27987d176105Sdrh       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
27997d176105Sdrh       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
28007d176105Sdrh       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
28017d176105Sdrh       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
28027d176105Sdrh       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
28037d176105Sdrh       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
28047d176105Sdrh       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
28057d176105Sdrh       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
28067d176105Sdrh       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
28077d176105Sdrh       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
28082dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
28092dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
28105b6afba9Sdrh       sqlite3VdbeAddOp3(v, op, r2, r1, target);
2811c5499befSdrh       testcase( regFree1==0 );
2812c5499befSdrh       testcase( regFree2==0 );
28130040077dSdrh       break;
28140040077dSdrh     }
2815cce7d176Sdrh     case TK_UMINUS: {
2816fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
2817fec19aadSdrh       assert( pLeft );
281813573c71Sdrh       if( pLeft->op==TK_INTEGER ){
281913573c71Sdrh         codeInteger(pParse, pLeft, 1, target);
282013573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
282113573c71Sdrh       }else if( pLeft->op==TK_FLOAT ){
282233e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
282333e619fcSdrh         codeReal(v, pLeft->u.zToken, 1, target);
282413573c71Sdrh #endif
28253c84ddffSdrh       }else{
282610d1edf0Sdrh         tempX.op = TK_INTEGER;
282710d1edf0Sdrh         tempX.flags = EP_IntValue|EP_TokenOnly;
282810d1edf0Sdrh         tempX.u.iValue = 0;
282910d1edf0Sdrh         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
2830e55cbd72Sdrh         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
28312dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
2832c5499befSdrh         testcase( regFree2==0 );
28333c84ddffSdrh       }
28349de221dfSdrh       inReg = target;
28356e142f54Sdrh       break;
28366e142f54Sdrh     }
2837bf4133cbSdrh     case TK_BITNOT:
28386e142f54Sdrh     case TK_NOT: {
28397d176105Sdrh       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
28407d176105Sdrh       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
2841e99fa2afSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2842e99fa2afSdrh       testcase( regFree1==0 );
2843e99fa2afSdrh       inReg = target;
2844e99fa2afSdrh       sqlite3VdbeAddOp2(v, op, r1, inReg);
2845cce7d176Sdrh       break;
2846cce7d176Sdrh     }
2847cce7d176Sdrh     case TK_ISNULL:
2848cce7d176Sdrh     case TK_NOTNULL: {
28496a288a33Sdrh       int addr;
28507d176105Sdrh       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
28517d176105Sdrh       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
28529de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
28532dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2854c5499befSdrh       testcase( regFree1==0 );
28552dcef11bSdrh       addr = sqlite3VdbeAddOp1(v, op, r1);
28567d176105Sdrh       VdbeCoverageIf(v, op==TK_ISNULL);
28577d176105Sdrh       VdbeCoverageIf(v, op==TK_NOTNULL);
2858a976979bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
28596a288a33Sdrh       sqlite3VdbeJumpHere(v, addr);
2860a37cdde0Sdanielk1977       break;
2861f2bc013cSdrh     }
28622282792aSdrh     case TK_AGG_FUNCTION: {
286313449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
28647e56e711Sdrh       if( pInfo==0 ){
286533e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
286633e619fcSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
28677e56e711Sdrh       }else{
28689de221dfSdrh         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
28697e56e711Sdrh       }
28702282792aSdrh       break;
28712282792aSdrh     }
2872cce7d176Sdrh     case TK_FUNCTION: {
287312ffee8cSdrh       ExprList *pFarg;       /* List of function arguments */
287412ffee8cSdrh       int nFarg;             /* Number of function arguments */
287512ffee8cSdrh       FuncDef *pDef;         /* The function definition object */
287612ffee8cSdrh       int nId;               /* Length of the function name in bytes */
287712ffee8cSdrh       const char *zId;       /* The function name */
2878693e6719Sdrh       u32 constMask = 0;     /* Mask of function arguments that are constant */
287912ffee8cSdrh       int i;                 /* Loop counter */
288012ffee8cSdrh       u8 enc = ENC(db);      /* The text encoding used by this database */
288112ffee8cSdrh       CollSeq *pColl = 0;    /* A collating sequence */
288217435752Sdrh 
28836ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2884c5cd1249Sdrh       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
288512ffee8cSdrh         pFarg = 0;
288612ffee8cSdrh       }else{
288712ffee8cSdrh         pFarg = pExpr->x.pList;
288812ffee8cSdrh       }
288912ffee8cSdrh       nFarg = pFarg ? pFarg->nExpr : 0;
289033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
289133e619fcSdrh       zId = pExpr->u.zToken;
2892b7916a78Sdrh       nId = sqlite3Strlen30(zId);
289312ffee8cSdrh       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
28940c4de2d9Sdrh       if( pDef==0 || pDef->xFunc==0 ){
2895feb306f5Sdrh         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
2896feb306f5Sdrh         break;
2897feb306f5Sdrh       }
2898ae6bb957Sdrh 
2899ae6bb957Sdrh       /* Attempt a direct implementation of the built-in COALESCE() and
290060ec914cSpeter.d.reid       ** IFNULL() functions.  This avoids unnecessary evaluation of
2901ae6bb957Sdrh       ** arguments past the first non-NULL argument.
2902ae6bb957Sdrh       */
2903d36e1041Sdrh       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
2904ae6bb957Sdrh         int endCoalesce = sqlite3VdbeMakeLabel(v);
2905ae6bb957Sdrh         assert( nFarg>=2 );
2906ae6bb957Sdrh         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
2907ae6bb957Sdrh         for(i=1; i<nFarg; i++){
2908ae6bb957Sdrh           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
2909688852abSdrh           VdbeCoverage(v);
2910f49f3523Sdrh           sqlite3ExprCacheRemove(pParse, target, 1);
2911ae6bb957Sdrh           sqlite3ExprCachePush(pParse);
2912ae6bb957Sdrh           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
2913d2490904Sdrh           sqlite3ExprCachePop(pParse);
2914ae6bb957Sdrh         }
2915ae6bb957Sdrh         sqlite3VdbeResolveLabel(v, endCoalesce);
2916ae6bb957Sdrh         break;
2917ae6bb957Sdrh       }
2918ae6bb957Sdrh 
2919cca9f3d2Sdrh       /* The UNLIKELY() function is a no-op.  The result is the value
2920cca9f3d2Sdrh       ** of the first argument.
2921cca9f3d2Sdrh       */
2922cca9f3d2Sdrh       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
2923cca9f3d2Sdrh         assert( nFarg>=1 );
29245f02ab09Sdrh         inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
2925cca9f3d2Sdrh         break;
2926cca9f3d2Sdrh       }
2927ae6bb957Sdrh 
2928d1a01edaSdrh       for(i=0; i<nFarg; i++){
2929d1a01edaSdrh         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
2930693e6719Sdrh           testcase( i==31 );
2931693e6719Sdrh           constMask |= MASKBIT32(i);
2932d1a01edaSdrh         }
2933d1a01edaSdrh         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
2934d1a01edaSdrh           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
2935d1a01edaSdrh         }
2936d1a01edaSdrh       }
293712ffee8cSdrh       if( pFarg ){
2938d1a01edaSdrh         if( constMask ){
2939d1a01edaSdrh           r1 = pParse->nMem+1;
2940d1a01edaSdrh           pParse->nMem += nFarg;
2941d1a01edaSdrh         }else{
294212ffee8cSdrh           r1 = sqlite3GetTempRange(pParse, nFarg);
2943d1a01edaSdrh         }
2944a748fdccSdrh 
2945a748fdccSdrh         /* For length() and typeof() functions with a column argument,
2946a748fdccSdrh         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
2947a748fdccSdrh         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
2948a748fdccSdrh         ** loading.
2949a748fdccSdrh         */
2950d36e1041Sdrh         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
29514e245a4cSdrh           u8 exprOp;
2952a748fdccSdrh           assert( nFarg==1 );
2953a748fdccSdrh           assert( pFarg->a[0].pExpr!=0 );
29544e245a4cSdrh           exprOp = pFarg->a[0].pExpr->op;
29554e245a4cSdrh           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
2956a748fdccSdrh             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
2957a748fdccSdrh             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
2958b1fba286Sdrh             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
2959b1fba286Sdrh             pFarg->a[0].pExpr->op2 =
2960b1fba286Sdrh                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
2961a748fdccSdrh           }
2962a748fdccSdrh         }
2963a748fdccSdrh 
2964d7d385ddSdrh         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
29655579d59fSdrh         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
2966d1a01edaSdrh                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
2967d2490904Sdrh         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
2968892d3179Sdrh       }else{
296912ffee8cSdrh         r1 = 0;
2970892d3179Sdrh       }
2971b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
2972a43fa227Sdrh       /* Possibly overload the function if the first argument is
2973a43fa227Sdrh       ** a virtual table column.
2974a43fa227Sdrh       **
2975a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2976a43fa227Sdrh       ** second argument, not the first, as the argument to test to
2977a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
2978a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
2979a43fa227Sdrh       ** control overloading) ends up as the second argument to the
2980a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
2981a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
2982a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
2983a43fa227Sdrh       */
298412ffee8cSdrh       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
298512ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
298612ffee8cSdrh       }else if( nFarg>0 ){
298712ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
2988b7f6f68fSdrh       }
2989b7f6f68fSdrh #endif
2990d36e1041Sdrh       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
29918b213899Sdrh         if( !pColl ) pColl = db->pDfltColl;
299266a5167bSdrh         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
2993682f68b0Sdanielk1977       }
29949c7c913cSdrh       sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
299566a5167bSdrh                         (char*)pDef, P4_FUNCDEF);
299612ffee8cSdrh       sqlite3VdbeChangeP5(v, (u8)nFarg);
2997d1a01edaSdrh       if( nFarg && constMask==0 ){
299812ffee8cSdrh         sqlite3ReleaseTempRange(pParse, r1, nFarg);
29992dcef11bSdrh       }
30006ec2733bSdrh       break;
30016ec2733bSdrh     }
3002fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
3003fe2093d7Sdrh     case TK_EXISTS:
300419a775c2Sdrh     case TK_SELECT: {
3005c5499befSdrh       testcase( op==TK_EXISTS );
3006c5499befSdrh       testcase( op==TK_SELECT );
30071450bc6eSdrh       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
300819a775c2Sdrh       break;
300919a775c2Sdrh     }
3010fef5208cSdrh     case TK_IN: {
3011e3365e6cSdrh       int destIfFalse = sqlite3VdbeMakeLabel(v);
3012e3365e6cSdrh       int destIfNull = sqlite3VdbeMakeLabel(v);
3013e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3014e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
301566ba23ceSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3016e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
3017e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3018e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfNull);
3019fef5208cSdrh       break;
3020fef5208cSdrh     }
3021e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
3022e3365e6cSdrh 
3023e3365e6cSdrh 
30242dcef11bSdrh     /*
30252dcef11bSdrh     **    x BETWEEN y AND z
30262dcef11bSdrh     **
30272dcef11bSdrh     ** This is equivalent to
30282dcef11bSdrh     **
30292dcef11bSdrh     **    x>=y AND x<=z
30302dcef11bSdrh     **
30312dcef11bSdrh     ** X is stored in pExpr->pLeft.
30322dcef11bSdrh     ** Y is stored in pExpr->pList->a[0].pExpr.
30332dcef11bSdrh     ** Z is stored in pExpr->pList->a[1].pExpr.
30342dcef11bSdrh     */
3035fef5208cSdrh     case TK_BETWEEN: {
3036be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
30376ab3a2ecSdanielk1977       struct ExprList_item *pLItem = pExpr->x.pList->a;
3038be5c89acSdrh       Expr *pRight = pLItem->pExpr;
303935573356Sdrh 
3040b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3041b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
3042c5499befSdrh       testcase( regFree1==0 );
3043c5499befSdrh       testcase( regFree2==0 );
30442dcef11bSdrh       r3 = sqlite3GetTempReg(pParse);
3045678ccce8Sdrh       r4 = sqlite3GetTempReg(pParse);
304635573356Sdrh       codeCompare(pParse, pLeft, pRight, OP_Ge,
30477d176105Sdrh                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
3048be5c89acSdrh       pLItem++;
3049be5c89acSdrh       pRight = pLItem->pExpr;
30502dcef11bSdrh       sqlite3ReleaseTempReg(pParse, regFree2);
30512dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
3052c5499befSdrh       testcase( regFree2==0 );
3053678ccce8Sdrh       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
3054688852abSdrh       VdbeCoverage(v);
3055678ccce8Sdrh       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
30562dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r3);
3057678ccce8Sdrh       sqlite3ReleaseTempReg(pParse, r4);
3058fef5208cSdrh       break;
3059fef5208cSdrh     }
3060ae80ddeaSdrh     case TK_COLLATE:
30614f07e5fbSdrh     case TK_UPLUS: {
30622dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3063a2e00042Sdrh       break;
3064a2e00042Sdrh     }
30652dcef11bSdrh 
3066165921a7Sdan     case TK_TRIGGER: {
306765a7cd16Sdan       /* If the opcode is TK_TRIGGER, then the expression is a reference
306865a7cd16Sdan       ** to a column in the new.* or old.* pseudo-tables available to
306965a7cd16Sdan       ** trigger programs. In this case Expr.iTable is set to 1 for the
307065a7cd16Sdan       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
307165a7cd16Sdan       ** is set to the column of the pseudo-table to read, or to -1 to
307265a7cd16Sdan       ** read the rowid field.
307365a7cd16Sdan       **
307465a7cd16Sdan       ** The expression is implemented using an OP_Param opcode. The p1
307565a7cd16Sdan       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
307665a7cd16Sdan       ** to reference another column of the old.* pseudo-table, where
307765a7cd16Sdan       ** i is the index of the column. For a new.rowid reference, p1 is
307865a7cd16Sdan       ** set to (n+1), where n is the number of columns in each pseudo-table.
307965a7cd16Sdan       ** For a reference to any other column in the new.* pseudo-table, p1
308065a7cd16Sdan       ** is set to (n+2+i), where n and i are as defined previously. For
308165a7cd16Sdan       ** example, if the table on which triggers are being fired is
308265a7cd16Sdan       ** declared as:
308365a7cd16Sdan       **
308465a7cd16Sdan       **   CREATE TABLE t1(a, b);
308565a7cd16Sdan       **
308665a7cd16Sdan       ** Then p1 is interpreted as follows:
308765a7cd16Sdan       **
308865a7cd16Sdan       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
308965a7cd16Sdan       **   p1==1   ->    old.a         p1==4   ->    new.a
309065a7cd16Sdan       **   p1==2   ->    old.b         p1==5   ->    new.b
309165a7cd16Sdan       */
30922832ad42Sdan       Table *pTab = pExpr->pTab;
309365a7cd16Sdan       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
309465a7cd16Sdan 
309565a7cd16Sdan       assert( pExpr->iTable==0 || pExpr->iTable==1 );
309665a7cd16Sdan       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
309765a7cd16Sdan       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
309865a7cd16Sdan       assert( p1>=0 && p1<(pTab->nCol*2+2) );
309965a7cd16Sdan 
310065a7cd16Sdan       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
310176d462eeSdan       VdbeComment((v, "%s.%s -> $%d",
3102165921a7Sdan         (pExpr->iTable ? "new" : "old"),
310376d462eeSdan         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
310476d462eeSdan         target
3105165921a7Sdan       ));
310665a7cd16Sdan 
310744dbca83Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
310865a7cd16Sdan       /* If the column has REAL affinity, it may currently be stored as an
3109113762a2Sdrh       ** integer. Use OP_RealAffinity to make sure it is really real.
3110113762a2Sdrh       **
3111113762a2Sdrh       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3112113762a2Sdrh       ** floating point when extracting it from the record.  */
31132832ad42Sdan       if( pExpr->iColumn>=0
31142832ad42Sdan        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
31152832ad42Sdan       ){
31162832ad42Sdan         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
31172832ad42Sdan       }
311844dbca83Sdrh #endif
3119165921a7Sdan       break;
3120165921a7Sdan     }
3121165921a7Sdan 
3122165921a7Sdan 
31232dcef11bSdrh     /*
31242dcef11bSdrh     ** Form A:
31252dcef11bSdrh     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
31262dcef11bSdrh     **
31272dcef11bSdrh     ** Form B:
31282dcef11bSdrh     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
31292dcef11bSdrh     **
31302dcef11bSdrh     ** Form A is can be transformed into the equivalent form B as follows:
31312dcef11bSdrh     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
31322dcef11bSdrh     **        WHEN x=eN THEN rN ELSE y END
31332dcef11bSdrh     **
31342dcef11bSdrh     ** X (if it exists) is in pExpr->pLeft.
3135c5cd1249Sdrh     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3136c5cd1249Sdrh     ** odd.  The Y is also optional.  If the number of elements in x.pList
3137c5cd1249Sdrh     ** is even, then Y is omitted and the "otherwise" result is NULL.
31382dcef11bSdrh     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
31392dcef11bSdrh     **
31402dcef11bSdrh     ** The result of the expression is the Ri for the first matching Ei,
31412dcef11bSdrh     ** or if there is no matching Ei, the ELSE term Y, or if there is
31422dcef11bSdrh     ** no ELSE term, NULL.
31432dcef11bSdrh     */
314433cd4909Sdrh     default: assert( op==TK_CASE ); {
31452dcef11bSdrh       int endLabel;                     /* GOTO label for end of CASE stmt */
31462dcef11bSdrh       int nextCase;                     /* GOTO label for next WHEN clause */
31472dcef11bSdrh       int nExpr;                        /* 2x number of WHEN terms */
31482dcef11bSdrh       int i;                            /* Loop counter */
31492dcef11bSdrh       ExprList *pEList;                 /* List of WHEN terms */
31502dcef11bSdrh       struct ExprList_item *aListelem;  /* Array of WHEN terms */
31512dcef11bSdrh       Expr opCompare;                   /* The X==Ei expression */
31522dcef11bSdrh       Expr *pX;                         /* The X expression */
31531bd10f8aSdrh       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
3154ceea3321Sdrh       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
315517a7f8ddSdrh 
31566ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
31576ab3a2ecSdanielk1977       assert(pExpr->x.pList->nExpr > 0);
31586ab3a2ecSdanielk1977       pEList = pExpr->x.pList;
3159be5c89acSdrh       aListelem = pEList->a;
3160be5c89acSdrh       nExpr = pEList->nExpr;
31612dcef11bSdrh       endLabel = sqlite3VdbeMakeLabel(v);
31622dcef11bSdrh       if( (pX = pExpr->pLeft)!=0 ){
316310d1edf0Sdrh         tempX = *pX;
316433cd4909Sdrh         testcase( pX->op==TK_COLUMN );
316510d1edf0Sdrh         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
3166c5499befSdrh         testcase( regFree1==0 );
31672dcef11bSdrh         opCompare.op = TK_EQ;
316810d1edf0Sdrh         opCompare.pLeft = &tempX;
31692dcef11bSdrh         pTest = &opCompare;
31708b1db07fSdrh         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
31718b1db07fSdrh         ** The value in regFree1 might get SCopy-ed into the file result.
31728b1db07fSdrh         ** So make sure that the regFree1 register is not reused for other
31738b1db07fSdrh         ** purposes and possibly overwritten.  */
31748b1db07fSdrh         regFree1 = 0;
3175cce7d176Sdrh       }
3176c5cd1249Sdrh       for(i=0; i<nExpr-1; i=i+2){
3177ceea3321Sdrh         sqlite3ExprCachePush(pParse);
31782dcef11bSdrh         if( pX ){
31791bd10f8aSdrh           assert( pTest!=0 );
31802dcef11bSdrh           opCompare.pRight = aListelem[i].pExpr;
3181f5905aa7Sdrh         }else{
31822dcef11bSdrh           pTest = aListelem[i].pExpr;
318317a7f8ddSdrh         }
31842dcef11bSdrh         nextCase = sqlite3VdbeMakeLabel(v);
318533cd4909Sdrh         testcase( pTest->op==TK_COLUMN );
31862dcef11bSdrh         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
3187c5499befSdrh         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
31889de221dfSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
3189076e85f5Sdrh         sqlite3VdbeGoto(v, endLabel);
3190d2490904Sdrh         sqlite3ExprCachePop(pParse);
31912dcef11bSdrh         sqlite3VdbeResolveLabel(v, nextCase);
3192f570f011Sdrh       }
3193c5cd1249Sdrh       if( (nExpr&1)!=0 ){
3194ceea3321Sdrh         sqlite3ExprCachePush(pParse);
3195c5cd1249Sdrh         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
3196d2490904Sdrh         sqlite3ExprCachePop(pParse);
319717a7f8ddSdrh       }else{
31989de221dfSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
319917a7f8ddSdrh       }
3200c1f4a19bSdanielk1977       assert( db->mallocFailed || pParse->nErr>0
3201c1f4a19bSdanielk1977            || pParse->iCacheLevel==iCacheLevel );
32022dcef11bSdrh       sqlite3VdbeResolveLabel(v, endLabel);
32036f34903eSdanielk1977       break;
32046f34903eSdanielk1977     }
32055338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
32066f34903eSdanielk1977     case TK_RAISE: {
3207165921a7Sdan       assert( pExpr->affinity==OE_Rollback
3208165921a7Sdan            || pExpr->affinity==OE_Abort
3209165921a7Sdan            || pExpr->affinity==OE_Fail
3210165921a7Sdan            || pExpr->affinity==OE_Ignore
3211165921a7Sdan       );
3212e0af83acSdan       if( !pParse->pTriggerTab ){
3213e0af83acSdan         sqlite3ErrorMsg(pParse,
3214e0af83acSdan                        "RAISE() may only be used within a trigger-program");
3215e0af83acSdan         return 0;
3216e0af83acSdan       }
3217e0af83acSdan       if( pExpr->affinity==OE_Abort ){
3218e0af83acSdan         sqlite3MayAbort(pParse);
3219e0af83acSdan       }
322033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3221e0af83acSdan       if( pExpr->affinity==OE_Ignore ){
3222e0af83acSdan         sqlite3VdbeAddOp4(
3223e0af83acSdan             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
3224688852abSdrh         VdbeCoverage(v);
3225e0af83acSdan       }else{
3226433dccfbSdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
3227f9c8ce3cSdrh                               pExpr->affinity, pExpr->u.zToken, 0, 0);
3228e0af83acSdan       }
3229e0af83acSdan 
3230ffe07b2dSdrh       break;
323117a7f8ddSdrh     }
32325338a5f7Sdanielk1977 #endif
3233ffe07b2dSdrh   }
32342dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
32352dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
32362dcef11bSdrh   return inReg;
32375b6afba9Sdrh }
32382dcef11bSdrh 
32392dcef11bSdrh /*
3240d1a01edaSdrh ** Factor out the code of the given expression to initialization time.
3241d1a01edaSdrh */
3242d673cddaSdrh void sqlite3ExprCodeAtInit(
3243d673cddaSdrh   Parse *pParse,    /* Parsing context */
3244d673cddaSdrh   Expr *pExpr,      /* The expression to code when the VDBE initializes */
3245d673cddaSdrh   int regDest,      /* Store the value in this register */
3246d673cddaSdrh   u8 reusable       /* True if this expression is reusable */
3247d673cddaSdrh ){
3248d1a01edaSdrh   ExprList *p;
3249d9f158e7Sdrh   assert( ConstFactorOk(pParse) );
3250d1a01edaSdrh   p = pParse->pConstExpr;
3251d1a01edaSdrh   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3252d1a01edaSdrh   p = sqlite3ExprListAppend(pParse, p, pExpr);
3253d673cddaSdrh   if( p ){
3254d673cddaSdrh      struct ExprList_item *pItem = &p->a[p->nExpr-1];
3255d673cddaSdrh      pItem->u.iConstExprReg = regDest;
3256d673cddaSdrh      pItem->reusable = reusable;
3257d673cddaSdrh   }
3258d1a01edaSdrh   pParse->pConstExpr = p;
3259d1a01edaSdrh }
3260d1a01edaSdrh 
3261d1a01edaSdrh /*
32622dcef11bSdrh ** Generate code to evaluate an expression and store the results
32632dcef11bSdrh ** into a register.  Return the register number where the results
32642dcef11bSdrh ** are stored.
32652dcef11bSdrh **
32662dcef11bSdrh ** If the register is a temporary register that can be deallocated,
3267678ccce8Sdrh ** then write its number into *pReg.  If the result register is not
32682dcef11bSdrh ** a temporary, then set *pReg to zero.
3269f30a969bSdrh **
3270f30a969bSdrh ** If pExpr is a constant, then this routine might generate this
3271f30a969bSdrh ** code to fill the register in the initialization section of the
3272f30a969bSdrh ** VDBE program, in order to factor it out of the evaluation loop.
32732dcef11bSdrh */
32742dcef11bSdrh int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
3275f30a969bSdrh   int r2;
3276f30a969bSdrh   pExpr = sqlite3ExprSkipCollate(pExpr);
3277d9f158e7Sdrh   if( ConstFactorOk(pParse)
3278f30a969bSdrh    && pExpr->op!=TK_REGISTER
3279f30a969bSdrh    && sqlite3ExprIsConstantNotJoin(pExpr)
3280f30a969bSdrh   ){
3281f30a969bSdrh     ExprList *p = pParse->pConstExpr;
3282f30a969bSdrh     int i;
3283f30a969bSdrh     *pReg  = 0;
3284f30a969bSdrh     if( p ){
3285d673cddaSdrh       struct ExprList_item *pItem;
3286d673cddaSdrh       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3287d673cddaSdrh         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3288d673cddaSdrh           return pItem->u.iConstExprReg;
3289f30a969bSdrh         }
3290f30a969bSdrh       }
3291f30a969bSdrh     }
3292f30a969bSdrh     r2 = ++pParse->nMem;
3293d673cddaSdrh     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
3294f30a969bSdrh   }else{
32952dcef11bSdrh     int r1 = sqlite3GetTempReg(pParse);
3296f30a969bSdrh     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
32972dcef11bSdrh     if( r2==r1 ){
32982dcef11bSdrh       *pReg = r1;
32992dcef11bSdrh     }else{
33002dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r1);
33012dcef11bSdrh       *pReg = 0;
33022dcef11bSdrh     }
3303f30a969bSdrh   }
33042dcef11bSdrh   return r2;
33052dcef11bSdrh }
33062dcef11bSdrh 
33072dcef11bSdrh /*
33082dcef11bSdrh ** Generate code that will evaluate expression pExpr and store the
33092dcef11bSdrh ** results in register target.  The results are guaranteed to appear
33102dcef11bSdrh ** in register target.
33112dcef11bSdrh */
331205a86c5cSdrh void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
33139cbf3425Sdrh   int inReg;
33149cbf3425Sdrh 
33159cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
3316ebc16717Sdrh   if( pExpr && pExpr->op==TK_REGISTER ){
3317ebc16717Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3318ebc16717Sdrh   }else{
33199cbf3425Sdrh     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
33200e359b30Sdrh     assert( pParse->pVdbe || pParse->db->mallocFailed );
33210e359b30Sdrh     if( inReg!=target && pParse->pVdbe ){
33229cbf3425Sdrh       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
332317a7f8ddSdrh     }
3324ebc16717Sdrh   }
3325cce7d176Sdrh }
3326cce7d176Sdrh 
3327cce7d176Sdrh /*
332805a86c5cSdrh ** Generate code that will evaluate expression pExpr and store the
332905a86c5cSdrh ** results in register target.  The results are guaranteed to appear
333005a86c5cSdrh ** in register target.  If the expression is constant, then this routine
333105a86c5cSdrh ** might choose to code the expression at initialization time.
333205a86c5cSdrh */
333305a86c5cSdrh void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
333405a86c5cSdrh   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
333505a86c5cSdrh     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
333605a86c5cSdrh   }else{
333705a86c5cSdrh     sqlite3ExprCode(pParse, pExpr, target);
333805a86c5cSdrh   }
3339cce7d176Sdrh }
3340cce7d176Sdrh 
3341cce7d176Sdrh /*
334260ec914cSpeter.d.reid ** Generate code that evaluates the given expression and puts the result
3343de4fcfddSdrh ** in register target.
334425303780Sdrh **
33452dcef11bSdrh ** Also make a copy of the expression results into another "cache" register
33462dcef11bSdrh ** and modify the expression so that the next time it is evaluated,
33472dcef11bSdrh ** the result is a copy of the cache register.
33482dcef11bSdrh **
33492dcef11bSdrh ** This routine is used for expressions that are used multiple
33502dcef11bSdrh ** times.  They are evaluated once and the results of the expression
33512dcef11bSdrh ** are reused.
335225303780Sdrh */
335305a86c5cSdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
335425303780Sdrh   Vdbe *v = pParse->pVdbe;
335525303780Sdrh   int iMem;
335605a86c5cSdrh 
335705a86c5cSdrh   assert( target>0 );
335805a86c5cSdrh   assert( pExpr->op!=TK_REGISTER );
335905a86c5cSdrh   sqlite3ExprCode(pParse, pExpr, target);
33602dcef11bSdrh   iMem = ++pParse->nMem;
336105a86c5cSdrh   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
3362a4c3c87eSdrh   exprToRegister(pExpr, iMem);
336325303780Sdrh }
33647e02e5e6Sdrh 
3365678ccce8Sdrh /*
3366268380caSdrh ** Generate code that pushes the value of every element of the given
33679cbf3425Sdrh ** expression list into a sequence of registers beginning at target.
3368268380caSdrh **
3369892d3179Sdrh ** Return the number of elements evaluated.
3370d1a01edaSdrh **
3371d1a01edaSdrh ** The SQLITE_ECEL_DUP flag prevents the arguments from being
3372d1a01edaSdrh ** filled using OP_SCopy.  OP_Copy must be used instead.
3373d1a01edaSdrh **
3374d1a01edaSdrh ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
3375d1a01edaSdrh ** factored out into initialization code.
3376b0df9634Sdrh **
3377b0df9634Sdrh ** The SQLITE_ECEL_REF flag means that expressions in the list with
3378b0df9634Sdrh ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
3379b0df9634Sdrh ** in registers at srcReg, and so the value can be copied from there.
3380268380caSdrh */
33814adee20fSdanielk1977 int sqlite3ExprCodeExprList(
3382268380caSdrh   Parse *pParse,     /* Parsing context */
3383389a1adbSdrh   ExprList *pList,   /* The expression list to be coded */
3384191b54cbSdrh   int target,        /* Where to write results */
33855579d59fSdrh   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
3386d1a01edaSdrh   u8 flags           /* SQLITE_ECEL_* flags */
3387268380caSdrh ){
3388268380caSdrh   struct ExprList_item *pItem;
33895579d59fSdrh   int i, j, n;
3390d1a01edaSdrh   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
33915579d59fSdrh   Vdbe *v = pParse->pVdbe;
33929d8b3072Sdrh   assert( pList!=0 );
33939cbf3425Sdrh   assert( target>0 );
3394d81a142bSdrh   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
3395268380caSdrh   n = pList->nExpr;
3396d9f158e7Sdrh   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
3397191b54cbSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
33987445ffe2Sdrh     Expr *pExpr = pItem->pExpr;
33995579d59fSdrh     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
34005579d59fSdrh       sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
34015579d59fSdrh     }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
3402d673cddaSdrh       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
3403d1a01edaSdrh     }else{
34047445ffe2Sdrh       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
3405746fd9ccSdrh       if( inReg!=target+i ){
34064eded604Sdrh         VdbeOp *pOp;
34074eded604Sdrh         if( copyOp==OP_Copy
34084eded604Sdrh          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
34094eded604Sdrh          && pOp->p1+pOp->p3+1==inReg
34104eded604Sdrh          && pOp->p2+pOp->p3+1==target+i
34114eded604Sdrh         ){
34124eded604Sdrh           pOp->p3++;
34134eded604Sdrh         }else{
34144eded604Sdrh           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
34154eded604Sdrh         }
3416d1a01edaSdrh       }
3417d176611bSdrh     }
3418268380caSdrh   }
3419f9b596ebSdrh   return n;
3420268380caSdrh }
3421268380caSdrh 
3422268380caSdrh /*
342336c563a2Sdrh ** Generate code for a BETWEEN operator.
342436c563a2Sdrh **
342536c563a2Sdrh **    x BETWEEN y AND z
342636c563a2Sdrh **
342736c563a2Sdrh ** The above is equivalent to
342836c563a2Sdrh **
342936c563a2Sdrh **    x>=y AND x<=z
343036c563a2Sdrh **
343136c563a2Sdrh ** Code it as such, taking care to do the common subexpression
343260ec914cSpeter.d.reid ** elimination of x.
343336c563a2Sdrh */
343436c563a2Sdrh static void exprCodeBetween(
343536c563a2Sdrh   Parse *pParse,    /* Parsing and code generating context */
343636c563a2Sdrh   Expr *pExpr,      /* The BETWEEN expression */
343736c563a2Sdrh   int dest,         /* Jump here if the jump is taken */
343836c563a2Sdrh   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
343936c563a2Sdrh   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
344036c563a2Sdrh ){
344136c563a2Sdrh   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
344236c563a2Sdrh   Expr compLeft;    /* The  x>=y  term */
344336c563a2Sdrh   Expr compRight;   /* The  x<=z  term */
344436c563a2Sdrh   Expr exprX;       /* The  x  subexpression */
344536c563a2Sdrh   int regFree1 = 0; /* Temporary use register */
344636c563a2Sdrh 
344736c563a2Sdrh   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
344836c563a2Sdrh   exprX = *pExpr->pLeft;
344936c563a2Sdrh   exprAnd.op = TK_AND;
345036c563a2Sdrh   exprAnd.pLeft = &compLeft;
345136c563a2Sdrh   exprAnd.pRight = &compRight;
345236c563a2Sdrh   compLeft.op = TK_GE;
345336c563a2Sdrh   compLeft.pLeft = &exprX;
345436c563a2Sdrh   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
345536c563a2Sdrh   compRight.op = TK_LE;
345636c563a2Sdrh   compRight.pLeft = &exprX;
345736c563a2Sdrh   compRight.pRight = pExpr->x.pList->a[1].pExpr;
3458a4c3c87eSdrh   exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
345936c563a2Sdrh   if( jumpIfTrue ){
346036c563a2Sdrh     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
346136c563a2Sdrh   }else{
346236c563a2Sdrh     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
346336c563a2Sdrh   }
346436c563a2Sdrh   sqlite3ReleaseTempReg(pParse, regFree1);
346536c563a2Sdrh 
346636c563a2Sdrh   /* Ensure adequate test coverage */
346736c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
346836c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
346936c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
347036c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
347136c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
347236c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
347336c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
347436c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
347536c563a2Sdrh }
347636c563a2Sdrh 
347736c563a2Sdrh /*
3478cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
3479cce7d176Sdrh ** to the label "dest" if the expression is true but execution
3480cce7d176Sdrh ** continues straight thru if the expression is false.
3481f5905aa7Sdrh **
3482f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
348335573356Sdrh ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
3484f2bc013cSdrh **
3485f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
3486f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3487f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
3488f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
3489f2bc013cSdrh ** below verify that the numbers are aligned correctly.
3490cce7d176Sdrh */
34914adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3492cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3493cce7d176Sdrh   int op = 0;
34942dcef11bSdrh   int regFree1 = 0;
34952dcef11bSdrh   int regFree2 = 0;
34962dcef11bSdrh   int r1, r2;
34972dcef11bSdrh 
349835573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
349948864df9Smistachkin   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
350033cd4909Sdrh   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
3501f2bc013cSdrh   op = pExpr->op;
3502f2bc013cSdrh   switch( op ){
3503cce7d176Sdrh     case TK_AND: {
35044adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3505c5499befSdrh       testcase( jumpIfNull==0 );
350635573356Sdrh       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
350754e2adb5Sdrh       sqlite3ExprCachePush(pParse);
35084adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
35094adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3510d2490904Sdrh       sqlite3ExprCachePop(pParse);
3511cce7d176Sdrh       break;
3512cce7d176Sdrh     }
3513cce7d176Sdrh     case TK_OR: {
3514c5499befSdrh       testcase( jumpIfNull==0 );
35154adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
351654e2adb5Sdrh       sqlite3ExprCachePush(pParse);
35174adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3518d2490904Sdrh       sqlite3ExprCachePop(pParse);
3519cce7d176Sdrh       break;
3520cce7d176Sdrh     }
3521cce7d176Sdrh     case TK_NOT: {
3522c5499befSdrh       testcase( jumpIfNull==0 );
35234adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3524cce7d176Sdrh       break;
3525cce7d176Sdrh     }
3526cce7d176Sdrh     case TK_LT:
3527cce7d176Sdrh     case TK_LE:
3528cce7d176Sdrh     case TK_GT:
3529cce7d176Sdrh     case TK_GE:
3530cce7d176Sdrh     case TK_NE:
35310ac65892Sdrh     case TK_EQ: {
3532c5499befSdrh       testcase( jumpIfNull==0 );
3533b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3534b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
353535573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
35362dcef11bSdrh                   r1, r2, dest, jumpIfNull);
35377d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
35387d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
35397d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
35407d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
35417d176105Sdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
35427d176105Sdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3543c5499befSdrh       testcase( regFree1==0 );
3544c5499befSdrh       testcase( regFree2==0 );
3545cce7d176Sdrh       break;
3546cce7d176Sdrh     }
35476a2fe093Sdrh     case TK_IS:
35486a2fe093Sdrh     case TK_ISNOT: {
35496a2fe093Sdrh       testcase( op==TK_IS );
35506a2fe093Sdrh       testcase( op==TK_ISNOT );
3551b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3552b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
35536a2fe093Sdrh       op = (op==TK_IS) ? TK_EQ : TK_NE;
35546a2fe093Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
35556a2fe093Sdrh                   r1, r2, dest, SQLITE_NULLEQ);
35567d176105Sdrh       VdbeCoverageIf(v, op==TK_EQ);
35577d176105Sdrh       VdbeCoverageIf(v, op==TK_NE);
35586a2fe093Sdrh       testcase( regFree1==0 );
35596a2fe093Sdrh       testcase( regFree2==0 );
35606a2fe093Sdrh       break;
35616a2fe093Sdrh     }
3562cce7d176Sdrh     case TK_ISNULL:
3563cce7d176Sdrh     case TK_NOTNULL: {
35647d176105Sdrh       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
35657d176105Sdrh       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
35662dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
35672dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
35687d176105Sdrh       VdbeCoverageIf(v, op==TK_ISNULL);
35697d176105Sdrh       VdbeCoverageIf(v, op==TK_NOTNULL);
3570c5499befSdrh       testcase( regFree1==0 );
3571cce7d176Sdrh       break;
3572cce7d176Sdrh     }
3573fef5208cSdrh     case TK_BETWEEN: {
35745c03f30aSdrh       testcase( jumpIfNull==0 );
357536c563a2Sdrh       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
3576fef5208cSdrh       break;
3577fef5208cSdrh     }
3578bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
3579e3365e6cSdrh     case TK_IN: {
3580e3365e6cSdrh       int destIfFalse = sqlite3VdbeMakeLabel(v);
3581e3365e6cSdrh       int destIfNull = jumpIfNull ? dest : destIfFalse;
3582e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3583076e85f5Sdrh       sqlite3VdbeGoto(v, dest);
3584e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
3585e3365e6cSdrh       break;
3586e3365e6cSdrh     }
3587bb201344Sshaneh #endif
3588cce7d176Sdrh     default: {
3589991a1985Sdrh       if( exprAlwaysTrue(pExpr) ){
3590076e85f5Sdrh         sqlite3VdbeGoto(v, dest);
3591991a1985Sdrh       }else if( exprAlwaysFalse(pExpr) ){
3592991a1985Sdrh         /* No-op */
3593991a1985Sdrh       }else{
35942dcef11bSdrh         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
35952dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
3596688852abSdrh         VdbeCoverage(v);
3597c5499befSdrh         testcase( regFree1==0 );
3598c5499befSdrh         testcase( jumpIfNull==0 );
3599991a1985Sdrh       }
3600cce7d176Sdrh       break;
3601cce7d176Sdrh     }
3602cce7d176Sdrh   }
36032dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
36042dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3605cce7d176Sdrh }
3606cce7d176Sdrh 
3607cce7d176Sdrh /*
360866b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
3609cce7d176Sdrh ** to the label "dest" if the expression is false but execution
3610cce7d176Sdrh ** continues straight thru if the expression is true.
3611f5905aa7Sdrh **
3612f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
361335573356Sdrh ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
361435573356Sdrh ** is 0.
3615cce7d176Sdrh */
36164adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3617cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3618cce7d176Sdrh   int op = 0;
36192dcef11bSdrh   int regFree1 = 0;
36202dcef11bSdrh   int regFree2 = 0;
36212dcef11bSdrh   int r1, r2;
36222dcef11bSdrh 
362335573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
362448864df9Smistachkin   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
362533cd4909Sdrh   if( pExpr==0 )    return;
3626f2bc013cSdrh 
3627f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
3628f2bc013cSdrh   **
3629f2bc013cSdrh   **       pExpr->op            op
3630f2bc013cSdrh   **       ---------          ----------
3631f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
3632f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
3633f2bc013cSdrh   **       TK_NE              OP_Eq
3634f2bc013cSdrh   **       TK_EQ              OP_Ne
3635f2bc013cSdrh   **       TK_GT              OP_Le
3636f2bc013cSdrh   **       TK_LE              OP_Gt
3637f2bc013cSdrh   **       TK_GE              OP_Lt
3638f2bc013cSdrh   **       TK_LT              OP_Ge
3639f2bc013cSdrh   **
3640f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
3641f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
3642f2bc013cSdrh   ** can compute the mapping above using the following expression.
3643f2bc013cSdrh   ** Assert()s verify that the computation is correct.
3644f2bc013cSdrh   */
3645f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3646f2bc013cSdrh 
3647f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
3648f2bc013cSdrh   */
3649f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3650f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3651f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
3652f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
3653f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
3654f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
3655f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
3656f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
3657f2bc013cSdrh 
3658cce7d176Sdrh   switch( pExpr->op ){
3659cce7d176Sdrh     case TK_AND: {
3660c5499befSdrh       testcase( jumpIfNull==0 );
36614adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
366254e2adb5Sdrh       sqlite3ExprCachePush(pParse);
36634adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3664d2490904Sdrh       sqlite3ExprCachePop(pParse);
3665cce7d176Sdrh       break;
3666cce7d176Sdrh     }
3667cce7d176Sdrh     case TK_OR: {
36684adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3669c5499befSdrh       testcase( jumpIfNull==0 );
367035573356Sdrh       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
367154e2adb5Sdrh       sqlite3ExprCachePush(pParse);
36724adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
36734adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3674d2490904Sdrh       sqlite3ExprCachePop(pParse);
3675cce7d176Sdrh       break;
3676cce7d176Sdrh     }
3677cce7d176Sdrh     case TK_NOT: {
36785c03f30aSdrh       testcase( jumpIfNull==0 );
36794adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3680cce7d176Sdrh       break;
3681cce7d176Sdrh     }
3682cce7d176Sdrh     case TK_LT:
3683cce7d176Sdrh     case TK_LE:
3684cce7d176Sdrh     case TK_GT:
3685cce7d176Sdrh     case TK_GE:
3686cce7d176Sdrh     case TK_NE:
3687cce7d176Sdrh     case TK_EQ: {
3688c5499befSdrh       testcase( jumpIfNull==0 );
3689b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3690b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
369135573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
36922dcef11bSdrh                   r1, r2, dest, jumpIfNull);
36937d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
36947d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
36957d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
36967d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
36977d176105Sdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
36987d176105Sdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3699c5499befSdrh       testcase( regFree1==0 );
3700c5499befSdrh       testcase( regFree2==0 );
3701cce7d176Sdrh       break;
3702cce7d176Sdrh     }
37036a2fe093Sdrh     case TK_IS:
37046a2fe093Sdrh     case TK_ISNOT: {
37056d4486aeSdrh       testcase( pExpr->op==TK_IS );
37066d4486aeSdrh       testcase( pExpr->op==TK_ISNOT );
3707b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3708b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
37096a2fe093Sdrh       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
37106a2fe093Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
37116a2fe093Sdrh                   r1, r2, dest, SQLITE_NULLEQ);
37127d176105Sdrh       VdbeCoverageIf(v, op==TK_EQ);
37137d176105Sdrh       VdbeCoverageIf(v, op==TK_NE);
37146a2fe093Sdrh       testcase( regFree1==0 );
37156a2fe093Sdrh       testcase( regFree2==0 );
37166a2fe093Sdrh       break;
37176a2fe093Sdrh     }
3718cce7d176Sdrh     case TK_ISNULL:
3719cce7d176Sdrh     case TK_NOTNULL: {
37202dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
37212dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
37227d176105Sdrh       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
37237d176105Sdrh       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
3724c5499befSdrh       testcase( regFree1==0 );
3725cce7d176Sdrh       break;
3726cce7d176Sdrh     }
3727fef5208cSdrh     case TK_BETWEEN: {
37285c03f30aSdrh       testcase( jumpIfNull==0 );
372936c563a2Sdrh       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
3730fef5208cSdrh       break;
3731fef5208cSdrh     }
3732bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
3733e3365e6cSdrh     case TK_IN: {
3734e3365e6cSdrh       if( jumpIfNull ){
3735e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
3736e3365e6cSdrh       }else{
3737e3365e6cSdrh         int destIfNull = sqlite3VdbeMakeLabel(v);
3738e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
3739e3365e6cSdrh         sqlite3VdbeResolveLabel(v, destIfNull);
3740e3365e6cSdrh       }
3741e3365e6cSdrh       break;
3742e3365e6cSdrh     }
3743bb201344Sshaneh #endif
3744cce7d176Sdrh     default: {
3745991a1985Sdrh       if( exprAlwaysFalse(pExpr) ){
3746076e85f5Sdrh         sqlite3VdbeGoto(v, dest);
3747991a1985Sdrh       }else if( exprAlwaysTrue(pExpr) ){
3748991a1985Sdrh         /* no-op */
3749991a1985Sdrh       }else{
37502dcef11bSdrh         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
37512dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
3752688852abSdrh         VdbeCoverage(v);
3753c5499befSdrh         testcase( regFree1==0 );
3754c5499befSdrh         testcase( jumpIfNull==0 );
3755991a1985Sdrh       }
3756cce7d176Sdrh       break;
3757cce7d176Sdrh     }
3758cce7d176Sdrh   }
37592dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
37602dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3761cce7d176Sdrh }
37622282792aSdrh 
37632282792aSdrh /*
376472bc8208Sdrh ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
376572bc8208Sdrh ** code generation, and that copy is deleted after code generation. This
376672bc8208Sdrh ** ensures that the original pExpr is unchanged.
376772bc8208Sdrh */
376872bc8208Sdrh void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
376972bc8208Sdrh   sqlite3 *db = pParse->db;
377072bc8208Sdrh   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
377172bc8208Sdrh   if( db->mallocFailed==0 ){
377272bc8208Sdrh     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
377372bc8208Sdrh   }
377472bc8208Sdrh   sqlite3ExprDelete(db, pCopy);
377572bc8208Sdrh }
377672bc8208Sdrh 
377772bc8208Sdrh 
377872bc8208Sdrh /*
37791d9da70aSdrh ** Do a deep comparison of two expression trees.  Return 0 if the two
37801d9da70aSdrh ** expressions are completely identical.  Return 1 if they differ only
37811d9da70aSdrh ** by a COLLATE operator at the top level.  Return 2 if there are differences
37821d9da70aSdrh ** other than the top-level COLLATE operator.
3783d40aab0eSdrh **
3784619a1305Sdrh ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
3785619a1305Sdrh ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
3786619a1305Sdrh **
378766518ca7Sdrh ** The pA side might be using TK_REGISTER.  If that is the case and pB is
378866518ca7Sdrh ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
378966518ca7Sdrh **
37901d9da70aSdrh ** Sometimes this routine will return 2 even if the two expressions
3791d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
37921d9da70aSdrh ** identical, we return 2 just to be safe.  So if this routine
37931d9da70aSdrh ** returns 2, then you do not really know for certain if the two
37941d9da70aSdrh ** expressions are the same.  But if you get a 0 or 1 return, then you
3795d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
37961d9da70aSdrh ** this routine is used, it does not hurt to get an extra 2 - that
3797d40aab0eSdrh ** just might result in some slightly slower code.  But returning
37981d9da70aSdrh ** an incorrect 0 or 1 could lead to a malfunction.
37992282792aSdrh */
3800619a1305Sdrh int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
380110d1edf0Sdrh   u32 combinedFlags;
38024b202ae2Sdanielk1977   if( pA==0 || pB==0 ){
38031d9da70aSdrh     return pB==pA ? 0 : 2;
38042282792aSdrh   }
380510d1edf0Sdrh   combinedFlags = pA->flags | pB->flags;
380610d1edf0Sdrh   if( combinedFlags & EP_IntValue ){
380710d1edf0Sdrh     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
380810d1edf0Sdrh       return 0;
380910d1edf0Sdrh     }
38101d9da70aSdrh     return 2;
38116ab3a2ecSdanielk1977   }
3812c2acc4e4Sdrh   if( pA->op!=pB->op ){
3813619a1305Sdrh     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
3814ae80ddeaSdrh       return 1;
3815ae80ddeaSdrh     }
3816619a1305Sdrh     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
3817ae80ddeaSdrh       return 1;
3818ae80ddeaSdrh     }
3819ae80ddeaSdrh     return 2;
3820ae80ddeaSdrh   }
3821*2edc5fd7Sdrh   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
3822390b88a4Sdrh     if( pA->op==TK_FUNCTION ){
3823390b88a4Sdrh       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
3824390b88a4Sdrh     }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
382510d1edf0Sdrh       return pA->op==TK_COLLATE ? 1 : 2;
382610d1edf0Sdrh     }
382710d1edf0Sdrh   }
382810d1edf0Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
382985f8aa79Sdrh   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
383010d1edf0Sdrh     if( combinedFlags & EP_xIsSelect ) return 2;
3831619a1305Sdrh     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
3832619a1305Sdrh     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
3833619a1305Sdrh     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
38347693c42fSdrh     if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
3835619a1305Sdrh       if( pA->iColumn!=pB->iColumn ) return 2;
383666518ca7Sdrh       if( pA->iTable!=pB->iTable
383785f8aa79Sdrh        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
38381d9da70aSdrh     }
38391d9da70aSdrh   }
38402646da7eSdrh   return 0;
38412646da7eSdrh }
38422282792aSdrh 
38438c6f666bSdrh /*
38448c6f666bSdrh ** Compare two ExprList objects.  Return 0 if they are identical and
38458c6f666bSdrh ** non-zero if they differ in any way.
38468c6f666bSdrh **
3847619a1305Sdrh ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
3848619a1305Sdrh ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
3849619a1305Sdrh **
38508c6f666bSdrh ** This routine might return non-zero for equivalent ExprLists.  The
38518c6f666bSdrh ** only consequence will be disabled optimizations.  But this routine
38528c6f666bSdrh ** must never return 0 if the two ExprList objects are different, or
38538c6f666bSdrh ** a malfunction will result.
38548c6f666bSdrh **
38558c6f666bSdrh ** Two NULL pointers are considered to be the same.  But a NULL pointer
38568c6f666bSdrh ** always differs from a non-NULL pointer.
38578c6f666bSdrh */
3858619a1305Sdrh int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
38598c6f666bSdrh   int i;
38608c6f666bSdrh   if( pA==0 && pB==0 ) return 0;
38618c6f666bSdrh   if( pA==0 || pB==0 ) return 1;
38628c6f666bSdrh   if( pA->nExpr!=pB->nExpr ) return 1;
38638c6f666bSdrh   for(i=0; i<pA->nExpr; i++){
38648c6f666bSdrh     Expr *pExprA = pA->a[i].pExpr;
38658c6f666bSdrh     Expr *pExprB = pB->a[i].pExpr;
38668c6f666bSdrh     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
3867619a1305Sdrh     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
38688c6f666bSdrh   }
38698c6f666bSdrh   return 0;
38708c6f666bSdrh }
387113449892Sdrh 
38722282792aSdrh /*
38734bd5f73fSdrh ** Return true if we can prove the pE2 will always be true if pE1 is
38744bd5f73fSdrh ** true.  Return false if we cannot complete the proof or if pE2 might
38754bd5f73fSdrh ** be false.  Examples:
38764bd5f73fSdrh **
3877619a1305Sdrh **     pE1: x==5       pE2: x==5             Result: true
38784bd5f73fSdrh **     pE1: x>0        pE2: x==5             Result: false
3879619a1305Sdrh **     pE1: x=21       pE2: x=21 OR y=43     Result: true
38804bd5f73fSdrh **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
3881619a1305Sdrh **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
3882619a1305Sdrh **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
3883619a1305Sdrh **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
38844bd5f73fSdrh **
38854bd5f73fSdrh ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
38864bd5f73fSdrh ** Expr.iTable<0 then assume a table number given by iTab.
38874bd5f73fSdrh **
38884bd5f73fSdrh ** When in doubt, return false.  Returning true might give a performance
38894bd5f73fSdrh ** improvement.  Returning false might cause a performance reduction, but
38904bd5f73fSdrh ** it will always give the correct answer and is hence always safe.
38914bd5f73fSdrh */
38924bd5f73fSdrh int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
3893619a1305Sdrh   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
3894619a1305Sdrh     return 1;
3895619a1305Sdrh   }
3896619a1305Sdrh   if( pE2->op==TK_OR
3897619a1305Sdrh    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
3898619a1305Sdrh              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
3899619a1305Sdrh   ){
3900619a1305Sdrh     return 1;
3901619a1305Sdrh   }
3902619a1305Sdrh   if( pE2->op==TK_NOTNULL
3903619a1305Sdrh    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
3904619a1305Sdrh    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
3905619a1305Sdrh   ){
3906619a1305Sdrh     return 1;
3907619a1305Sdrh   }
3908619a1305Sdrh   return 0;
39094bd5f73fSdrh }
39104bd5f73fSdrh 
39114bd5f73fSdrh /*
3912030796dfSdrh ** An instance of the following structure is used by the tree walker
3913030796dfSdrh ** to count references to table columns in the arguments of an
3914ed551b95Sdrh ** aggregate function, in order to implement the
3915ed551b95Sdrh ** sqlite3FunctionThisSrc() routine.
3916374fdce4Sdrh */
3917030796dfSdrh struct SrcCount {
3918030796dfSdrh   SrcList *pSrc;   /* One particular FROM clause in a nested query */
3919030796dfSdrh   int nThis;       /* Number of references to columns in pSrcList */
3920030796dfSdrh   int nOther;      /* Number of references to columns in other FROM clauses */
3921030796dfSdrh };
3922030796dfSdrh 
3923030796dfSdrh /*
3924030796dfSdrh ** Count the number of references to columns.
3925030796dfSdrh */
3926030796dfSdrh static int exprSrcCount(Walker *pWalker, Expr *pExpr){
3927fb0a6081Sdrh   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
3928fb0a6081Sdrh   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
3929fb0a6081Sdrh   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
3930fb0a6081Sdrh   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
3931fb0a6081Sdrh   ** NEVER() will need to be removed. */
3932fb0a6081Sdrh   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
3933374fdce4Sdrh     int i;
3934030796dfSdrh     struct SrcCount *p = pWalker->u.pSrcCount;
3935030796dfSdrh     SrcList *pSrc = p->pSrc;
3936655814d2Sdrh     int nSrc = pSrc ? pSrc->nSrc : 0;
3937655814d2Sdrh     for(i=0; i<nSrc; i++){
3938030796dfSdrh       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
3939374fdce4Sdrh     }
3940655814d2Sdrh     if( i<nSrc ){
3941030796dfSdrh       p->nThis++;
3942374fdce4Sdrh     }else{
3943030796dfSdrh       p->nOther++;
3944374fdce4Sdrh     }
3945374fdce4Sdrh   }
3946030796dfSdrh   return WRC_Continue;
3947030796dfSdrh }
3948374fdce4Sdrh 
3949374fdce4Sdrh /*
3950030796dfSdrh ** Determine if any of the arguments to the pExpr Function reference
3951030796dfSdrh ** pSrcList.  Return true if they do.  Also return true if the function
3952030796dfSdrh ** has no arguments or has only constant arguments.  Return false if pExpr
3953030796dfSdrh ** references columns but not columns of tables found in pSrcList.
3954374fdce4Sdrh */
3955030796dfSdrh int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
3956374fdce4Sdrh   Walker w;
3957030796dfSdrh   struct SrcCount cnt;
3958374fdce4Sdrh   assert( pExpr->op==TK_AGG_FUNCTION );
3959374fdce4Sdrh   memset(&w, 0, sizeof(w));
3960030796dfSdrh   w.xExprCallback = exprSrcCount;
3961030796dfSdrh   w.u.pSrcCount = &cnt;
3962030796dfSdrh   cnt.pSrc = pSrcList;
3963030796dfSdrh   cnt.nThis = 0;
3964030796dfSdrh   cnt.nOther = 0;
3965030796dfSdrh   sqlite3WalkExprList(&w, pExpr->x.pList);
3966030796dfSdrh   return cnt.nThis>0 || cnt.nOther==0;
3967374fdce4Sdrh }
3968374fdce4Sdrh 
3969374fdce4Sdrh /*
397013449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
397113449892Sdrh ** the new element.  Return a negative number if malloc fails.
39722282792aSdrh */
397317435752Sdrh static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
397413449892Sdrh   int i;
3975cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
397617435752Sdrh        db,
3977cf643729Sdrh        pInfo->aCol,
3978cf643729Sdrh        sizeof(pInfo->aCol[0]),
3979cf643729Sdrh        &pInfo->nColumn,
3980cf643729Sdrh        &i
3981cf643729Sdrh   );
398213449892Sdrh   return i;
39832282792aSdrh }
398413449892Sdrh 
398513449892Sdrh /*
398613449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
398713449892Sdrh ** the new element.  Return a negative number if malloc fails.
398813449892Sdrh */
398917435752Sdrh static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
399013449892Sdrh   int i;
3991cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
399217435752Sdrh        db,
3993cf643729Sdrh        pInfo->aFunc,
3994cf643729Sdrh        sizeof(pInfo->aFunc[0]),
3995cf643729Sdrh        &pInfo->nFunc,
3996cf643729Sdrh        &i
3997cf643729Sdrh   );
399813449892Sdrh   return i;
39992282792aSdrh }
40002282792aSdrh 
40012282792aSdrh /*
40027d10d5a6Sdrh ** This is the xExprCallback for a tree walker.  It is used to
40037d10d5a6Sdrh ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
4004626a879aSdrh ** for additional information.
40052282792aSdrh */
40067d10d5a6Sdrh static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
40072282792aSdrh   int i;
40087d10d5a6Sdrh   NameContext *pNC = pWalker->u.pNC;
4009a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
4010a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
401113449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
401213449892Sdrh 
40132282792aSdrh   switch( pExpr->op ){
401489c69d00Sdrh     case TK_AGG_COLUMN:
4015967e8b73Sdrh     case TK_COLUMN: {
40168b213899Sdrh       testcase( pExpr->op==TK_AGG_COLUMN );
40178b213899Sdrh       testcase( pExpr->op==TK_COLUMN );
401813449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
401913449892Sdrh       ** clause of the aggregate query */
402020bc393cSdrh       if( ALWAYS(pSrcList!=0) ){
402113449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
402213449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
402313449892Sdrh           struct AggInfo_col *pCol;
4024c5cd1249Sdrh           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
402513449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
402613449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
402713449892Sdrh             ** that is in the FROM clause of the aggregate query.
402813449892Sdrh             **
402913449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
403013449892Sdrh             ** is not an entry there already.
403113449892Sdrh             */
40327f906d63Sdrh             int k;
403313449892Sdrh             pCol = pAggInfo->aCol;
40347f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
403513449892Sdrh               if( pCol->iTable==pExpr->iTable &&
403613449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
40372282792aSdrh                 break;
40382282792aSdrh               }
40392282792aSdrh             }
40401e536953Sdanielk1977             if( (k>=pAggInfo->nColumn)
40411e536953Sdanielk1977              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
40421e536953Sdanielk1977             ){
40437f906d63Sdrh               pCol = &pAggInfo->aCol[k];
40440817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
404513449892Sdrh               pCol->iTable = pExpr->iTable;
404613449892Sdrh               pCol->iColumn = pExpr->iColumn;
40470a07c107Sdrh               pCol->iMem = ++pParse->nMem;
404813449892Sdrh               pCol->iSorterColumn = -1;
40495774b806Sdrh               pCol->pExpr = pExpr;
405013449892Sdrh               if( pAggInfo->pGroupBy ){
405113449892Sdrh                 int j, n;
405213449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
405313449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
405413449892Sdrh                 n = pGB->nExpr;
405513449892Sdrh                 for(j=0; j<n; j++, pTerm++){
405613449892Sdrh                   Expr *pE = pTerm->pExpr;
405713449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
405813449892Sdrh                       pE->iColumn==pExpr->iColumn ){
405913449892Sdrh                     pCol->iSorterColumn = j;
406013449892Sdrh                     break;
40612282792aSdrh                   }
406213449892Sdrh                 }
406313449892Sdrh               }
406413449892Sdrh               if( pCol->iSorterColumn<0 ){
406513449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
406613449892Sdrh               }
406713449892Sdrh             }
406813449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
406913449892Sdrh             ** because it was there before or because we just created it).
407013449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
407113449892Sdrh             ** pAggInfo->aCol[] entry.
407213449892Sdrh             */
4073ebb6a65dSdrh             ExprSetVVAProperty(pExpr, EP_NoReduce);
407413449892Sdrh             pExpr->pAggInfo = pAggInfo;
407513449892Sdrh             pExpr->op = TK_AGG_COLUMN;
4076cf697396Sshane             pExpr->iAgg = (i16)k;
407713449892Sdrh             break;
407813449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
407913449892Sdrh         } /* end loop over pSrcList */
4080a58fdfb1Sdanielk1977       }
40817d10d5a6Sdrh       return WRC_Prune;
40822282792aSdrh     }
40832282792aSdrh     case TK_AGG_FUNCTION: {
40843a8c4be7Sdrh       if( (pNC->ncFlags & NC_InAggFunc)==0
4085ed551b95Sdrh        && pWalker->walkerDepth==pExpr->op2
40863a8c4be7Sdrh       ){
408713449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
408813449892Sdrh         ** function that is already in the pAggInfo structure
408913449892Sdrh         */
409013449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
409113449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
4092619a1305Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
40932282792aSdrh             break;
40942282792aSdrh           }
40952282792aSdrh         }
409613449892Sdrh         if( i>=pAggInfo->nFunc ){
409713449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
409813449892Sdrh           */
409914db2665Sdanielk1977           u8 enc = ENC(pParse->db);
41001e536953Sdanielk1977           i = addAggInfoFunc(pParse->db, pAggInfo);
410113449892Sdrh           if( i>=0 ){
41026ab3a2ecSdanielk1977             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
410313449892Sdrh             pItem = &pAggInfo->aFunc[i];
410413449892Sdrh             pItem->pExpr = pExpr;
41050a07c107Sdrh             pItem->iMem = ++pParse->nMem;
410633e619fcSdrh             assert( !ExprHasProperty(pExpr, EP_IntValue) );
410713449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
410833e619fcSdrh                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
41096ab3a2ecSdanielk1977                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
4110fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
4111fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
4112fd357974Sdrh             }else{
4113fd357974Sdrh               pItem->iDistinct = -1;
4114fd357974Sdrh             }
41152282792aSdrh           }
411613449892Sdrh         }
411713449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
411813449892Sdrh         */
4119c5cd1249Sdrh         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
4120ebb6a65dSdrh         ExprSetVVAProperty(pExpr, EP_NoReduce);
4121cf697396Sshane         pExpr->iAgg = (i16)i;
412213449892Sdrh         pExpr->pAggInfo = pAggInfo;
41233a8c4be7Sdrh         return WRC_Prune;
41246e83a57fSdrh       }else{
41256e83a57fSdrh         return WRC_Continue;
41266e83a57fSdrh       }
41272282792aSdrh     }
4128a58fdfb1Sdanielk1977   }
41297d10d5a6Sdrh   return WRC_Continue;
41307d10d5a6Sdrh }
41317d10d5a6Sdrh static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
4132d5a336efSdrh   UNUSED_PARAMETER(pWalker);
4133d5a336efSdrh   UNUSED_PARAMETER(pSelect);
41347d10d5a6Sdrh   return WRC_Continue;
4135a58fdfb1Sdanielk1977 }
4136626a879aSdrh 
4137626a879aSdrh /*
4138e8abb4caSdrh ** Analyze the pExpr expression looking for aggregate functions and
4139e8abb4caSdrh ** for variables that need to be added to AggInfo object that pNC->pAggInfo
4140e8abb4caSdrh ** points to.  Additional entries are made on the AggInfo object as
4141e8abb4caSdrh ** necessary.
4142626a879aSdrh **
4143626a879aSdrh ** This routine should only be called after the expression has been
41447d10d5a6Sdrh ** analyzed by sqlite3ResolveExprNames().
4145626a879aSdrh */
4146d2b3e23bSdrh void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
41477d10d5a6Sdrh   Walker w;
4148374fdce4Sdrh   memset(&w, 0, sizeof(w));
41497d10d5a6Sdrh   w.xExprCallback = analyzeAggregate;
41507d10d5a6Sdrh   w.xSelectCallback = analyzeAggregatesInSelect;
41517d10d5a6Sdrh   w.u.pNC = pNC;
415220bc393cSdrh   assert( pNC->pSrcList!=0 );
41537d10d5a6Sdrh   sqlite3WalkExpr(&w, pExpr);
41542282792aSdrh }
41555d9a4af9Sdrh 
41565d9a4af9Sdrh /*
41575d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
41585d9a4af9Sdrh ** expression list.  Return the number of errors.
41595d9a4af9Sdrh **
41605d9a4af9Sdrh ** If an error is found, the analysis is cut short.
41615d9a4af9Sdrh */
4162d2b3e23bSdrh void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
41635d9a4af9Sdrh   struct ExprList_item *pItem;
41645d9a4af9Sdrh   int i;
41655d9a4af9Sdrh   if( pList ){
4166d2b3e23bSdrh     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4167d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
41685d9a4af9Sdrh     }
41695d9a4af9Sdrh   }
41705d9a4af9Sdrh }
4171892d3179Sdrh 
4172892d3179Sdrh /*
4173ceea3321Sdrh ** Allocate a single new register for use to hold some intermediate result.
4174892d3179Sdrh */
4175892d3179Sdrh int sqlite3GetTempReg(Parse *pParse){
4176e55cbd72Sdrh   if( pParse->nTempReg==0 ){
4177892d3179Sdrh     return ++pParse->nMem;
4178892d3179Sdrh   }
41792f425f6bSdanielk1977   return pParse->aTempReg[--pParse->nTempReg];
4180892d3179Sdrh }
4181ceea3321Sdrh 
4182ceea3321Sdrh /*
4183ceea3321Sdrh ** Deallocate a register, making available for reuse for some other
4184ceea3321Sdrh ** purpose.
4185ceea3321Sdrh **
4186ceea3321Sdrh ** If a register is currently being used by the column cache, then
418760ec914cSpeter.d.reid ** the deallocation is deferred until the column cache line that uses
4188ceea3321Sdrh ** the register becomes stale.
4189ceea3321Sdrh */
4190892d3179Sdrh void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
41912dcef11bSdrh   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
4192ceea3321Sdrh     int i;
4193ceea3321Sdrh     struct yColCache *p;
4194ceea3321Sdrh     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4195ceea3321Sdrh       if( p->iReg==iReg ){
4196ceea3321Sdrh         p->tempReg = 1;
4197ceea3321Sdrh         return;
4198ceea3321Sdrh       }
4199ceea3321Sdrh     }
4200892d3179Sdrh     pParse->aTempReg[pParse->nTempReg++] = iReg;
4201892d3179Sdrh   }
4202892d3179Sdrh }
4203892d3179Sdrh 
4204892d3179Sdrh /*
4205892d3179Sdrh ** Allocate or deallocate a block of nReg consecutive registers
4206892d3179Sdrh */
4207892d3179Sdrh int sqlite3GetTempRange(Parse *pParse, int nReg){
4208e55cbd72Sdrh   int i, n;
4209892d3179Sdrh   i = pParse->iRangeReg;
4210e55cbd72Sdrh   n = pParse->nRangeReg;
4211f49f3523Sdrh   if( nReg<=n ){
4212f49f3523Sdrh     assert( !usedAsColumnCache(pParse, i, i+n-1) );
4213892d3179Sdrh     pParse->iRangeReg += nReg;
4214892d3179Sdrh     pParse->nRangeReg -= nReg;
4215892d3179Sdrh   }else{
4216892d3179Sdrh     i = pParse->nMem+1;
4217892d3179Sdrh     pParse->nMem += nReg;
4218892d3179Sdrh   }
4219892d3179Sdrh   return i;
4220892d3179Sdrh }
4221892d3179Sdrh void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
4222f49f3523Sdrh   sqlite3ExprCacheRemove(pParse, iReg, nReg);
4223892d3179Sdrh   if( nReg>pParse->nRangeReg ){
4224892d3179Sdrh     pParse->nRangeReg = nReg;
4225892d3179Sdrh     pParse->iRangeReg = iReg;
4226892d3179Sdrh   }
4227892d3179Sdrh }
4228cdc69557Sdrh 
4229cdc69557Sdrh /*
4230cdc69557Sdrh ** Mark all temporary registers as being unavailable for reuse.
4231cdc69557Sdrh */
4232cdc69557Sdrh void sqlite3ClearTempRegCache(Parse *pParse){
4233cdc69557Sdrh   pParse->nTempReg = 0;
4234cdc69557Sdrh   pParse->nRangeReg = 0;
4235cdc69557Sdrh }
4236