xref: /sqlite-3.40.0/src/expr.c (revision 71c57db0)
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 );
8840aced5cSdrh   sqlite3TokenInit(&s, (char*)zC);
8980103fc6Sdan   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
900a8a406eSdrh }
910a8a406eSdrh 
920a8a406eSdrh /*
930b8d255cSdrh ** Skip over any TK_COLLATE operators and any unlikely()
94a4c3c87eSdrh ** or likelihood() function at the root of an expression.
950a8a406eSdrh */
960a8a406eSdrh Expr *sqlite3ExprSkipCollate(Expr *pExpr){
97a4c3c87eSdrh   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
98a4c3c87eSdrh     if( ExprHasProperty(pExpr, EP_Unlikely) ){
99cca9f3d2Sdrh       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
100cca9f3d2Sdrh       assert( pExpr->x.pList->nExpr>0 );
101a4c3c87eSdrh       assert( pExpr->op==TK_FUNCTION );
102cca9f3d2Sdrh       pExpr = pExpr->x.pList->a[0].pExpr;
103cca9f3d2Sdrh     }else{
1040b8d255cSdrh       assert( pExpr->op==TK_COLLATE );
105d91eba96Sdrh       pExpr = pExpr->pLeft;
106cca9f3d2Sdrh     }
107d91eba96Sdrh   }
1080a8a406eSdrh   return pExpr;
1098b4c40d8Sdrh }
1108b4c40d8Sdrh 
1118b4c40d8Sdrh /*
112ae80ddeaSdrh ** Return the collation sequence for the expression pExpr. If
113ae80ddeaSdrh ** there is no defined collating sequence, return NULL.
114ae80ddeaSdrh **
115ae80ddeaSdrh ** The collating sequence might be determined by a COLLATE operator
116ae80ddeaSdrh ** or by the presence of a column with a defined collating sequence.
117ae80ddeaSdrh ** COLLATE operators take first precedence.  Left operands take
118ae80ddeaSdrh ** precedence over right operands.
1190202b29eSdanielk1977 */
1207cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
121ae80ddeaSdrh   sqlite3 *db = pParse->db;
1227cedc8d4Sdanielk1977   CollSeq *pColl = 0;
1237d10d5a6Sdrh   Expr *p = pExpr;
124261d8a51Sdrh   while( p ){
125ae80ddeaSdrh     int op = p->op;
126fbb24d10Sdrh     if( p->flags & EP_Generic ) break;
127ae80ddeaSdrh     if( op==TK_CAST || op==TK_UPLUS ){
128ae80ddeaSdrh       p = p->pLeft;
129ae80ddeaSdrh       continue;
130ae80ddeaSdrh     }
13136e78309Sdan     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
1327a66da13Sdrh       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
133ae80ddeaSdrh       break;
134ae80ddeaSdrh     }
135a58d4a96Sdrh     if( (op==TK_AGG_COLUMN || op==TK_COLUMN
136ae80ddeaSdrh           || op==TK_REGISTER || op==TK_TRIGGER)
137a58d4a96Sdrh      && p->pTab!=0
138ae80ddeaSdrh     ){
1397d10d5a6Sdrh       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
1407d10d5a6Sdrh       ** a TK_COLUMN but was previously evaluated and cached in a register */
1417d10d5a6Sdrh       int j = p->iColumn;
1427d10d5a6Sdrh       if( j>=0 ){
143ae80ddeaSdrh         const char *zColl = p->pTab->aCol[j].zColl;
144c4a64facSdrh         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
1450202b29eSdanielk1977       }
1467d10d5a6Sdrh       break;
1477d10d5a6Sdrh     }
148ae80ddeaSdrh     if( p->flags & EP_Collate ){
1492308ed38Sdrh       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
1507d10d5a6Sdrh         p = p->pLeft;
151ae80ddeaSdrh       }else{
1522308ed38Sdrh         Expr *pNext  = p->pRight;
1536728cd91Sdrh         /* The Expr.x union is never used at the same time as Expr.pRight */
1546728cd91Sdrh         assert( p->x.pList==0 || p->pRight==0 );
1556728cd91Sdrh         /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
1566728cd91Sdrh         ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
1576728cd91Sdrh         ** least one EP_Collate. Thus the following two ALWAYS. */
1586728cd91Sdrh         if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
1592308ed38Sdrh           int i;
1606728cd91Sdrh           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
1612308ed38Sdrh             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
1622308ed38Sdrh               pNext = p->x.pList->a[i].pExpr;
1632308ed38Sdrh               break;
1642308ed38Sdrh             }
1652308ed38Sdrh           }
1662308ed38Sdrh         }
1672308ed38Sdrh         p = pNext;
168ae80ddeaSdrh       }
169ae80ddeaSdrh     }else{
170ae80ddeaSdrh       break;
171ae80ddeaSdrh     }
1720202b29eSdanielk1977   }
1737cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
1747cedc8d4Sdanielk1977     pColl = 0;
1757cedc8d4Sdanielk1977   }
1767cedc8d4Sdanielk1977   return pColl;
1770202b29eSdanielk1977 }
1780202b29eSdanielk1977 
1790202b29eSdanielk1977 /*
180626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
181626a879aSdrh ** type affinity of the other operand.  This routine returns the
18253db1458Sdrh ** type affinity that should be used for the comparison operator.
18353db1458Sdrh */
184e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
185bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
186e014a838Sdanielk1977   if( aff1 && aff2 ){
1878df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
1888df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
189e014a838Sdanielk1977     */
1908a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
191e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
192e014a838Sdanielk1977     }else{
19305883a34Sdrh       return SQLITE_AFF_BLOB;
194e014a838Sdanielk1977     }
195e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
1965f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
1975f6a87b3Sdrh     ** results directly.
198e014a838Sdanielk1977     */
19905883a34Sdrh     return SQLITE_AFF_BLOB;
200e014a838Sdanielk1977   }else{
201e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
202fe05af87Sdrh     assert( aff1==0 || aff2==0 );
203e014a838Sdanielk1977     return (aff1 + aff2);
204e014a838Sdanielk1977   }
205e014a838Sdanielk1977 }
206e014a838Sdanielk1977 
20753db1458Sdrh /*
20853db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
20953db1458Sdrh ** be applied to both operands prior to doing the comparison.
21053db1458Sdrh */
211e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
212e014a838Sdanielk1977   char aff;
213e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
214e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
2156a2fe093Sdrh           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
216e014a838Sdanielk1977   assert( pExpr->pLeft );
217bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
218e014a838Sdanielk1977   if( pExpr->pRight ){
219e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
2206ab3a2ecSdanielk1977   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2216ab3a2ecSdanielk1977     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
2226ab3a2ecSdanielk1977   }else if( !aff ){
22305883a34Sdrh     aff = SQLITE_AFF_BLOB;
224e014a838Sdanielk1977   }
225e014a838Sdanielk1977   return aff;
226e014a838Sdanielk1977 }
227e014a838Sdanielk1977 
228e014a838Sdanielk1977 /*
229e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
230e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
231e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
232e014a838Sdanielk1977 ** the comparison in pExpr.
233e014a838Sdanielk1977 */
234e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
235e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
2368a51256cSdrh   switch( aff ){
23705883a34Sdrh     case SQLITE_AFF_BLOB:
2388a51256cSdrh       return 1;
2398a51256cSdrh     case SQLITE_AFF_TEXT:
2408a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
2418a51256cSdrh     default:
2428a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
2438a51256cSdrh   }
244e014a838Sdanielk1977 }
245e014a838Sdanielk1977 
246a37cdde0Sdanielk1977 /*
24735573356Sdrh ** Return the P5 value that should be used for a binary comparison
248a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
249a37cdde0Sdanielk1977 */
25035573356Sdrh static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
25135573356Sdrh   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
2521bd10f8aSdrh   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
25335573356Sdrh   return aff;
254a37cdde0Sdanielk1977 }
255a37cdde0Sdanielk1977 
256a2e00042Sdrh /*
2570202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
2580202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
2590202b29eSdanielk1977 **
2600202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
2610202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
2620202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
2630202b29eSdanielk1977 ** type.
264bcbb04e5Sdanielk1977 **
265bcbb04e5Sdanielk1977 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
266bcbb04e5Sdanielk1977 ** it is not considered.
2670202b29eSdanielk1977 */
268bcbb04e5Sdanielk1977 CollSeq *sqlite3BinaryCompareCollSeq(
269bcbb04e5Sdanielk1977   Parse *pParse,
270bcbb04e5Sdanielk1977   Expr *pLeft,
271bcbb04e5Sdanielk1977   Expr *pRight
272bcbb04e5Sdanielk1977 ){
273ec41ddacSdrh   CollSeq *pColl;
274ec41ddacSdrh   assert( pLeft );
275ae80ddeaSdrh   if( pLeft->flags & EP_Collate ){
276ae80ddeaSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
277ae80ddeaSdrh   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
278ae80ddeaSdrh     pColl = sqlite3ExprCollSeq(pParse, pRight);
279ec41ddacSdrh   }else{
280ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
2810202b29eSdanielk1977     if( !pColl ){
2827cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
2830202b29eSdanielk1977     }
284ec41ddacSdrh   }
2850202b29eSdanielk1977   return pColl;
2860202b29eSdanielk1977 }
2870202b29eSdanielk1977 
2880202b29eSdanielk1977 /*
289be5c89acSdrh ** Generate code for a comparison operator.
290be5c89acSdrh */
291be5c89acSdrh static int codeCompare(
292be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
293be5c89acSdrh   Expr *pLeft,      /* The left operand */
294be5c89acSdrh   Expr *pRight,     /* The right operand */
295be5c89acSdrh   int opcode,       /* The comparison opcode */
29635573356Sdrh   int in1, int in2, /* Register holding operands */
297be5c89acSdrh   int dest,         /* Jump here if true.  */
298be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
299be5c89acSdrh ){
30035573356Sdrh   int p5;
30135573356Sdrh   int addr;
30235573356Sdrh   CollSeq *p4;
30335573356Sdrh 
30435573356Sdrh   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
30535573356Sdrh   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
30635573356Sdrh   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
30735573356Sdrh                            (void*)p4, P4_COLLSEQ);
3081bd10f8aSdrh   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
30935573356Sdrh   return addr;
310be5c89acSdrh }
311be5c89acSdrh 
312*71c57db0Sdan int sqlite3ExprVectorSize(Expr *pExpr){
313*71c57db0Sdan   if( (pExpr->flags & EP_Vector)==0 ) return 1;
314*71c57db0Sdan   if( pExpr->flags & EP_xIsSelect ){
315*71c57db0Sdan     return pExpr->x.pSelect->pEList->nExpr;
316*71c57db0Sdan   }
317*71c57db0Sdan   return pExpr->x.pList->nExpr;
318*71c57db0Sdan }
319*71c57db0Sdan 
320*71c57db0Sdan static Expr *exprVectorField(Expr *pVector, int i){
321*71c57db0Sdan   if( pVector->flags & EP_xIsSelect ){
322*71c57db0Sdan     return pVector->x.pSelect->pEList->a[i].pExpr;
323*71c57db0Sdan   }
324*71c57db0Sdan   return pVector->x.pList->a[i].pExpr;
325*71c57db0Sdan }
326*71c57db0Sdan 
327*71c57db0Sdan static void codeVectorCompare(Parse *pParse, Expr *pExpr, int dest){
328*71c57db0Sdan   Vdbe *v = pParse->pVdbe;
329*71c57db0Sdan   Expr *pLeft = pExpr->pLeft;
330*71c57db0Sdan   Expr *pRight = pExpr->pRight;
331*71c57db0Sdan   int nLeft = sqlite3ExprVectorSize(pLeft);
332*71c57db0Sdan   int nRight = sqlite3ExprVectorSize(pRight);
333*71c57db0Sdan   int addr = sqlite3VdbeMakeLabel(v);
334*71c57db0Sdan 
335*71c57db0Sdan   /* Check that both sides of the comparison are vectors, and that
336*71c57db0Sdan   ** both are the same length.  */
337*71c57db0Sdan   if( nLeft!=nRight ){
338*71c57db0Sdan     sqlite3ErrorMsg(pParse, "invalid use of row value");
339*71c57db0Sdan   }else{
340*71c57db0Sdan     int p5 = (pExpr->op==TK_IS || pExpr->op==TK_ISNOT) ? SQLITE_NULLEQ : 0;
341*71c57db0Sdan     int opCmp;
342*71c57db0Sdan     int opTest;
343*71c57db0Sdan     int i;
344*71c57db0Sdan     int p3 = 1;
345*71c57db0Sdan     int regLeft = 0;
346*71c57db0Sdan     int regRight = 0;
347*71c57db0Sdan 
348*71c57db0Sdan     assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
349*71c57db0Sdan          || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
350*71c57db0Sdan          || pExpr->op==TK_LT || pExpr->op==TK_GT
351*71c57db0Sdan          || pExpr->op==TK_LE || pExpr->op==TK_GE
352*71c57db0Sdan     );
353*71c57db0Sdan 
354*71c57db0Sdan     switch( pExpr->op ){
355*71c57db0Sdan       case TK_EQ:
356*71c57db0Sdan       case TK_IS:
357*71c57db0Sdan         opTest = OP_IfNot;
358*71c57db0Sdan         opCmp = OP_Eq;
359*71c57db0Sdan         break;
360*71c57db0Sdan 
361*71c57db0Sdan       case TK_NE:
362*71c57db0Sdan       case TK_ISNOT:
363*71c57db0Sdan         opTest = OP_If;
364*71c57db0Sdan         opCmp = OP_Ne;
365*71c57db0Sdan         break;
366*71c57db0Sdan 
367*71c57db0Sdan       case TK_LT:
368*71c57db0Sdan       case TK_LE:
369*71c57db0Sdan       case TK_GT:
370*71c57db0Sdan       case TK_GE:
371*71c57db0Sdan         opCmp = OP_Cmp;
372*71c57db0Sdan         opTest = OP_CmpTest;
373*71c57db0Sdan         p3 = pExpr->op;
374*71c57db0Sdan         break;
375*71c57db0Sdan     }
376*71c57db0Sdan 
377*71c57db0Sdan     if( pLeft->flags & EP_xIsSelect ){
378*71c57db0Sdan       assert( pLeft->op==TK_SELECT || pLeft->op==TK_REGISTER );
379*71c57db0Sdan       regLeft = sqlite3ExprCodeTarget(pParse, pLeft, 1);
380*71c57db0Sdan       assert( regLeft!=1 );
381*71c57db0Sdan     }
382*71c57db0Sdan     if( pRight->flags & EP_xIsSelect ){
383*71c57db0Sdan       assert( pRight->op==TK_SELECT || pRight->op==TK_REGISTER );
384*71c57db0Sdan       regRight = sqlite3ExprCodeTarget(pParse, pRight, 1);
385*71c57db0Sdan       assert( regRight!=1 );
386*71c57db0Sdan     }
387*71c57db0Sdan     if( pParse->nErr ) return;
388*71c57db0Sdan 
389*71c57db0Sdan     for(i=0; i<nLeft; i++){
390*71c57db0Sdan       int regFree1 = 0, regFree2 = 0;
391*71c57db0Sdan       Expr *pL, *pR;
392*71c57db0Sdan       int r1, r2;
393*71c57db0Sdan 
394*71c57db0Sdan       if( regLeft ){
395*71c57db0Sdan         pL = pLeft->x.pSelect->pEList->a[i].pExpr;
396*71c57db0Sdan         r1 = regLeft+i;
397*71c57db0Sdan       }else{
398*71c57db0Sdan         pL = pLeft->x.pList->a[i].pExpr;
399*71c57db0Sdan         r1 = sqlite3ExprCodeTemp(pParse, pL, &regFree1);
400*71c57db0Sdan       }
401*71c57db0Sdan 
402*71c57db0Sdan       if( regRight ){
403*71c57db0Sdan         pR = pRight->x.pSelect->pEList->a[i].pExpr;
404*71c57db0Sdan         r2 = regRight+i;
405*71c57db0Sdan       }else{
406*71c57db0Sdan         pR = pRight->x.pList->a[i].pExpr;
407*71c57db0Sdan         r2 = sqlite3ExprCodeTemp(pParse, pR, &regFree1);
408*71c57db0Sdan       }
409*71c57db0Sdan 
410*71c57db0Sdan       codeCompare(pParse, pL, pR, opCmp, r1, r2, dest, SQLITE_STOREP2 | p5);
411*71c57db0Sdan       sqlite3VdbeAddOp3(v, opTest, dest, addr, p3);
412*71c57db0Sdan       sqlite3ReleaseTempReg(pParse, regFree1);
413*71c57db0Sdan       sqlite3ReleaseTempReg(pParse, regFree2);
414*71c57db0Sdan     }
415*71c57db0Sdan   }
416*71c57db0Sdan 
417*71c57db0Sdan   sqlite3VdbeResolveLabel(v, addr);
418*71c57db0Sdan }
419*71c57db0Sdan 
4204b5255acSdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
4214b5255acSdanielk1977 /*
4224b5255acSdanielk1977 ** Check that argument nHeight is less than or equal to the maximum
4234b5255acSdanielk1977 ** expression depth allowed. If it is not, leave an error message in
4244b5255acSdanielk1977 ** pParse.
4254b5255acSdanielk1977 */
4267d10d5a6Sdrh int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
4274b5255acSdanielk1977   int rc = SQLITE_OK;
4284b5255acSdanielk1977   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
4294b5255acSdanielk1977   if( nHeight>mxHeight ){
4304b5255acSdanielk1977     sqlite3ErrorMsg(pParse,
4314b5255acSdanielk1977        "Expression tree is too large (maximum depth %d)", mxHeight
4324b5255acSdanielk1977     );
4334b5255acSdanielk1977     rc = SQLITE_ERROR;
4344b5255acSdanielk1977   }
4354b5255acSdanielk1977   return rc;
4364b5255acSdanielk1977 }
4374b5255acSdanielk1977 
4384b5255acSdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
4394b5255acSdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
4404b5255acSdanielk1977 ** of any expression tree referenced by the structure passed as the
4414b5255acSdanielk1977 ** first argument.
4424b5255acSdanielk1977 **
4434b5255acSdanielk1977 ** If this maximum height is greater than the current value pointed
4444b5255acSdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
4454b5255acSdanielk1977 ** value.
4464b5255acSdanielk1977 */
4474b5255acSdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
4484b5255acSdanielk1977   if( p ){
4494b5255acSdanielk1977     if( p->nHeight>*pnHeight ){
4504b5255acSdanielk1977       *pnHeight = p->nHeight;
4514b5255acSdanielk1977     }
4524b5255acSdanielk1977   }
4534b5255acSdanielk1977 }
4544b5255acSdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
4554b5255acSdanielk1977   if( p ){
4564b5255acSdanielk1977     int i;
4574b5255acSdanielk1977     for(i=0; i<p->nExpr; i++){
4584b5255acSdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
4594b5255acSdanielk1977     }
4604b5255acSdanielk1977   }
4614b5255acSdanielk1977 }
4624b5255acSdanielk1977 static void heightOfSelect(Select *p, int *pnHeight){
4634b5255acSdanielk1977   if( p ){
4644b5255acSdanielk1977     heightOfExpr(p->pWhere, pnHeight);
4654b5255acSdanielk1977     heightOfExpr(p->pHaving, pnHeight);
4664b5255acSdanielk1977     heightOfExpr(p->pLimit, pnHeight);
4674b5255acSdanielk1977     heightOfExpr(p->pOffset, pnHeight);
4684b5255acSdanielk1977     heightOfExprList(p->pEList, pnHeight);
4694b5255acSdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
4704b5255acSdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
4714b5255acSdanielk1977     heightOfSelect(p->pPrior, pnHeight);
4724b5255acSdanielk1977   }
4734b5255acSdanielk1977 }
4744b5255acSdanielk1977 
4754b5255acSdanielk1977 /*
4764b5255acSdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
4774b5255acSdanielk1977 ** argument. An expression with no children, Expr.pList or
4784b5255acSdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
4794b5255acSdanielk1977 ** has a height equal to the maximum height of any other
4804b5255acSdanielk1977 ** referenced Expr plus one.
4812308ed38Sdrh **
4822308ed38Sdrh ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
4832308ed38Sdrh ** if appropriate.
4844b5255acSdanielk1977 */
4854b5255acSdanielk1977 static void exprSetHeight(Expr *p){
4864b5255acSdanielk1977   int nHeight = 0;
4874b5255acSdanielk1977   heightOfExpr(p->pLeft, &nHeight);
4884b5255acSdanielk1977   heightOfExpr(p->pRight, &nHeight);
4896ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_xIsSelect) ){
4906ab3a2ecSdanielk1977     heightOfSelect(p->x.pSelect, &nHeight);
4912308ed38Sdrh   }else if( p->x.pList ){
4926ab3a2ecSdanielk1977     heightOfExprList(p->x.pList, &nHeight);
4932308ed38Sdrh     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
4946ab3a2ecSdanielk1977   }
4954b5255acSdanielk1977   p->nHeight = nHeight + 1;
4964b5255acSdanielk1977 }
4974b5255acSdanielk1977 
4984b5255acSdanielk1977 /*
4994b5255acSdanielk1977 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
5004b5255acSdanielk1977 ** the height is greater than the maximum allowed expression depth,
5014b5255acSdanielk1977 ** leave an error in pParse.
5022308ed38Sdrh **
5032308ed38Sdrh ** Also propagate all EP_Propagate flags from the Expr.x.pList into
5042308ed38Sdrh ** Expr.flags.
5054b5255acSdanielk1977 */
5062308ed38Sdrh void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
50774893a4cSdrh   if( pParse->nErr ) return;
5084b5255acSdanielk1977   exprSetHeight(p);
5097d10d5a6Sdrh   sqlite3ExprCheckHeight(pParse, p->nHeight);
5104b5255acSdanielk1977 }
5114b5255acSdanielk1977 
5124b5255acSdanielk1977 /*
5134b5255acSdanielk1977 ** Return the maximum height of any expression tree referenced
5144b5255acSdanielk1977 ** by the select statement passed as an argument.
5154b5255acSdanielk1977 */
5164b5255acSdanielk1977 int sqlite3SelectExprHeight(Select *p){
5174b5255acSdanielk1977   int nHeight = 0;
5184b5255acSdanielk1977   heightOfSelect(p, &nHeight);
5194b5255acSdanielk1977   return nHeight;
5204b5255acSdanielk1977 }
5212308ed38Sdrh #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
5222308ed38Sdrh /*
5232308ed38Sdrh ** Propagate all EP_Propagate flags from the Expr.x.pList into
5242308ed38Sdrh ** Expr.flags.
5252308ed38Sdrh */
5262308ed38Sdrh void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
5272308ed38Sdrh   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
5282308ed38Sdrh     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
5292308ed38Sdrh   }
5302308ed38Sdrh }
5314b5255acSdanielk1977 #define exprSetHeight(y)
5324b5255acSdanielk1977 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
5334b5255acSdanielk1977 
534be5c89acSdrh /*
535b7916a78Sdrh ** This routine is the core allocator for Expr nodes.
536b7916a78Sdrh **
537a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
538b7916a78Sdrh ** for this node and for the pToken argument is a single allocation
539b7916a78Sdrh ** obtained from sqlite3DbMalloc().  The calling function
540a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
541b7916a78Sdrh **
542b7916a78Sdrh ** If dequote is true, then the token (if it exists) is dequoted.
543e792b5b4Sdrh ** If dequote is false, no dequoting is performed.  The deQuote
544b7916a78Sdrh ** parameter is ignored if pToken is NULL or if the token does not
545b7916a78Sdrh ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
546b7916a78Sdrh ** then the EP_DblQuoted flag is set on the expression node.
54733e619fcSdrh **
54833e619fcSdrh ** Special case:  If op==TK_INTEGER and pToken points to a string that
54933e619fcSdrh ** can be translated into a 32-bit integer, then the token is not
55033e619fcSdrh ** stored in u.zToken.  Instead, the integer values is written
55133e619fcSdrh ** into u.iValue and the EP_IntValue flag is set.  No extra storage
55233e619fcSdrh ** is allocated to hold the integer text and the dequote flag is ignored.
553a76b5dfcSdrh */
554b7916a78Sdrh Expr *sqlite3ExprAlloc(
555a1644fd8Sdanielk1977   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
55617435752Sdrh   int op,                 /* Expression opcode */
557b7916a78Sdrh   const Token *pToken,    /* Token argument.  Might be NULL */
558b7916a78Sdrh   int dequote             /* True to dequote */
55917435752Sdrh ){
560a76b5dfcSdrh   Expr *pNew;
56133e619fcSdrh   int nExtra = 0;
562cf697396Sshane   int iValue = 0;
563b7916a78Sdrh 
564575fad65Sdrh   assert( db!=0 );
565b7916a78Sdrh   if( pToken ){
56633e619fcSdrh     if( op!=TK_INTEGER || pToken->z==0
56733e619fcSdrh           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
568b7916a78Sdrh       nExtra = pToken->n+1;
569d50ffc41Sdrh       assert( iValue>=0 );
57033e619fcSdrh     }
571a76b5dfcSdrh   }
572575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
573b7916a78Sdrh   if( pNew ){
574ca3862dcSdrh     memset(pNew, 0, sizeof(Expr));
5751bd10f8aSdrh     pNew->op = (u8)op;
576a58fdfb1Sdanielk1977     pNew->iAgg = -1;
577a76b5dfcSdrh     if( pToken ){
57833e619fcSdrh       if( nExtra==0 ){
57933e619fcSdrh         pNew->flags |= EP_IntValue;
58033e619fcSdrh         pNew->u.iValue = iValue;
58133e619fcSdrh       }else{
58233e619fcSdrh         pNew->u.zToken = (char*)&pNew[1];
583b07028f7Sdrh         assert( pToken->z!=0 || pToken->n==0 );
584b07028f7Sdrh         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
58533e619fcSdrh         pNew->u.zToken[pToken->n] = 0;
586244b9d6eSdrh         if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
587244b9d6eSdrh           if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
58833e619fcSdrh           sqlite3Dequote(pNew->u.zToken);
589a34001c9Sdrh         }
590a34001c9Sdrh       }
59133e619fcSdrh     }
592b7916a78Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
593b7916a78Sdrh     pNew->nHeight = 1;
594b7916a78Sdrh #endif
595a34001c9Sdrh   }
596a76b5dfcSdrh   return pNew;
597a76b5dfcSdrh }
598a76b5dfcSdrh 
599a76b5dfcSdrh /*
600b7916a78Sdrh ** Allocate a new expression node from a zero-terminated token that has
601b7916a78Sdrh ** already been dequoted.
602b7916a78Sdrh */
603b7916a78Sdrh Expr *sqlite3Expr(
604b7916a78Sdrh   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
605b7916a78Sdrh   int op,                 /* Expression opcode */
606b7916a78Sdrh   const char *zToken      /* Token argument.  Might be NULL */
607b7916a78Sdrh ){
608b7916a78Sdrh   Token x;
609b7916a78Sdrh   x.z = zToken;
610b7916a78Sdrh   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
611b7916a78Sdrh   return sqlite3ExprAlloc(db, op, &x, 0);
612b7916a78Sdrh }
613b7916a78Sdrh 
614b7916a78Sdrh /*
615b7916a78Sdrh ** Attach subtrees pLeft and pRight to the Expr node pRoot.
616b7916a78Sdrh **
617b7916a78Sdrh ** If pRoot==NULL that means that a memory allocation error has occurred.
618b7916a78Sdrh ** In that case, delete the subtrees pLeft and pRight.
619b7916a78Sdrh */
620b7916a78Sdrh void sqlite3ExprAttachSubtrees(
621b7916a78Sdrh   sqlite3 *db,
622b7916a78Sdrh   Expr *pRoot,
623b7916a78Sdrh   Expr *pLeft,
624b7916a78Sdrh   Expr *pRight
625b7916a78Sdrh ){
626b7916a78Sdrh   if( pRoot==0 ){
627b7916a78Sdrh     assert( db->mallocFailed );
628b7916a78Sdrh     sqlite3ExprDelete(db, pLeft);
629b7916a78Sdrh     sqlite3ExprDelete(db, pRight);
630b7916a78Sdrh   }else{
631b7916a78Sdrh     if( pRight ){
632b7916a78Sdrh       pRoot->pRight = pRight;
633885a5b03Sdrh       pRoot->flags |= EP_Propagate & pRight->flags;
634b7916a78Sdrh     }
635b7916a78Sdrh     if( pLeft ){
636b7916a78Sdrh       pRoot->pLeft = pLeft;
637885a5b03Sdrh       pRoot->flags |= EP_Propagate & pLeft->flags;
638b7916a78Sdrh     }
639b7916a78Sdrh     exprSetHeight(pRoot);
640b7916a78Sdrh   }
641b7916a78Sdrh }
642b7916a78Sdrh 
643b7916a78Sdrh /*
64460ec914cSpeter.d.reid ** Allocate an Expr node which joins as many as two subtrees.
645b7916a78Sdrh **
646bf664469Sdrh ** One or both of the subtrees can be NULL.  Return a pointer to the new
647bf664469Sdrh ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
648bf664469Sdrh ** free the subtrees and return NULL.
649206f3d96Sdrh */
65017435752Sdrh Expr *sqlite3PExpr(
65117435752Sdrh   Parse *pParse,          /* Parsing context */
65217435752Sdrh   int op,                 /* Expression opcode */
65317435752Sdrh   Expr *pLeft,            /* Left operand */
65417435752Sdrh   Expr *pRight,           /* Right operand */
65517435752Sdrh   const Token *pToken     /* Argument token */
65617435752Sdrh ){
6575fb52caaSdrh   Expr *p;
6581167d327Sdrh   if( op==TK_AND && pParse->nErr==0 ){
6595fb52caaSdrh     /* Take advantage of short-circuit false optimization for AND */
6605fb52caaSdrh     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
6615fb52caaSdrh   }else{
6621167d327Sdrh     p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
663b7916a78Sdrh     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
6645fb52caaSdrh   }
6652b359bdbSdan   if( p ) {
6662b359bdbSdan     sqlite3ExprCheckHeight(pParse, p->nHeight);
6672b359bdbSdan   }
6684e0cff60Sdrh   return p;
6694e0cff60Sdrh }
6704e0cff60Sdrh 
6714e0cff60Sdrh /*
67208de4f79Sdrh ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
67308de4f79Sdrh ** do a memory allocation failure) then delete the pSelect object.
67408de4f79Sdrh */
67508de4f79Sdrh void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
67608de4f79Sdrh   if( pExpr ){
67708de4f79Sdrh     pExpr->x.pSelect = pSelect;
67808de4f79Sdrh     ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
67908de4f79Sdrh     sqlite3ExprSetHeightAndFlags(pParse, pExpr);
68008de4f79Sdrh   }else{
68108de4f79Sdrh     assert( pParse->db->mallocFailed );
68208de4f79Sdrh     sqlite3SelectDelete(pParse->db, pSelect);
68308de4f79Sdrh   }
68408de4f79Sdrh }
68508de4f79Sdrh 
68608de4f79Sdrh 
68708de4f79Sdrh /*
688991a1985Sdrh ** If the expression is always either TRUE or FALSE (respectively),
689991a1985Sdrh ** then return 1.  If one cannot determine the truth value of the
690991a1985Sdrh ** expression at compile-time return 0.
691991a1985Sdrh **
692991a1985Sdrh ** This is an optimization.  If is OK to return 0 here even if
693991a1985Sdrh ** the expression really is always false or false (a false negative).
694991a1985Sdrh ** But it is a bug to return 1 if the expression might have different
695991a1985Sdrh ** boolean values in different circumstances (a false positive.)
6965fb52caaSdrh **
6975fb52caaSdrh ** Note that if the expression is part of conditional for a
6985fb52caaSdrh ** LEFT JOIN, then we cannot determine at compile-time whether or not
6995fb52caaSdrh ** is it true or false, so always return 0.
7005fb52caaSdrh */
701991a1985Sdrh static int exprAlwaysTrue(Expr *p){
702991a1985Sdrh   int v = 0;
703991a1985Sdrh   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
704991a1985Sdrh   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
705991a1985Sdrh   return v!=0;
706991a1985Sdrh }
7075fb52caaSdrh static int exprAlwaysFalse(Expr *p){
7085fb52caaSdrh   int v = 0;
7095fb52caaSdrh   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
7105fb52caaSdrh   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
7115fb52caaSdrh   return v==0;
7125fb52caaSdrh }
7135fb52caaSdrh 
7145fb52caaSdrh /*
71591bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
71691bb0eedSdrh ** NULL, then just return the other expression.
7175fb52caaSdrh **
7185fb52caaSdrh ** If one side or the other of the AND is known to be false, then instead
7195fb52caaSdrh ** of returning an AND expression, just return a constant expression with
7205fb52caaSdrh ** a value of false.
72191bb0eedSdrh */
7221e536953Sdanielk1977 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
72391bb0eedSdrh   if( pLeft==0 ){
72491bb0eedSdrh     return pRight;
72591bb0eedSdrh   }else if( pRight==0 ){
72691bb0eedSdrh     return pLeft;
7275fb52caaSdrh   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
7285fb52caaSdrh     sqlite3ExprDelete(db, pLeft);
7295fb52caaSdrh     sqlite3ExprDelete(db, pRight);
7305fb52caaSdrh     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
73191bb0eedSdrh   }else{
732b7916a78Sdrh     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
733b7916a78Sdrh     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
734b7916a78Sdrh     return pNew;
735a76b5dfcSdrh   }
736a76b5dfcSdrh }
737a76b5dfcSdrh 
738a76b5dfcSdrh /*
739a76b5dfcSdrh ** Construct a new expression node for a function with multiple
740a76b5dfcSdrh ** arguments.
741a76b5dfcSdrh */
74217435752Sdrh Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
743a76b5dfcSdrh   Expr *pNew;
744633e6d57Sdrh   sqlite3 *db = pParse->db;
7454b202ae2Sdanielk1977   assert( pToken );
746b7916a78Sdrh   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
747a76b5dfcSdrh   if( pNew==0 ){
748d9da78a2Sdrh     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
749a76b5dfcSdrh     return 0;
750a76b5dfcSdrh   }
7516ab3a2ecSdanielk1977   pNew->x.pList = pList;
7526ab3a2ecSdanielk1977   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
7532308ed38Sdrh   sqlite3ExprSetHeightAndFlags(pParse, pNew);
754a76b5dfcSdrh   return pNew;
755a76b5dfcSdrh }
756a76b5dfcSdrh 
757a76b5dfcSdrh /*
758fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
759fa6bc000Sdrh ** in the original SQL statement.
760fa6bc000Sdrh **
761fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
762fa6bc000Sdrh ** variable number.
763fa6bc000Sdrh **
764fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
765fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
766fa6bc000Sdrh ** the SQL statement comes from an external source.
767fa6bc000Sdrh **
76851f49f17Sdrh ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
769fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
77060ec914cSpeter.d.reid ** instance of the wildcard, the next sequential variable number is
771fa6bc000Sdrh ** assigned.
772fa6bc000Sdrh */
773fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
77417435752Sdrh   sqlite3 *db = pParse->db;
775b7916a78Sdrh   const char *z;
77617435752Sdrh 
777fa6bc000Sdrh   if( pExpr==0 ) return;
778c5cd1249Sdrh   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
77933e619fcSdrh   z = pExpr->u.zToken;
780b7916a78Sdrh   assert( z!=0 );
781b7916a78Sdrh   assert( z[0]!=0 );
782b7916a78Sdrh   if( z[1]==0 ){
783fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
784b7916a78Sdrh     assert( z[0]=='?' );
7858677d308Sdrh     pExpr->iColumn = (ynVar)(++pParse->nVar);
786124c0b49Sdrh   }else{
787124c0b49Sdrh     ynVar x = 0;
788124c0b49Sdrh     u32 n = sqlite3Strlen30(z);
789124c0b49Sdrh     if( z[0]=='?' ){
790fa6bc000Sdrh       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
791fa6bc000Sdrh       ** use it as the variable number */
792c8d735aeSdan       i64 i;
793124c0b49Sdrh       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
794124c0b49Sdrh       pExpr->iColumn = x = (ynVar)i;
795c5499befSdrh       testcase( i==0 );
796c5499befSdrh       testcase( i==1 );
797c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
798c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
799c8d735aeSdan       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
800fa6bc000Sdrh         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
801bb4957f8Sdrh             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
802124c0b49Sdrh         x = 0;
803fa6bc000Sdrh       }
804fa6bc000Sdrh       if( i>pParse->nVar ){
8051df2db7fSshaneh         pParse->nVar = (int)i;
806fa6bc000Sdrh       }
807fa6bc000Sdrh     }else{
80851f49f17Sdrh       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
809fa6bc000Sdrh       ** number as the prior appearance of the same name, or if the name
810fa6bc000Sdrh       ** has never appeared before, reuse the same variable number
811fa6bc000Sdrh       */
812124c0b49Sdrh       ynVar i;
813124c0b49Sdrh       for(i=0; i<pParse->nzVar; i++){
814503a686eSdrh         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
815124c0b49Sdrh           pExpr->iColumn = x = (ynVar)i+1;
816fa6bc000Sdrh           break;
817fa6bc000Sdrh         }
818fa6bc000Sdrh       }
819124c0b49Sdrh       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
820fa6bc000Sdrh     }
821124c0b49Sdrh     if( x>0 ){
822124c0b49Sdrh       if( x>pParse->nzVar ){
823124c0b49Sdrh         char **a;
824124c0b49Sdrh         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
8254a642b60Sdrh         if( a==0 ){
8264a642b60Sdrh           assert( db->mallocFailed ); /* Error reported through mallocFailed */
8274a642b60Sdrh           return;
8284a642b60Sdrh         }
829124c0b49Sdrh         pParse->azVar = a;
830124c0b49Sdrh         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
831124c0b49Sdrh         pParse->nzVar = x;
832124c0b49Sdrh       }
833124c0b49Sdrh       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
834124c0b49Sdrh         sqlite3DbFree(db, pParse->azVar[x-1]);
835124c0b49Sdrh         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
836fa6bc000Sdrh       }
837fa6bc000Sdrh     }
838fa6bc000Sdrh   }
839bb4957f8Sdrh   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
840832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
841832b2664Sdanielk1977   }
842fa6bc000Sdrh }
843fa6bc000Sdrh 
844fa6bc000Sdrh /*
845f6963f99Sdan ** Recursively delete an expression tree.
846a2e00042Sdrh */
8474f0010b1Sdrh static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
8484f0010b1Sdrh   assert( p!=0 );
849d50ffc41Sdrh   /* Sanity check: Assert that the IntValue is non-negative if it exists */
850d50ffc41Sdrh   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
851c5cd1249Sdrh   if( !ExprHasProperty(p, EP_TokenOnly) ){
852c5cd1249Sdrh     /* The Expr.x union is never used at the same time as Expr.pRight */
853c5cd1249Sdrh     assert( p->x.pList==0 || p->pRight==0 );
854*71c57db0Sdan     if( p->op!=TK_SELECT_COLUMN ) sqlite3ExprDelete(db, p->pLeft);
855633e6d57Sdrh     sqlite3ExprDelete(db, p->pRight);
856c5cd1249Sdrh     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
8576ab3a2ecSdanielk1977     if( ExprHasProperty(p, EP_xIsSelect) ){
8586ab3a2ecSdanielk1977       sqlite3SelectDelete(db, p->x.pSelect);
8596ab3a2ecSdanielk1977     }else{
8606ab3a2ecSdanielk1977       sqlite3ExprListDelete(db, p->x.pList);
8616ab3a2ecSdanielk1977     }
8626ab3a2ecSdanielk1977   }
86333e619fcSdrh   if( !ExprHasProperty(p, EP_Static) ){
864633e6d57Sdrh     sqlite3DbFree(db, p);
865a2e00042Sdrh   }
86633e619fcSdrh }
8674f0010b1Sdrh void sqlite3ExprDelete(sqlite3 *db, Expr *p){
8684f0010b1Sdrh   if( p ) sqlite3ExprDeleteNN(db, p);
8694f0010b1Sdrh }
870a2e00042Sdrh 
871d2687b77Sdrh /*
8726ab3a2ecSdanielk1977 ** Return the number of bytes allocated for the expression structure
8736ab3a2ecSdanielk1977 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
8746ab3a2ecSdanielk1977 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
8756ab3a2ecSdanielk1977 */
8766ab3a2ecSdanielk1977 static int exprStructSize(Expr *p){
8776ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
8786ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
8796ab3a2ecSdanielk1977   return EXPR_FULLSIZE;
8806ab3a2ecSdanielk1977 }
8816ab3a2ecSdanielk1977 
8826ab3a2ecSdanielk1977 /*
88333e619fcSdrh ** The dupedExpr*Size() routines each return the number of bytes required
88433e619fcSdrh ** to store a copy of an expression or expression tree.  They differ in
88533e619fcSdrh ** how much of the tree is measured.
88633e619fcSdrh **
88733e619fcSdrh **     dupedExprStructSize()     Size of only the Expr structure
88833e619fcSdrh **     dupedExprNodeSize()       Size of Expr + space for token
88933e619fcSdrh **     dupedExprSize()           Expr + token + subtree components
89033e619fcSdrh **
89133e619fcSdrh ***************************************************************************
89233e619fcSdrh **
89333e619fcSdrh ** The dupedExprStructSize() function returns two values OR-ed together:
89433e619fcSdrh ** (1) the space required for a copy of the Expr structure only and
89533e619fcSdrh ** (2) the EP_xxx flags that indicate what the structure size should be.
89633e619fcSdrh ** The return values is always one of:
89733e619fcSdrh **
89833e619fcSdrh **      EXPR_FULLSIZE
89933e619fcSdrh **      EXPR_REDUCEDSIZE   | EP_Reduced
90033e619fcSdrh **      EXPR_TOKENONLYSIZE | EP_TokenOnly
90133e619fcSdrh **
90233e619fcSdrh ** The size of the structure can be found by masking the return value
90333e619fcSdrh ** of this routine with 0xfff.  The flags can be found by masking the
90433e619fcSdrh ** return value with EP_Reduced|EP_TokenOnly.
90533e619fcSdrh **
90633e619fcSdrh ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
90733e619fcSdrh ** (unreduced) Expr objects as they or originally constructed by the parser.
90833e619fcSdrh ** During expression analysis, extra information is computed and moved into
90933e619fcSdrh ** later parts of teh Expr object and that extra information might get chopped
91033e619fcSdrh ** off if the expression is reduced.  Note also that it does not work to
91160ec914cSpeter.d.reid ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
91233e619fcSdrh ** to reduce a pristine expression tree from the parser.  The implementation
91333e619fcSdrh ** of dupedExprStructSize() contain multiple assert() statements that attempt
91433e619fcSdrh ** to enforce this constraint.
9156ab3a2ecSdanielk1977 */
9166ab3a2ecSdanielk1977 static int dupedExprStructSize(Expr *p, int flags){
9176ab3a2ecSdanielk1977   int nSize;
91833e619fcSdrh   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
919aecd8021Sdrh   assert( EXPR_FULLSIZE<=0xfff );
920aecd8021Sdrh   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
9213c19469cSdrh   if( 0==flags ){
9226ab3a2ecSdanielk1977     nSize = EXPR_FULLSIZE;
9236ab3a2ecSdanielk1977   }else{
924c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
92533e619fcSdrh     assert( !ExprHasProperty(p, EP_FromJoin) );
926c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_MemToken) );
927ebb6a65dSdrh     assert( !ExprHasProperty(p, EP_NoReduce) );
928aecd8021Sdrh     if( p->pLeft || p->x.pList ){
92933e619fcSdrh       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
93033e619fcSdrh     }else{
931aecd8021Sdrh       assert( p->pRight==0 );
93233e619fcSdrh       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
93333e619fcSdrh     }
9346ab3a2ecSdanielk1977   }
9356ab3a2ecSdanielk1977   return nSize;
9366ab3a2ecSdanielk1977 }
9376ab3a2ecSdanielk1977 
9386ab3a2ecSdanielk1977 /*
93933e619fcSdrh ** This function returns the space in bytes required to store the copy
94033e619fcSdrh ** of the Expr structure and a copy of the Expr.u.zToken string (if that
94133e619fcSdrh ** string is defined.)
9426ab3a2ecSdanielk1977 */
9436ab3a2ecSdanielk1977 static int dupedExprNodeSize(Expr *p, int flags){
94433e619fcSdrh   int nByte = dupedExprStructSize(p, flags) & 0xfff;
94533e619fcSdrh   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
94633e619fcSdrh     nByte += sqlite3Strlen30(p->u.zToken)+1;
9476ab3a2ecSdanielk1977   }
948bc73971dSdanielk1977   return ROUND8(nByte);
9496ab3a2ecSdanielk1977 }
9506ab3a2ecSdanielk1977 
9516ab3a2ecSdanielk1977 /*
9526ab3a2ecSdanielk1977 ** Return the number of bytes required to create a duplicate of the
9536ab3a2ecSdanielk1977 ** expression passed as the first argument. The second argument is a
9546ab3a2ecSdanielk1977 ** mask containing EXPRDUP_XXX flags.
9556ab3a2ecSdanielk1977 **
9566ab3a2ecSdanielk1977 ** The value returned includes space to create a copy of the Expr struct
95733e619fcSdrh ** itself and the buffer referred to by Expr.u.zToken, if any.
9586ab3a2ecSdanielk1977 **
9596ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
9606ab3a2ecSdanielk1977 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
9616ab3a2ecSdanielk1977 ** and Expr.pRight variables (but not for any structures pointed to or
9626ab3a2ecSdanielk1977 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
9636ab3a2ecSdanielk1977 */
9646ab3a2ecSdanielk1977 static int dupedExprSize(Expr *p, int flags){
9656ab3a2ecSdanielk1977   int nByte = 0;
9666ab3a2ecSdanielk1977   if( p ){
9676ab3a2ecSdanielk1977     nByte = dupedExprNodeSize(p, flags);
9686ab3a2ecSdanielk1977     if( flags&EXPRDUP_REDUCE ){
969b7916a78Sdrh       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
9706ab3a2ecSdanielk1977     }
9716ab3a2ecSdanielk1977   }
9726ab3a2ecSdanielk1977   return nByte;
9736ab3a2ecSdanielk1977 }
9746ab3a2ecSdanielk1977 
9756ab3a2ecSdanielk1977 /*
9766ab3a2ecSdanielk1977 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
9776ab3a2ecSdanielk1977 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
97833e619fcSdrh ** to store the copy of expression p, the copies of p->u.zToken
9796ab3a2ecSdanielk1977 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
98060ec914cSpeter.d.reid ** if any. Before returning, *pzBuffer is set to the first byte past the
9816ab3a2ecSdanielk1977 ** portion of the buffer copied into by this function.
9826ab3a2ecSdanielk1977 */
9833c19469cSdrh static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
9843c19469cSdrh   Expr *pNew;           /* Value to return */
9853c19469cSdrh   u8 *zAlloc;           /* Memory space from which to build Expr object */
9863c19469cSdrh   u32 staticFlag;       /* EP_Static if space not obtained from malloc */
9876ab3a2ecSdanielk1977 
9883c19469cSdrh   assert( db!=0 );
9893c19469cSdrh   assert( p );
9903c19469cSdrh   assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
9913c19469cSdrh   assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
9926ab3a2ecSdanielk1977 
9936ab3a2ecSdanielk1977   /* Figure out where to write the new Expr structure. */
9946ab3a2ecSdanielk1977   if( pzBuffer ){
9956ab3a2ecSdanielk1977     zAlloc = *pzBuffer;
99633e619fcSdrh     staticFlag = EP_Static;
9976ab3a2ecSdanielk1977   }else{
9983c19469cSdrh     zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
9993c19469cSdrh     staticFlag = 0;
10006ab3a2ecSdanielk1977   }
10016ab3a2ecSdanielk1977   pNew = (Expr *)zAlloc;
10026ab3a2ecSdanielk1977 
10036ab3a2ecSdanielk1977   if( pNew ){
10046ab3a2ecSdanielk1977     /* Set nNewSize to the size allocated for the structure pointed to
10056ab3a2ecSdanielk1977     ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
10066ab3a2ecSdanielk1977     ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
100733e619fcSdrh     ** by the copy of the p->u.zToken string (if any).
10086ab3a2ecSdanielk1977     */
10093c19469cSdrh     const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
101033e619fcSdrh     const int nNewSize = nStructSize & 0xfff;
101133e619fcSdrh     int nToken;
101233e619fcSdrh     if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
101333e619fcSdrh       nToken = sqlite3Strlen30(p->u.zToken) + 1;
101433e619fcSdrh     }else{
101533e619fcSdrh       nToken = 0;
101633e619fcSdrh     }
10173c19469cSdrh     if( dupFlags ){
10186ab3a2ecSdanielk1977       assert( ExprHasProperty(p, EP_Reduced)==0 );
10196ab3a2ecSdanielk1977       memcpy(zAlloc, p, nNewSize);
10206ab3a2ecSdanielk1977     }else{
10213e6a1411Sdan       u32 nSize = (u32)exprStructSize(p);
10226ab3a2ecSdanielk1977       memcpy(zAlloc, p, nSize);
102372ea29d7Sdrh       if( nSize<EXPR_FULLSIZE ){
10246ab3a2ecSdanielk1977         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
10256ab3a2ecSdanielk1977       }
102672ea29d7Sdrh     }
10276ab3a2ecSdanielk1977 
102833e619fcSdrh     /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1029c5cd1249Sdrh     pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
103033e619fcSdrh     pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
103133e619fcSdrh     pNew->flags |= staticFlag;
10326ab3a2ecSdanielk1977 
103333e619fcSdrh     /* Copy the p->u.zToken string, if any. */
10346ab3a2ecSdanielk1977     if( nToken ){
103533e619fcSdrh       char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
103633e619fcSdrh       memcpy(zToken, p->u.zToken, nToken);
10376ab3a2ecSdanielk1977     }
10386ab3a2ecSdanielk1977 
10396ab3a2ecSdanielk1977     if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
10406ab3a2ecSdanielk1977       /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
10416ab3a2ecSdanielk1977       if( ExprHasProperty(p, EP_xIsSelect) ){
10423c19469cSdrh         pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
10436ab3a2ecSdanielk1977       }else{
10443c19469cSdrh         pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
10456ab3a2ecSdanielk1977       }
10466ab3a2ecSdanielk1977     }
10476ab3a2ecSdanielk1977 
10486ab3a2ecSdanielk1977     /* Fill in pNew->pLeft and pNew->pRight. */
1049c5cd1249Sdrh     if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
10503c19469cSdrh       zAlloc += dupedExprNodeSize(p, dupFlags);
10516ab3a2ecSdanielk1977       if( ExprHasProperty(pNew, EP_Reduced) ){
10523c19469cSdrh         pNew->pLeft = p->pLeft ?
10533c19469cSdrh                       exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
10543c19469cSdrh         pNew->pRight = p->pRight ?
10553c19469cSdrh                        exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
10566ab3a2ecSdanielk1977       }
10576ab3a2ecSdanielk1977       if( pzBuffer ){
10586ab3a2ecSdanielk1977         *pzBuffer = zAlloc;
10596ab3a2ecSdanielk1977       }
1060b7916a78Sdrh     }else{
1061c5cd1249Sdrh       if( !ExprHasProperty(p, EP_TokenOnly) ){
10626ab3a2ecSdanielk1977         pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
10636ab3a2ecSdanielk1977         pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
10646ab3a2ecSdanielk1977       }
10656ab3a2ecSdanielk1977     }
10666ab3a2ecSdanielk1977   }
10676ab3a2ecSdanielk1977   return pNew;
10686ab3a2ecSdanielk1977 }
10696ab3a2ecSdanielk1977 
10706ab3a2ecSdanielk1977 /*
1071bfe31e7fSdan ** Create and return a deep copy of the object passed as the second
1072bfe31e7fSdan ** argument. If an OOM condition is encountered, NULL is returned
1073bfe31e7fSdan ** and the db->mallocFailed flag set.
1074bfe31e7fSdan */
1075eede6a53Sdan #ifndef SQLITE_OMIT_CTE
1076bfe31e7fSdan static With *withDup(sqlite3 *db, With *p){
10774e9119d9Sdan   With *pRet = 0;
10784e9119d9Sdan   if( p ){
10794e9119d9Sdan     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
10804e9119d9Sdan     pRet = sqlite3DbMallocZero(db, nByte);
10814e9119d9Sdan     if( pRet ){
10824e9119d9Sdan       int i;
10834e9119d9Sdan       pRet->nCte = p->nCte;
10844e9119d9Sdan       for(i=0; i<p->nCte; i++){
10854e9119d9Sdan         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
10864e9119d9Sdan         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
10874e9119d9Sdan         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
10884e9119d9Sdan       }
10894e9119d9Sdan     }
10904e9119d9Sdan   }
10914e9119d9Sdan   return pRet;
10924e9119d9Sdan }
1093eede6a53Sdan #else
1094eede6a53Sdan # define withDup(x,y) 0
1095eede6a53Sdan #endif
10964e9119d9Sdan 
1097a76b5dfcSdrh /*
1098ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
1099ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
1100ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
1101ff78bd2fSdrh ** without effecting the originals.
1102ff78bd2fSdrh **
11034adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
11044adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1105ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
1106ff78bd2fSdrh **
1107ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
11086ab3a2ecSdanielk1977 **
1109b7916a78Sdrh ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
11106ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
11116ab3a2ecSdanielk1977 ** truncated version of the usual Expr structure that will be stored as
11126ab3a2ecSdanielk1977 ** part of the in-memory representation of the database schema.
1113ff78bd2fSdrh */
11146ab3a2ecSdanielk1977 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
111572ea29d7Sdrh   assert( flags==0 || flags==EXPRDUP_REDUCE );
11163c19469cSdrh   return p ? exprDup(db, p, flags, 0) : 0;
1117ff78bd2fSdrh }
11186ab3a2ecSdanielk1977 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
1119ff78bd2fSdrh   ExprList *pNew;
1120145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
1121ff78bd2fSdrh   int i;
1122575fad65Sdrh   assert( db!=0 );
1123ff78bd2fSdrh   if( p==0 ) return 0;
1124575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1125ff78bd2fSdrh   if( pNew==0 ) return 0;
1126d872bb18Sdrh   pNew->nExpr = i = p->nExpr;
1127d872bb18Sdrh   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
1128575fad65Sdrh   pNew->a = pItem = sqlite3DbMallocRawNN(db,  i*sizeof(p->a[0]) );
1129e0048400Sdanielk1977   if( pItem==0 ){
1130633e6d57Sdrh     sqlite3DbFree(db, pNew);
1131e0048400Sdanielk1977     return 0;
1132e0048400Sdanielk1977   }
1133145716b3Sdrh   pOldItem = p->a;
1134145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
11356ab3a2ecSdanielk1977     Expr *pOldExpr = pOldItem->pExpr;
1136b5526ea6Sdrh     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
113717435752Sdrh     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1138b7916a78Sdrh     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
1139145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
11403e7bc9caSdrh     pItem->done = 0;
11412c036cffSdrh     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
1142c2acc4e4Sdrh     pItem->u = pOldItem->u;
1143ff78bd2fSdrh   }
1144ff78bd2fSdrh   return pNew;
1145ff78bd2fSdrh }
114693758c8dSdanielk1977 
114793758c8dSdanielk1977 /*
114893758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
114993758c8dSdanielk1977 ** the build, then none of the following routines, except for
115093758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
115193758c8dSdanielk1977 ** called with a NULL argument.
115293758c8dSdanielk1977 */
11536a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
11546a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
11556ab3a2ecSdanielk1977 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1156ad3cab52Sdrh   SrcList *pNew;
1157ad3cab52Sdrh   int i;
1158113088ecSdrh   int nByte;
1159575fad65Sdrh   assert( db!=0 );
1160ad3cab52Sdrh   if( p==0 ) return 0;
1161113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1162575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, nByte );
1163ad3cab52Sdrh   if( pNew==0 ) return 0;
11644305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
1165ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
11664efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
11674efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
1168ed8a3bb1Sdrh     Table *pTab;
116941fb5cd1Sdan     pNewItem->pSchema = pOldItem->pSchema;
117017435752Sdrh     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
117117435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
117217435752Sdrh     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
11738a48b9c0Sdrh     pNewItem->fg = pOldItem->fg;
11744efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
11755b6a9ed4Sdrh     pNewItem->addrFillSub = pOldItem->addrFillSub;
11765b6a9ed4Sdrh     pNewItem->regReturn = pOldItem->regReturn;
11778a48b9c0Sdrh     if( pNewItem->fg.isIndexedBy ){
11788a48b9c0Sdrh       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
11798a48b9c0Sdrh     }
11808a48b9c0Sdrh     pNewItem->pIBIndex = pOldItem->pIBIndex;
11818a48b9c0Sdrh     if( pNewItem->fg.isTabFunc ){
11828a48b9c0Sdrh       pNewItem->u1.pFuncArg =
11838a48b9c0Sdrh           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
11848a48b9c0Sdrh     }
1185ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
1186ed8a3bb1Sdrh     if( pTab ){
1187ed8a3bb1Sdrh       pTab->nRef++;
1188a1cb183dSdanielk1977     }
11896ab3a2ecSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
11906ab3a2ecSdanielk1977     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
119117435752Sdrh     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
11926c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
1193ad3cab52Sdrh   }
1194ad3cab52Sdrh   return pNew;
1195ad3cab52Sdrh }
119617435752Sdrh IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1197ff78bd2fSdrh   IdList *pNew;
1198ff78bd2fSdrh   int i;
1199575fad65Sdrh   assert( db!=0 );
1200ff78bd2fSdrh   if( p==0 ) return 0;
1201575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1202ff78bd2fSdrh   if( pNew==0 ) return 0;
12036c535158Sdrh   pNew->nId = p->nId;
1204575fad65Sdrh   pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
1205d5d56523Sdanielk1977   if( pNew->a==0 ){
1206633e6d57Sdrh     sqlite3DbFree(db, pNew);
1207d5d56523Sdanielk1977     return 0;
1208d5d56523Sdanielk1977   }
12096c535158Sdrh   /* Note that because the size of the allocation for p->a[] is not
12106c535158Sdrh   ** necessarily a power of two, sqlite3IdListAppend() may not be called
12116c535158Sdrh   ** on the duplicate created by this function. */
1212ff78bd2fSdrh   for(i=0; i<p->nId; i++){
12134efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
12144efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
121517435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
12164efc4754Sdrh     pNewItem->idx = pOldItem->idx;
1217ff78bd2fSdrh   }
1218ff78bd2fSdrh   return pNew;
1219ff78bd2fSdrh }
12206ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
122123b1b372Sdrh   Select *pNew, *pPrior;
1222575fad65Sdrh   assert( db!=0 );
1223ff78bd2fSdrh   if( p==0 ) return 0;
1224575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1225ff78bd2fSdrh   if( pNew==0 ) return 0;
1226b7916a78Sdrh   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
12276ab3a2ecSdanielk1977   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
12286ab3a2ecSdanielk1977   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
12296ab3a2ecSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
12306ab3a2ecSdanielk1977   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
12316ab3a2ecSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1232ff78bd2fSdrh   pNew->op = p->op;
123323b1b372Sdrh   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
123423b1b372Sdrh   if( pPrior ) pPrior->pNext = pNew;
123523b1b372Sdrh   pNew->pNext = 0;
12366ab3a2ecSdanielk1977   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
12376ab3a2ecSdanielk1977   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
123892b01d53Sdrh   pNew->iLimit = 0;
123992b01d53Sdrh   pNew->iOffset = 0;
12407d10d5a6Sdrh   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1241b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
1242b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
1243ec2da854Sdrh   pNew->nSelectRow = p->nSelectRow;
12444e9119d9Sdan   pNew->pWith = withDup(db, p->pWith);
1245eb9b884cSdrh   sqlite3SelectSetName(pNew, p->zSelName);
1246ff78bd2fSdrh   return pNew;
1247ff78bd2fSdrh }
124893758c8dSdanielk1977 #else
12496ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
125093758c8dSdanielk1977   assert( p==0 );
125193758c8dSdanielk1977   return 0;
125293758c8dSdanielk1977 }
125393758c8dSdanielk1977 #endif
1254ff78bd2fSdrh 
1255ff78bd2fSdrh 
1256ff78bd2fSdrh /*
1257a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
1258a76b5dfcSdrh ** initially NULL, then create a new expression list.
1259b7916a78Sdrh **
1260b7916a78Sdrh ** If a memory allocation error occurs, the entire list is freed and
1261b7916a78Sdrh ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1262b7916a78Sdrh ** that the new entry was successfully appended.
1263a76b5dfcSdrh */
126417435752Sdrh ExprList *sqlite3ExprListAppend(
126517435752Sdrh   Parse *pParse,          /* Parsing context */
126617435752Sdrh   ExprList *pList,        /* List to which to append. Might be NULL */
1267b7916a78Sdrh   Expr *pExpr             /* Expression to be appended. Might be NULL */
126817435752Sdrh ){
126917435752Sdrh   sqlite3 *db = pParse->db;
1270575fad65Sdrh   assert( db!=0 );
1271a76b5dfcSdrh   if( pList==0 ){
1272575fad65Sdrh     pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
1273a76b5dfcSdrh     if( pList==0 ){
1274d5d56523Sdanielk1977       goto no_mem;
1275a76b5dfcSdrh     }
1276c263f7c4Sdrh     pList->nExpr = 0;
1277575fad65Sdrh     pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
1278d872bb18Sdrh     if( pList->a==0 ) goto no_mem;
1279d872bb18Sdrh   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
1280d5d56523Sdanielk1977     struct ExprList_item *a;
1281d872bb18Sdrh     assert( pList->nExpr>0 );
1282d872bb18Sdrh     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
1283d5d56523Sdanielk1977     if( a==0 ){
1284d5d56523Sdanielk1977       goto no_mem;
1285a76b5dfcSdrh     }
1286d5d56523Sdanielk1977     pList->a = a;
1287a76b5dfcSdrh   }
12884efc4754Sdrh   assert( pList->a!=0 );
1289b7916a78Sdrh   if( 1 ){
12904efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
12914efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
1292e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
1293a76b5dfcSdrh   }
1294a76b5dfcSdrh   return pList;
1295d5d56523Sdanielk1977 
1296d5d56523Sdanielk1977 no_mem:
1297d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
1298633e6d57Sdrh   sqlite3ExprDelete(db, pExpr);
1299633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1300d5d56523Sdanielk1977   return 0;
1301a76b5dfcSdrh }
1302a76b5dfcSdrh 
1303a76b5dfcSdrh /*
1304bc622bc0Sdrh ** Set the sort order for the last element on the given ExprList.
1305bc622bc0Sdrh */
1306bc622bc0Sdrh void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1307bc622bc0Sdrh   if( p==0 ) return;
1308bc622bc0Sdrh   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1309bc622bc0Sdrh   assert( p->nExpr>0 );
1310bc622bc0Sdrh   if( iSortOrder<0 ){
1311bc622bc0Sdrh     assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1312bc622bc0Sdrh     return;
1313bc622bc0Sdrh   }
1314bc622bc0Sdrh   p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
1315bc622bc0Sdrh }
1316bc622bc0Sdrh 
1317bc622bc0Sdrh /*
1318b7916a78Sdrh ** Set the ExprList.a[].zName element of the most recently added item
1319b7916a78Sdrh ** on the expression list.
1320b7916a78Sdrh **
1321b7916a78Sdrh ** pList might be NULL following an OOM error.  But pName should never be
1322b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1323b7916a78Sdrh ** is set.
1324b7916a78Sdrh */
1325b7916a78Sdrh void sqlite3ExprListSetName(
1326b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1327b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1328b7916a78Sdrh   Token *pName,           /* Name to be added */
1329b7916a78Sdrh   int dequote             /* True to cause the name to be dequoted */
1330b7916a78Sdrh ){
1331b7916a78Sdrh   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1332b7916a78Sdrh   if( pList ){
1333b7916a78Sdrh     struct ExprList_item *pItem;
1334b7916a78Sdrh     assert( pList->nExpr>0 );
1335b7916a78Sdrh     pItem = &pList->a[pList->nExpr-1];
1336b7916a78Sdrh     assert( pItem->zName==0 );
1337b7916a78Sdrh     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1338244b9d6eSdrh     if( dequote ) sqlite3Dequote(pItem->zName);
1339b7916a78Sdrh   }
1340b7916a78Sdrh }
1341b7916a78Sdrh 
1342b7916a78Sdrh /*
1343b7916a78Sdrh ** Set the ExprList.a[].zSpan element of the most recently added item
1344b7916a78Sdrh ** on the expression list.
1345b7916a78Sdrh **
1346b7916a78Sdrh ** pList might be NULL following an OOM error.  But pSpan should never be
1347b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1348b7916a78Sdrh ** is set.
1349b7916a78Sdrh */
1350b7916a78Sdrh void sqlite3ExprListSetSpan(
1351b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1352b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1353b7916a78Sdrh   ExprSpan *pSpan         /* The span to be added */
1354b7916a78Sdrh ){
1355b7916a78Sdrh   sqlite3 *db = pParse->db;
1356b7916a78Sdrh   assert( pList!=0 || db->mallocFailed!=0 );
1357b7916a78Sdrh   if( pList ){
1358b7916a78Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1359b7916a78Sdrh     assert( pList->nExpr>0 );
1360b7916a78Sdrh     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1361b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1362b7916a78Sdrh     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1363cf697396Sshane                                     (int)(pSpan->zEnd - pSpan->zStart));
1364b7916a78Sdrh   }
1365b7916a78Sdrh }
1366b7916a78Sdrh 
1367b7916a78Sdrh /*
13687a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
13697a15a4beSdanielk1977 ** leave an error message in pParse.
13707a15a4beSdanielk1977 */
13717a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
13727a15a4beSdanielk1977   Parse *pParse,
13737a15a4beSdanielk1977   ExprList *pEList,
13747a15a4beSdanielk1977   const char *zObject
13757a15a4beSdanielk1977 ){
1376b1a6c3c1Sdrh   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1377c5499befSdrh   testcase( pEList && pEList->nExpr==mx );
1378c5499befSdrh   testcase( pEList && pEList->nExpr==mx+1 );
1379b1a6c3c1Sdrh   if( pEList && pEList->nExpr>mx ){
13807a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
13817a15a4beSdanielk1977   }
13827a15a4beSdanielk1977 }
13837a15a4beSdanielk1977 
13847a15a4beSdanielk1977 /*
1385a76b5dfcSdrh ** Delete an entire expression list.
1386a76b5dfcSdrh */
1387affa855cSdrh static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
1388a76b5dfcSdrh   int i;
1389be5c89acSdrh   struct ExprList_item *pItem;
1390d872bb18Sdrh   assert( pList->a!=0 || pList->nExpr==0 );
1391be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1392633e6d57Sdrh     sqlite3ExprDelete(db, pItem->pExpr);
1393633e6d57Sdrh     sqlite3DbFree(db, pItem->zName);
1394b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1395a76b5dfcSdrh   }
1396633e6d57Sdrh   sqlite3DbFree(db, pList->a);
1397633e6d57Sdrh   sqlite3DbFree(db, pList);
1398a76b5dfcSdrh }
1399affa855cSdrh void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1400affa855cSdrh   if( pList ) exprListDeleteNN(db, pList);
1401affa855cSdrh }
1402a76b5dfcSdrh 
1403a76b5dfcSdrh /*
14042308ed38Sdrh ** Return the bitwise-OR of all Expr.flags fields in the given
14052308ed38Sdrh ** ExprList.
1406885a5b03Sdrh */
14072308ed38Sdrh u32 sqlite3ExprListFlags(const ExprList *pList){
1408885a5b03Sdrh   int i;
14092308ed38Sdrh   u32 m = 0;
14102308ed38Sdrh   if( pList ){
1411885a5b03Sdrh     for(i=0; i<pList->nExpr; i++){
1412d0c73053Sdrh        Expr *pExpr = pList->a[i].pExpr;
1413de845c2fSdrh        assert( pExpr!=0 );
1414de845c2fSdrh        m |= pExpr->flags;
1415885a5b03Sdrh     }
14162308ed38Sdrh   }
14172308ed38Sdrh   return m;
1418885a5b03Sdrh }
1419885a5b03Sdrh 
1420885a5b03Sdrh /*
1421059b2d50Sdrh ** These routines are Walker callbacks used to check expressions to
1422059b2d50Sdrh ** see if they are "constant" for some definition of constant.  The
1423059b2d50Sdrh ** Walker.eCode value determines the type of "constant" we are looking
1424059b2d50Sdrh ** for.
142573b211abSdrh **
14267d10d5a6Sdrh ** These callback routines are used to implement the following:
1427626a879aSdrh **
1428059b2d50Sdrh **     sqlite3ExprIsConstant()                  pWalker->eCode==1
1429059b2d50Sdrh **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
1430fcb9f4f3Sdrh **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
1431059b2d50Sdrh **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
143287abf5c0Sdrh **
1433059b2d50Sdrh ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1434059b2d50Sdrh ** is found to not be a constant.
143587abf5c0Sdrh **
1436feada2dfSdrh ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
1437059b2d50Sdrh ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
1438059b2d50Sdrh ** an existing schema and 4 when processing a new statement.  A bound
1439feada2dfSdrh ** parameter raises an error for new statements, but is silently converted
1440feada2dfSdrh ** to NULL for existing schemas.  This allows sqlite_master tables that
1441feada2dfSdrh ** contain a bound parameter because they were generated by older versions
1442feada2dfSdrh ** of SQLite to be parsed by newer versions of SQLite without raising a
1443feada2dfSdrh ** malformed schema error.
1444626a879aSdrh */
14457d10d5a6Sdrh static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1446626a879aSdrh 
1447059b2d50Sdrh   /* If pWalker->eCode is 2 then any term of the expression that comes from
1448059b2d50Sdrh   ** the ON or USING clauses of a left join disqualifies the expression
14490a168377Sdrh   ** from being considered constant. */
1450059b2d50Sdrh   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1451059b2d50Sdrh     pWalker->eCode = 0;
14527d10d5a6Sdrh     return WRC_Abort;
14530a168377Sdrh   }
14540a168377Sdrh 
1455626a879aSdrh   switch( pExpr->op ){
1456eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
1457059b2d50Sdrh     ** and either pWalker->eCode==4 or 5 or the function has the
1458059b2d50Sdrh     ** SQLITE_FUNC_CONST flag. */
1459eb55bd2fSdrh     case TK_FUNCTION:
146063f84573Sdrh       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
1461b1fba286Sdrh         return WRC_Continue;
1462059b2d50Sdrh       }else{
1463059b2d50Sdrh         pWalker->eCode = 0;
1464059b2d50Sdrh         return WRC_Abort;
1465b1fba286Sdrh       }
1466626a879aSdrh     case TK_ID:
1467626a879aSdrh     case TK_COLUMN:
1468626a879aSdrh     case TK_AGG_FUNCTION:
146913449892Sdrh     case TK_AGG_COLUMN:
1470c5499befSdrh       testcase( pExpr->op==TK_ID );
1471c5499befSdrh       testcase( pExpr->op==TK_COLUMN );
1472c5499befSdrh       testcase( pExpr->op==TK_AGG_FUNCTION );
1473c5499befSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1474059b2d50Sdrh       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1475059b2d50Sdrh         return WRC_Continue;
1476059b2d50Sdrh       }else{
1477059b2d50Sdrh         pWalker->eCode = 0;
14787d10d5a6Sdrh         return WRC_Abort;
1479059b2d50Sdrh       }
1480feada2dfSdrh     case TK_VARIABLE:
1481059b2d50Sdrh       if( pWalker->eCode==5 ){
1482feada2dfSdrh         /* Silently convert bound parameters that appear inside of CREATE
1483feada2dfSdrh         ** statements into a NULL when parsing the CREATE statement text out
1484feada2dfSdrh         ** of the sqlite_master table */
1485feada2dfSdrh         pExpr->op = TK_NULL;
1486059b2d50Sdrh       }else if( pWalker->eCode==4 ){
1487feada2dfSdrh         /* A bound parameter in a CREATE statement that originates from
1488feada2dfSdrh         ** sqlite3_prepare() causes an error */
1489059b2d50Sdrh         pWalker->eCode = 0;
1490feada2dfSdrh         return WRC_Abort;
1491feada2dfSdrh       }
1492feada2dfSdrh       /* Fall through */
1493626a879aSdrh     default:
1494b74b1017Sdrh       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1495b74b1017Sdrh       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
14967d10d5a6Sdrh       return WRC_Continue;
1497626a879aSdrh   }
1498626a879aSdrh }
149962c14b34Sdanielk1977 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
150062c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
1501059b2d50Sdrh   pWalker->eCode = 0;
15027d10d5a6Sdrh   return WRC_Abort;
15037d10d5a6Sdrh }
1504059b2d50Sdrh static int exprIsConst(Expr *p, int initFlag, int iCur){
15057d10d5a6Sdrh   Walker w;
1506aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
1507059b2d50Sdrh   w.eCode = initFlag;
15087d10d5a6Sdrh   w.xExprCallback = exprNodeIsConstant;
15097d10d5a6Sdrh   w.xSelectCallback = selectNodeIsConstant;
1510059b2d50Sdrh   w.u.iCur = iCur;
15117d10d5a6Sdrh   sqlite3WalkExpr(&w, p);
1512059b2d50Sdrh   return w.eCode;
15137d10d5a6Sdrh }
1514626a879aSdrh 
1515626a879aSdrh /*
1516059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1517eb55bd2fSdrh ** and 0 if it involves variables or function calls.
15182398937bSdrh **
15192398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
15202398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
15212398937bSdrh ** a constant.
1522fef5208cSdrh */
15234adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
1524059b2d50Sdrh   return exprIsConst(p, 1, 0);
1525fef5208cSdrh }
1526fef5208cSdrh 
1527fef5208cSdrh /*
1528059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
15290a168377Sdrh ** that does no originate from the ON or USING clauses of a join.
15300a168377Sdrh ** Return 0 if it involves variables or function calls or terms from
15310a168377Sdrh ** an ON or USING clause.
15320a168377Sdrh */
15330a168377Sdrh int sqlite3ExprIsConstantNotJoin(Expr *p){
1534059b2d50Sdrh   return exprIsConst(p, 2, 0);
15350a168377Sdrh }
15360a168377Sdrh 
15370a168377Sdrh /*
1538fcb9f4f3Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1539059b2d50Sdrh ** for any single row of the table with cursor iCur.  In other words, the
1540059b2d50Sdrh ** expression must not refer to any non-deterministic function nor any
1541059b2d50Sdrh ** table other than iCur.
1542059b2d50Sdrh */
1543059b2d50Sdrh int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1544059b2d50Sdrh   return exprIsConst(p, 3, iCur);
1545059b2d50Sdrh }
1546059b2d50Sdrh 
1547059b2d50Sdrh /*
1548059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1549eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
1550eb55bd2fSdrh ** are any variables.
1551eb55bd2fSdrh **
1552eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
1553eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
1554eb55bd2fSdrh ** a constant.
1555eb55bd2fSdrh */
1556feada2dfSdrh int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1557feada2dfSdrh   assert( isInit==0 || isInit==1 );
1558059b2d50Sdrh   return exprIsConst(p, 4+isInit, 0);
1559eb55bd2fSdrh }
1560eb55bd2fSdrh 
15615b88bc4bSdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS
15625b88bc4bSdrh /*
15635b88bc4bSdrh ** Walk an expression tree.  Return 1 if the expression contains a
15645b88bc4bSdrh ** subquery of some kind.  Return 0 if there are no subqueries.
15655b88bc4bSdrh */
15665b88bc4bSdrh int sqlite3ExprContainsSubquery(Expr *p){
15675b88bc4bSdrh   Walker w;
15685b88bc4bSdrh   memset(&w, 0, sizeof(w));
1569bec2476aSdrh   w.eCode = 1;
15705b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
15715b88bc4bSdrh   w.xSelectCallback = selectNodeIsConstant;
15725b88bc4bSdrh   sqlite3WalkExpr(&w, p);
157307194bffSdrh   return w.eCode==0;
15745b88bc4bSdrh }
15755b88bc4bSdrh #endif
15765b88bc4bSdrh 
1577eb55bd2fSdrh /*
157873b211abSdrh ** If the expression p codes a constant integer that is small enough
1579202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
1580202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
1581202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1582e4de1febSdrh */
15834adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
158492b01d53Sdrh   int rc = 0;
1585cd92e84dSdrh 
1586cd92e84dSdrh   /* If an expression is an integer literal that fits in a signed 32-bit
1587cd92e84dSdrh   ** integer, then the EP_IntValue flag will have already been set */
1588cd92e84dSdrh   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1589cd92e84dSdrh            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1590cd92e84dSdrh 
159192b01d53Sdrh   if( p->flags & EP_IntValue ){
159233e619fcSdrh     *pValue = p->u.iValue;
1593e4de1febSdrh     return 1;
1594e4de1febSdrh   }
159592b01d53Sdrh   switch( p->op ){
15964b59ab5eSdrh     case TK_UPLUS: {
159792b01d53Sdrh       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1598f6e369a1Sdrh       break;
15994b59ab5eSdrh     }
1600e4de1febSdrh     case TK_UMINUS: {
1601e4de1febSdrh       int v;
16024adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1603f6418891Smistachkin         assert( v!=(-2147483647-1) );
1604e4de1febSdrh         *pValue = -v;
160592b01d53Sdrh         rc = 1;
1606e4de1febSdrh       }
1607e4de1febSdrh       break;
1608e4de1febSdrh     }
1609e4de1febSdrh     default: break;
1610e4de1febSdrh   }
161192b01d53Sdrh   return rc;
1612e4de1febSdrh }
1613e4de1febSdrh 
1614e4de1febSdrh /*
1615039fc32eSdrh ** Return FALSE if there is no chance that the expression can be NULL.
1616039fc32eSdrh **
1617039fc32eSdrh ** If the expression might be NULL or if the expression is too complex
1618039fc32eSdrh ** to tell return TRUE.
1619039fc32eSdrh **
1620039fc32eSdrh ** This routine is used as an optimization, to skip OP_IsNull opcodes
1621039fc32eSdrh ** when we know that a value cannot be NULL.  Hence, a false positive
1622039fc32eSdrh ** (returning TRUE when in fact the expression can never be NULL) might
1623039fc32eSdrh ** be a small performance hit but is otherwise harmless.  On the other
1624039fc32eSdrh ** hand, a false negative (returning FALSE when the result could be NULL)
1625039fc32eSdrh ** will likely result in an incorrect answer.  So when in doubt, return
1626039fc32eSdrh ** TRUE.
1627039fc32eSdrh */
1628039fc32eSdrh int sqlite3ExprCanBeNull(const Expr *p){
1629039fc32eSdrh   u8 op;
1630cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1631039fc32eSdrh   op = p->op;
1632039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
1633039fc32eSdrh   switch( op ){
1634039fc32eSdrh     case TK_INTEGER:
1635039fc32eSdrh     case TK_STRING:
1636039fc32eSdrh     case TK_FLOAT:
1637039fc32eSdrh     case TK_BLOB:
1638039fc32eSdrh       return 0;
16397248a8b2Sdrh     case TK_COLUMN:
16407248a8b2Sdrh       assert( p->pTab!=0 );
164172673a24Sdrh       return ExprHasProperty(p, EP_CanBeNull) ||
164272673a24Sdrh              (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
1643039fc32eSdrh     default:
1644039fc32eSdrh       return 1;
1645039fc32eSdrh   }
1646039fc32eSdrh }
1647039fc32eSdrh 
1648039fc32eSdrh /*
1649039fc32eSdrh ** Return TRUE if the given expression is a constant which would be
1650039fc32eSdrh ** unchanged by OP_Affinity with the affinity given in the second
1651039fc32eSdrh ** argument.
1652039fc32eSdrh **
1653039fc32eSdrh ** This routine is used to determine if the OP_Affinity operation
1654039fc32eSdrh ** can be omitted.  When in doubt return FALSE.  A false negative
1655039fc32eSdrh ** is harmless.  A false positive, however, can result in the wrong
1656039fc32eSdrh ** answer.
1657039fc32eSdrh */
1658039fc32eSdrh int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1659039fc32eSdrh   u8 op;
166005883a34Sdrh   if( aff==SQLITE_AFF_BLOB ) return 1;
1661cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1662039fc32eSdrh   op = p->op;
1663039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
1664039fc32eSdrh   switch( op ){
1665039fc32eSdrh     case TK_INTEGER: {
1666039fc32eSdrh       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1667039fc32eSdrh     }
1668039fc32eSdrh     case TK_FLOAT: {
1669039fc32eSdrh       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1670039fc32eSdrh     }
1671039fc32eSdrh     case TK_STRING: {
1672039fc32eSdrh       return aff==SQLITE_AFF_TEXT;
1673039fc32eSdrh     }
1674039fc32eSdrh     case TK_BLOB: {
1675039fc32eSdrh       return 1;
1676039fc32eSdrh     }
16772f2855b6Sdrh     case TK_COLUMN: {
167888376ca7Sdrh       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
167988376ca7Sdrh       return p->iColumn<0
16802f2855b6Sdrh           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
16812f2855b6Sdrh     }
1682039fc32eSdrh     default: {
1683039fc32eSdrh       return 0;
1684039fc32eSdrh     }
1685039fc32eSdrh   }
1686039fc32eSdrh }
1687039fc32eSdrh 
1688039fc32eSdrh /*
1689c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
1690c4a3c779Sdrh */
16914adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
16924adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
16934adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
16944adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1695c4a3c779Sdrh   return 0;
1696c4a3c779Sdrh }
1697c4a3c779Sdrh 
16989a96b668Sdanielk1977 /*
169969c355bdSdrh ** pX is the RHS of an IN operator.  If pX is a SELECT statement
170069c355bdSdrh ** that can be simplified to a direct table access, then return
170169c355bdSdrh ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
170269c355bdSdrh ** or if the SELECT statement needs to be manifested into a transient
170369c355bdSdrh ** table, then return NULL.
1704b287f4b6Sdrh */
1705b287f4b6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
170669c355bdSdrh static Select *isCandidateForInOpt(Expr *pX){
170769c355bdSdrh   Select *p;
1708b287f4b6Sdrh   SrcList *pSrc;
1709b287f4b6Sdrh   ExprList *pEList;
171069c355bdSdrh   Expr *pRes;
1711b287f4b6Sdrh   Table *pTab;
171269c355bdSdrh   if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
171369c355bdSdrh   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
171469c355bdSdrh   p = pX->x.pSelect;
1715b287f4b6Sdrh   if( p->pPrior ) return 0;              /* Not a compound SELECT */
17167d10d5a6Sdrh   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1717b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1718b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
17197d10d5a6Sdrh     return 0; /* No DISTINCT keyword and no aggregate functions */
17207d10d5a6Sdrh   }
1721b74b1017Sdrh   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
1722b287f4b6Sdrh   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
1723b74b1017Sdrh   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
1724b287f4b6Sdrh   if( p->pWhere ) return 0;              /* Has no WHERE clause */
1725b287f4b6Sdrh   pSrc = p->pSrc;
1726d1fa7bcaSdrh   assert( pSrc!=0 );
1727d1fa7bcaSdrh   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
1728b74b1017Sdrh   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
1729b287f4b6Sdrh   pTab = pSrc->a[0].pTab;
173069c355bdSdrh   assert( pTab!=0 );
1731b74b1017Sdrh   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
1732b287f4b6Sdrh   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
1733b287f4b6Sdrh   pEList = p->pEList;
1734b287f4b6Sdrh   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
173590730c9eSdrh   pRes = pEList->a[0].pExpr;
173690730c9eSdrh   if( pRes->op!=TK_COLUMN ) return 0;    /* Result is a column */
173769c355bdSdrh   assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
173869c355bdSdrh   return p;
1739b287f4b6Sdrh }
1740b287f4b6Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1741b287f4b6Sdrh 
1742b287f4b6Sdrh /*
17431d8cb21fSdan ** Code an OP_Once instruction and allocate space for its flag. Return the
17441d8cb21fSdan ** address of the new instruction.
17451d8cb21fSdan */
17461d8cb21fSdan int sqlite3CodeOnce(Parse *pParse){
17471d8cb21fSdan   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
17481d8cb21fSdan   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
17491d8cb21fSdan }
17501d8cb21fSdan 
17511d8cb21fSdan /*
17524c259e9fSdrh ** Generate code that checks the left-most column of index table iCur to see if
17534c259e9fSdrh ** it contains any NULL entries.  Cause the register at regHasNull to be set
17546be515ebSdrh ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
17556be515ebSdrh ** to be set to NULL if iCur contains one or more NULL values.
17566be515ebSdrh */
17576be515ebSdrh static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
1758728e0f91Sdrh   int addr1;
17596be515ebSdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
1760728e0f91Sdrh   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
17616be515ebSdrh   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
17626be515ebSdrh   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
17634c259e9fSdrh   VdbeComment((v, "first_entry_in(%d)", iCur));
1764728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
17656be515ebSdrh }
17666be515ebSdrh 
1767bb53ecb1Sdrh 
1768bb53ecb1Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1769bb53ecb1Sdrh /*
1770bb53ecb1Sdrh ** The argument is an IN operator with a list (not a subquery) on the
1771bb53ecb1Sdrh ** right-hand side.  Return TRUE if that list is constant.
1772bb53ecb1Sdrh */
1773bb53ecb1Sdrh static int sqlite3InRhsIsConstant(Expr *pIn){
1774bb53ecb1Sdrh   Expr *pLHS;
1775bb53ecb1Sdrh   int res;
1776bb53ecb1Sdrh   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
1777bb53ecb1Sdrh   pLHS = pIn->pLeft;
1778bb53ecb1Sdrh   pIn->pLeft = 0;
1779bb53ecb1Sdrh   res = sqlite3ExprIsConstant(pIn);
1780bb53ecb1Sdrh   pIn->pLeft = pLHS;
1781bb53ecb1Sdrh   return res;
1782bb53ecb1Sdrh }
1783bb53ecb1Sdrh #endif
1784bb53ecb1Sdrh 
17856be515ebSdrh /*
17869a96b668Sdanielk1977 ** This function is used by the implementation of the IN (...) operator.
1787d4305ca6Sdrh ** The pX parameter is the expression on the RHS of the IN operator, which
1788d4305ca6Sdrh ** might be either a list of expressions or a subquery.
17899a96b668Sdanielk1977 **
1790d4305ca6Sdrh ** The job of this routine is to find or create a b-tree object that can
1791d4305ca6Sdrh ** be used either to test for membership in the RHS set or to iterate through
1792d4305ca6Sdrh ** all members of the RHS set, skipping duplicates.
1793d4305ca6Sdrh **
17943a85625dSdrh ** A cursor is opened on the b-tree object that is the RHS of the IN operator
1795d4305ca6Sdrh ** and pX->iTable is set to the index of that cursor.
1796d4305ca6Sdrh **
1797b74b1017Sdrh ** The returned value of this function indicates the b-tree type, as follows:
17989a96b668Sdanielk1977 **
17999a96b668Sdanielk1977 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
18001ccce449Sdrh **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
18011ccce449Sdrh **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
18029a96b668Sdanielk1977 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
18039a96b668Sdanielk1977 **                         populated epheremal table.
1804bb53ecb1Sdrh **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
1805bb53ecb1Sdrh **                         implemented as a sequence of comparisons.
18069a96b668Sdanielk1977 **
1807d4305ca6Sdrh ** An existing b-tree might be used if the RHS expression pX is a simple
1808d4305ca6Sdrh ** subquery such as:
18099a96b668Sdanielk1977 **
18109a96b668Sdanielk1977 **     SELECT <column> FROM <table>
18119a96b668Sdanielk1977 **
1812d4305ca6Sdrh ** If the RHS of the IN operator is a list or a more complex subquery, then
1813d4305ca6Sdrh ** an ephemeral table might need to be generated from the RHS and then
181460ec914cSpeter.d.reid ** pX->iTable made to point to the ephemeral table instead of an
1815d4305ca6Sdrh ** existing table.
1816d4305ca6Sdrh **
18173a85625dSdrh ** The inFlags parameter must contain exactly one of the bits
18183a85625dSdrh ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
18193a85625dSdrh ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
18203a85625dSdrh ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
18213a85625dSdrh ** IN index will be used to loop over all values of the RHS of the
18223a85625dSdrh ** IN operator.
18233a85625dSdrh **
18243a85625dSdrh ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
18253a85625dSdrh ** through the set members) then the b-tree must not contain duplicates.
18263a85625dSdrh ** An epheremal table must be used unless the selected <column> is guaranteed
18279a96b668Sdanielk1977 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
1828b74b1017Sdrh ** has a UNIQUE constraint or UNIQUE index.
18290cdc022eSdanielk1977 **
18303a85625dSdrh ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
18313a85625dSdrh ** for fast set membership tests) then an epheremal table must
18320cdc022eSdanielk1977 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
18330cdc022eSdanielk1977 ** be found with <column> as its left-most column.
18340cdc022eSdanielk1977 **
1835bb53ecb1Sdrh ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
1836bb53ecb1Sdrh ** if the RHS of the IN operator is a list (not a subquery) then this
1837bb53ecb1Sdrh ** routine might decide that creating an ephemeral b-tree for membership
1838bb53ecb1Sdrh ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
1839bb53ecb1Sdrh ** calling routine should implement the IN operator using a sequence
1840bb53ecb1Sdrh ** of Eq or Ne comparison operations.
1841bb53ecb1Sdrh **
1842b74b1017Sdrh ** When the b-tree is being used for membership tests, the calling function
18433a85625dSdrh ** might need to know whether or not the RHS side of the IN operator
1844e21a6e1dSdrh ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
18453a85625dSdrh ** if there is any chance that the (...) might contain a NULL value at
18460cdc022eSdanielk1977 ** runtime, then a register is allocated and the register number written
1847e21a6e1dSdrh ** to *prRhsHasNull. If there is no chance that the (...) contains a
1848e21a6e1dSdrh ** NULL value, then *prRhsHasNull is left unchanged.
18490cdc022eSdanielk1977 **
1850e21a6e1dSdrh ** If a register is allocated and its location stored in *prRhsHasNull, then
18516be515ebSdrh ** the value in that register will be NULL if the b-tree contains one or more
18526be515ebSdrh ** NULL values, and it will be some non-NULL value if the b-tree contains no
18536be515ebSdrh ** NULL values.
18549a96b668Sdanielk1977 */
1855284f4acaSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1856e21a6e1dSdrh int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
1857b74b1017Sdrh   Select *p;                            /* SELECT to the right of IN operator */
1858b74b1017Sdrh   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
1859b74b1017Sdrh   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
18603a85625dSdrh   int mustBeUnique;                     /* True if RHS must be unique */
1861b8475df8Sdrh   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
18629a96b668Sdanielk1977 
18631450bc6eSdrh   assert( pX->op==TK_IN );
18643a85625dSdrh   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
18651450bc6eSdrh 
1866b74b1017Sdrh   /* Check to see if an existing table or index can be used to
1867b74b1017Sdrh   ** satisfy the query.  This is preferable to generating a new
1868b74b1017Sdrh   ** ephemeral table.
18699a96b668Sdanielk1977   */
187069c355bdSdrh   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
1871e1fb65a0Sdanielk1977     sqlite3 *db = pParse->db;              /* Database connection */
1872b07028f7Sdrh     Table *pTab;                           /* Table <table>. */
1873b07028f7Sdrh     Expr *pExpr;                           /* Expression <column> */
1874bbbdc83bSdrh     i16 iCol;                              /* Index of column <column> */
1875bbbdc83bSdrh     i16 iDb;                               /* Database idx for pTab */
1876e1fb65a0Sdanielk1977 
1877b07028f7Sdrh     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
1878b07028f7Sdrh     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
1879b07028f7Sdrh     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
1880b07028f7Sdrh     pTab = p->pSrc->a[0].pTab;
1881b07028f7Sdrh     pExpr = p->pEList->a[0].pExpr;
1882bbbdc83bSdrh     iCol = (i16)pExpr->iColumn;
1883b07028f7Sdrh 
1884b22f7c83Sdrh     /* Code an OP_Transaction and OP_TableLock for <table>. */
1885e1fb65a0Sdanielk1977     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1886e1fb65a0Sdanielk1977     sqlite3CodeVerifySchema(pParse, iDb);
1887e1fb65a0Sdanielk1977     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
18889a96b668Sdanielk1977 
18899a96b668Sdanielk1977     /* This function is only called from two places. In both cases the vdbe
18909a96b668Sdanielk1977     ** has already been allocated. So assume sqlite3GetVdbe() is always
18919a96b668Sdanielk1977     ** successful here.
18929a96b668Sdanielk1977     */
18939a96b668Sdanielk1977     assert(v);
18949a96b668Sdanielk1977     if( iCol<0 ){
18957d176105Sdrh       int iAddr = sqlite3CodeOnce(pParse);
18967d176105Sdrh       VdbeCoverage(v);
18979a96b668Sdanielk1977 
18989a96b668Sdanielk1977       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
18999a96b668Sdanielk1977       eType = IN_INDEX_ROWID;
19009a96b668Sdanielk1977 
19019a96b668Sdanielk1977       sqlite3VdbeJumpHere(v, iAddr);
19029a96b668Sdanielk1977     }else{
1903e1fb65a0Sdanielk1977       Index *pIdx;                         /* Iterator variable */
1904e1fb65a0Sdanielk1977 
19059a96b668Sdanielk1977       /* The collation sequence used by the comparison. If an index is to
19069a96b668Sdanielk1977       ** be used in place of a temp-table, it must be ordered according
1907e1fb65a0Sdanielk1977       ** to this collation sequence.  */
19089a96b668Sdanielk1977       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
19099a96b668Sdanielk1977 
19109a96b668Sdanielk1977       /* Check that the affinity that will be used to perform the
19119a96b668Sdanielk1977       ** comparison is the same as the affinity of the column. If
19129a96b668Sdanielk1977       ** it is not, it is not possible to use any index.
19139a96b668Sdanielk1977       */
1914dbaee5e3Sdrh       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
19159a96b668Sdanielk1977 
19169a96b668Sdanielk1977       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
19179a96b668Sdanielk1977         if( (pIdx->aiColumn[0]==iCol)
1918b74b1017Sdrh          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
19195f1d1d9cSdrh          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
19209a96b668Sdanielk1977         ){
19217d176105Sdrh           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
19222ec2fb22Sdrh           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
19232ec2fb22Sdrh           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1924207872a4Sdanielk1977           VdbeComment((v, "%s", pIdx->zName));
19251ccce449Sdrh           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
19261ccce449Sdrh           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
19279a96b668Sdanielk1977 
1928e21a6e1dSdrh           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
19293480bfdaSdan #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
19303480bfdaSdan             const i64 sOne = 1;
19313480bfdaSdan             sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
19323480bfdaSdan                 iTab, 0, 0, (u8*)&sOne, P4_INT64);
19333480bfdaSdan #endif
1934e21a6e1dSdrh             *prRhsHasNull = ++pParse->nMem;
19356be515ebSdrh             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
19360cdc022eSdanielk1977           }
1937552fd454Sdrh           sqlite3VdbeJumpHere(v, iAddr);
19389a96b668Sdanielk1977         }
19399a96b668Sdanielk1977       }
19409a96b668Sdanielk1977     }
19419a96b668Sdanielk1977   }
19429a96b668Sdanielk1977 
1943bb53ecb1Sdrh   /* If no preexisting index is available for the IN clause
1944bb53ecb1Sdrh   ** and IN_INDEX_NOOP is an allowed reply
1945bb53ecb1Sdrh   ** and the RHS of the IN operator is a list, not a subquery
1946*71c57db0Sdan   ** and the RHS is not constant or has two or fewer terms,
194760ec914cSpeter.d.reid   ** then it is not worth creating an ephemeral table to evaluate
1948bb53ecb1Sdrh   ** the IN operator so return IN_INDEX_NOOP.
1949bb53ecb1Sdrh   */
1950bb53ecb1Sdrh   if( eType==0
1951bb53ecb1Sdrh    && (inFlags & IN_INDEX_NOOP_OK)
1952bb53ecb1Sdrh    && !ExprHasProperty(pX, EP_xIsSelect)
1953bb53ecb1Sdrh    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
1954bb53ecb1Sdrh   ){
1955bb53ecb1Sdrh     eType = IN_INDEX_NOOP;
1956bb53ecb1Sdrh   }
1957bb53ecb1Sdrh 
1958bb53ecb1Sdrh 
19599a96b668Sdanielk1977   if( eType==0 ){
19604387006cSdrh     /* Could not find an existing table or index to use as the RHS b-tree.
1961b74b1017Sdrh     ** We will have to generate an ephemeral table to do the job.
1962b74b1017Sdrh     */
19638e23daf3Sdrh     u32 savedNQueryLoop = pParse->nQueryLoop;
19640cdc022eSdanielk1977     int rMayHaveNull = 0;
196541a05b7bSdanielk1977     eType = IN_INDEX_EPH;
19663a85625dSdrh     if( inFlags & IN_INDEX_LOOP ){
19674a5acf8eSdrh       pParse->nQueryLoop = 0;
1968c5cd1249Sdrh       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
196941a05b7bSdanielk1977         eType = IN_INDEX_ROWID;
19700cdc022eSdanielk1977       }
1971e21a6e1dSdrh     }else if( prRhsHasNull ){
1972e21a6e1dSdrh       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
1973cf4d38aaSdrh     }
197441a05b7bSdanielk1977     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
1975cf4d38aaSdrh     pParse->nQueryLoop = savedNQueryLoop;
19769a96b668Sdanielk1977   }else{
19779a96b668Sdanielk1977     pX->iTable = iTab;
19789a96b668Sdanielk1977   }
19799a96b668Sdanielk1977   return eType;
19809a96b668Sdanielk1977 }
1981284f4acaSdanielk1977 #endif
1982626a879aSdrh 
1983*71c57db0Sdan static char *exprINAffinity(Parse *pParse, Expr *pExpr){
1984*71c57db0Sdan   Expr *pLeft = pExpr->pLeft;
1985*71c57db0Sdan   int nVal = sqlite3ExprVectorSize(pLeft);
1986*71c57db0Sdan   char *zRet;
1987*71c57db0Sdan 
1988*71c57db0Sdan   zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
1989*71c57db0Sdan   if( zRet ){
1990*71c57db0Sdan     int i;
1991*71c57db0Sdan     for(i=0; i<nVal; i++){
1992*71c57db0Sdan       Expr *pA;
1993*71c57db0Sdan       char a;
1994*71c57db0Sdan       if( nVal==1 ){
1995*71c57db0Sdan         pA = pLeft;
1996*71c57db0Sdan       }else{
1997*71c57db0Sdan         pA = exprVectorField(pLeft, i);
1998*71c57db0Sdan       }
1999*71c57db0Sdan       a = sqlite3ExprAffinity(pA);
2000*71c57db0Sdan       zRet[i] = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[i].pExpr, a);
2001*71c57db0Sdan     }
2002*71c57db0Sdan     zRet[nVal] = '\0';
2003*71c57db0Sdan   }
2004*71c57db0Sdan   return zRet;
2005*71c57db0Sdan }
2006*71c57db0Sdan 
2007626a879aSdrh /*
2008d4187c71Sdrh ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2009d4187c71Sdrh ** or IN operators.  Examples:
2010626a879aSdrh **
20119cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
20129cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
20139cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
20149cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
2015fef5208cSdrh **
20169cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
20179cbe6352Sdrh ** operator or subquery.
201841a05b7bSdanielk1977 **
201941a05b7bSdanielk1977 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
202041a05b7bSdanielk1977 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
202141a05b7bSdanielk1977 ** to some integer key column of a table B-Tree. In this case, use an
202241a05b7bSdanielk1977 ** intkey B-Tree to store the set of IN(...) values instead of the usual
202341a05b7bSdanielk1977 ** (slower) variable length keys B-Tree.
2024fd773cf9Sdrh **
2025fd773cf9Sdrh ** If rMayHaveNull is non-zero, that means that the operation is an IN
2026fd773cf9Sdrh ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
20273a85625dSdrh ** All this routine does is initialize the register given by rMayHaveNull
20283a85625dSdrh ** to NULL.  Calling routines will take care of changing this register
20293a85625dSdrh ** value to non-NULL if the RHS is NULL-free.
20301450bc6eSdrh **
20311450bc6eSdrh ** For a SELECT or EXISTS operator, return the register that holds the
20321450bc6eSdrh ** result.  For IN operators or if an error occurs, the return value is 0.
2033cce7d176Sdrh */
203451522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
20351450bc6eSdrh int sqlite3CodeSubselect(
2036fd773cf9Sdrh   Parse *pParse,          /* Parsing context */
2037fd773cf9Sdrh   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
20386be515ebSdrh   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
2039fd773cf9Sdrh   int isRowid             /* If true, LHS of IN operator is a rowid */
204041a05b7bSdanielk1977 ){
20416be515ebSdrh   int jmpIfDynamic = -1;                      /* One-time test address */
20421450bc6eSdrh   int rReg = 0;                           /* Register storing resulting */
2043b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
20441450bc6eSdrh   if( NEVER(v==0) ) return 0;
2045ceea3321Sdrh   sqlite3ExprCachePush(pParse);
2046fc976065Sdanielk1977 
204757dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
204857dbd7b3Sdrh   ** if any of the following is true:
204957dbd7b3Sdrh   **
205057dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
205157dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
205257dbd7b3Sdrh   **    *  We are inside a trigger
205357dbd7b3Sdrh   **
205457dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
205557dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
2056b3bce662Sdanielk1977   */
2057c5cd1249Sdrh   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
20586be515ebSdrh     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
2059b3bce662Sdanielk1977   }
2060b3bce662Sdanielk1977 
20614a07e3dbSdan #ifndef SQLITE_OMIT_EXPLAIN
20624a07e3dbSdan   if( pParse->explain==2 ){
206362aaa6caSdrh     char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
206462aaa6caSdrh         jmpIfDynamic>=0?"":"CORRELATED ",
206562aaa6caSdrh         pExpr->op==TK_IN?"LIST":"SCALAR",
206662aaa6caSdrh         pParse->iNextSelectId
20674a07e3dbSdan     );
20684a07e3dbSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
20694a07e3dbSdan   }
20704a07e3dbSdan #endif
20714a07e3dbSdan 
2072cce7d176Sdrh   switch( pExpr->op ){
2073fef5208cSdrh     case TK_IN: {
2074b9bb7c18Sdrh       int addr;                   /* Address of OP_OpenEphemeral instruction */
2075d4187c71Sdrh       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
2076323df790Sdrh       KeyInfo *pKeyInfo = 0;      /* Key information */
2077*71c57db0Sdan       int nVal;                   /* Size of vector pLeft */
2078d3d39e93Sdrh 
2079*71c57db0Sdan       nVal = sqlite3ExprVectorSize(pLeft);
2080e014a838Sdanielk1977 
2081e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
20828cff69dfSdrh       ** expression it is handled the same way.  An ephemeral table is
2083e014a838Sdanielk1977       ** filled with single-field index keys representing the results
2084e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
2085fef5208cSdrh       **
2086e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
2087e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
2088e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
2089e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
2090e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
2091e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
2092e014a838Sdanielk1977       ** is used.
2093fef5208cSdrh       */
2094832508b7Sdrh       pExpr->iTable = pParse->nTab++;
2095*71c57db0Sdan       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2096*71c57db0Sdan           pExpr->iTable, (isRowid?0:nVal));
2097*71c57db0Sdan       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
2098e014a838Sdanielk1977 
20996ab3a2ecSdanielk1977       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2100e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
2101e014a838Sdanielk1977         **
2102e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
2103e014a838Sdanielk1977         ** table allocated and opened above.
2104e014a838Sdanielk1977         */
21054387006cSdrh         Select *pSelect = pExpr->x.pSelect;
2106*71c57db0Sdan         ExprList *pEList = pSelect->pEList;
21071013c932Sdrh 
210841a05b7bSdanielk1977         assert( !isRowid );
2109*71c57db0Sdan         if( pEList->nExpr!=nVal ){
2110*71c57db0Sdan           sqlite3ErrorMsg(pParse, "SELECT has %d columns - expected %d",
2111*71c57db0Sdan               pEList->nExpr, nVal);
2112*71c57db0Sdan         }else{
2113*71c57db0Sdan           SelectDest dest;
2114*71c57db0Sdan           int i;
21151013c932Sdrh           sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2116*71c57db0Sdan           dest.zAffSdst = exprINAffinity(pParse, pExpr);
2117e014a838Sdanielk1977           assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
21184387006cSdrh           pSelect->iLimit = 0;
21194387006cSdrh           testcase( pSelect->selFlags & SF_Distinct );
2120812ea833Sdrh           testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
21214387006cSdrh           if( sqlite3Select(pParse, pSelect, &dest) ){
2122*71c57db0Sdan             sqlite3DbFree(pParse->db, dest.zAffSdst);
21232ec2fb22Sdrh             sqlite3KeyInfoUnref(pKeyInfo);
21241450bc6eSdrh             return 0;
212594ccde58Sdrh           }
2126*71c57db0Sdan           sqlite3DbFree(pParse->db, dest.zAffSdst);
2127812ea833Sdrh           assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
21283535ec3eSdrh           assert( pEList!=0 );
21293535ec3eSdrh           assert( pEList->nExpr>0 );
21302ec2fb22Sdrh           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2131*71c57db0Sdan           for(i=0; i<nVal; i++){
2132*71c57db0Sdan             Expr *p = (nVal>1) ? exprVectorField(pLeft, i) : pLeft;
2133*71c57db0Sdan             pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2134*71c57db0Sdan                 pParse, p, pEList->a[i].pExpr
2135*71c57db0Sdan             );
2136*71c57db0Sdan           }
2137*71c57db0Sdan         }
2138a7d2db17Sdrh       }else if( ALWAYS(pExpr->x.pList!=0) ){
2139fef5208cSdrh         /* Case 2:     expr IN (exprlist)
2140fef5208cSdrh         **
2141e014a838Sdanielk1977         ** For each expression, build an index key from the evaluation and
2142e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
2143e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
2144e014a838Sdanielk1977         ** a column, use numeric affinity.
2145fef5208cSdrh         */
2146*71c57db0Sdan         char affinity;            /* Affinity of the LHS of the IN */
2147e014a838Sdanielk1977         int i;
21486ab3a2ecSdanielk1977         ExprList *pList = pExpr->x.pList;
214957dbd7b3Sdrh         struct ExprList_item *pItem;
2150ecc31805Sdrh         int r1, r2, r3;
215157dbd7b3Sdrh 
2152*71c57db0Sdan         affinity = sqlite3ExprAffinity(pLeft);
2153e014a838Sdanielk1977         if( !affinity ){
215405883a34Sdrh           affinity = SQLITE_AFF_BLOB;
2155e014a838Sdanielk1977         }
2156323df790Sdrh         if( pKeyInfo ){
21572ec2fb22Sdrh           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2158323df790Sdrh           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2159323df790Sdrh         }
2160e014a838Sdanielk1977 
2161e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
21622d401ab8Sdrh         r1 = sqlite3GetTempReg(pParse);
21632d401ab8Sdrh         r2 = sqlite3GetTempReg(pParse);
216437e08081Sdrh         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
216557dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
216657dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
2167e05c929bSdrh           int iValToIns;
2168e014a838Sdanielk1977 
216957dbd7b3Sdrh           /* If the expression is not constant then we will need to
217057dbd7b3Sdrh           ** disable the test that was generated above that makes sure
217157dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
217257dbd7b3Sdrh           ** expression we need to rerun this code each time.
217357dbd7b3Sdrh           */
21746be515ebSdrh           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
21756be515ebSdrh             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
21766be515ebSdrh             jmpIfDynamic = -1;
21774794b980Sdrh           }
2178e014a838Sdanielk1977 
2179e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
2180e05c929bSdrh           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2181e05c929bSdrh             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
2182e05c929bSdrh           }else{
2183ecc31805Sdrh             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
218441a05b7bSdanielk1977             if( isRowid ){
2185e05c929bSdrh               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2186e05c929bSdrh                                 sqlite3VdbeCurrentAddr(v)+2);
2187688852abSdrh               VdbeCoverage(v);
218841a05b7bSdanielk1977               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
218941a05b7bSdanielk1977             }else{
2190ecc31805Sdrh               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
21913c31fc23Sdrh               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
21922d401ab8Sdrh               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2193fef5208cSdrh             }
219441a05b7bSdanielk1977           }
2195e05c929bSdrh         }
21962d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r1);
21972d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r2);
2198fef5208cSdrh       }
2199323df790Sdrh       if( pKeyInfo ){
22002ec2fb22Sdrh         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
220141a05b7bSdanielk1977       }
2202b3bce662Sdanielk1977       break;
2203fef5208cSdrh     }
2204fef5208cSdrh 
220551522cd3Sdrh     case TK_EXISTS:
2206fd773cf9Sdrh     case TK_SELECT:
2207fd773cf9Sdrh     default: {
2208fd773cf9Sdrh       /* If this has to be a scalar SELECT.  Generate code to put the
2209fef5208cSdrh       ** value of this select in a memory cell and record the number
2210fd773cf9Sdrh       ** of the memory cell in iColumn.  If this is an EXISTS, write
2211fd773cf9Sdrh       ** an integer 0 (not exists) or 1 (exists) into a memory cell
2212fd773cf9Sdrh       ** and record that memory cell in iColumn.
2213fef5208cSdrh       */
2214fd773cf9Sdrh       Select *pSel;                         /* SELECT statement to encode */
2215fd773cf9Sdrh       SelectDest dest;                      /* How to deal with SELECt result */
2216*71c57db0Sdan       int nReg;                             /* Registers to allocate */
22171398ad36Sdrh 
2218cf697396Sshane       testcase( pExpr->op==TK_EXISTS );
2219cf697396Sshane       testcase( pExpr->op==TK_SELECT );
2220cf697396Sshane       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
22216ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
2222*71c57db0Sdan 
22236ab3a2ecSdanielk1977       pSel = pExpr->x.pSelect;
2224*71c57db0Sdan       nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2225*71c57db0Sdan       sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2226*71c57db0Sdan       pParse->nMem += nReg;
222751522cd3Sdrh       if( pExpr->op==TK_SELECT ){
22286c8c8ce0Sdanielk1977         dest.eDest = SRT_Mem;
222953932ce8Sdrh         dest.iSdst = dest.iSDParm;
2230*71c57db0Sdan         dest.nSdst = nReg;
2231*71c57db0Sdan         sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
2232d4e70ebdSdrh         VdbeComment((v, "Init subquery result"));
223351522cd3Sdrh       }else{
22346c8c8ce0Sdanielk1977         dest.eDest = SRT_Exists;
22352b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
2236d4e70ebdSdrh         VdbeComment((v, "Init EXISTS result"));
223751522cd3Sdrh       }
2238633e6d57Sdrh       sqlite3ExprDelete(pParse->db, pSel->pLimit);
2239094430ebSdrh       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2240094430ebSdrh                                   &sqlite3IntTokens[1]);
224148b5b041Sdrh       pSel->iLimit = 0;
2242772460fdSdrh       pSel->selFlags &= ~SF_MultiValue;
22437d10d5a6Sdrh       if( sqlite3Select(pParse, pSel, &dest) ){
22441450bc6eSdrh         return 0;
224594ccde58Sdrh       }
22462b596da8Sdrh       rReg = dest.iSDParm;
2247ebb6a65dSdrh       ExprSetVVAProperty(pExpr, EP_NoReduce);
2248b3bce662Sdanielk1977       break;
224919a775c2Sdrh     }
2250cce7d176Sdrh   }
2251b3bce662Sdanielk1977 
22526be515ebSdrh   if( rHasNullFlag ){
22536be515ebSdrh     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
2254b3bce662Sdanielk1977   }
22556be515ebSdrh 
22566be515ebSdrh   if( jmpIfDynamic>=0 ){
22576be515ebSdrh     sqlite3VdbeJumpHere(v, jmpIfDynamic);
2258b3bce662Sdanielk1977   }
2259d2490904Sdrh   sqlite3ExprCachePop(pParse);
2260fc976065Sdanielk1977 
22611450bc6eSdrh   return rReg;
2262cce7d176Sdrh }
226351522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
2264cce7d176Sdrh 
2265e3365e6cSdrh #ifndef SQLITE_OMIT_SUBQUERY
2266*71c57db0Sdan void exprCodeVectorIN(
2267*71c57db0Sdan   Parse *pParse,        /* Parsing and code generating context */
2268*71c57db0Sdan   Expr *pExpr,          /* The IN expression */
2269*71c57db0Sdan   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
2270*71c57db0Sdan   int destIfNull        /* Jump here if the results are unknown due to NULLs */
2271*71c57db0Sdan ){
2272*71c57db0Sdan   int i;
2273*71c57db0Sdan   int addrNext;
2274*71c57db0Sdan   int iSkip;
2275*71c57db0Sdan   int r1;
2276*71c57db0Sdan   int r2 = sqlite3GetTempReg(pParse);
2277*71c57db0Sdan   int r3 = sqlite3GetTempReg(pParse);
2278*71c57db0Sdan   int r4 = sqlite3GetTempReg(pParse);
2279*71c57db0Sdan   int regResult = sqlite3GetTempReg(pParse);
2280*71c57db0Sdan   int nVal = sqlite3ExprVectorSize(pExpr->pLeft);
2281*71c57db0Sdan 
2282*71c57db0Sdan   Expr *pLeft = pExpr->pLeft;
2283*71c57db0Sdan   Vdbe *v = pParse->pVdbe;
2284*71c57db0Sdan 
2285*71c57db0Sdan   /* Code the LHS, the <expr> from "<expr> IN (...)". Leave the results in
2286*71c57db0Sdan   ** an array of nVal registers starting at r1.  */
2287*71c57db0Sdan   sqlite3ExprCachePush(pParse);
2288*71c57db0Sdan   if( pLeft->flags & EP_xIsSelect ){
2289*71c57db0Sdan     r1 = sqlite3CodeSubselect(pParse, pLeft, 0, 0);
2290*71c57db0Sdan   }else{
2291*71c57db0Sdan     r1 = pParse->nMem + 1;
2292*71c57db0Sdan     pParse->nMem += nVal;
2293*71c57db0Sdan     sqlite3ExprCodeExprList(pParse, pLeft->x.pList, r1, 0, 0);
2294*71c57db0Sdan   }
2295*71c57db0Sdan 
2296*71c57db0Sdan   /* Generate an epheremal index containing the contents of the SELECT
2297*71c57db0Sdan   ** to the right of the "<expr> IN (SELECT ...)" expression. The cursor
2298*71c57db0Sdan   ** number for the epheremal table is left in pExpr->iTable.  */
2299*71c57db0Sdan   assert( pExpr->flags & EP_xIsSelect );
2300*71c57db0Sdan   sqlite3CodeSubselect(pParse, pExpr, 0, 0);
2301*71c57db0Sdan 
2302*71c57db0Sdan   sqlite3VdbeAddOp2(v, OP_Integer, 0, regResult);
2303*71c57db0Sdan 
2304*71c57db0Sdan   /* Iterate through the ephemeral table just populated */
2305*71c57db0Sdan   addrNext = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2306*71c57db0Sdan   for(i=0; i<nVal; i++){
2307*71c57db0Sdan     Expr *p;
2308*71c57db0Sdan     CollSeq *pColl;
2309*71c57db0Sdan     p = exprVectorField(pLeft, i);
2310*71c57db0Sdan     pColl = sqlite3ExprCollSeq(pParse, p);
2311*71c57db0Sdan     sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r2);
2312*71c57db0Sdan     sqlite3VdbeAddOp4(v, OP_Eq, r1+i, i==0?r3:r4, r2, (void*)pColl,P4_COLLSEQ);
2313*71c57db0Sdan     sqlite3VdbeChangeP5(v, SQLITE_STOREP2);
2314*71c57db0Sdan     VdbeCoverage(v);
2315*71c57db0Sdan     if( i!=0 ){
2316*71c57db0Sdan       sqlite3VdbeAddOp3(v, OP_And, r3, r4, r4);
2317*71c57db0Sdan     }
2318*71c57db0Sdan   }
2319*71c57db0Sdan   sqlite3VdbeAddOp2(v, OP_If, r4, sqlite3VdbeCurrentAddr(v)+6);
2320*71c57db0Sdan   sqlite3VdbeAddOp2(v, OP_IfNot, r4, sqlite3VdbeCurrentAddr(v)+2);
2321*71c57db0Sdan   sqlite3VdbeAddOp2(v, OP_Null, 0, regResult);
2322*71c57db0Sdan   sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrNext);
2323*71c57db0Sdan   sqlite3VdbeAddOp3(v, OP_If, regResult, destIfNull, 1);
2324*71c57db0Sdan   sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
2325*71c57db0Sdan 
2326*71c57db0Sdan   sqlite3ReleaseTempReg(pParse, r2);
2327*71c57db0Sdan   sqlite3ReleaseTempReg(pParse, r3);
2328*71c57db0Sdan   sqlite3ReleaseTempReg(pParse, r4);
2329*71c57db0Sdan   sqlite3ReleaseTempReg(pParse, regResult);
2330*71c57db0Sdan   sqlite3ExprCachePop(pParse);
2331*71c57db0Sdan }
2332*71c57db0Sdan #endif
2333*71c57db0Sdan 
2334*71c57db0Sdan #ifndef SQLITE_OMIT_SUBQUERY
2335e3365e6cSdrh /*
2336e3365e6cSdrh ** Generate code for an IN expression.
2337e3365e6cSdrh **
2338e3365e6cSdrh **      x IN (SELECT ...)
2339e3365e6cSdrh **      x IN (value, value, ...)
2340e3365e6cSdrh **
2341e3365e6cSdrh ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
2342e3365e6cSdrh ** is an array of zero or more values.  The expression is true if the LHS is
2343e3365e6cSdrh ** contained within the RHS.  The value of the expression is unknown (NULL)
2344e3365e6cSdrh ** if the LHS is NULL or if the LHS is not contained within the RHS and the
2345e3365e6cSdrh ** RHS contains one or more NULL values.
2346e3365e6cSdrh **
23476be515ebSdrh ** This routine generates code that jumps to destIfFalse if the LHS is not
2348e3365e6cSdrh ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
2349e3365e6cSdrh ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
2350e3365e6cSdrh ** within the RHS then fall through.
2351e3365e6cSdrh */
2352e3365e6cSdrh static void sqlite3ExprCodeIN(
2353e3365e6cSdrh   Parse *pParse,        /* Parsing and code generating context */
2354e3365e6cSdrh   Expr *pExpr,          /* The IN expression */
2355e3365e6cSdrh   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
2356e3365e6cSdrh   int destIfNull        /* Jump here if the results are unknown due to NULLs */
2357e3365e6cSdrh ){
2358e3365e6cSdrh   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
2359e3365e6cSdrh   char affinity;        /* Comparison affinity to use */
2360e3365e6cSdrh   int eType;            /* Type of the RHS */
2361e3365e6cSdrh   int r1;               /* Temporary use register */
2362e3365e6cSdrh   Vdbe *v;              /* Statement under construction */
2363e3365e6cSdrh 
2364*71c57db0Sdan   if( pExpr->pLeft->flags & EP_Vector ){
2365*71c57db0Sdan     return exprCodeVectorIN(pParse, pExpr, destIfFalse, destIfNull);
2366*71c57db0Sdan   }
2367*71c57db0Sdan 
2368e3365e6cSdrh   /* Compute the RHS.   After this step, the table with cursor
2369e3365e6cSdrh   ** pExpr->iTable will contains the values that make up the RHS.
2370e3365e6cSdrh   */
2371e3365e6cSdrh   v = pParse->pVdbe;
2372e3365e6cSdrh   assert( v!=0 );       /* OOM detected prior to this routine */
2373e3365e6cSdrh   VdbeNoopComment((v, "begin IN expr"));
2374bb53ecb1Sdrh   eType = sqlite3FindInIndex(pParse, pExpr,
2375bb53ecb1Sdrh                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
23763a85625dSdrh                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
2377e3365e6cSdrh 
2378e3365e6cSdrh   /* Figure out the affinity to use to create a key from the results
2379e3365e6cSdrh   ** of the expression. affinityStr stores a static string suitable for
2380e3365e6cSdrh   ** P4 of OP_MakeRecord.
2381e3365e6cSdrh   */
2382e3365e6cSdrh   affinity = comparisonAffinity(pExpr);
2383e3365e6cSdrh 
2384e3365e6cSdrh   /* Code the LHS, the <expr> from "<expr> IN (...)".
2385e3365e6cSdrh   */
2386e3365e6cSdrh   sqlite3ExprCachePush(pParse);
2387e3365e6cSdrh   r1 = sqlite3GetTempReg(pParse);
2388e3365e6cSdrh   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
2389e3365e6cSdrh 
2390bb53ecb1Sdrh   /* If sqlite3FindInIndex() did not find or create an index that is
2391bb53ecb1Sdrh   ** suitable for evaluating the IN operator, then evaluate using a
2392bb53ecb1Sdrh   ** sequence of comparisons.
2393bb53ecb1Sdrh   */
2394bb53ecb1Sdrh   if( eType==IN_INDEX_NOOP ){
2395bb53ecb1Sdrh     ExprList *pList = pExpr->x.pList;
2396bb53ecb1Sdrh     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2397bb53ecb1Sdrh     int labelOk = sqlite3VdbeMakeLabel(v);
2398bb53ecb1Sdrh     int r2, regToFree;
2399bb53ecb1Sdrh     int regCkNull = 0;
2400bb53ecb1Sdrh     int ii;
2401bb53ecb1Sdrh     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2402bb53ecb1Sdrh     if( destIfNull!=destIfFalse ){
2403bb53ecb1Sdrh       regCkNull = sqlite3GetTempReg(pParse);
2404a976979bSdrh       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
2405bb53ecb1Sdrh     }
2406bb53ecb1Sdrh     for(ii=0; ii<pList->nExpr; ii++){
2407bb53ecb1Sdrh       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
2408a976979bSdrh       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
2409bb53ecb1Sdrh         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2410bb53ecb1Sdrh       }
2411bb53ecb1Sdrh       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2412bb53ecb1Sdrh         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
24134336b0e6Sdrh                           (void*)pColl, P4_COLLSEQ);
24144336b0e6Sdrh         VdbeCoverageIf(v, ii<pList->nExpr-1);
24154336b0e6Sdrh         VdbeCoverageIf(v, ii==pList->nExpr-1);
2416bb53ecb1Sdrh         sqlite3VdbeChangeP5(v, affinity);
2417bb53ecb1Sdrh       }else{
2418bb53ecb1Sdrh         assert( destIfNull==destIfFalse );
2419bb53ecb1Sdrh         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2420bb53ecb1Sdrh                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
2421bb53ecb1Sdrh         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
2422bb53ecb1Sdrh       }
2423bb53ecb1Sdrh       sqlite3ReleaseTempReg(pParse, regToFree);
2424bb53ecb1Sdrh     }
2425bb53ecb1Sdrh     if( regCkNull ){
2426bb53ecb1Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
2427076e85f5Sdrh       sqlite3VdbeGoto(v, destIfFalse);
2428bb53ecb1Sdrh     }
2429bb53ecb1Sdrh     sqlite3VdbeResolveLabel(v, labelOk);
2430bb53ecb1Sdrh     sqlite3ReleaseTempReg(pParse, regCkNull);
2431bb53ecb1Sdrh   }else{
2432bb53ecb1Sdrh 
2433094430ebSdrh     /* If the LHS is NULL, then the result is either false or NULL depending
2434094430ebSdrh     ** on whether the RHS is empty or not, respectively.
2435094430ebSdrh     */
24367248a8b2Sdrh     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
2437094430ebSdrh       if( destIfNull==destIfFalse ){
2438094430ebSdrh         /* Shortcut for the common case where the false and NULL outcomes are
2439094430ebSdrh         ** the same. */
2440688852abSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
2441094430ebSdrh       }else{
2442688852abSdrh         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2443094430ebSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2444688852abSdrh         VdbeCoverage(v);
2445076e85f5Sdrh         sqlite3VdbeGoto(v, destIfNull);
2446094430ebSdrh         sqlite3VdbeJumpHere(v, addr1);
2447094430ebSdrh       }
24487248a8b2Sdrh     }
2449e3365e6cSdrh 
2450e3365e6cSdrh     if( eType==IN_INDEX_ROWID ){
2451e3365e6cSdrh       /* In this case, the RHS is the ROWID of table b-tree
2452e3365e6cSdrh       */
2453eeb9565aSdrh       sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
2454688852abSdrh       VdbeCoverage(v);
2455e3365e6cSdrh     }else{
2456e3365e6cSdrh       /* In this case, the RHS is an index b-tree.
2457e3365e6cSdrh       */
24588cff69dfSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
2459e3365e6cSdrh 
2460e3365e6cSdrh       /* If the set membership test fails, then the result of the
2461e3365e6cSdrh       ** "x IN (...)" expression must be either 0 or NULL. If the set
2462e3365e6cSdrh       ** contains no NULL values, then the result is 0. If the set
2463e3365e6cSdrh       ** contains one or more NULL values, then the result of the
2464e3365e6cSdrh       ** expression is also NULL.
2465e3365e6cSdrh       */
2466e80c9b9aSdrh       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
2467e80c9b9aSdrh       if( rRhsHasNull==0 ){
2468e3365e6cSdrh         /* This branch runs if it is known at compile time that the RHS
2469e3365e6cSdrh         ** cannot contain NULL values. This happens as the result
2470e3365e6cSdrh         ** of a "NOT NULL" constraint in the database schema.
2471e3365e6cSdrh         **
2472e3365e6cSdrh         ** Also run this branch if NULL is equivalent to FALSE
2473e3365e6cSdrh         ** for this particular IN operator.
2474e3365e6cSdrh         */
24758cff69dfSdrh         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
2476688852abSdrh         VdbeCoverage(v);
2477e3365e6cSdrh       }else{
2478e3365e6cSdrh         /* In this branch, the RHS of the IN might contain a NULL and
2479e3365e6cSdrh         ** the presence of a NULL on the RHS makes a difference in the
2480e3365e6cSdrh         ** outcome.
2481e3365e6cSdrh         */
2482728e0f91Sdrh         int addr1;
2483e3365e6cSdrh 
2484e3365e6cSdrh         /* First check to see if the LHS is contained in the RHS.  If so,
24856be515ebSdrh         ** then the answer is TRUE the presence of NULLs in the RHS does
24866be515ebSdrh         ** not matter.  If the LHS is not contained in the RHS, then the
24876be515ebSdrh         ** answer is NULL if the RHS contains NULLs and the answer is
24886be515ebSdrh         ** FALSE if the RHS is NULL-free.
2489e3365e6cSdrh         */
2490728e0f91Sdrh         addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
2491688852abSdrh         VdbeCoverage(v);
24926be515ebSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2493552fd454Sdrh         VdbeCoverage(v);
2494076e85f5Sdrh         sqlite3VdbeGoto(v, destIfFalse);
2495728e0f91Sdrh         sqlite3VdbeJumpHere(v, addr1);
2496e3365e6cSdrh       }
2497e3365e6cSdrh     }
2498bb53ecb1Sdrh   }
2499e3365e6cSdrh   sqlite3ReleaseTempReg(pParse, r1);
2500d2490904Sdrh   sqlite3ExprCachePop(pParse);
2501e3365e6cSdrh   VdbeComment((v, "end IN expr"));
2502e3365e6cSdrh }
2503e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
2504e3365e6cSdrh 
250513573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2506598f1340Sdrh /*
2507598f1340Sdrh ** Generate an instruction that will put the floating point
25089cbf3425Sdrh ** value described by z[0..n-1] into register iMem.
25090cf19ed8Sdrh **
25100cf19ed8Sdrh ** The z[] string will probably not be zero-terminated.  But the
25110cf19ed8Sdrh ** z[n] character is guaranteed to be something that does not look
25120cf19ed8Sdrh ** like the continuation of the number.
2513598f1340Sdrh */
2514b7916a78Sdrh static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
2515fd773cf9Sdrh   if( ALWAYS(z!=0) ){
2516598f1340Sdrh     double value;
25179339da1fSdrh     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
2518d0015161Sdrh     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2519598f1340Sdrh     if( negateFlag ) value = -value;
252097bae794Sdrh     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
2521598f1340Sdrh   }
2522598f1340Sdrh }
252313573c71Sdrh #endif
2524598f1340Sdrh 
2525598f1340Sdrh 
2526598f1340Sdrh /*
2527fec19aadSdrh ** Generate an instruction that will put the integer describe by
25289cbf3425Sdrh ** text z[0..n-1] into register iMem.
25290cf19ed8Sdrh **
25305f1d6b61Sshaneh ** Expr.u.zToken is always UTF8 and zero-terminated.
2531fec19aadSdrh */
253213573c71Sdrh static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
253313573c71Sdrh   Vdbe *v = pParse->pVdbe;
253492b01d53Sdrh   if( pExpr->flags & EP_IntValue ){
253533e619fcSdrh     int i = pExpr->u.iValue;
2536d50ffc41Sdrh     assert( i>=0 );
253792b01d53Sdrh     if( negFlag ) i = -i;
253892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
2539fd773cf9Sdrh   }else{
25405f1d6b61Sshaneh     int c;
25415f1d6b61Sshaneh     i64 value;
2542fd773cf9Sdrh     const char *z = pExpr->u.zToken;
2543fd773cf9Sdrh     assert( z!=0 );
25449296c18aSdrh     c = sqlite3DecOrHexToI64(z, &value);
25455f1d6b61Sshaneh     if( c==0 || (c==2 && negFlag) ){
2546158b9cb9Sdrh       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
254797bae794Sdrh       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
2548fec19aadSdrh     }else{
254913573c71Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
255013573c71Sdrh       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
255113573c71Sdrh #else
25521b7ddc59Sdrh #ifndef SQLITE_OMIT_HEX_INTEGER
25539296c18aSdrh       if( sqlite3_strnicmp(z,"0x",2)==0 ){
25549296c18aSdrh         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
25551b7ddc59Sdrh       }else
25561b7ddc59Sdrh #endif
25571b7ddc59Sdrh       {
2558b7916a78Sdrh         codeReal(v, z, negFlag, iMem);
25599296c18aSdrh       }
256013573c71Sdrh #endif
2561fec19aadSdrh     }
2562fec19aadSdrh   }
2563c9cf901dSdanielk1977 }
2564fec19aadSdrh 
2565bea119cdSdrh #if defined(SQLITE_DEBUG)
2566bea119cdSdrh /*
2567bea119cdSdrh ** Verify the consistency of the column cache
2568bea119cdSdrh */
2569bea119cdSdrh static int cacheIsValid(Parse *pParse){
2570bea119cdSdrh   int i, n;
2571bea119cdSdrh   for(i=n=0; i<SQLITE_N_COLCACHE; i++){
2572bea119cdSdrh     if( pParse->aColCache[i].iReg>0 ) n++;
2573bea119cdSdrh   }
2574bea119cdSdrh   return n==pParse->nColCache;
2575bea119cdSdrh }
2576bea119cdSdrh #endif
2577bea119cdSdrh 
2578ceea3321Sdrh /*
2579ceea3321Sdrh ** Clear a cache entry.
2580ceea3321Sdrh */
2581ceea3321Sdrh static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2582ceea3321Sdrh   if( p->tempReg ){
2583ceea3321Sdrh     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2584ceea3321Sdrh       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2585ceea3321Sdrh     }
2586ceea3321Sdrh     p->tempReg = 0;
2587ceea3321Sdrh   }
2588bea119cdSdrh   p->iReg = 0;
2589bea119cdSdrh   pParse->nColCache--;
2590ee65eea4Sdan   assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
2591ceea3321Sdrh }
2592ceea3321Sdrh 
2593ceea3321Sdrh 
2594ceea3321Sdrh /*
2595ceea3321Sdrh ** Record in the column cache that a particular column from a
2596ceea3321Sdrh ** particular table is stored in a particular register.
2597ceea3321Sdrh */
2598ceea3321Sdrh void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2599ceea3321Sdrh   int i;
2600ceea3321Sdrh   int minLru;
2601ceea3321Sdrh   int idxLru;
2602ceea3321Sdrh   struct yColCache *p;
2603ceea3321Sdrh 
2604ce8f53d4Sdan   /* Unless an error has occurred, register numbers are always positive. */
2605ce8f53d4Sdan   assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
260620411ea7Sdrh   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
260720411ea7Sdrh 
2608b6da74ebSdrh   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
2609b6da74ebSdrh   ** for testing only - to verify that SQLite always gets the same answer
2610b6da74ebSdrh   ** with and without the column cache.
2611b6da74ebSdrh   */
26127e5418e4Sdrh   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
2613b6da74ebSdrh 
261427ee406eSdrh   /* First replace any existing entry.
261527ee406eSdrh   **
261627ee406eSdrh   ** Actually, the way the column cache is currently used, we are guaranteed
261727ee406eSdrh   ** that the object will never already be in cache.  Verify this guarantee.
261827ee406eSdrh   */
261927ee406eSdrh #ifndef NDEBUG
2620ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
262127ee406eSdrh     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
2622ceea3321Sdrh   }
262327ee406eSdrh #endif
2624ceea3321Sdrh 
2625ceea3321Sdrh   /* Find an empty slot and replace it */
2626ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2627ceea3321Sdrh     if( p->iReg==0 ){
2628ceea3321Sdrh       p->iLevel = pParse->iCacheLevel;
2629ceea3321Sdrh       p->iTable = iTab;
2630ceea3321Sdrh       p->iColumn = iCol;
2631ceea3321Sdrh       p->iReg = iReg;
2632ceea3321Sdrh       p->tempReg = 0;
2633ceea3321Sdrh       p->lru = pParse->iCacheCnt++;
2634bea119cdSdrh       pParse->nColCache++;
2635ee65eea4Sdan       assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
2636ceea3321Sdrh       return;
2637ceea3321Sdrh     }
2638ceea3321Sdrh   }
2639ceea3321Sdrh 
2640ceea3321Sdrh   /* Replace the last recently used */
2641ceea3321Sdrh   minLru = 0x7fffffff;
2642ceea3321Sdrh   idxLru = -1;
2643ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2644ceea3321Sdrh     if( p->lru<minLru ){
2645ceea3321Sdrh       idxLru = i;
2646ceea3321Sdrh       minLru = p->lru;
2647ceea3321Sdrh     }
2648ceea3321Sdrh   }
264920411ea7Sdrh   if( ALWAYS(idxLru>=0) ){
2650ceea3321Sdrh     p = &pParse->aColCache[idxLru];
2651ceea3321Sdrh     p->iLevel = pParse->iCacheLevel;
2652ceea3321Sdrh     p->iTable = iTab;
2653ceea3321Sdrh     p->iColumn = iCol;
2654ceea3321Sdrh     p->iReg = iReg;
2655ceea3321Sdrh     p->tempReg = 0;
2656ceea3321Sdrh     p->lru = pParse->iCacheCnt++;
2657bea119cdSdrh     assert( cacheIsValid(pParse) );
2658ceea3321Sdrh     return;
2659ceea3321Sdrh   }
2660ceea3321Sdrh }
2661ceea3321Sdrh 
2662ceea3321Sdrh /*
2663f49f3523Sdrh ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2664f49f3523Sdrh ** Purge the range of registers from the column cache.
2665ceea3321Sdrh */
2666f49f3523Sdrh void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
2667ceea3321Sdrh   struct yColCache *p;
2668bea119cdSdrh   if( iReg<=0 || pParse->nColCache==0 ) return;
2669bea119cdSdrh   p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
2670bea119cdSdrh   while(1){
2671bea119cdSdrh     if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
2672bea119cdSdrh     if( p==pParse->aColCache ) break;
2673bea119cdSdrh     p--;
2674ceea3321Sdrh   }
2675ceea3321Sdrh }
2676ceea3321Sdrh 
2677ceea3321Sdrh /*
2678ceea3321Sdrh ** Remember the current column cache context.  Any new entries added
2679ceea3321Sdrh ** added to the column cache after this call are removed when the
2680ceea3321Sdrh ** corresponding pop occurs.
2681ceea3321Sdrh */
2682ceea3321Sdrh void sqlite3ExprCachePush(Parse *pParse){
2683ceea3321Sdrh   pParse->iCacheLevel++;
26849ac7962aSdrh #ifdef SQLITE_DEBUG
26859ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
26869ac7962aSdrh     printf("PUSH to %d\n", pParse->iCacheLevel);
26879ac7962aSdrh   }
26889ac7962aSdrh #endif
2689ceea3321Sdrh }
2690ceea3321Sdrh 
2691ceea3321Sdrh /*
2692ceea3321Sdrh ** Remove from the column cache any entries that were added since the
2693d2490904Sdrh ** the previous sqlite3ExprCachePush operation.  In other words, restore
2694d2490904Sdrh ** the cache to the state it was in prior the most recent Push.
2695ceea3321Sdrh */
2696d2490904Sdrh void sqlite3ExprCachePop(Parse *pParse){
2697ceea3321Sdrh   int i;
2698ceea3321Sdrh   struct yColCache *p;
2699d2490904Sdrh   assert( pParse->iCacheLevel>=1 );
2700d2490904Sdrh   pParse->iCacheLevel--;
27019ac7962aSdrh #ifdef SQLITE_DEBUG
27029ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
27039ac7962aSdrh     printf("POP  to %d\n", pParse->iCacheLevel);
27049ac7962aSdrh   }
27059ac7962aSdrh #endif
2706ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2707ceea3321Sdrh     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2708ceea3321Sdrh       cacheEntryClear(pParse, p);
2709ceea3321Sdrh     }
2710ceea3321Sdrh   }
2711ceea3321Sdrh }
2712945498f3Sdrh 
2713945498f3Sdrh /*
27145cd79239Sdrh ** When a cached column is reused, make sure that its register is
27155cd79239Sdrh ** no longer available as a temp register.  ticket #3879:  that same
27165cd79239Sdrh ** register might be in the cache in multiple places, so be sure to
27175cd79239Sdrh ** get them all.
27185cd79239Sdrh */
27195cd79239Sdrh static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
27205cd79239Sdrh   int i;
27215cd79239Sdrh   struct yColCache *p;
27225cd79239Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
27235cd79239Sdrh     if( p->iReg==iReg ){
27245cd79239Sdrh       p->tempReg = 0;
27255cd79239Sdrh     }
27265cd79239Sdrh   }
27275cd79239Sdrh }
27285cd79239Sdrh 
27291f9ca2c8Sdrh /* Generate code that will load into register regOut a value that is
27301f9ca2c8Sdrh ** appropriate for the iIdxCol-th column of index pIdx.
27311f9ca2c8Sdrh */
27321f9ca2c8Sdrh void sqlite3ExprCodeLoadIndexColumn(
27331f9ca2c8Sdrh   Parse *pParse,  /* The parsing context */
27341f9ca2c8Sdrh   Index *pIdx,    /* The index whose column is to be loaded */
27351f9ca2c8Sdrh   int iTabCur,    /* Cursor pointing to a table row */
27361f9ca2c8Sdrh   int iIdxCol,    /* The column of the index to be loaded */
27371f9ca2c8Sdrh   int regOut      /* Store the index column value in this register */
27381f9ca2c8Sdrh ){
27391f9ca2c8Sdrh   i16 iTabCol = pIdx->aiColumn[iIdxCol];
27404b92f98cSdrh   if( iTabCol==XN_EXPR ){
27411f9ca2c8Sdrh     assert( pIdx->aColExpr );
27421f9ca2c8Sdrh     assert( pIdx->aColExpr->nExpr>iIdxCol );
27431f9ca2c8Sdrh     pParse->iSelfTab = iTabCur;
27441c75c9d7Sdrh     sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
27454b92f98cSdrh   }else{
27464b92f98cSdrh     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
27474b92f98cSdrh                                     iTabCol, regOut);
27484b92f98cSdrh   }
27491f9ca2c8Sdrh }
27501f9ca2c8Sdrh 
27515cd79239Sdrh /*
27525c092e8aSdrh ** Generate code to extract the value of the iCol-th column of a table.
27535c092e8aSdrh */
27545c092e8aSdrh void sqlite3ExprCodeGetColumnOfTable(
27555c092e8aSdrh   Vdbe *v,        /* The VDBE under construction */
27565c092e8aSdrh   Table *pTab,    /* The table containing the value */
2757313619f5Sdrh   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
27585c092e8aSdrh   int iCol,       /* Index of the column to extract */
2759313619f5Sdrh   int regOut      /* Extract the value into this register */
27605c092e8aSdrh ){
27615c092e8aSdrh   if( iCol<0 || iCol==pTab->iPKey ){
27625c092e8aSdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
27635c092e8aSdrh   }else{
27645c092e8aSdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
2765ee0ec8e1Sdrh     int x = iCol;
276635db31b2Sdrh     if( !HasRowid(pTab) && !IsVirtual(pTab) ){
2767ee0ec8e1Sdrh       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
2768ee0ec8e1Sdrh     }
2769ee0ec8e1Sdrh     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
27705c092e8aSdrh   }
27715c092e8aSdrh   if( iCol>=0 ){
27725c092e8aSdrh     sqlite3ColumnDefault(v, pTab, iCol, regOut);
27735c092e8aSdrh   }
27745c092e8aSdrh }
27755c092e8aSdrh 
27765c092e8aSdrh /*
2777945498f3Sdrh ** Generate code that will extract the iColumn-th column from
2778ce78bc6eSdrh ** table pTab and store the column value in a register.
2779ce78bc6eSdrh **
2780ce78bc6eSdrh ** An effort is made to store the column value in register iReg.  This
2781ce78bc6eSdrh ** is not garanteeed for GetColumn() - the result can be stored in
2782ce78bc6eSdrh ** any register.  But the result is guaranteed to land in register iReg
2783ce78bc6eSdrh ** for GetColumnToReg().
2784e55cbd72Sdrh **
2785e55cbd72Sdrh ** There must be an open cursor to pTab in iTable when this routine
2786e55cbd72Sdrh ** is called.  If iColumn<0 then code is generated that extracts the rowid.
2787945498f3Sdrh */
2788e55cbd72Sdrh int sqlite3ExprCodeGetColumn(
2789e55cbd72Sdrh   Parse *pParse,   /* Parsing and code generating context */
27902133d822Sdrh   Table *pTab,     /* Description of the table we are reading from */
27912133d822Sdrh   int iColumn,     /* Index of the table column */
27922133d822Sdrh   int iTable,      /* The cursor pointing to the table */
2793a748fdccSdrh   int iReg,        /* Store results here */
2794ce78bc6eSdrh   u8 p5            /* P5 value for OP_Column + FLAGS */
27952133d822Sdrh ){
2796e55cbd72Sdrh   Vdbe *v = pParse->pVdbe;
2797e55cbd72Sdrh   int i;
2798da250ea5Sdrh   struct yColCache *p;
2799e55cbd72Sdrh 
2800ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2801b6da74ebSdrh     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
2802ceea3321Sdrh       p->lru = pParse->iCacheCnt++;
28035cd79239Sdrh       sqlite3ExprCachePinRegister(pParse, p->iReg);
2804da250ea5Sdrh       return p->iReg;
2805e55cbd72Sdrh     }
2806e55cbd72Sdrh   }
2807e55cbd72Sdrh   assert( v!=0 );
28085c092e8aSdrh   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
2809a748fdccSdrh   if( p5 ){
2810a748fdccSdrh     sqlite3VdbeChangeP5(v, p5);
2811a748fdccSdrh   }else{
2812ceea3321Sdrh     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2813a748fdccSdrh   }
2814e55cbd72Sdrh   return iReg;
2815e55cbd72Sdrh }
2816ce78bc6eSdrh void sqlite3ExprCodeGetColumnToReg(
2817ce78bc6eSdrh   Parse *pParse,   /* Parsing and code generating context */
2818ce78bc6eSdrh   Table *pTab,     /* Description of the table we are reading from */
2819ce78bc6eSdrh   int iColumn,     /* Index of the table column */
2820ce78bc6eSdrh   int iTable,      /* The cursor pointing to the table */
2821ce78bc6eSdrh   int iReg         /* Store results here */
2822ce78bc6eSdrh ){
2823ce78bc6eSdrh   int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
2824ce78bc6eSdrh   if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
2825ce78bc6eSdrh }
2826ce78bc6eSdrh 
2827e55cbd72Sdrh 
2828e55cbd72Sdrh /*
2829ceea3321Sdrh ** Clear all column cache entries.
2830e55cbd72Sdrh */
2831ceea3321Sdrh void sqlite3ExprCacheClear(Parse *pParse){
2832e55cbd72Sdrh   int i;
2833ceea3321Sdrh   struct yColCache *p;
2834ceea3321Sdrh 
28359ac7962aSdrh #if SQLITE_DEBUG
28369ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
28379ac7962aSdrh     printf("CLEAR\n");
28389ac7962aSdrh   }
28399ac7962aSdrh #endif
2840ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2841ceea3321Sdrh     if( p->iReg ){
2842ceea3321Sdrh       cacheEntryClear(pParse, p);
2843e55cbd72Sdrh     }
2844da250ea5Sdrh   }
2845da250ea5Sdrh }
2846e55cbd72Sdrh 
2847e55cbd72Sdrh /*
2848da250ea5Sdrh ** Record the fact that an affinity change has occurred on iCount
2849da250ea5Sdrh ** registers starting with iStart.
2850e55cbd72Sdrh */
2851da250ea5Sdrh void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2852f49f3523Sdrh   sqlite3ExprCacheRemove(pParse, iStart, iCount);
2853e55cbd72Sdrh }
2854e55cbd72Sdrh 
2855e55cbd72Sdrh /*
2856b21e7c70Sdrh ** Generate code to move content from registers iFrom...iFrom+nReg-1
2857b21e7c70Sdrh ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
2858e55cbd72Sdrh */
2859b21e7c70Sdrh void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
2860e8e4af76Sdrh   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
2861079a3072Sdrh   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
2862236241aeSdrh   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
2863945498f3Sdrh }
2864945498f3Sdrh 
2865f49f3523Sdrh #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
286692b01d53Sdrh /*
2867652fbf55Sdrh ** Return true if any register in the range iFrom..iTo (inclusive)
2868652fbf55Sdrh ** is used as part of the column cache.
2869f49f3523Sdrh **
2870f49f3523Sdrh ** This routine is used within assert() and testcase() macros only
2871f49f3523Sdrh ** and does not appear in a normal build.
2872652fbf55Sdrh */
2873652fbf55Sdrh static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2874652fbf55Sdrh   int i;
2875ceea3321Sdrh   struct yColCache *p;
2876ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2877ceea3321Sdrh     int r = p->iReg;
2878f49f3523Sdrh     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
2879652fbf55Sdrh   }
2880652fbf55Sdrh   return 0;
2881652fbf55Sdrh }
2882f49f3523Sdrh #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
2883652fbf55Sdrh 
2884bea119cdSdrh 
2885652fbf55Sdrh /*
2886a4c3c87eSdrh ** Convert an expression node to a TK_REGISTER
2887a4c3c87eSdrh */
2888a4c3c87eSdrh static void exprToRegister(Expr *p, int iReg){
2889a4c3c87eSdrh   p->op2 = p->op;
2890a4c3c87eSdrh   p->op = TK_REGISTER;
2891a4c3c87eSdrh   p->iTable = iReg;
2892a4c3c87eSdrh   ExprClearProperty(p, EP_Skip);
2893a4c3c87eSdrh }
2894a4c3c87eSdrh 
2895*71c57db0Sdan static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
2896*71c57db0Sdan 
2897a4c3c87eSdrh /*
2898cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
28992dcef11bSdrh ** expression.  Attempt to store the results in register "target".
29002dcef11bSdrh ** Return the register where results are stored.
2901389a1adbSdrh **
29028b213899Sdrh ** With this routine, there is no guarantee that results will
29032dcef11bSdrh ** be stored in target.  The result might be stored in some other
29042dcef11bSdrh ** register if it is convenient to do so.  The calling function
29052dcef11bSdrh ** must check the return code and move the results to the desired
29062dcef11bSdrh ** register.
2907cce7d176Sdrh */
2908678ccce8Sdrh int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
29092dcef11bSdrh   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
29102dcef11bSdrh   int op;                   /* The opcode being coded */
29112dcef11bSdrh   int inReg = target;       /* Results stored in register inReg */
29122dcef11bSdrh   int regFree1 = 0;         /* If non-zero free this temporary register */
29132dcef11bSdrh   int regFree2 = 0;         /* If non-zero free this temporary register */
2914678ccce8Sdrh   int r1, r2, r3, r4;       /* Various register numbers */
291520411ea7Sdrh   sqlite3 *db = pParse->db; /* The database connection */
291610d1edf0Sdrh   Expr tempX;               /* Temporary expression node */
2917*71c57db0Sdan   int p5 = 0;
2918ffe07b2dSdrh 
29199cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
292020411ea7Sdrh   if( v==0 ){
292120411ea7Sdrh     assert( pParse->db->mallocFailed );
292220411ea7Sdrh     return 0;
292320411ea7Sdrh   }
2924389a1adbSdrh 
2925389a1adbSdrh   if( pExpr==0 ){
2926389a1adbSdrh     op = TK_NULL;
2927389a1adbSdrh   }else{
2928f2bc013cSdrh     op = pExpr->op;
2929389a1adbSdrh   }
2930f2bc013cSdrh   switch( op ){
293113449892Sdrh     case TK_AGG_COLUMN: {
293213449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
293313449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
293413449892Sdrh       if( !pAggInfo->directMode ){
29359de221dfSdrh         assert( pCol->iMem>0 );
29369de221dfSdrh         inReg = pCol->iMem;
293713449892Sdrh         break;
293813449892Sdrh       }else if( pAggInfo->useSortingIdx ){
29395134d135Sdan         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
2940389a1adbSdrh                               pCol->iSorterColumn, target);
294113449892Sdrh         break;
294213449892Sdrh       }
294313449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
294413449892Sdrh     }
2945967e8b73Sdrh     case TK_COLUMN: {
2946b2b9d3d7Sdrh       int iTab = pExpr->iTable;
2947b2b9d3d7Sdrh       if( iTab<0 ){
2948b2b9d3d7Sdrh         if( pParse->ckBase>0 ){
2949b2b9d3d7Sdrh           /* Generating CHECK constraints or inserting into partial index */
2950aa9b8963Sdrh           inReg = pExpr->iColumn + pParse->ckBase;
2951b2b9d3d7Sdrh           break;
2952c4a3c779Sdrh         }else{
29531f9ca2c8Sdrh           /* Coding an expression that is part of an index where column names
29541f9ca2c8Sdrh           ** in the index refer to the table to which the index belongs */
29551f9ca2c8Sdrh           iTab = pParse->iSelfTab;
29562282792aSdrh         }
2957b2b9d3d7Sdrh       }
2958b2b9d3d7Sdrh       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2959b2b9d3d7Sdrh                                pExpr->iColumn, iTab, target,
2960b2b9d3d7Sdrh                                pExpr->op2);
2961cce7d176Sdrh       break;
2962cce7d176Sdrh     }
2963cce7d176Sdrh     case TK_INTEGER: {
296413573c71Sdrh       codeInteger(pParse, pExpr, 0, target);
2965fec19aadSdrh       break;
296651e9a445Sdrh     }
296713573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2968598f1340Sdrh     case TK_FLOAT: {
296933e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
297033e619fcSdrh       codeReal(v, pExpr->u.zToken, 0, target);
2971598f1340Sdrh       break;
2972598f1340Sdrh     }
297313573c71Sdrh #endif
2974fec19aadSdrh     case TK_STRING: {
297533e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2976076e85f5Sdrh       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
2977cce7d176Sdrh       break;
2978cce7d176Sdrh     }
2979f0863fe5Sdrh     case TK_NULL: {
29809de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2981f0863fe5Sdrh       break;
2982f0863fe5Sdrh     }
29835338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
2984c572ef7fSdanielk1977     case TK_BLOB: {
29856c8c6cecSdrh       int n;
29866c8c6cecSdrh       const char *z;
2987ca48c90fSdrh       char *zBlob;
298833e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
298933e619fcSdrh       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
299033e619fcSdrh       assert( pExpr->u.zToken[1]=='\'' );
299133e619fcSdrh       z = &pExpr->u.zToken[2];
2992b7916a78Sdrh       n = sqlite3Strlen30(z) - 1;
2993b7916a78Sdrh       assert( z[n]=='\'' );
2994ca48c90fSdrh       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2995ca48c90fSdrh       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2996c572ef7fSdanielk1977       break;
2997c572ef7fSdanielk1977     }
29985338a5f7Sdanielk1977 #endif
299950457896Sdrh     case TK_VARIABLE: {
300033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
300133e619fcSdrh       assert( pExpr->u.zToken!=0 );
300233e619fcSdrh       assert( pExpr->u.zToken[0]!=0 );
3003eaf52d88Sdrh       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
300433e619fcSdrh       if( pExpr->u.zToken[1]!=0 ){
300504e9eeadSdrh         assert( pExpr->u.zToken[0]=='?'
300604e9eeadSdrh              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
300704e9eeadSdrh         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
3008895d7472Sdrh       }
300950457896Sdrh       break;
301050457896Sdrh     }
30114e0cff60Sdrh     case TK_REGISTER: {
30129de221dfSdrh       inReg = pExpr->iTable;
30134e0cff60Sdrh       break;
30144e0cff60Sdrh     }
3015487e262fSdrh #ifndef SQLITE_OMIT_CAST
3016487e262fSdrh     case TK_CAST: {
3017487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
30182dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
30191735fa88Sdrh       if( inReg!=target ){
30201735fa88Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
30211735fa88Sdrh         inReg = target;
30221735fa88Sdrh       }
30234169e430Sdrh       sqlite3VdbeAddOp2(v, OP_Cast, target,
30244169e430Sdrh                         sqlite3AffinityType(pExpr->u.zToken, 0));
3025c5499befSdrh       testcase( usedAsColumnCache(pParse, inReg, inReg) );
3026b3843a82Sdrh       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
3027487e262fSdrh       break;
3028487e262fSdrh     }
3029487e262fSdrh #endif /* SQLITE_OMIT_CAST */
3030*71c57db0Sdan     case TK_IS:
3031*71c57db0Sdan     case TK_ISNOT:
3032*71c57db0Sdan       op = (op==TK_IS) ? TK_EQ : TK_NE;
3033*71c57db0Sdan       p5 = SQLITE_NULLEQ;
3034*71c57db0Sdan       /* fall-through */
3035c9b84a1fSdrh     case TK_LT:
3036c9b84a1fSdrh     case TK_LE:
3037c9b84a1fSdrh     case TK_GT:
3038c9b84a1fSdrh     case TK_GE:
3039c9b84a1fSdrh     case TK_NE:
3040c9b84a1fSdrh     case TK_EQ: {
3041*71c57db0Sdan       Expr *pLeft = pExpr->pLeft;
3042*71c57db0Sdan       if( (pLeft->flags & EP_Vector) ){
3043*71c57db0Sdan         codeVectorCompare(pParse, pExpr, target);
3044*71c57db0Sdan       }else{
3045*71c57db0Sdan         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3046b6da74ebSdrh         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3047*71c57db0Sdan         codeCompare(pParse, pLeft, pExpr->pRight, op,
3048*71c57db0Sdan             r1, r2, inReg, SQLITE_STOREP2 | p5);
30497d176105Sdrh         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
30507d176105Sdrh         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
30517d176105Sdrh         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
30527d176105Sdrh         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
30537d176105Sdrh         assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
30547d176105Sdrh         assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3055c5499befSdrh         testcase( regFree1==0 );
3056c5499befSdrh         testcase( regFree2==0 );
3057c9b84a1fSdrh       }
30586a2fe093Sdrh       break;
30596a2fe093Sdrh     }
3060cce7d176Sdrh     case TK_AND:
3061cce7d176Sdrh     case TK_OR:
3062cce7d176Sdrh     case TK_PLUS:
3063cce7d176Sdrh     case TK_STAR:
3064cce7d176Sdrh     case TK_MINUS:
3065bf4133cbSdrh     case TK_REM:
3066bf4133cbSdrh     case TK_BITAND:
3067bf4133cbSdrh     case TK_BITOR:
306817c40294Sdrh     case TK_SLASH:
3069bf4133cbSdrh     case TK_LSHIFT:
3070855eb1cfSdrh     case TK_RSHIFT:
30710040077dSdrh     case TK_CONCAT: {
30727d176105Sdrh       assert( TK_AND==OP_And );            testcase( op==TK_AND );
30737d176105Sdrh       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
30747d176105Sdrh       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
30757d176105Sdrh       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
30767d176105Sdrh       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
30777d176105Sdrh       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
30787d176105Sdrh       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
30797d176105Sdrh       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
30807d176105Sdrh       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
30817d176105Sdrh       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
30827d176105Sdrh       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
30832dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
30842dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
30855b6afba9Sdrh       sqlite3VdbeAddOp3(v, op, r2, r1, target);
3086c5499befSdrh       testcase( regFree1==0 );
3087c5499befSdrh       testcase( regFree2==0 );
30880040077dSdrh       break;
30890040077dSdrh     }
3090cce7d176Sdrh     case TK_UMINUS: {
3091fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
3092fec19aadSdrh       assert( pLeft );
309313573c71Sdrh       if( pLeft->op==TK_INTEGER ){
309413573c71Sdrh         codeInteger(pParse, pLeft, 1, target);
309513573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
309613573c71Sdrh       }else if( pLeft->op==TK_FLOAT ){
309733e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
309833e619fcSdrh         codeReal(v, pLeft->u.zToken, 1, target);
309913573c71Sdrh #endif
31003c84ddffSdrh       }else{
310110d1edf0Sdrh         tempX.op = TK_INTEGER;
310210d1edf0Sdrh         tempX.flags = EP_IntValue|EP_TokenOnly;
310310d1edf0Sdrh         tempX.u.iValue = 0;
310410d1edf0Sdrh         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
3105e55cbd72Sdrh         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
31062dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
3107c5499befSdrh         testcase( regFree2==0 );
31083c84ddffSdrh       }
31099de221dfSdrh       inReg = target;
31106e142f54Sdrh       break;
31116e142f54Sdrh     }
3112bf4133cbSdrh     case TK_BITNOT:
31136e142f54Sdrh     case TK_NOT: {
31147d176105Sdrh       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
31157d176105Sdrh       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
3116e99fa2afSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3117e99fa2afSdrh       testcase( regFree1==0 );
3118e99fa2afSdrh       inReg = target;
3119e99fa2afSdrh       sqlite3VdbeAddOp2(v, op, r1, inReg);
3120cce7d176Sdrh       break;
3121cce7d176Sdrh     }
3122cce7d176Sdrh     case TK_ISNULL:
3123cce7d176Sdrh     case TK_NOTNULL: {
31246a288a33Sdrh       int addr;
31257d176105Sdrh       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
31267d176105Sdrh       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
31279de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
31282dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3129c5499befSdrh       testcase( regFree1==0 );
31302dcef11bSdrh       addr = sqlite3VdbeAddOp1(v, op, r1);
31317d176105Sdrh       VdbeCoverageIf(v, op==TK_ISNULL);
31327d176105Sdrh       VdbeCoverageIf(v, op==TK_NOTNULL);
3133a976979bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
31346a288a33Sdrh       sqlite3VdbeJumpHere(v, addr);
3135a37cdde0Sdanielk1977       break;
3136f2bc013cSdrh     }
31372282792aSdrh     case TK_AGG_FUNCTION: {
313813449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
31397e56e711Sdrh       if( pInfo==0 ){
314033e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
314133e619fcSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
31427e56e711Sdrh       }else{
31439de221dfSdrh         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
31447e56e711Sdrh       }
31452282792aSdrh       break;
31462282792aSdrh     }
3147cce7d176Sdrh     case TK_FUNCTION: {
314812ffee8cSdrh       ExprList *pFarg;       /* List of function arguments */
314912ffee8cSdrh       int nFarg;             /* Number of function arguments */
315012ffee8cSdrh       FuncDef *pDef;         /* The function definition object */
315112ffee8cSdrh       const char *zId;       /* The function name */
3152693e6719Sdrh       u32 constMask = 0;     /* Mask of function arguments that are constant */
315312ffee8cSdrh       int i;                 /* Loop counter */
315412ffee8cSdrh       u8 enc = ENC(db);      /* The text encoding used by this database */
315512ffee8cSdrh       CollSeq *pColl = 0;    /* A collating sequence */
315617435752Sdrh 
31576ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3158c5cd1249Sdrh       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
315912ffee8cSdrh         pFarg = 0;
316012ffee8cSdrh       }else{
316112ffee8cSdrh         pFarg = pExpr->x.pList;
316212ffee8cSdrh       }
316312ffee8cSdrh       nFarg = pFarg ? pFarg->nExpr : 0;
316433e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
316533e619fcSdrh       zId = pExpr->u.zToken;
316680738d9cSdrh       pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
31672d80151fSdrh       if( pDef==0 || pDef->xFinalize!=0 ){
316880738d9cSdrh         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
3169feb306f5Sdrh         break;
3170feb306f5Sdrh       }
3171ae6bb957Sdrh 
3172ae6bb957Sdrh       /* Attempt a direct implementation of the built-in COALESCE() and
317360ec914cSpeter.d.reid       ** IFNULL() functions.  This avoids unnecessary evaluation of
3174ae6bb957Sdrh       ** arguments past the first non-NULL argument.
3175ae6bb957Sdrh       */
3176d36e1041Sdrh       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
3177ae6bb957Sdrh         int endCoalesce = sqlite3VdbeMakeLabel(v);
3178ae6bb957Sdrh         assert( nFarg>=2 );
3179ae6bb957Sdrh         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3180ae6bb957Sdrh         for(i=1; i<nFarg; i++){
3181ae6bb957Sdrh           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
3182688852abSdrh           VdbeCoverage(v);
3183f49f3523Sdrh           sqlite3ExprCacheRemove(pParse, target, 1);
3184ae6bb957Sdrh           sqlite3ExprCachePush(pParse);
3185ae6bb957Sdrh           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
3186d2490904Sdrh           sqlite3ExprCachePop(pParse);
3187ae6bb957Sdrh         }
3188ae6bb957Sdrh         sqlite3VdbeResolveLabel(v, endCoalesce);
3189ae6bb957Sdrh         break;
3190ae6bb957Sdrh       }
3191ae6bb957Sdrh 
3192cca9f3d2Sdrh       /* The UNLIKELY() function is a no-op.  The result is the value
3193cca9f3d2Sdrh       ** of the first argument.
3194cca9f3d2Sdrh       */
3195cca9f3d2Sdrh       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3196cca9f3d2Sdrh         assert( nFarg>=1 );
31975f02ab09Sdrh         inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
3198cca9f3d2Sdrh         break;
3199cca9f3d2Sdrh       }
3200ae6bb957Sdrh 
3201d1a01edaSdrh       for(i=0; i<nFarg; i++){
3202d1a01edaSdrh         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
3203693e6719Sdrh           testcase( i==31 );
3204693e6719Sdrh           constMask |= MASKBIT32(i);
3205d1a01edaSdrh         }
3206d1a01edaSdrh         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3207d1a01edaSdrh           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3208d1a01edaSdrh         }
3209d1a01edaSdrh       }
321012ffee8cSdrh       if( pFarg ){
3211d1a01edaSdrh         if( constMask ){
3212d1a01edaSdrh           r1 = pParse->nMem+1;
3213d1a01edaSdrh           pParse->nMem += nFarg;
3214d1a01edaSdrh         }else{
321512ffee8cSdrh           r1 = sqlite3GetTempRange(pParse, nFarg);
3216d1a01edaSdrh         }
3217a748fdccSdrh 
3218a748fdccSdrh         /* For length() and typeof() functions with a column argument,
3219a748fdccSdrh         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3220a748fdccSdrh         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3221a748fdccSdrh         ** loading.
3222a748fdccSdrh         */
3223d36e1041Sdrh         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
32244e245a4cSdrh           u8 exprOp;
3225a748fdccSdrh           assert( nFarg==1 );
3226a748fdccSdrh           assert( pFarg->a[0].pExpr!=0 );
32274e245a4cSdrh           exprOp = pFarg->a[0].pExpr->op;
32284e245a4cSdrh           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
3229a748fdccSdrh             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3230a748fdccSdrh             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
3231b1fba286Sdrh             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3232b1fba286Sdrh             pFarg->a[0].pExpr->op2 =
3233b1fba286Sdrh                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
3234a748fdccSdrh           }
3235a748fdccSdrh         }
3236a748fdccSdrh 
3237d7d385ddSdrh         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
32385579d59fSdrh         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
3239d1a01edaSdrh                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
3240d2490904Sdrh         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
3241892d3179Sdrh       }else{
324212ffee8cSdrh         r1 = 0;
3243892d3179Sdrh       }
3244b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
3245a43fa227Sdrh       /* Possibly overload the function if the first argument is
3246a43fa227Sdrh       ** a virtual table column.
3247a43fa227Sdrh       **
3248a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3249a43fa227Sdrh       ** second argument, not the first, as the argument to test to
3250a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
3251a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
3252a43fa227Sdrh       ** control overloading) ends up as the second argument to the
3253a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
3254a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
3255a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
3256a43fa227Sdrh       */
325712ffee8cSdrh       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
325812ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
325912ffee8cSdrh       }else if( nFarg>0 ){
326012ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
3261b7f6f68fSdrh       }
3262b7f6f68fSdrh #endif
3263d36e1041Sdrh       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
32648b213899Sdrh         if( !pColl ) pColl = db->pDfltColl;
326566a5167bSdrh         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
3266682f68b0Sdanielk1977       }
32679c7c913cSdrh       sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
326866a5167bSdrh                         (char*)pDef, P4_FUNCDEF);
326912ffee8cSdrh       sqlite3VdbeChangeP5(v, (u8)nFarg);
3270d1a01edaSdrh       if( nFarg && constMask==0 ){
327112ffee8cSdrh         sqlite3ReleaseTempRange(pParse, r1, nFarg);
32722dcef11bSdrh       }
32736ec2733bSdrh       break;
32746ec2733bSdrh     }
3275fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
3276fe2093d7Sdrh     case TK_EXISTS:
327719a775c2Sdrh     case TK_SELECT: {
3278c5499befSdrh       testcase( op==TK_EXISTS );
3279c5499befSdrh       testcase( op==TK_SELECT );
32801450bc6eSdrh       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
328119a775c2Sdrh       break;
328219a775c2Sdrh     }
3283fef5208cSdrh     case TK_IN: {
3284e3365e6cSdrh       int destIfFalse = sqlite3VdbeMakeLabel(v);
3285e3365e6cSdrh       int destIfNull = sqlite3VdbeMakeLabel(v);
3286e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3287e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
328866ba23ceSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3289e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
3290e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3291e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfNull);
3292fef5208cSdrh       break;
3293fef5208cSdrh     }
3294e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
3295e3365e6cSdrh 
3296e3365e6cSdrh 
32972dcef11bSdrh     /*
32982dcef11bSdrh     **    x BETWEEN y AND z
32992dcef11bSdrh     **
33002dcef11bSdrh     ** This is equivalent to
33012dcef11bSdrh     **
33022dcef11bSdrh     **    x>=y AND x<=z
33032dcef11bSdrh     **
33042dcef11bSdrh     ** X is stored in pExpr->pLeft.
33052dcef11bSdrh     ** Y is stored in pExpr->pList->a[0].pExpr.
33062dcef11bSdrh     ** Z is stored in pExpr->pList->a[1].pExpr.
33072dcef11bSdrh     */
3308fef5208cSdrh     case TK_BETWEEN: {
3309*71c57db0Sdan       exprCodeBetween(pParse, pExpr, target, 0, 0);
3310*71c57db0Sdan #if 0
3311be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
33126ab3a2ecSdanielk1977       struct ExprList_item *pLItem = pExpr->x.pList->a;
3313be5c89acSdrh       Expr *pRight = pLItem->pExpr;
331435573356Sdrh 
3315b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3316b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
3317c5499befSdrh       testcase( regFree1==0 );
3318c5499befSdrh       testcase( regFree2==0 );
33192dcef11bSdrh       r3 = sqlite3GetTempReg(pParse);
3320678ccce8Sdrh       r4 = sqlite3GetTempReg(pParse);
332135573356Sdrh       codeCompare(pParse, pLeft, pRight, OP_Ge,
33227d176105Sdrh                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
3323be5c89acSdrh       pLItem++;
3324be5c89acSdrh       pRight = pLItem->pExpr;
33252dcef11bSdrh       sqlite3ReleaseTempReg(pParse, regFree2);
33262dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
3327c5499befSdrh       testcase( regFree2==0 );
3328678ccce8Sdrh       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
3329688852abSdrh       VdbeCoverage(v);
3330678ccce8Sdrh       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
33312dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r3);
3332678ccce8Sdrh       sqlite3ReleaseTempReg(pParse, r4);
3333*71c57db0Sdan #endif
3334fef5208cSdrh       break;
3335fef5208cSdrh     }
333694fa9c41Sdrh     case TK_SPAN:
3337ae80ddeaSdrh     case TK_COLLATE:
33384f07e5fbSdrh     case TK_UPLUS: {
33392dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3340a2e00042Sdrh       break;
3341a2e00042Sdrh     }
33422dcef11bSdrh 
3343165921a7Sdan     case TK_TRIGGER: {
334465a7cd16Sdan       /* If the opcode is TK_TRIGGER, then the expression is a reference
334565a7cd16Sdan       ** to a column in the new.* or old.* pseudo-tables available to
334665a7cd16Sdan       ** trigger programs. In this case Expr.iTable is set to 1 for the
334765a7cd16Sdan       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
334865a7cd16Sdan       ** is set to the column of the pseudo-table to read, or to -1 to
334965a7cd16Sdan       ** read the rowid field.
335065a7cd16Sdan       **
335165a7cd16Sdan       ** The expression is implemented using an OP_Param opcode. The p1
335265a7cd16Sdan       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
335365a7cd16Sdan       ** to reference another column of the old.* pseudo-table, where
335465a7cd16Sdan       ** i is the index of the column. For a new.rowid reference, p1 is
335565a7cd16Sdan       ** set to (n+1), where n is the number of columns in each pseudo-table.
335665a7cd16Sdan       ** For a reference to any other column in the new.* pseudo-table, p1
335765a7cd16Sdan       ** is set to (n+2+i), where n and i are as defined previously. For
335865a7cd16Sdan       ** example, if the table on which triggers are being fired is
335965a7cd16Sdan       ** declared as:
336065a7cd16Sdan       **
336165a7cd16Sdan       **   CREATE TABLE t1(a, b);
336265a7cd16Sdan       **
336365a7cd16Sdan       ** Then p1 is interpreted as follows:
336465a7cd16Sdan       **
336565a7cd16Sdan       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
336665a7cd16Sdan       **   p1==1   ->    old.a         p1==4   ->    new.a
336765a7cd16Sdan       **   p1==2   ->    old.b         p1==5   ->    new.b
336865a7cd16Sdan       */
33692832ad42Sdan       Table *pTab = pExpr->pTab;
337065a7cd16Sdan       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
337165a7cd16Sdan 
337265a7cd16Sdan       assert( pExpr->iTable==0 || pExpr->iTable==1 );
337365a7cd16Sdan       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
337465a7cd16Sdan       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
337565a7cd16Sdan       assert( p1>=0 && p1<(pTab->nCol*2+2) );
337665a7cd16Sdan 
337765a7cd16Sdan       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
337876d462eeSdan       VdbeComment((v, "%s.%s -> $%d",
3379165921a7Sdan         (pExpr->iTable ? "new" : "old"),
338076d462eeSdan         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
338176d462eeSdan         target
3382165921a7Sdan       ));
338365a7cd16Sdan 
338444dbca83Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
338565a7cd16Sdan       /* If the column has REAL affinity, it may currently be stored as an
3386113762a2Sdrh       ** integer. Use OP_RealAffinity to make sure it is really real.
3387113762a2Sdrh       **
3388113762a2Sdrh       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3389113762a2Sdrh       ** floating point when extracting it from the record.  */
33902832ad42Sdan       if( pExpr->iColumn>=0
33912832ad42Sdan        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
33922832ad42Sdan       ){
33932832ad42Sdan         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
33942832ad42Sdan       }
339544dbca83Sdrh #endif
3396165921a7Sdan       break;
3397165921a7Sdan     }
3398165921a7Sdan 
3399*71c57db0Sdan     case TK_VECTOR: {
3400*71c57db0Sdan       sqlite3ErrorMsg(pParse, "invalid use of row value (1)");
3401*71c57db0Sdan       break;
3402*71c57db0Sdan     }
3403*71c57db0Sdan 
3404*71c57db0Sdan     case TK_SELECT_COLUMN: {
3405*71c57db0Sdan       Expr *pLeft = pExpr->pLeft;
3406*71c57db0Sdan       assert( pLeft );
3407*71c57db0Sdan       assert( pLeft->op==TK_SELECT || pLeft->op==TK_REGISTER );
3408*71c57db0Sdan       if( pLeft->op==TK_SELECT ){
3409*71c57db0Sdan         pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft, 0, 0);
3410*71c57db0Sdan         pLeft->op = TK_REGISTER;
3411*71c57db0Sdan       }
3412*71c57db0Sdan       inReg = pLeft->iTable + pExpr->iColumn;
3413*71c57db0Sdan       break;
3414*71c57db0Sdan     }
3415165921a7Sdan 
34162dcef11bSdrh     /*
34172dcef11bSdrh     ** Form A:
34182dcef11bSdrh     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
34192dcef11bSdrh     **
34202dcef11bSdrh     ** Form B:
34212dcef11bSdrh     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
34222dcef11bSdrh     **
34232dcef11bSdrh     ** Form A is can be transformed into the equivalent form B as follows:
34242dcef11bSdrh     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
34252dcef11bSdrh     **        WHEN x=eN THEN rN ELSE y END
34262dcef11bSdrh     **
34272dcef11bSdrh     ** X (if it exists) is in pExpr->pLeft.
3428c5cd1249Sdrh     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3429c5cd1249Sdrh     ** odd.  The Y is also optional.  If the number of elements in x.pList
3430c5cd1249Sdrh     ** is even, then Y is omitted and the "otherwise" result is NULL.
34312dcef11bSdrh     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
34322dcef11bSdrh     **
34332dcef11bSdrh     ** The result of the expression is the Ri for the first matching Ei,
34342dcef11bSdrh     ** or if there is no matching Ei, the ELSE term Y, or if there is
34352dcef11bSdrh     ** no ELSE term, NULL.
34362dcef11bSdrh     */
343733cd4909Sdrh     default: assert( op==TK_CASE ); {
34382dcef11bSdrh       int endLabel;                     /* GOTO label for end of CASE stmt */
34392dcef11bSdrh       int nextCase;                     /* GOTO label for next WHEN clause */
34402dcef11bSdrh       int nExpr;                        /* 2x number of WHEN terms */
34412dcef11bSdrh       int i;                            /* Loop counter */
34422dcef11bSdrh       ExprList *pEList;                 /* List of WHEN terms */
34432dcef11bSdrh       struct ExprList_item *aListelem;  /* Array of WHEN terms */
34442dcef11bSdrh       Expr opCompare;                   /* The X==Ei expression */
34452dcef11bSdrh       Expr *pX;                         /* The X expression */
34461bd10f8aSdrh       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
3447ceea3321Sdrh       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
344817a7f8ddSdrh 
34496ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
34506ab3a2ecSdanielk1977       assert(pExpr->x.pList->nExpr > 0);
34516ab3a2ecSdanielk1977       pEList = pExpr->x.pList;
3452be5c89acSdrh       aListelem = pEList->a;
3453be5c89acSdrh       nExpr = pEList->nExpr;
34542dcef11bSdrh       endLabel = sqlite3VdbeMakeLabel(v);
34552dcef11bSdrh       if( (pX = pExpr->pLeft)!=0 ){
345610d1edf0Sdrh         tempX = *pX;
345733cd4909Sdrh         testcase( pX->op==TK_COLUMN );
345810d1edf0Sdrh         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
3459c5499befSdrh         testcase( regFree1==0 );
34602dcef11bSdrh         opCompare.op = TK_EQ;
346110d1edf0Sdrh         opCompare.pLeft = &tempX;
34622dcef11bSdrh         pTest = &opCompare;
34638b1db07fSdrh         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
34648b1db07fSdrh         ** The value in regFree1 might get SCopy-ed into the file result.
34658b1db07fSdrh         ** So make sure that the regFree1 register is not reused for other
34668b1db07fSdrh         ** purposes and possibly overwritten.  */
34678b1db07fSdrh         regFree1 = 0;
3468cce7d176Sdrh       }
3469c5cd1249Sdrh       for(i=0; i<nExpr-1; i=i+2){
3470ceea3321Sdrh         sqlite3ExprCachePush(pParse);
34712dcef11bSdrh         if( pX ){
34721bd10f8aSdrh           assert( pTest!=0 );
34732dcef11bSdrh           opCompare.pRight = aListelem[i].pExpr;
3474f5905aa7Sdrh         }else{
34752dcef11bSdrh           pTest = aListelem[i].pExpr;
347617a7f8ddSdrh         }
34772dcef11bSdrh         nextCase = sqlite3VdbeMakeLabel(v);
347833cd4909Sdrh         testcase( pTest->op==TK_COLUMN );
34792dcef11bSdrh         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
3480c5499befSdrh         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
34819de221dfSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
3482076e85f5Sdrh         sqlite3VdbeGoto(v, endLabel);
3483d2490904Sdrh         sqlite3ExprCachePop(pParse);
34842dcef11bSdrh         sqlite3VdbeResolveLabel(v, nextCase);
3485f570f011Sdrh       }
3486c5cd1249Sdrh       if( (nExpr&1)!=0 ){
3487ceea3321Sdrh         sqlite3ExprCachePush(pParse);
3488c5cd1249Sdrh         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
3489d2490904Sdrh         sqlite3ExprCachePop(pParse);
349017a7f8ddSdrh       }else{
34919de221dfSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
349217a7f8ddSdrh       }
3493c1f4a19bSdanielk1977       assert( db->mallocFailed || pParse->nErr>0
3494c1f4a19bSdanielk1977            || pParse->iCacheLevel==iCacheLevel );
34952dcef11bSdrh       sqlite3VdbeResolveLabel(v, endLabel);
34966f34903eSdanielk1977       break;
34976f34903eSdanielk1977     }
34985338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
34996f34903eSdanielk1977     case TK_RAISE: {
3500165921a7Sdan       assert( pExpr->affinity==OE_Rollback
3501165921a7Sdan            || pExpr->affinity==OE_Abort
3502165921a7Sdan            || pExpr->affinity==OE_Fail
3503165921a7Sdan            || pExpr->affinity==OE_Ignore
3504165921a7Sdan       );
3505e0af83acSdan       if( !pParse->pTriggerTab ){
3506e0af83acSdan         sqlite3ErrorMsg(pParse,
3507e0af83acSdan                        "RAISE() may only be used within a trigger-program");
3508e0af83acSdan         return 0;
3509e0af83acSdan       }
3510e0af83acSdan       if( pExpr->affinity==OE_Abort ){
3511e0af83acSdan         sqlite3MayAbort(pParse);
3512e0af83acSdan       }
351333e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3514e0af83acSdan       if( pExpr->affinity==OE_Ignore ){
3515e0af83acSdan         sqlite3VdbeAddOp4(
3516e0af83acSdan             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
3517688852abSdrh         VdbeCoverage(v);
3518e0af83acSdan       }else{
3519433dccfbSdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
3520f9c8ce3cSdrh                               pExpr->affinity, pExpr->u.zToken, 0, 0);
3521e0af83acSdan       }
3522e0af83acSdan 
3523ffe07b2dSdrh       break;
352417a7f8ddSdrh     }
35255338a5f7Sdanielk1977 #endif
3526ffe07b2dSdrh   }
35272dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
35282dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
35292dcef11bSdrh   return inReg;
35305b6afba9Sdrh }
35312dcef11bSdrh 
35322dcef11bSdrh /*
3533d1a01edaSdrh ** Factor out the code of the given expression to initialization time.
3534d1a01edaSdrh */
3535d673cddaSdrh void sqlite3ExprCodeAtInit(
3536d673cddaSdrh   Parse *pParse,    /* Parsing context */
3537d673cddaSdrh   Expr *pExpr,      /* The expression to code when the VDBE initializes */
3538d673cddaSdrh   int regDest,      /* Store the value in this register */
3539d673cddaSdrh   u8 reusable       /* True if this expression is reusable */
3540d673cddaSdrh ){
3541d1a01edaSdrh   ExprList *p;
3542d9f158e7Sdrh   assert( ConstFactorOk(pParse) );
3543d1a01edaSdrh   p = pParse->pConstExpr;
3544d1a01edaSdrh   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3545d1a01edaSdrh   p = sqlite3ExprListAppend(pParse, p, pExpr);
3546d673cddaSdrh   if( p ){
3547d673cddaSdrh      struct ExprList_item *pItem = &p->a[p->nExpr-1];
3548d673cddaSdrh      pItem->u.iConstExprReg = regDest;
3549d673cddaSdrh      pItem->reusable = reusable;
3550d673cddaSdrh   }
3551d1a01edaSdrh   pParse->pConstExpr = p;
3552d1a01edaSdrh }
3553d1a01edaSdrh 
3554d1a01edaSdrh /*
35552dcef11bSdrh ** Generate code to evaluate an expression and store the results
35562dcef11bSdrh ** into a register.  Return the register number where the results
35572dcef11bSdrh ** are stored.
35582dcef11bSdrh **
35592dcef11bSdrh ** If the register is a temporary register that can be deallocated,
3560678ccce8Sdrh ** then write its number into *pReg.  If the result register is not
35612dcef11bSdrh ** a temporary, then set *pReg to zero.
3562f30a969bSdrh **
3563f30a969bSdrh ** If pExpr is a constant, then this routine might generate this
3564f30a969bSdrh ** code to fill the register in the initialization section of the
3565f30a969bSdrh ** VDBE program, in order to factor it out of the evaluation loop.
35662dcef11bSdrh */
35672dcef11bSdrh int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
3568f30a969bSdrh   int r2;
3569f30a969bSdrh   pExpr = sqlite3ExprSkipCollate(pExpr);
3570d9f158e7Sdrh   if( ConstFactorOk(pParse)
3571f30a969bSdrh    && pExpr->op!=TK_REGISTER
3572f30a969bSdrh    && sqlite3ExprIsConstantNotJoin(pExpr)
3573f30a969bSdrh   ){
3574f30a969bSdrh     ExprList *p = pParse->pConstExpr;
3575f30a969bSdrh     int i;
3576f30a969bSdrh     *pReg  = 0;
3577f30a969bSdrh     if( p ){
3578d673cddaSdrh       struct ExprList_item *pItem;
3579d673cddaSdrh       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3580d673cddaSdrh         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3581d673cddaSdrh           return pItem->u.iConstExprReg;
3582f30a969bSdrh         }
3583f30a969bSdrh       }
3584f30a969bSdrh     }
3585f30a969bSdrh     r2 = ++pParse->nMem;
3586d673cddaSdrh     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
3587f30a969bSdrh   }else{
35882dcef11bSdrh     int r1 = sqlite3GetTempReg(pParse);
3589f30a969bSdrh     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
35902dcef11bSdrh     if( r2==r1 ){
35912dcef11bSdrh       *pReg = r1;
35922dcef11bSdrh     }else{
35932dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r1);
35942dcef11bSdrh       *pReg = 0;
35952dcef11bSdrh     }
3596f30a969bSdrh   }
35972dcef11bSdrh   return r2;
35982dcef11bSdrh }
35992dcef11bSdrh 
36002dcef11bSdrh /*
36012dcef11bSdrh ** Generate code that will evaluate expression pExpr and store the
36022dcef11bSdrh ** results in register target.  The results are guaranteed to appear
36032dcef11bSdrh ** in register target.
36042dcef11bSdrh */
360505a86c5cSdrh void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
36069cbf3425Sdrh   int inReg;
36079cbf3425Sdrh 
36089cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
3609ebc16717Sdrh   if( pExpr && pExpr->op==TK_REGISTER ){
3610ebc16717Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3611ebc16717Sdrh   }else{
36129cbf3425Sdrh     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
36131c75c9d7Sdrh     assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
36140e359b30Sdrh     if( inReg!=target && pParse->pVdbe ){
36159cbf3425Sdrh       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
361617a7f8ddSdrh     }
3617ebc16717Sdrh   }
3618cce7d176Sdrh }
3619cce7d176Sdrh 
3620cce7d176Sdrh /*
36211c75c9d7Sdrh ** Make a transient copy of expression pExpr and then code it using
36221c75c9d7Sdrh ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
36231c75c9d7Sdrh ** except that the input expression is guaranteed to be unchanged.
36241c75c9d7Sdrh */
36251c75c9d7Sdrh void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
36261c75c9d7Sdrh   sqlite3 *db = pParse->db;
36271c75c9d7Sdrh   pExpr = sqlite3ExprDup(db, pExpr, 0);
36281c75c9d7Sdrh   if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
36291c75c9d7Sdrh   sqlite3ExprDelete(db, pExpr);
36301c75c9d7Sdrh }
36311c75c9d7Sdrh 
36321c75c9d7Sdrh /*
363305a86c5cSdrh ** Generate code that will evaluate expression pExpr and store the
363405a86c5cSdrh ** results in register target.  The results are guaranteed to appear
363505a86c5cSdrh ** in register target.  If the expression is constant, then this routine
363605a86c5cSdrh ** might choose to code the expression at initialization time.
363705a86c5cSdrh */
363805a86c5cSdrh void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
363905a86c5cSdrh   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
364005a86c5cSdrh     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
364105a86c5cSdrh   }else{
364205a86c5cSdrh     sqlite3ExprCode(pParse, pExpr, target);
364305a86c5cSdrh   }
3644cce7d176Sdrh }
3645cce7d176Sdrh 
3646cce7d176Sdrh /*
364760ec914cSpeter.d.reid ** Generate code that evaluates the given expression and puts the result
3648de4fcfddSdrh ** in register target.
364925303780Sdrh **
36502dcef11bSdrh ** Also make a copy of the expression results into another "cache" register
36512dcef11bSdrh ** and modify the expression so that the next time it is evaluated,
36522dcef11bSdrh ** the result is a copy of the cache register.
36532dcef11bSdrh **
36542dcef11bSdrh ** This routine is used for expressions that are used multiple
36552dcef11bSdrh ** times.  They are evaluated once and the results of the expression
36562dcef11bSdrh ** are reused.
365725303780Sdrh */
365805a86c5cSdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
365925303780Sdrh   Vdbe *v = pParse->pVdbe;
366025303780Sdrh   int iMem;
366105a86c5cSdrh 
366205a86c5cSdrh   assert( target>0 );
366305a86c5cSdrh   assert( pExpr->op!=TK_REGISTER );
366405a86c5cSdrh   sqlite3ExprCode(pParse, pExpr, target);
36652dcef11bSdrh   iMem = ++pParse->nMem;
366605a86c5cSdrh   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
3667a4c3c87eSdrh   exprToRegister(pExpr, iMem);
366825303780Sdrh }
36697e02e5e6Sdrh 
3670678ccce8Sdrh /*
3671268380caSdrh ** Generate code that pushes the value of every element of the given
36729cbf3425Sdrh ** expression list into a sequence of registers beginning at target.
3673268380caSdrh **
3674892d3179Sdrh ** Return the number of elements evaluated.
3675d1a01edaSdrh **
3676d1a01edaSdrh ** The SQLITE_ECEL_DUP flag prevents the arguments from being
3677d1a01edaSdrh ** filled using OP_SCopy.  OP_Copy must be used instead.
3678d1a01edaSdrh **
3679d1a01edaSdrh ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
3680d1a01edaSdrh ** factored out into initialization code.
3681b0df9634Sdrh **
3682b0df9634Sdrh ** The SQLITE_ECEL_REF flag means that expressions in the list with
3683b0df9634Sdrh ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
3684b0df9634Sdrh ** in registers at srcReg, and so the value can be copied from there.
3685268380caSdrh */
36864adee20fSdanielk1977 int sqlite3ExprCodeExprList(
3687268380caSdrh   Parse *pParse,     /* Parsing context */
3688389a1adbSdrh   ExprList *pList,   /* The expression list to be coded */
3689191b54cbSdrh   int target,        /* Where to write results */
36905579d59fSdrh   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
3691d1a01edaSdrh   u8 flags           /* SQLITE_ECEL_* flags */
3692268380caSdrh ){
3693268380caSdrh   struct ExprList_item *pItem;
36945579d59fSdrh   int i, j, n;
3695d1a01edaSdrh   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
36965579d59fSdrh   Vdbe *v = pParse->pVdbe;
36979d8b3072Sdrh   assert( pList!=0 );
36989cbf3425Sdrh   assert( target>0 );
3699d81a142bSdrh   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
3700268380caSdrh   n = pList->nExpr;
3701d9f158e7Sdrh   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
3702191b54cbSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
37037445ffe2Sdrh     Expr *pExpr = pItem->pExpr;
37045579d59fSdrh     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
37055579d59fSdrh       sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
37065579d59fSdrh     }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
3707d673cddaSdrh       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
3708d1a01edaSdrh     }else{
37097445ffe2Sdrh       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
3710746fd9ccSdrh       if( inReg!=target+i ){
37114eded604Sdrh         VdbeOp *pOp;
37124eded604Sdrh         if( copyOp==OP_Copy
37134eded604Sdrh          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
37144eded604Sdrh          && pOp->p1+pOp->p3+1==inReg
37154eded604Sdrh          && pOp->p2+pOp->p3+1==target+i
37164eded604Sdrh         ){
37174eded604Sdrh           pOp->p3++;
37184eded604Sdrh         }else{
37194eded604Sdrh           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
37204eded604Sdrh         }
3721d1a01edaSdrh       }
3722d176611bSdrh     }
3723268380caSdrh   }
3724f9b596ebSdrh   return n;
3725268380caSdrh }
3726268380caSdrh 
3727268380caSdrh /*
372836c563a2Sdrh ** Generate code for a BETWEEN operator.
372936c563a2Sdrh **
373036c563a2Sdrh **    x BETWEEN y AND z
373136c563a2Sdrh **
373236c563a2Sdrh ** The above is equivalent to
373336c563a2Sdrh **
373436c563a2Sdrh **    x>=y AND x<=z
373536c563a2Sdrh **
373636c563a2Sdrh ** Code it as such, taking care to do the common subexpression
373760ec914cSpeter.d.reid ** elimination of x.
373836c563a2Sdrh */
373936c563a2Sdrh static void exprCodeBetween(
374036c563a2Sdrh   Parse *pParse,    /* Parsing and code generating context */
374136c563a2Sdrh   Expr *pExpr,      /* The BETWEEN expression */
374236c563a2Sdrh   int dest,         /* Jump here if the jump is taken */
3743*71c57db0Sdan   void (*xJumpIf)(Parse*,Expr*,int,int),
374436c563a2Sdrh   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
374536c563a2Sdrh ){
374636c563a2Sdrh   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
374736c563a2Sdrh   Expr compLeft;    /* The  x>=y  term */
374836c563a2Sdrh   Expr compRight;   /* The  x<=z  term */
374936c563a2Sdrh   Expr exprX;       /* The  x  subexpression */
375036c563a2Sdrh   int regFree1 = 0; /* Temporary use register */
375136c563a2Sdrh 
3752*71c57db0Sdan   memset(&compLeft, 0, sizeof(Expr));
3753*71c57db0Sdan   memset(&compRight, 0, sizeof(Expr));
3754*71c57db0Sdan   memset(&exprAnd, 0, sizeof(Expr));
3755*71c57db0Sdan 
375636c563a2Sdrh   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
375736c563a2Sdrh   exprX = *pExpr->pLeft;
375836c563a2Sdrh   exprAnd.op = TK_AND;
375936c563a2Sdrh   exprAnd.pLeft = &compLeft;
376036c563a2Sdrh   exprAnd.pRight = &compRight;
376136c563a2Sdrh   compLeft.op = TK_GE;
376236c563a2Sdrh   compLeft.pLeft = &exprX;
376336c563a2Sdrh   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
376436c563a2Sdrh   compRight.op = TK_LE;
376536c563a2Sdrh   compRight.pLeft = &exprX;
376636c563a2Sdrh   compRight.pRight = pExpr->x.pList->a[1].pExpr;
3767*71c57db0Sdan   if( (exprX.flags & EP_Vector)==0 ){
3768a4c3c87eSdrh     exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
3769*71c57db0Sdan   }
3770*71c57db0Sdan   if( xJumpIf ){
3771*71c57db0Sdan     xJumpIf(pParse, &exprAnd, dest, jumpIfNull);
377236c563a2Sdrh   }else{
3773*71c57db0Sdan     exprX.flags |= EP_FromJoin;
3774*71c57db0Sdan     sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
377536c563a2Sdrh   }
377636c563a2Sdrh   sqlite3ReleaseTempReg(pParse, regFree1);
377736c563a2Sdrh 
377836c563a2Sdrh   /* Ensure adequate test coverage */
377936c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
378036c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
378136c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
378236c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
378336c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
378436c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
378536c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
378636c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
378736c563a2Sdrh }
378836c563a2Sdrh 
378936c563a2Sdrh /*
3790cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
3791cce7d176Sdrh ** to the label "dest" if the expression is true but execution
3792cce7d176Sdrh ** continues straight thru if the expression is false.
3793f5905aa7Sdrh **
3794f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
379535573356Sdrh ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
3796f2bc013cSdrh **
3797f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
3798f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3799f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
3800f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
3801f2bc013cSdrh ** below verify that the numbers are aligned correctly.
3802cce7d176Sdrh */
38034adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3804cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3805cce7d176Sdrh   int op = 0;
38062dcef11bSdrh   int regFree1 = 0;
38072dcef11bSdrh   int regFree2 = 0;
38082dcef11bSdrh   int r1, r2;
38092dcef11bSdrh 
381035573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
381148864df9Smistachkin   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
381233cd4909Sdrh   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
3813f2bc013cSdrh   op = pExpr->op;
3814*71c57db0Sdan   switch( op | (pExpr->pLeft ? (pExpr->pLeft->flags & EP_Vector) : 0)){
3815cce7d176Sdrh     case TK_AND: {
38164adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3817c5499befSdrh       testcase( jumpIfNull==0 );
381835573356Sdrh       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
381954e2adb5Sdrh       sqlite3ExprCachePush(pParse);
38204adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
38214adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3822d2490904Sdrh       sqlite3ExprCachePop(pParse);
3823cce7d176Sdrh       break;
3824cce7d176Sdrh     }
3825cce7d176Sdrh     case TK_OR: {
3826c5499befSdrh       testcase( jumpIfNull==0 );
38274adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
382854e2adb5Sdrh       sqlite3ExprCachePush(pParse);
38294adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3830d2490904Sdrh       sqlite3ExprCachePop(pParse);
3831cce7d176Sdrh       break;
3832cce7d176Sdrh     }
3833cce7d176Sdrh     case TK_NOT: {
3834c5499befSdrh       testcase( jumpIfNull==0 );
38354adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3836cce7d176Sdrh       break;
3837cce7d176Sdrh     }
3838de845c2fSdrh     case TK_IS:
3839de845c2fSdrh     case TK_ISNOT:
3840de845c2fSdrh       testcase( op==TK_IS );
3841de845c2fSdrh       testcase( op==TK_ISNOT );
3842de845c2fSdrh       op = (op==TK_IS) ? TK_EQ : TK_NE;
3843de845c2fSdrh       jumpIfNull = SQLITE_NULLEQ;
3844de845c2fSdrh       /* Fall thru */
3845cce7d176Sdrh     case TK_LT:
3846cce7d176Sdrh     case TK_LE:
3847cce7d176Sdrh     case TK_GT:
3848cce7d176Sdrh     case TK_GE:
3849cce7d176Sdrh     case TK_NE:
38500ac65892Sdrh     case TK_EQ: {
3851c5499befSdrh       testcase( jumpIfNull==0 );
3852b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3853b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
385435573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
38552dcef11bSdrh                   r1, r2, dest, jumpIfNull);
38567d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
38577d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
38587d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
38597d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3860de845c2fSdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
3861de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
3862de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
3863de845c2fSdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
3864de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
3865de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
38666a2fe093Sdrh       testcase( regFree1==0 );
38676a2fe093Sdrh       testcase( regFree2==0 );
38686a2fe093Sdrh       break;
38696a2fe093Sdrh     }
3870cce7d176Sdrh     case TK_ISNULL:
3871cce7d176Sdrh     case TK_NOTNULL: {
38727d176105Sdrh       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
38737d176105Sdrh       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
38742dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
38752dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
38767d176105Sdrh       VdbeCoverageIf(v, op==TK_ISNULL);
38777d176105Sdrh       VdbeCoverageIf(v, op==TK_NOTNULL);
3878c5499befSdrh       testcase( regFree1==0 );
3879cce7d176Sdrh       break;
3880cce7d176Sdrh     }
3881fef5208cSdrh     case TK_BETWEEN: {
38825c03f30aSdrh       testcase( jumpIfNull==0 );
3883*71c57db0Sdan       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
3884fef5208cSdrh       break;
3885fef5208cSdrh     }
3886bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
3887e3365e6cSdrh     case TK_IN: {
3888e3365e6cSdrh       int destIfFalse = sqlite3VdbeMakeLabel(v);
3889e3365e6cSdrh       int destIfNull = jumpIfNull ? dest : destIfFalse;
3890e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3891076e85f5Sdrh       sqlite3VdbeGoto(v, dest);
3892e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
3893e3365e6cSdrh       break;
3894e3365e6cSdrh     }
3895bb201344Sshaneh #endif
3896cce7d176Sdrh     default: {
3897991a1985Sdrh       if( exprAlwaysTrue(pExpr) ){
3898076e85f5Sdrh         sqlite3VdbeGoto(v, dest);
3899991a1985Sdrh       }else if( exprAlwaysFalse(pExpr) ){
3900991a1985Sdrh         /* No-op */
3901991a1985Sdrh       }else{
39022dcef11bSdrh         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
39032dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
3904688852abSdrh         VdbeCoverage(v);
3905c5499befSdrh         testcase( regFree1==0 );
3906c5499befSdrh         testcase( jumpIfNull==0 );
3907991a1985Sdrh       }
3908cce7d176Sdrh       break;
3909cce7d176Sdrh     }
3910cce7d176Sdrh   }
39112dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
39122dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3913cce7d176Sdrh }
3914cce7d176Sdrh 
3915cce7d176Sdrh /*
391666b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
3917cce7d176Sdrh ** to the label "dest" if the expression is false but execution
3918cce7d176Sdrh ** continues straight thru if the expression is true.
3919f5905aa7Sdrh **
3920f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
392135573356Sdrh ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
392235573356Sdrh ** is 0.
3923cce7d176Sdrh */
39244adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3925cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3926cce7d176Sdrh   int op = 0;
39272dcef11bSdrh   int regFree1 = 0;
39282dcef11bSdrh   int regFree2 = 0;
39292dcef11bSdrh   int r1, r2;
39302dcef11bSdrh 
393135573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
393248864df9Smistachkin   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
393333cd4909Sdrh   if( pExpr==0 )    return;
3934f2bc013cSdrh 
3935f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
3936f2bc013cSdrh   **
3937f2bc013cSdrh   **       pExpr->op            op
3938f2bc013cSdrh   **       ---------          ----------
3939f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
3940f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
3941f2bc013cSdrh   **       TK_NE              OP_Eq
3942f2bc013cSdrh   **       TK_EQ              OP_Ne
3943f2bc013cSdrh   **       TK_GT              OP_Le
3944f2bc013cSdrh   **       TK_LE              OP_Gt
3945f2bc013cSdrh   **       TK_GE              OP_Lt
3946f2bc013cSdrh   **       TK_LT              OP_Ge
3947f2bc013cSdrh   **
3948f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
3949f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
3950f2bc013cSdrh   ** can compute the mapping above using the following expression.
3951f2bc013cSdrh   ** Assert()s verify that the computation is correct.
3952f2bc013cSdrh   */
3953f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3954f2bc013cSdrh 
3955f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
3956f2bc013cSdrh   */
3957f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3958f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3959f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
3960f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
3961f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
3962f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
3963f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
3964f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
3965f2bc013cSdrh 
3966*71c57db0Sdan   switch( pExpr->op | (pExpr->pLeft ? (pExpr->pLeft->flags & EP_Vector) : 0)){
3967cce7d176Sdrh     case TK_AND: {
3968c5499befSdrh       testcase( jumpIfNull==0 );
39694adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
397054e2adb5Sdrh       sqlite3ExprCachePush(pParse);
39714adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3972d2490904Sdrh       sqlite3ExprCachePop(pParse);
3973cce7d176Sdrh       break;
3974cce7d176Sdrh     }
3975cce7d176Sdrh     case TK_OR: {
39764adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3977c5499befSdrh       testcase( jumpIfNull==0 );
397835573356Sdrh       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
397954e2adb5Sdrh       sqlite3ExprCachePush(pParse);
39804adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
39814adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3982d2490904Sdrh       sqlite3ExprCachePop(pParse);
3983cce7d176Sdrh       break;
3984cce7d176Sdrh     }
3985cce7d176Sdrh     case TK_NOT: {
39865c03f30aSdrh       testcase( jumpIfNull==0 );
39874adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3988cce7d176Sdrh       break;
3989cce7d176Sdrh     }
3990de845c2fSdrh     case TK_IS:
3991de845c2fSdrh     case TK_ISNOT:
3992de845c2fSdrh       testcase( pExpr->op==TK_IS );
3993de845c2fSdrh       testcase( pExpr->op==TK_ISNOT );
3994de845c2fSdrh       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
3995de845c2fSdrh       jumpIfNull = SQLITE_NULLEQ;
3996de845c2fSdrh       /* Fall thru */
3997cce7d176Sdrh     case TK_LT:
3998cce7d176Sdrh     case TK_LE:
3999cce7d176Sdrh     case TK_GT:
4000cce7d176Sdrh     case TK_GE:
4001cce7d176Sdrh     case TK_NE:
4002cce7d176Sdrh     case TK_EQ: {
4003c5499befSdrh       testcase( jumpIfNull==0 );
4004b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4005b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
400635573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
40072dcef11bSdrh                   r1, r2, dest, jumpIfNull);
40087d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
40097d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
40107d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
40117d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4012de845c2fSdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4013de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4014de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4015de845c2fSdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4016de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4017de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
40186a2fe093Sdrh       testcase( regFree1==0 );
40196a2fe093Sdrh       testcase( regFree2==0 );
40206a2fe093Sdrh       break;
40216a2fe093Sdrh     }
4022cce7d176Sdrh     case TK_ISNULL:
4023cce7d176Sdrh     case TK_NOTNULL: {
40242dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
40252dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
40267d176105Sdrh       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
40277d176105Sdrh       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
4028c5499befSdrh       testcase( regFree1==0 );
4029cce7d176Sdrh       break;
4030cce7d176Sdrh     }
4031fef5208cSdrh     case TK_BETWEEN: {
40325c03f30aSdrh       testcase( jumpIfNull==0 );
4033*71c57db0Sdan       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
4034fef5208cSdrh       break;
4035fef5208cSdrh     }
4036bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
4037e3365e6cSdrh     case TK_IN: {
4038e3365e6cSdrh       if( jumpIfNull ){
4039e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4040e3365e6cSdrh       }else{
4041e3365e6cSdrh         int destIfNull = sqlite3VdbeMakeLabel(v);
4042e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4043e3365e6cSdrh         sqlite3VdbeResolveLabel(v, destIfNull);
4044e3365e6cSdrh       }
4045e3365e6cSdrh       break;
4046e3365e6cSdrh     }
4047bb201344Sshaneh #endif
4048cce7d176Sdrh     default: {
4049991a1985Sdrh       if( exprAlwaysFalse(pExpr) ){
4050076e85f5Sdrh         sqlite3VdbeGoto(v, dest);
4051991a1985Sdrh       }else if( exprAlwaysTrue(pExpr) ){
4052991a1985Sdrh         /* no-op */
4053991a1985Sdrh       }else{
40542dcef11bSdrh         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
40552dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
4056688852abSdrh         VdbeCoverage(v);
4057c5499befSdrh         testcase( regFree1==0 );
4058c5499befSdrh         testcase( jumpIfNull==0 );
4059991a1985Sdrh       }
4060cce7d176Sdrh       break;
4061cce7d176Sdrh     }
4062cce7d176Sdrh   }
40632dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
40642dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
4065cce7d176Sdrh }
40662282792aSdrh 
40672282792aSdrh /*
406872bc8208Sdrh ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
406972bc8208Sdrh ** code generation, and that copy is deleted after code generation. This
407072bc8208Sdrh ** ensures that the original pExpr is unchanged.
407172bc8208Sdrh */
407272bc8208Sdrh void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
407372bc8208Sdrh   sqlite3 *db = pParse->db;
407472bc8208Sdrh   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
407572bc8208Sdrh   if( db->mallocFailed==0 ){
407672bc8208Sdrh     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
407772bc8208Sdrh   }
407872bc8208Sdrh   sqlite3ExprDelete(db, pCopy);
407972bc8208Sdrh }
408072bc8208Sdrh 
408172bc8208Sdrh 
408272bc8208Sdrh /*
40831d9da70aSdrh ** Do a deep comparison of two expression trees.  Return 0 if the two
40841d9da70aSdrh ** expressions are completely identical.  Return 1 if they differ only
40851d9da70aSdrh ** by a COLLATE operator at the top level.  Return 2 if there are differences
40861d9da70aSdrh ** other than the top-level COLLATE operator.
4087d40aab0eSdrh **
4088619a1305Sdrh ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4089619a1305Sdrh ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4090619a1305Sdrh **
409166518ca7Sdrh ** The pA side might be using TK_REGISTER.  If that is the case and pB is
409266518ca7Sdrh ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
409366518ca7Sdrh **
40941d9da70aSdrh ** Sometimes this routine will return 2 even if the two expressions
4095d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
40961d9da70aSdrh ** identical, we return 2 just to be safe.  So if this routine
40971d9da70aSdrh ** returns 2, then you do not really know for certain if the two
40981d9da70aSdrh ** expressions are the same.  But if you get a 0 or 1 return, then you
4099d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
41001d9da70aSdrh ** this routine is used, it does not hurt to get an extra 2 - that
4101d40aab0eSdrh ** just might result in some slightly slower code.  But returning
41021d9da70aSdrh ** an incorrect 0 or 1 could lead to a malfunction.
41032282792aSdrh */
4104619a1305Sdrh int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
410510d1edf0Sdrh   u32 combinedFlags;
41064b202ae2Sdanielk1977   if( pA==0 || pB==0 ){
41071d9da70aSdrh     return pB==pA ? 0 : 2;
41082282792aSdrh   }
410910d1edf0Sdrh   combinedFlags = pA->flags | pB->flags;
411010d1edf0Sdrh   if( combinedFlags & EP_IntValue ){
411110d1edf0Sdrh     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
411210d1edf0Sdrh       return 0;
411310d1edf0Sdrh     }
41141d9da70aSdrh     return 2;
41156ab3a2ecSdanielk1977   }
4116c2acc4e4Sdrh   if( pA->op!=pB->op ){
4117619a1305Sdrh     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
4118ae80ddeaSdrh       return 1;
4119ae80ddeaSdrh     }
4120619a1305Sdrh     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
4121ae80ddeaSdrh       return 1;
4122ae80ddeaSdrh     }
4123ae80ddeaSdrh     return 2;
4124ae80ddeaSdrh   }
41252edc5fd7Sdrh   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
4126390b88a4Sdrh     if( pA->op==TK_FUNCTION ){
4127390b88a4Sdrh       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4128390b88a4Sdrh     }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
412910d1edf0Sdrh       return pA->op==TK_COLLATE ? 1 : 2;
413010d1edf0Sdrh     }
413110d1edf0Sdrh   }
413210d1edf0Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
413385f8aa79Sdrh   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
413410d1edf0Sdrh     if( combinedFlags & EP_xIsSelect ) return 2;
4135619a1305Sdrh     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4136619a1305Sdrh     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4137619a1305Sdrh     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
41387693c42fSdrh     if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
4139619a1305Sdrh       if( pA->iColumn!=pB->iColumn ) return 2;
414066518ca7Sdrh       if( pA->iTable!=pB->iTable
414185f8aa79Sdrh        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
41421d9da70aSdrh     }
41431d9da70aSdrh   }
41442646da7eSdrh   return 0;
41452646da7eSdrh }
41462282792aSdrh 
41478c6f666bSdrh /*
41488c6f666bSdrh ** Compare two ExprList objects.  Return 0 if they are identical and
41498c6f666bSdrh ** non-zero if they differ in any way.
41508c6f666bSdrh **
4151619a1305Sdrh ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4152619a1305Sdrh ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4153619a1305Sdrh **
41548c6f666bSdrh ** This routine might return non-zero for equivalent ExprLists.  The
41558c6f666bSdrh ** only consequence will be disabled optimizations.  But this routine
41568c6f666bSdrh ** must never return 0 if the two ExprList objects are different, or
41578c6f666bSdrh ** a malfunction will result.
41588c6f666bSdrh **
41598c6f666bSdrh ** Two NULL pointers are considered to be the same.  But a NULL pointer
41608c6f666bSdrh ** always differs from a non-NULL pointer.
41618c6f666bSdrh */
4162619a1305Sdrh int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
41638c6f666bSdrh   int i;
41648c6f666bSdrh   if( pA==0 && pB==0 ) return 0;
41658c6f666bSdrh   if( pA==0 || pB==0 ) return 1;
41668c6f666bSdrh   if( pA->nExpr!=pB->nExpr ) return 1;
41678c6f666bSdrh   for(i=0; i<pA->nExpr; i++){
41688c6f666bSdrh     Expr *pExprA = pA->a[i].pExpr;
41698c6f666bSdrh     Expr *pExprB = pB->a[i].pExpr;
41708c6f666bSdrh     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
4171619a1305Sdrh     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
41728c6f666bSdrh   }
41738c6f666bSdrh   return 0;
41748c6f666bSdrh }
417513449892Sdrh 
41762282792aSdrh /*
41774bd5f73fSdrh ** Return true if we can prove the pE2 will always be true if pE1 is
41784bd5f73fSdrh ** true.  Return false if we cannot complete the proof or if pE2 might
41794bd5f73fSdrh ** be false.  Examples:
41804bd5f73fSdrh **
4181619a1305Sdrh **     pE1: x==5       pE2: x==5             Result: true
41824bd5f73fSdrh **     pE1: x>0        pE2: x==5             Result: false
4183619a1305Sdrh **     pE1: x=21       pE2: x=21 OR y=43     Result: true
41844bd5f73fSdrh **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
4185619a1305Sdrh **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
4186619a1305Sdrh **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
4187619a1305Sdrh **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
41884bd5f73fSdrh **
41894bd5f73fSdrh ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
41904bd5f73fSdrh ** Expr.iTable<0 then assume a table number given by iTab.
41914bd5f73fSdrh **
41924bd5f73fSdrh ** When in doubt, return false.  Returning true might give a performance
41934bd5f73fSdrh ** improvement.  Returning false might cause a performance reduction, but
41944bd5f73fSdrh ** it will always give the correct answer and is hence always safe.
41954bd5f73fSdrh */
41964bd5f73fSdrh int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
4197619a1305Sdrh   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4198619a1305Sdrh     return 1;
4199619a1305Sdrh   }
4200619a1305Sdrh   if( pE2->op==TK_OR
4201619a1305Sdrh    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4202619a1305Sdrh              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4203619a1305Sdrh   ){
4204619a1305Sdrh     return 1;
4205619a1305Sdrh   }
4206619a1305Sdrh   if( pE2->op==TK_NOTNULL
4207619a1305Sdrh    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
4208619a1305Sdrh    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
4209619a1305Sdrh   ){
4210619a1305Sdrh     return 1;
4211619a1305Sdrh   }
4212619a1305Sdrh   return 0;
42134bd5f73fSdrh }
42144bd5f73fSdrh 
42154bd5f73fSdrh /*
4216030796dfSdrh ** An instance of the following structure is used by the tree walker
4217030796dfSdrh ** to count references to table columns in the arguments of an
4218ed551b95Sdrh ** aggregate function, in order to implement the
4219ed551b95Sdrh ** sqlite3FunctionThisSrc() routine.
4220374fdce4Sdrh */
4221030796dfSdrh struct SrcCount {
4222030796dfSdrh   SrcList *pSrc;   /* One particular FROM clause in a nested query */
4223030796dfSdrh   int nThis;       /* Number of references to columns in pSrcList */
4224030796dfSdrh   int nOther;      /* Number of references to columns in other FROM clauses */
4225030796dfSdrh };
4226030796dfSdrh 
4227030796dfSdrh /*
4228030796dfSdrh ** Count the number of references to columns.
4229030796dfSdrh */
4230030796dfSdrh static int exprSrcCount(Walker *pWalker, Expr *pExpr){
4231fb0a6081Sdrh   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4232fb0a6081Sdrh   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4233fb0a6081Sdrh   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
4234fb0a6081Sdrh   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4235fb0a6081Sdrh   ** NEVER() will need to be removed. */
4236fb0a6081Sdrh   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
4237374fdce4Sdrh     int i;
4238030796dfSdrh     struct SrcCount *p = pWalker->u.pSrcCount;
4239030796dfSdrh     SrcList *pSrc = p->pSrc;
4240655814d2Sdrh     int nSrc = pSrc ? pSrc->nSrc : 0;
4241655814d2Sdrh     for(i=0; i<nSrc; i++){
4242030796dfSdrh       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
4243374fdce4Sdrh     }
4244655814d2Sdrh     if( i<nSrc ){
4245030796dfSdrh       p->nThis++;
4246374fdce4Sdrh     }else{
4247030796dfSdrh       p->nOther++;
4248374fdce4Sdrh     }
4249374fdce4Sdrh   }
4250030796dfSdrh   return WRC_Continue;
4251030796dfSdrh }
4252374fdce4Sdrh 
4253374fdce4Sdrh /*
4254030796dfSdrh ** Determine if any of the arguments to the pExpr Function reference
4255030796dfSdrh ** pSrcList.  Return true if they do.  Also return true if the function
4256030796dfSdrh ** has no arguments or has only constant arguments.  Return false if pExpr
4257030796dfSdrh ** references columns but not columns of tables found in pSrcList.
4258374fdce4Sdrh */
4259030796dfSdrh int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
4260374fdce4Sdrh   Walker w;
4261030796dfSdrh   struct SrcCount cnt;
4262374fdce4Sdrh   assert( pExpr->op==TK_AGG_FUNCTION );
4263374fdce4Sdrh   memset(&w, 0, sizeof(w));
4264030796dfSdrh   w.xExprCallback = exprSrcCount;
4265030796dfSdrh   w.u.pSrcCount = &cnt;
4266030796dfSdrh   cnt.pSrc = pSrcList;
4267030796dfSdrh   cnt.nThis = 0;
4268030796dfSdrh   cnt.nOther = 0;
4269030796dfSdrh   sqlite3WalkExprList(&w, pExpr->x.pList);
4270030796dfSdrh   return cnt.nThis>0 || cnt.nOther==0;
4271374fdce4Sdrh }
4272374fdce4Sdrh 
4273374fdce4Sdrh /*
427413449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
427513449892Sdrh ** the new element.  Return a negative number if malloc fails.
42762282792aSdrh */
427717435752Sdrh static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
427813449892Sdrh   int i;
4279cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
428017435752Sdrh        db,
4281cf643729Sdrh        pInfo->aCol,
4282cf643729Sdrh        sizeof(pInfo->aCol[0]),
4283cf643729Sdrh        &pInfo->nColumn,
4284cf643729Sdrh        &i
4285cf643729Sdrh   );
428613449892Sdrh   return i;
42872282792aSdrh }
428813449892Sdrh 
428913449892Sdrh /*
429013449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
429113449892Sdrh ** the new element.  Return a negative number if malloc fails.
429213449892Sdrh */
429317435752Sdrh static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
429413449892Sdrh   int i;
4295cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
429617435752Sdrh        db,
4297cf643729Sdrh        pInfo->aFunc,
4298cf643729Sdrh        sizeof(pInfo->aFunc[0]),
4299cf643729Sdrh        &pInfo->nFunc,
4300cf643729Sdrh        &i
4301cf643729Sdrh   );
430213449892Sdrh   return i;
43032282792aSdrh }
43042282792aSdrh 
43052282792aSdrh /*
43067d10d5a6Sdrh ** This is the xExprCallback for a tree walker.  It is used to
43077d10d5a6Sdrh ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
4308626a879aSdrh ** for additional information.
43092282792aSdrh */
43107d10d5a6Sdrh static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
43112282792aSdrh   int i;
43127d10d5a6Sdrh   NameContext *pNC = pWalker->u.pNC;
4313a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
4314a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
431513449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
431613449892Sdrh 
43172282792aSdrh   switch( pExpr->op ){
431889c69d00Sdrh     case TK_AGG_COLUMN:
4319967e8b73Sdrh     case TK_COLUMN: {
43208b213899Sdrh       testcase( pExpr->op==TK_AGG_COLUMN );
43218b213899Sdrh       testcase( pExpr->op==TK_COLUMN );
432213449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
432313449892Sdrh       ** clause of the aggregate query */
432420bc393cSdrh       if( ALWAYS(pSrcList!=0) ){
432513449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
432613449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
432713449892Sdrh           struct AggInfo_col *pCol;
4328c5cd1249Sdrh           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
432913449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
433013449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
433113449892Sdrh             ** that is in the FROM clause of the aggregate query.
433213449892Sdrh             **
433313449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
433413449892Sdrh             ** is not an entry there already.
433513449892Sdrh             */
43367f906d63Sdrh             int k;
433713449892Sdrh             pCol = pAggInfo->aCol;
43387f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
433913449892Sdrh               if( pCol->iTable==pExpr->iTable &&
434013449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
43412282792aSdrh                 break;
43422282792aSdrh               }
43432282792aSdrh             }
43441e536953Sdanielk1977             if( (k>=pAggInfo->nColumn)
43451e536953Sdanielk1977              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
43461e536953Sdanielk1977             ){
43477f906d63Sdrh               pCol = &pAggInfo->aCol[k];
43480817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
434913449892Sdrh               pCol->iTable = pExpr->iTable;
435013449892Sdrh               pCol->iColumn = pExpr->iColumn;
43510a07c107Sdrh               pCol->iMem = ++pParse->nMem;
435213449892Sdrh               pCol->iSorterColumn = -1;
43535774b806Sdrh               pCol->pExpr = pExpr;
435413449892Sdrh               if( pAggInfo->pGroupBy ){
435513449892Sdrh                 int j, n;
435613449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
435713449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
435813449892Sdrh                 n = pGB->nExpr;
435913449892Sdrh                 for(j=0; j<n; j++, pTerm++){
436013449892Sdrh                   Expr *pE = pTerm->pExpr;
436113449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
436213449892Sdrh                       pE->iColumn==pExpr->iColumn ){
436313449892Sdrh                     pCol->iSorterColumn = j;
436413449892Sdrh                     break;
43652282792aSdrh                   }
436613449892Sdrh                 }
436713449892Sdrh               }
436813449892Sdrh               if( pCol->iSorterColumn<0 ){
436913449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
437013449892Sdrh               }
437113449892Sdrh             }
437213449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
437313449892Sdrh             ** because it was there before or because we just created it).
437413449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
437513449892Sdrh             ** pAggInfo->aCol[] entry.
437613449892Sdrh             */
4377ebb6a65dSdrh             ExprSetVVAProperty(pExpr, EP_NoReduce);
437813449892Sdrh             pExpr->pAggInfo = pAggInfo;
437913449892Sdrh             pExpr->op = TK_AGG_COLUMN;
4380cf697396Sshane             pExpr->iAgg = (i16)k;
438113449892Sdrh             break;
438213449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
438313449892Sdrh         } /* end loop over pSrcList */
4384a58fdfb1Sdanielk1977       }
43857d10d5a6Sdrh       return WRC_Prune;
43862282792aSdrh     }
43872282792aSdrh     case TK_AGG_FUNCTION: {
43883a8c4be7Sdrh       if( (pNC->ncFlags & NC_InAggFunc)==0
4389ed551b95Sdrh        && pWalker->walkerDepth==pExpr->op2
43903a8c4be7Sdrh       ){
439113449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
439213449892Sdrh         ** function that is already in the pAggInfo structure
439313449892Sdrh         */
439413449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
439513449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
4396619a1305Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
43972282792aSdrh             break;
43982282792aSdrh           }
43992282792aSdrh         }
440013449892Sdrh         if( i>=pAggInfo->nFunc ){
440113449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
440213449892Sdrh           */
440314db2665Sdanielk1977           u8 enc = ENC(pParse->db);
44041e536953Sdanielk1977           i = addAggInfoFunc(pParse->db, pAggInfo);
440513449892Sdrh           if( i>=0 ){
44066ab3a2ecSdanielk1977             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
440713449892Sdrh             pItem = &pAggInfo->aFunc[i];
440813449892Sdrh             pItem->pExpr = pExpr;
44090a07c107Sdrh             pItem->iMem = ++pParse->nMem;
441033e619fcSdrh             assert( !ExprHasProperty(pExpr, EP_IntValue) );
441113449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
441280738d9cSdrh                    pExpr->u.zToken,
44136ab3a2ecSdanielk1977                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
4414fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
4415fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
4416fd357974Sdrh             }else{
4417fd357974Sdrh               pItem->iDistinct = -1;
4418fd357974Sdrh             }
44192282792aSdrh           }
442013449892Sdrh         }
442113449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
442213449892Sdrh         */
4423c5cd1249Sdrh         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
4424ebb6a65dSdrh         ExprSetVVAProperty(pExpr, EP_NoReduce);
4425cf697396Sshane         pExpr->iAgg = (i16)i;
442613449892Sdrh         pExpr->pAggInfo = pAggInfo;
44273a8c4be7Sdrh         return WRC_Prune;
44286e83a57fSdrh       }else{
44296e83a57fSdrh         return WRC_Continue;
44306e83a57fSdrh       }
44312282792aSdrh     }
4432a58fdfb1Sdanielk1977   }
44337d10d5a6Sdrh   return WRC_Continue;
44347d10d5a6Sdrh }
44357d10d5a6Sdrh static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
4436d5a336efSdrh   UNUSED_PARAMETER(pWalker);
4437d5a336efSdrh   UNUSED_PARAMETER(pSelect);
44387d10d5a6Sdrh   return WRC_Continue;
4439a58fdfb1Sdanielk1977 }
4440626a879aSdrh 
4441626a879aSdrh /*
4442e8abb4caSdrh ** Analyze the pExpr expression looking for aggregate functions and
4443e8abb4caSdrh ** for variables that need to be added to AggInfo object that pNC->pAggInfo
4444e8abb4caSdrh ** points to.  Additional entries are made on the AggInfo object as
4445e8abb4caSdrh ** necessary.
4446626a879aSdrh **
4447626a879aSdrh ** This routine should only be called after the expression has been
44487d10d5a6Sdrh ** analyzed by sqlite3ResolveExprNames().
4449626a879aSdrh */
4450d2b3e23bSdrh void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
44517d10d5a6Sdrh   Walker w;
4452374fdce4Sdrh   memset(&w, 0, sizeof(w));
44537d10d5a6Sdrh   w.xExprCallback = analyzeAggregate;
44547d10d5a6Sdrh   w.xSelectCallback = analyzeAggregatesInSelect;
44557d10d5a6Sdrh   w.u.pNC = pNC;
445620bc393cSdrh   assert( pNC->pSrcList!=0 );
44577d10d5a6Sdrh   sqlite3WalkExpr(&w, pExpr);
44582282792aSdrh }
44595d9a4af9Sdrh 
44605d9a4af9Sdrh /*
44615d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
44625d9a4af9Sdrh ** expression list.  Return the number of errors.
44635d9a4af9Sdrh **
44645d9a4af9Sdrh ** If an error is found, the analysis is cut short.
44655d9a4af9Sdrh */
4466d2b3e23bSdrh void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
44675d9a4af9Sdrh   struct ExprList_item *pItem;
44685d9a4af9Sdrh   int i;
44695d9a4af9Sdrh   if( pList ){
4470d2b3e23bSdrh     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4471d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
44725d9a4af9Sdrh     }
44735d9a4af9Sdrh   }
44745d9a4af9Sdrh }
4475892d3179Sdrh 
4476892d3179Sdrh /*
4477ceea3321Sdrh ** Allocate a single new register for use to hold some intermediate result.
4478892d3179Sdrh */
4479892d3179Sdrh int sqlite3GetTempReg(Parse *pParse){
4480e55cbd72Sdrh   if( pParse->nTempReg==0 ){
4481892d3179Sdrh     return ++pParse->nMem;
4482892d3179Sdrh   }
44832f425f6bSdanielk1977   return pParse->aTempReg[--pParse->nTempReg];
4484892d3179Sdrh }
4485ceea3321Sdrh 
4486ceea3321Sdrh /*
4487ceea3321Sdrh ** Deallocate a register, making available for reuse for some other
4488ceea3321Sdrh ** purpose.
4489ceea3321Sdrh **
4490ceea3321Sdrh ** If a register is currently being used by the column cache, then
449160ec914cSpeter.d.reid ** the deallocation is deferred until the column cache line that uses
4492ceea3321Sdrh ** the register becomes stale.
4493ceea3321Sdrh */
4494892d3179Sdrh void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
44952dcef11bSdrh   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
4496ceea3321Sdrh     int i;
4497ceea3321Sdrh     struct yColCache *p;
4498ceea3321Sdrh     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4499ceea3321Sdrh       if( p->iReg==iReg ){
4500ceea3321Sdrh         p->tempReg = 1;
4501ceea3321Sdrh         return;
4502ceea3321Sdrh       }
4503ceea3321Sdrh     }
4504892d3179Sdrh     pParse->aTempReg[pParse->nTempReg++] = iReg;
4505892d3179Sdrh   }
4506892d3179Sdrh }
4507892d3179Sdrh 
4508892d3179Sdrh /*
4509892d3179Sdrh ** Allocate or deallocate a block of nReg consecutive registers
4510892d3179Sdrh */
4511892d3179Sdrh int sqlite3GetTempRange(Parse *pParse, int nReg){
4512e55cbd72Sdrh   int i, n;
4513892d3179Sdrh   i = pParse->iRangeReg;
4514e55cbd72Sdrh   n = pParse->nRangeReg;
4515f49f3523Sdrh   if( nReg<=n ){
4516f49f3523Sdrh     assert( !usedAsColumnCache(pParse, i, i+n-1) );
4517892d3179Sdrh     pParse->iRangeReg += nReg;
4518892d3179Sdrh     pParse->nRangeReg -= nReg;
4519892d3179Sdrh   }else{
4520892d3179Sdrh     i = pParse->nMem+1;
4521892d3179Sdrh     pParse->nMem += nReg;
4522892d3179Sdrh   }
4523892d3179Sdrh   return i;
4524892d3179Sdrh }
4525892d3179Sdrh void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
4526f49f3523Sdrh   sqlite3ExprCacheRemove(pParse, iReg, nReg);
4527892d3179Sdrh   if( nReg>pParse->nRangeReg ){
4528892d3179Sdrh     pParse->nRangeReg = nReg;
4529892d3179Sdrh     pParse->iRangeReg = iReg;
4530892d3179Sdrh   }
4531892d3179Sdrh }
4532cdc69557Sdrh 
4533cdc69557Sdrh /*
4534cdc69557Sdrh ** Mark all temporary registers as being unavailable for reuse.
4535cdc69557Sdrh */
4536cdc69557Sdrh void sqlite3ClearTempRegCache(Parse *pParse){
4537cdc69557Sdrh   pParse->nTempReg = 0;
4538cdc69557Sdrh   pParse->nRangeReg = 0;
4539cdc69557Sdrh }
4540bb9b5f26Sdrh 
4541bb9b5f26Sdrh /*
4542bb9b5f26Sdrh ** Validate that no temporary register falls within the range of
4543bb9b5f26Sdrh ** iFirst..iLast, inclusive.  This routine is only call from within assert()
4544bb9b5f26Sdrh ** statements.
4545bb9b5f26Sdrh */
4546bb9b5f26Sdrh #ifdef SQLITE_DEBUG
4547bb9b5f26Sdrh int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
4548bb9b5f26Sdrh   int i;
4549bb9b5f26Sdrh   if( pParse->nRangeReg>0
4550bb9b5f26Sdrh    && pParse->iRangeReg+pParse->nRangeReg<iLast
4551bb9b5f26Sdrh    && pParse->iRangeReg>=iFirst
4552bb9b5f26Sdrh   ){
4553bb9b5f26Sdrh      return 0;
4554bb9b5f26Sdrh   }
4555bb9b5f26Sdrh   for(i=0; i<pParse->nTempReg; i++){
4556bb9b5f26Sdrh     if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
4557bb9b5f26Sdrh       return 0;
4558bb9b5f26Sdrh     }
4559bb9b5f26Sdrh   }
4560bb9b5f26Sdrh   return 1;
4561bb9b5f26Sdrh }
4562bb9b5f26Sdrh #endif /* SQLITE_DEBUG */
4563