xref: /sqlite-3.40.0/src/expr.c (revision 08de4f79)
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 
3124b5255acSdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
3134b5255acSdanielk1977 /*
3144b5255acSdanielk1977 ** Check that argument nHeight is less than or equal to the maximum
3154b5255acSdanielk1977 ** expression depth allowed. If it is not, leave an error message in
3164b5255acSdanielk1977 ** pParse.
3174b5255acSdanielk1977 */
3187d10d5a6Sdrh int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
3194b5255acSdanielk1977   int rc = SQLITE_OK;
3204b5255acSdanielk1977   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
3214b5255acSdanielk1977   if( nHeight>mxHeight ){
3224b5255acSdanielk1977     sqlite3ErrorMsg(pParse,
3234b5255acSdanielk1977        "Expression tree is too large (maximum depth %d)", mxHeight
3244b5255acSdanielk1977     );
3254b5255acSdanielk1977     rc = SQLITE_ERROR;
3264b5255acSdanielk1977   }
3274b5255acSdanielk1977   return rc;
3284b5255acSdanielk1977 }
3294b5255acSdanielk1977 
3304b5255acSdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
3314b5255acSdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
3324b5255acSdanielk1977 ** of any expression tree referenced by the structure passed as the
3334b5255acSdanielk1977 ** first argument.
3344b5255acSdanielk1977 **
3354b5255acSdanielk1977 ** If this maximum height is greater than the current value pointed
3364b5255acSdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
3374b5255acSdanielk1977 ** value.
3384b5255acSdanielk1977 */
3394b5255acSdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
3404b5255acSdanielk1977   if( p ){
3414b5255acSdanielk1977     if( p->nHeight>*pnHeight ){
3424b5255acSdanielk1977       *pnHeight = p->nHeight;
3434b5255acSdanielk1977     }
3444b5255acSdanielk1977   }
3454b5255acSdanielk1977 }
3464b5255acSdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
3474b5255acSdanielk1977   if( p ){
3484b5255acSdanielk1977     int i;
3494b5255acSdanielk1977     for(i=0; i<p->nExpr; i++){
3504b5255acSdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
3514b5255acSdanielk1977     }
3524b5255acSdanielk1977   }
3534b5255acSdanielk1977 }
3544b5255acSdanielk1977 static void heightOfSelect(Select *p, int *pnHeight){
3554b5255acSdanielk1977   if( p ){
3564b5255acSdanielk1977     heightOfExpr(p->pWhere, pnHeight);
3574b5255acSdanielk1977     heightOfExpr(p->pHaving, pnHeight);
3584b5255acSdanielk1977     heightOfExpr(p->pLimit, pnHeight);
3594b5255acSdanielk1977     heightOfExpr(p->pOffset, pnHeight);
3604b5255acSdanielk1977     heightOfExprList(p->pEList, pnHeight);
3614b5255acSdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
3624b5255acSdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
3634b5255acSdanielk1977     heightOfSelect(p->pPrior, pnHeight);
3644b5255acSdanielk1977   }
3654b5255acSdanielk1977 }
3664b5255acSdanielk1977 
3674b5255acSdanielk1977 /*
3684b5255acSdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
3694b5255acSdanielk1977 ** argument. An expression with no children, Expr.pList or
3704b5255acSdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
3714b5255acSdanielk1977 ** has a height equal to the maximum height of any other
3724b5255acSdanielk1977 ** referenced Expr plus one.
3732308ed38Sdrh **
3742308ed38Sdrh ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
3752308ed38Sdrh ** if appropriate.
3764b5255acSdanielk1977 */
3774b5255acSdanielk1977 static void exprSetHeight(Expr *p){
3784b5255acSdanielk1977   int nHeight = 0;
3794b5255acSdanielk1977   heightOfExpr(p->pLeft, &nHeight);
3804b5255acSdanielk1977   heightOfExpr(p->pRight, &nHeight);
3816ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_xIsSelect) ){
3826ab3a2ecSdanielk1977     heightOfSelect(p->x.pSelect, &nHeight);
3832308ed38Sdrh   }else if( p->x.pList ){
3846ab3a2ecSdanielk1977     heightOfExprList(p->x.pList, &nHeight);
3852308ed38Sdrh     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
3866ab3a2ecSdanielk1977   }
3874b5255acSdanielk1977   p->nHeight = nHeight + 1;
3884b5255acSdanielk1977 }
3894b5255acSdanielk1977 
3904b5255acSdanielk1977 /*
3914b5255acSdanielk1977 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
3924b5255acSdanielk1977 ** the height is greater than the maximum allowed expression depth,
3934b5255acSdanielk1977 ** leave an error in pParse.
3942308ed38Sdrh **
3952308ed38Sdrh ** Also propagate all EP_Propagate flags from the Expr.x.pList into
3962308ed38Sdrh ** Expr.flags.
3974b5255acSdanielk1977 */
3982308ed38Sdrh void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
39974893a4cSdrh   if( pParse->nErr ) return;
4004b5255acSdanielk1977   exprSetHeight(p);
4017d10d5a6Sdrh   sqlite3ExprCheckHeight(pParse, p->nHeight);
4024b5255acSdanielk1977 }
4034b5255acSdanielk1977 
4044b5255acSdanielk1977 /*
4054b5255acSdanielk1977 ** Return the maximum height of any expression tree referenced
4064b5255acSdanielk1977 ** by the select statement passed as an argument.
4074b5255acSdanielk1977 */
4084b5255acSdanielk1977 int sqlite3SelectExprHeight(Select *p){
4094b5255acSdanielk1977   int nHeight = 0;
4104b5255acSdanielk1977   heightOfSelect(p, &nHeight);
4114b5255acSdanielk1977   return nHeight;
4124b5255acSdanielk1977 }
4132308ed38Sdrh #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
4142308ed38Sdrh /*
4152308ed38Sdrh ** Propagate all EP_Propagate flags from the Expr.x.pList into
4162308ed38Sdrh ** Expr.flags.
4172308ed38Sdrh */
4182308ed38Sdrh void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
4192308ed38Sdrh   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
4202308ed38Sdrh     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
4212308ed38Sdrh   }
4222308ed38Sdrh }
4234b5255acSdanielk1977 #define exprSetHeight(y)
4244b5255acSdanielk1977 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
4254b5255acSdanielk1977 
426be5c89acSdrh /*
427b7916a78Sdrh ** This routine is the core allocator for Expr nodes.
428b7916a78Sdrh **
429a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
430b7916a78Sdrh ** for this node and for the pToken argument is a single allocation
431b7916a78Sdrh ** obtained from sqlite3DbMalloc().  The calling function
432a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
433b7916a78Sdrh **
434b7916a78Sdrh ** If dequote is true, then the token (if it exists) is dequoted.
435e792b5b4Sdrh ** If dequote is false, no dequoting is performed.  The deQuote
436b7916a78Sdrh ** parameter is ignored if pToken is NULL or if the token does not
437b7916a78Sdrh ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
438b7916a78Sdrh ** then the EP_DblQuoted flag is set on the expression node.
43933e619fcSdrh **
44033e619fcSdrh ** Special case:  If op==TK_INTEGER and pToken points to a string that
44133e619fcSdrh ** can be translated into a 32-bit integer, then the token is not
44233e619fcSdrh ** stored in u.zToken.  Instead, the integer values is written
44333e619fcSdrh ** into u.iValue and the EP_IntValue flag is set.  No extra storage
44433e619fcSdrh ** is allocated to hold the integer text and the dequote flag is ignored.
445a76b5dfcSdrh */
446b7916a78Sdrh Expr *sqlite3ExprAlloc(
447a1644fd8Sdanielk1977   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
44817435752Sdrh   int op,                 /* Expression opcode */
449b7916a78Sdrh   const Token *pToken,    /* Token argument.  Might be NULL */
450b7916a78Sdrh   int dequote             /* True to dequote */
45117435752Sdrh ){
452a76b5dfcSdrh   Expr *pNew;
45333e619fcSdrh   int nExtra = 0;
454cf697396Sshane   int iValue = 0;
455b7916a78Sdrh 
456575fad65Sdrh   assert( db!=0 );
457b7916a78Sdrh   if( pToken ){
45833e619fcSdrh     if( op!=TK_INTEGER || pToken->z==0
45933e619fcSdrh           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
460b7916a78Sdrh       nExtra = pToken->n+1;
461d50ffc41Sdrh       assert( iValue>=0 );
46233e619fcSdrh     }
463a76b5dfcSdrh   }
464575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
465b7916a78Sdrh   if( pNew ){
466ca3862dcSdrh     memset(pNew, 0, sizeof(Expr));
4671bd10f8aSdrh     pNew->op = (u8)op;
468a58fdfb1Sdanielk1977     pNew->iAgg = -1;
469a76b5dfcSdrh     if( pToken ){
47033e619fcSdrh       if( nExtra==0 ){
47133e619fcSdrh         pNew->flags |= EP_IntValue;
47233e619fcSdrh         pNew->u.iValue = iValue;
47333e619fcSdrh       }else{
474d9da78a2Sdrh         int c;
47533e619fcSdrh         pNew->u.zToken = (char*)&pNew[1];
476b07028f7Sdrh         assert( pToken->z!=0 || pToken->n==0 );
477b07028f7Sdrh         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
47833e619fcSdrh         pNew->u.zToken[pToken->n] = 0;
479b7916a78Sdrh         if( dequote && nExtra>=3
480d9da78a2Sdrh              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
48133e619fcSdrh           sqlite3Dequote(pNew->u.zToken);
48224fb627aSdrh           if( c=='"' ) pNew->flags |= EP_DblQuoted;
483a34001c9Sdrh         }
484a34001c9Sdrh       }
48533e619fcSdrh     }
486b7916a78Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
487b7916a78Sdrh     pNew->nHeight = 1;
488b7916a78Sdrh #endif
489a34001c9Sdrh   }
490a76b5dfcSdrh   return pNew;
491a76b5dfcSdrh }
492a76b5dfcSdrh 
493a76b5dfcSdrh /*
494b7916a78Sdrh ** Allocate a new expression node from a zero-terminated token that has
495b7916a78Sdrh ** already been dequoted.
496b7916a78Sdrh */
497b7916a78Sdrh Expr *sqlite3Expr(
498b7916a78Sdrh   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
499b7916a78Sdrh   int op,                 /* Expression opcode */
500b7916a78Sdrh   const char *zToken      /* Token argument.  Might be NULL */
501b7916a78Sdrh ){
502b7916a78Sdrh   Token x;
503b7916a78Sdrh   x.z = zToken;
504b7916a78Sdrh   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
505b7916a78Sdrh   return sqlite3ExprAlloc(db, op, &x, 0);
506b7916a78Sdrh }
507b7916a78Sdrh 
508b7916a78Sdrh /*
509b7916a78Sdrh ** Attach subtrees pLeft and pRight to the Expr node pRoot.
510b7916a78Sdrh **
511b7916a78Sdrh ** If pRoot==NULL that means that a memory allocation error has occurred.
512b7916a78Sdrh ** In that case, delete the subtrees pLeft and pRight.
513b7916a78Sdrh */
514b7916a78Sdrh void sqlite3ExprAttachSubtrees(
515b7916a78Sdrh   sqlite3 *db,
516b7916a78Sdrh   Expr *pRoot,
517b7916a78Sdrh   Expr *pLeft,
518b7916a78Sdrh   Expr *pRight
519b7916a78Sdrh ){
520b7916a78Sdrh   if( pRoot==0 ){
521b7916a78Sdrh     assert( db->mallocFailed );
522b7916a78Sdrh     sqlite3ExprDelete(db, pLeft);
523b7916a78Sdrh     sqlite3ExprDelete(db, pRight);
524b7916a78Sdrh   }else{
525b7916a78Sdrh     if( pRight ){
526b7916a78Sdrh       pRoot->pRight = pRight;
527885a5b03Sdrh       pRoot->flags |= EP_Propagate & pRight->flags;
528b7916a78Sdrh     }
529b7916a78Sdrh     if( pLeft ){
530b7916a78Sdrh       pRoot->pLeft = pLeft;
531885a5b03Sdrh       pRoot->flags |= EP_Propagate & pLeft->flags;
532b7916a78Sdrh     }
533b7916a78Sdrh     exprSetHeight(pRoot);
534b7916a78Sdrh   }
535b7916a78Sdrh }
536b7916a78Sdrh 
537b7916a78Sdrh /*
53860ec914cSpeter.d.reid ** Allocate an Expr node which joins as many as two subtrees.
539b7916a78Sdrh **
540bf664469Sdrh ** One or both of the subtrees can be NULL.  Return a pointer to the new
541bf664469Sdrh ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
542bf664469Sdrh ** free the subtrees and return NULL.
543206f3d96Sdrh */
54417435752Sdrh Expr *sqlite3PExpr(
54517435752Sdrh   Parse *pParse,          /* Parsing context */
54617435752Sdrh   int op,                 /* Expression opcode */
54717435752Sdrh   Expr *pLeft,            /* Left operand */
54817435752Sdrh   Expr *pRight,           /* Right operand */
54917435752Sdrh   const Token *pToken     /* Argument token */
55017435752Sdrh ){
5515fb52caaSdrh   Expr *p;
5521167d327Sdrh   if( op==TK_AND && pParse->nErr==0 ){
5535fb52caaSdrh     /* Take advantage of short-circuit false optimization for AND */
5545fb52caaSdrh     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
5555fb52caaSdrh   }else{
5561167d327Sdrh     p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
557b7916a78Sdrh     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
5585fb52caaSdrh   }
5592b359bdbSdan   if( p ) {
5602b359bdbSdan     sqlite3ExprCheckHeight(pParse, p->nHeight);
5612b359bdbSdan   }
5624e0cff60Sdrh   return p;
5634e0cff60Sdrh }
5644e0cff60Sdrh 
5654e0cff60Sdrh /*
566*08de4f79Sdrh ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
567*08de4f79Sdrh ** do a memory allocation failure) then delete the pSelect object.
568*08de4f79Sdrh */
569*08de4f79Sdrh void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
570*08de4f79Sdrh   if( pExpr ){
571*08de4f79Sdrh     pExpr->x.pSelect = pSelect;
572*08de4f79Sdrh     ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
573*08de4f79Sdrh     sqlite3ExprSetHeightAndFlags(pParse, pExpr);
574*08de4f79Sdrh   }else{
575*08de4f79Sdrh     assert( pParse->db->mallocFailed );
576*08de4f79Sdrh     sqlite3SelectDelete(pParse->db, pSelect);
577*08de4f79Sdrh   }
578*08de4f79Sdrh }
579*08de4f79Sdrh 
580*08de4f79Sdrh 
581*08de4f79Sdrh /*
582991a1985Sdrh ** If the expression is always either TRUE or FALSE (respectively),
583991a1985Sdrh ** then return 1.  If one cannot determine the truth value of the
584991a1985Sdrh ** expression at compile-time return 0.
585991a1985Sdrh **
586991a1985Sdrh ** This is an optimization.  If is OK to return 0 here even if
587991a1985Sdrh ** the expression really is always false or false (a false negative).
588991a1985Sdrh ** But it is a bug to return 1 if the expression might have different
589991a1985Sdrh ** boolean values in different circumstances (a false positive.)
5905fb52caaSdrh **
5915fb52caaSdrh ** Note that if the expression is part of conditional for a
5925fb52caaSdrh ** LEFT JOIN, then we cannot determine at compile-time whether or not
5935fb52caaSdrh ** is it true or false, so always return 0.
5945fb52caaSdrh */
595991a1985Sdrh static int exprAlwaysTrue(Expr *p){
596991a1985Sdrh   int v = 0;
597991a1985Sdrh   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
598991a1985Sdrh   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
599991a1985Sdrh   return v!=0;
600991a1985Sdrh }
6015fb52caaSdrh static int exprAlwaysFalse(Expr *p){
6025fb52caaSdrh   int v = 0;
6035fb52caaSdrh   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
6045fb52caaSdrh   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
6055fb52caaSdrh   return v==0;
6065fb52caaSdrh }
6075fb52caaSdrh 
6085fb52caaSdrh /*
60991bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
61091bb0eedSdrh ** NULL, then just return the other expression.
6115fb52caaSdrh **
6125fb52caaSdrh ** If one side or the other of the AND is known to be false, then instead
6135fb52caaSdrh ** of returning an AND expression, just return a constant expression with
6145fb52caaSdrh ** a value of false.
61591bb0eedSdrh */
6161e536953Sdanielk1977 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
61791bb0eedSdrh   if( pLeft==0 ){
61891bb0eedSdrh     return pRight;
61991bb0eedSdrh   }else if( pRight==0 ){
62091bb0eedSdrh     return pLeft;
6215fb52caaSdrh   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
6225fb52caaSdrh     sqlite3ExprDelete(db, pLeft);
6235fb52caaSdrh     sqlite3ExprDelete(db, pRight);
6245fb52caaSdrh     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
62591bb0eedSdrh   }else{
626b7916a78Sdrh     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
627b7916a78Sdrh     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
628b7916a78Sdrh     return pNew;
629a76b5dfcSdrh   }
630a76b5dfcSdrh }
631a76b5dfcSdrh 
632a76b5dfcSdrh /*
633a76b5dfcSdrh ** Construct a new expression node for a function with multiple
634a76b5dfcSdrh ** arguments.
635a76b5dfcSdrh */
63617435752Sdrh Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
637a76b5dfcSdrh   Expr *pNew;
638633e6d57Sdrh   sqlite3 *db = pParse->db;
6394b202ae2Sdanielk1977   assert( pToken );
640b7916a78Sdrh   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
641a76b5dfcSdrh   if( pNew==0 ){
642d9da78a2Sdrh     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
643a76b5dfcSdrh     return 0;
644a76b5dfcSdrh   }
6456ab3a2ecSdanielk1977   pNew->x.pList = pList;
6466ab3a2ecSdanielk1977   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
6472308ed38Sdrh   sqlite3ExprSetHeightAndFlags(pParse, pNew);
648a76b5dfcSdrh   return pNew;
649a76b5dfcSdrh }
650a76b5dfcSdrh 
651a76b5dfcSdrh /*
652fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
653fa6bc000Sdrh ** in the original SQL statement.
654fa6bc000Sdrh **
655fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
656fa6bc000Sdrh ** variable number.
657fa6bc000Sdrh **
658fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
659fa6bc000Sdrh ** sure "nnn" is not too be to avoid a denial of service attack when
660fa6bc000Sdrh ** the SQL statement comes from an external source.
661fa6bc000Sdrh **
66251f49f17Sdrh ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
663fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
66460ec914cSpeter.d.reid ** instance of the wildcard, the next sequential variable number is
665fa6bc000Sdrh ** assigned.
666fa6bc000Sdrh */
667fa6bc000Sdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
66817435752Sdrh   sqlite3 *db = pParse->db;
669b7916a78Sdrh   const char *z;
67017435752Sdrh 
671fa6bc000Sdrh   if( pExpr==0 ) return;
672c5cd1249Sdrh   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
67333e619fcSdrh   z = pExpr->u.zToken;
674b7916a78Sdrh   assert( z!=0 );
675b7916a78Sdrh   assert( z[0]!=0 );
676b7916a78Sdrh   if( z[1]==0 ){
677fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
678b7916a78Sdrh     assert( z[0]=='?' );
6798677d308Sdrh     pExpr->iColumn = (ynVar)(++pParse->nVar);
680124c0b49Sdrh   }else{
681124c0b49Sdrh     ynVar x = 0;
682124c0b49Sdrh     u32 n = sqlite3Strlen30(z);
683124c0b49Sdrh     if( z[0]=='?' ){
684fa6bc000Sdrh       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
685fa6bc000Sdrh       ** use it as the variable number */
686c8d735aeSdan       i64 i;
687124c0b49Sdrh       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
688124c0b49Sdrh       pExpr->iColumn = x = (ynVar)i;
689c5499befSdrh       testcase( i==0 );
690c5499befSdrh       testcase( i==1 );
691c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
692c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
693c8d735aeSdan       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
694fa6bc000Sdrh         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
695bb4957f8Sdrh             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
696124c0b49Sdrh         x = 0;
697fa6bc000Sdrh       }
698fa6bc000Sdrh       if( i>pParse->nVar ){
6991df2db7fSshaneh         pParse->nVar = (int)i;
700fa6bc000Sdrh       }
701fa6bc000Sdrh     }else{
70251f49f17Sdrh       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
703fa6bc000Sdrh       ** number as the prior appearance of the same name, or if the name
704fa6bc000Sdrh       ** has never appeared before, reuse the same variable number
705fa6bc000Sdrh       */
706124c0b49Sdrh       ynVar i;
707124c0b49Sdrh       for(i=0; i<pParse->nzVar; i++){
708503a686eSdrh         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
709124c0b49Sdrh           pExpr->iColumn = x = (ynVar)i+1;
710fa6bc000Sdrh           break;
711fa6bc000Sdrh         }
712fa6bc000Sdrh       }
713124c0b49Sdrh       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
714fa6bc000Sdrh     }
715124c0b49Sdrh     if( x>0 ){
716124c0b49Sdrh       if( x>pParse->nzVar ){
717124c0b49Sdrh         char **a;
718124c0b49Sdrh         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
7194a642b60Sdrh         if( a==0 ){
7204a642b60Sdrh           assert( db->mallocFailed ); /* Error reported through mallocFailed */
7214a642b60Sdrh           return;
7224a642b60Sdrh         }
723124c0b49Sdrh         pParse->azVar = a;
724124c0b49Sdrh         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
725124c0b49Sdrh         pParse->nzVar = x;
726124c0b49Sdrh       }
727124c0b49Sdrh       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
728124c0b49Sdrh         sqlite3DbFree(db, pParse->azVar[x-1]);
729124c0b49Sdrh         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
730fa6bc000Sdrh       }
731fa6bc000Sdrh     }
732fa6bc000Sdrh   }
733bb4957f8Sdrh   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
734832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
735832b2664Sdanielk1977   }
736fa6bc000Sdrh }
737fa6bc000Sdrh 
738fa6bc000Sdrh /*
739f6963f99Sdan ** Recursively delete an expression tree.
740a2e00042Sdrh */
741f6963f99Sdan void sqlite3ExprDelete(sqlite3 *db, Expr *p){
742f6963f99Sdan   if( p==0 ) return;
743d50ffc41Sdrh   /* Sanity check: Assert that the IntValue is non-negative if it exists */
744d50ffc41Sdrh   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
745c5cd1249Sdrh   if( !ExprHasProperty(p, EP_TokenOnly) ){
746c5cd1249Sdrh     /* The Expr.x union is never used at the same time as Expr.pRight */
747c5cd1249Sdrh     assert( p->x.pList==0 || p->pRight==0 );
748633e6d57Sdrh     sqlite3ExprDelete(db, p->pLeft);
749633e6d57Sdrh     sqlite3ExprDelete(db, p->pRight);
750c5cd1249Sdrh     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
7516ab3a2ecSdanielk1977     if( ExprHasProperty(p, EP_xIsSelect) ){
7526ab3a2ecSdanielk1977       sqlite3SelectDelete(db, p->x.pSelect);
7536ab3a2ecSdanielk1977     }else{
7546ab3a2ecSdanielk1977       sqlite3ExprListDelete(db, p->x.pList);
7556ab3a2ecSdanielk1977     }
7566ab3a2ecSdanielk1977   }
75733e619fcSdrh   if( !ExprHasProperty(p, EP_Static) ){
758633e6d57Sdrh     sqlite3DbFree(db, p);
759a2e00042Sdrh   }
76033e619fcSdrh }
761a2e00042Sdrh 
762d2687b77Sdrh /*
7636ab3a2ecSdanielk1977 ** Return the number of bytes allocated for the expression structure
7646ab3a2ecSdanielk1977 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
7656ab3a2ecSdanielk1977 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
7666ab3a2ecSdanielk1977 */
7676ab3a2ecSdanielk1977 static int exprStructSize(Expr *p){
7686ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
7696ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
7706ab3a2ecSdanielk1977   return EXPR_FULLSIZE;
7716ab3a2ecSdanielk1977 }
7726ab3a2ecSdanielk1977 
7736ab3a2ecSdanielk1977 /*
77433e619fcSdrh ** The dupedExpr*Size() routines each return the number of bytes required
77533e619fcSdrh ** to store a copy of an expression or expression tree.  They differ in
77633e619fcSdrh ** how much of the tree is measured.
77733e619fcSdrh **
77833e619fcSdrh **     dupedExprStructSize()     Size of only the Expr structure
77933e619fcSdrh **     dupedExprNodeSize()       Size of Expr + space for token
78033e619fcSdrh **     dupedExprSize()           Expr + token + subtree components
78133e619fcSdrh **
78233e619fcSdrh ***************************************************************************
78333e619fcSdrh **
78433e619fcSdrh ** The dupedExprStructSize() function returns two values OR-ed together:
78533e619fcSdrh ** (1) the space required for a copy of the Expr structure only and
78633e619fcSdrh ** (2) the EP_xxx flags that indicate what the structure size should be.
78733e619fcSdrh ** The return values is always one of:
78833e619fcSdrh **
78933e619fcSdrh **      EXPR_FULLSIZE
79033e619fcSdrh **      EXPR_REDUCEDSIZE   | EP_Reduced
79133e619fcSdrh **      EXPR_TOKENONLYSIZE | EP_TokenOnly
79233e619fcSdrh **
79333e619fcSdrh ** The size of the structure can be found by masking the return value
79433e619fcSdrh ** of this routine with 0xfff.  The flags can be found by masking the
79533e619fcSdrh ** return value with EP_Reduced|EP_TokenOnly.
79633e619fcSdrh **
79733e619fcSdrh ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
79833e619fcSdrh ** (unreduced) Expr objects as they or originally constructed by the parser.
79933e619fcSdrh ** During expression analysis, extra information is computed and moved into
80033e619fcSdrh ** later parts of teh Expr object and that extra information might get chopped
80133e619fcSdrh ** off if the expression is reduced.  Note also that it does not work to
80260ec914cSpeter.d.reid ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
80333e619fcSdrh ** to reduce a pristine expression tree from the parser.  The implementation
80433e619fcSdrh ** of dupedExprStructSize() contain multiple assert() statements that attempt
80533e619fcSdrh ** to enforce this constraint.
8066ab3a2ecSdanielk1977 */
8076ab3a2ecSdanielk1977 static int dupedExprStructSize(Expr *p, int flags){
8086ab3a2ecSdanielk1977   int nSize;
80933e619fcSdrh   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
810aecd8021Sdrh   assert( EXPR_FULLSIZE<=0xfff );
811aecd8021Sdrh   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
8126ab3a2ecSdanielk1977   if( 0==(flags&EXPRDUP_REDUCE) ){
8136ab3a2ecSdanielk1977     nSize = EXPR_FULLSIZE;
8146ab3a2ecSdanielk1977   }else{
815c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
81633e619fcSdrh     assert( !ExprHasProperty(p, EP_FromJoin) );
817c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_MemToken) );
818ebb6a65dSdrh     assert( !ExprHasProperty(p, EP_NoReduce) );
819aecd8021Sdrh     if( p->pLeft || p->x.pList ){
82033e619fcSdrh       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
82133e619fcSdrh     }else{
822aecd8021Sdrh       assert( p->pRight==0 );
82333e619fcSdrh       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
82433e619fcSdrh     }
8256ab3a2ecSdanielk1977   }
8266ab3a2ecSdanielk1977   return nSize;
8276ab3a2ecSdanielk1977 }
8286ab3a2ecSdanielk1977 
8296ab3a2ecSdanielk1977 /*
83033e619fcSdrh ** This function returns the space in bytes required to store the copy
83133e619fcSdrh ** of the Expr structure and a copy of the Expr.u.zToken string (if that
83233e619fcSdrh ** string is defined.)
8336ab3a2ecSdanielk1977 */
8346ab3a2ecSdanielk1977 static int dupedExprNodeSize(Expr *p, int flags){
83533e619fcSdrh   int nByte = dupedExprStructSize(p, flags) & 0xfff;
83633e619fcSdrh   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83733e619fcSdrh     nByte += sqlite3Strlen30(p->u.zToken)+1;
8386ab3a2ecSdanielk1977   }
839bc73971dSdanielk1977   return ROUND8(nByte);
8406ab3a2ecSdanielk1977 }
8416ab3a2ecSdanielk1977 
8426ab3a2ecSdanielk1977 /*
8436ab3a2ecSdanielk1977 ** Return the number of bytes required to create a duplicate of the
8446ab3a2ecSdanielk1977 ** expression passed as the first argument. The second argument is a
8456ab3a2ecSdanielk1977 ** mask containing EXPRDUP_XXX flags.
8466ab3a2ecSdanielk1977 **
8476ab3a2ecSdanielk1977 ** The value returned includes space to create a copy of the Expr struct
84833e619fcSdrh ** itself and the buffer referred to by Expr.u.zToken, if any.
8496ab3a2ecSdanielk1977 **
8506ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
8516ab3a2ecSdanielk1977 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
8526ab3a2ecSdanielk1977 ** and Expr.pRight variables (but not for any structures pointed to or
8536ab3a2ecSdanielk1977 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
8546ab3a2ecSdanielk1977 */
8556ab3a2ecSdanielk1977 static int dupedExprSize(Expr *p, int flags){
8566ab3a2ecSdanielk1977   int nByte = 0;
8576ab3a2ecSdanielk1977   if( p ){
8586ab3a2ecSdanielk1977     nByte = dupedExprNodeSize(p, flags);
8596ab3a2ecSdanielk1977     if( flags&EXPRDUP_REDUCE ){
860b7916a78Sdrh       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
8616ab3a2ecSdanielk1977     }
8626ab3a2ecSdanielk1977   }
8636ab3a2ecSdanielk1977   return nByte;
8646ab3a2ecSdanielk1977 }
8656ab3a2ecSdanielk1977 
8666ab3a2ecSdanielk1977 /*
8676ab3a2ecSdanielk1977 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
8686ab3a2ecSdanielk1977 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
86933e619fcSdrh ** to store the copy of expression p, the copies of p->u.zToken
8706ab3a2ecSdanielk1977 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
87160ec914cSpeter.d.reid ** if any. Before returning, *pzBuffer is set to the first byte past the
8726ab3a2ecSdanielk1977 ** portion of the buffer copied into by this function.
8736ab3a2ecSdanielk1977 */
8746ab3a2ecSdanielk1977 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
8756ab3a2ecSdanielk1977   Expr *pNew = 0;                      /* Value to return */
87672ea29d7Sdrh   assert( flags==0 || flags==EXPRDUP_REDUCE );
877575fad65Sdrh   assert( db!=0 );
8786ab3a2ecSdanielk1977   if( p ){
8796ab3a2ecSdanielk1977     const int isReduced = (flags&EXPRDUP_REDUCE);
8806ab3a2ecSdanielk1977     u8 *zAlloc;
88133e619fcSdrh     u32 staticFlag = 0;
8826ab3a2ecSdanielk1977 
8836ab3a2ecSdanielk1977     assert( pzBuffer==0 || isReduced );
8846ab3a2ecSdanielk1977 
8856ab3a2ecSdanielk1977     /* Figure out where to write the new Expr structure. */
8866ab3a2ecSdanielk1977     if( pzBuffer ){
8876ab3a2ecSdanielk1977       zAlloc = *pzBuffer;
88833e619fcSdrh       staticFlag = EP_Static;
8896ab3a2ecSdanielk1977     }else{
890575fad65Sdrh       zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, flags));
8916ab3a2ecSdanielk1977     }
8926ab3a2ecSdanielk1977     pNew = (Expr *)zAlloc;
8936ab3a2ecSdanielk1977 
8946ab3a2ecSdanielk1977     if( pNew ){
8956ab3a2ecSdanielk1977       /* Set nNewSize to the size allocated for the structure pointed to
8966ab3a2ecSdanielk1977       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
8976ab3a2ecSdanielk1977       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
89833e619fcSdrh       ** by the copy of the p->u.zToken string (if any).
8996ab3a2ecSdanielk1977       */
90033e619fcSdrh       const unsigned nStructSize = dupedExprStructSize(p, flags);
90133e619fcSdrh       const int nNewSize = nStructSize & 0xfff;
90233e619fcSdrh       int nToken;
90333e619fcSdrh       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90433e619fcSdrh         nToken = sqlite3Strlen30(p->u.zToken) + 1;
90533e619fcSdrh       }else{
90633e619fcSdrh         nToken = 0;
90733e619fcSdrh       }
9086ab3a2ecSdanielk1977       if( isReduced ){
9096ab3a2ecSdanielk1977         assert( ExprHasProperty(p, EP_Reduced)==0 );
9106ab3a2ecSdanielk1977         memcpy(zAlloc, p, nNewSize);
9116ab3a2ecSdanielk1977       }else{
9123e6a1411Sdan         u32 nSize = (u32)exprStructSize(p);
9136ab3a2ecSdanielk1977         memcpy(zAlloc, p, nSize);
91472ea29d7Sdrh         if( nSize<EXPR_FULLSIZE ){
9156ab3a2ecSdanielk1977           memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
9166ab3a2ecSdanielk1977         }
91772ea29d7Sdrh       }
9186ab3a2ecSdanielk1977 
91933e619fcSdrh       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
920c5cd1249Sdrh       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
92133e619fcSdrh       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
92233e619fcSdrh       pNew->flags |= staticFlag;
9236ab3a2ecSdanielk1977 
92433e619fcSdrh       /* Copy the p->u.zToken string, if any. */
9256ab3a2ecSdanielk1977       if( nToken ){
92633e619fcSdrh         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
92733e619fcSdrh         memcpy(zToken, p->u.zToken, nToken);
9286ab3a2ecSdanielk1977       }
9296ab3a2ecSdanielk1977 
9306ab3a2ecSdanielk1977       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
9316ab3a2ecSdanielk1977         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
9326ab3a2ecSdanielk1977         if( ExprHasProperty(p, EP_xIsSelect) ){
9336ab3a2ecSdanielk1977           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
9346ab3a2ecSdanielk1977         }else{
9356ab3a2ecSdanielk1977           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
9366ab3a2ecSdanielk1977         }
9376ab3a2ecSdanielk1977       }
9386ab3a2ecSdanielk1977 
9396ab3a2ecSdanielk1977       /* Fill in pNew->pLeft and pNew->pRight. */
940c5cd1249Sdrh       if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
9416ab3a2ecSdanielk1977         zAlloc += dupedExprNodeSize(p, flags);
9426ab3a2ecSdanielk1977         if( ExprHasProperty(pNew, EP_Reduced) ){
9436ab3a2ecSdanielk1977           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
9446ab3a2ecSdanielk1977           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
9456ab3a2ecSdanielk1977         }
9466ab3a2ecSdanielk1977         if( pzBuffer ){
9476ab3a2ecSdanielk1977           *pzBuffer = zAlloc;
9486ab3a2ecSdanielk1977         }
949b7916a78Sdrh       }else{
950c5cd1249Sdrh         if( !ExprHasProperty(p, EP_TokenOnly) ){
9516ab3a2ecSdanielk1977           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
9526ab3a2ecSdanielk1977           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
9536ab3a2ecSdanielk1977         }
9546ab3a2ecSdanielk1977       }
955b7916a78Sdrh 
956b7916a78Sdrh     }
9576ab3a2ecSdanielk1977   }
9586ab3a2ecSdanielk1977   return pNew;
9596ab3a2ecSdanielk1977 }
9606ab3a2ecSdanielk1977 
9616ab3a2ecSdanielk1977 /*
962bfe31e7fSdan ** Create and return a deep copy of the object passed as the second
963bfe31e7fSdan ** argument. If an OOM condition is encountered, NULL is returned
964bfe31e7fSdan ** and the db->mallocFailed flag set.
965bfe31e7fSdan */
966eede6a53Sdan #ifndef SQLITE_OMIT_CTE
967bfe31e7fSdan static With *withDup(sqlite3 *db, With *p){
9684e9119d9Sdan   With *pRet = 0;
9694e9119d9Sdan   if( p ){
9704e9119d9Sdan     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
9714e9119d9Sdan     pRet = sqlite3DbMallocZero(db, nByte);
9724e9119d9Sdan     if( pRet ){
9734e9119d9Sdan       int i;
9744e9119d9Sdan       pRet->nCte = p->nCte;
9754e9119d9Sdan       for(i=0; i<p->nCte; i++){
9764e9119d9Sdan         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
9774e9119d9Sdan         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
9784e9119d9Sdan         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
9794e9119d9Sdan       }
9804e9119d9Sdan     }
9814e9119d9Sdan   }
9824e9119d9Sdan   return pRet;
9834e9119d9Sdan }
984eede6a53Sdan #else
985eede6a53Sdan # define withDup(x,y) 0
986eede6a53Sdan #endif
9874e9119d9Sdan 
988a76b5dfcSdrh /*
989ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
990ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
991ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
992ff78bd2fSdrh ** without effecting the originals.
993ff78bd2fSdrh **
9944adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
9954adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
996ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
997ff78bd2fSdrh **
998ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
9996ab3a2ecSdanielk1977 **
1000b7916a78Sdrh ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
10016ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
10026ab3a2ecSdanielk1977 ** truncated version of the usual Expr structure that will be stored as
10036ab3a2ecSdanielk1977 ** part of the in-memory representation of the database schema.
1004ff78bd2fSdrh */
10056ab3a2ecSdanielk1977 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
100672ea29d7Sdrh   assert( flags==0 || flags==EXPRDUP_REDUCE );
10076ab3a2ecSdanielk1977   return exprDup(db, p, flags, 0);
1008ff78bd2fSdrh }
10096ab3a2ecSdanielk1977 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
1010ff78bd2fSdrh   ExprList *pNew;
1011145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
1012ff78bd2fSdrh   int i;
1013575fad65Sdrh   assert( db!=0 );
1014ff78bd2fSdrh   if( p==0 ) return 0;
1015575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1016ff78bd2fSdrh   if( pNew==0 ) return 0;
1017d872bb18Sdrh   pNew->nExpr = i = p->nExpr;
1018d872bb18Sdrh   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
1019575fad65Sdrh   pNew->a = pItem = sqlite3DbMallocRawNN(db,  i*sizeof(p->a[0]) );
1020e0048400Sdanielk1977   if( pItem==0 ){
1021633e6d57Sdrh     sqlite3DbFree(db, pNew);
1022e0048400Sdanielk1977     return 0;
1023e0048400Sdanielk1977   }
1024145716b3Sdrh   pOldItem = p->a;
1025145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
10266ab3a2ecSdanielk1977     Expr *pOldExpr = pOldItem->pExpr;
1027b5526ea6Sdrh     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
102817435752Sdrh     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1029b7916a78Sdrh     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
1030145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
10313e7bc9caSdrh     pItem->done = 0;
10322c036cffSdrh     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
1033c2acc4e4Sdrh     pItem->u = pOldItem->u;
1034ff78bd2fSdrh   }
1035ff78bd2fSdrh   return pNew;
1036ff78bd2fSdrh }
103793758c8dSdanielk1977 
103893758c8dSdanielk1977 /*
103993758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
104093758c8dSdanielk1977 ** the build, then none of the following routines, except for
104193758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
104293758c8dSdanielk1977 ** called with a NULL argument.
104393758c8dSdanielk1977 */
10446a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
10456a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
10466ab3a2ecSdanielk1977 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1047ad3cab52Sdrh   SrcList *pNew;
1048ad3cab52Sdrh   int i;
1049113088ecSdrh   int nByte;
1050575fad65Sdrh   assert( db!=0 );
1051ad3cab52Sdrh   if( p==0 ) return 0;
1052113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1053575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, nByte );
1054ad3cab52Sdrh   if( pNew==0 ) return 0;
10554305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
1056ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
10574efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
10584efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
1059ed8a3bb1Sdrh     Table *pTab;
106041fb5cd1Sdan     pNewItem->pSchema = pOldItem->pSchema;
106117435752Sdrh     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
106217435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
106317435752Sdrh     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
10648a48b9c0Sdrh     pNewItem->fg = pOldItem->fg;
10654efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
10665b6a9ed4Sdrh     pNewItem->addrFillSub = pOldItem->addrFillSub;
10675b6a9ed4Sdrh     pNewItem->regReturn = pOldItem->regReturn;
10688a48b9c0Sdrh     if( pNewItem->fg.isIndexedBy ){
10698a48b9c0Sdrh       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
10708a48b9c0Sdrh     }
10718a48b9c0Sdrh     pNewItem->pIBIndex = pOldItem->pIBIndex;
10728a48b9c0Sdrh     if( pNewItem->fg.isTabFunc ){
10738a48b9c0Sdrh       pNewItem->u1.pFuncArg =
10748a48b9c0Sdrh           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
10758a48b9c0Sdrh     }
1076ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
1077ed8a3bb1Sdrh     if( pTab ){
1078ed8a3bb1Sdrh       pTab->nRef++;
1079a1cb183dSdanielk1977     }
10806ab3a2ecSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
10816ab3a2ecSdanielk1977     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
108217435752Sdrh     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
10836c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
1084ad3cab52Sdrh   }
1085ad3cab52Sdrh   return pNew;
1086ad3cab52Sdrh }
108717435752Sdrh IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1088ff78bd2fSdrh   IdList *pNew;
1089ff78bd2fSdrh   int i;
1090575fad65Sdrh   assert( db!=0 );
1091ff78bd2fSdrh   if( p==0 ) return 0;
1092575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1093ff78bd2fSdrh   if( pNew==0 ) return 0;
10946c535158Sdrh   pNew->nId = p->nId;
1095575fad65Sdrh   pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
1096d5d56523Sdanielk1977   if( pNew->a==0 ){
1097633e6d57Sdrh     sqlite3DbFree(db, pNew);
1098d5d56523Sdanielk1977     return 0;
1099d5d56523Sdanielk1977   }
11006c535158Sdrh   /* Note that because the size of the allocation for p->a[] is not
11016c535158Sdrh   ** necessarily a power of two, sqlite3IdListAppend() may not be called
11026c535158Sdrh   ** on the duplicate created by this function. */
1103ff78bd2fSdrh   for(i=0; i<p->nId; i++){
11044efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
11054efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
110617435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
11074efc4754Sdrh     pNewItem->idx = pOldItem->idx;
1108ff78bd2fSdrh   }
1109ff78bd2fSdrh   return pNew;
1110ff78bd2fSdrh }
11116ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
111223b1b372Sdrh   Select *pNew, *pPrior;
1113575fad65Sdrh   assert( db!=0 );
1114ff78bd2fSdrh   if( p==0 ) return 0;
1115575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1116ff78bd2fSdrh   if( pNew==0 ) return 0;
1117b7916a78Sdrh   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
11186ab3a2ecSdanielk1977   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
11196ab3a2ecSdanielk1977   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
11206ab3a2ecSdanielk1977   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
11216ab3a2ecSdanielk1977   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
11226ab3a2ecSdanielk1977   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1123ff78bd2fSdrh   pNew->op = p->op;
112423b1b372Sdrh   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
112523b1b372Sdrh   if( pPrior ) pPrior->pNext = pNew;
112623b1b372Sdrh   pNew->pNext = 0;
11276ab3a2ecSdanielk1977   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
11286ab3a2ecSdanielk1977   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
112992b01d53Sdrh   pNew->iLimit = 0;
113092b01d53Sdrh   pNew->iOffset = 0;
11317d10d5a6Sdrh   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1132b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
1133b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
1134ec2da854Sdrh   pNew->nSelectRow = p->nSelectRow;
11354e9119d9Sdan   pNew->pWith = withDup(db, p->pWith);
1136eb9b884cSdrh   sqlite3SelectSetName(pNew, p->zSelName);
1137ff78bd2fSdrh   return pNew;
1138ff78bd2fSdrh }
113993758c8dSdanielk1977 #else
11406ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
114193758c8dSdanielk1977   assert( p==0 );
114293758c8dSdanielk1977   return 0;
114393758c8dSdanielk1977 }
114493758c8dSdanielk1977 #endif
1145ff78bd2fSdrh 
1146ff78bd2fSdrh 
1147ff78bd2fSdrh /*
1148a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
1149a76b5dfcSdrh ** initially NULL, then create a new expression list.
1150b7916a78Sdrh **
1151b7916a78Sdrh ** If a memory allocation error occurs, the entire list is freed and
1152b7916a78Sdrh ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1153b7916a78Sdrh ** that the new entry was successfully appended.
1154a76b5dfcSdrh */
115517435752Sdrh ExprList *sqlite3ExprListAppend(
115617435752Sdrh   Parse *pParse,          /* Parsing context */
115717435752Sdrh   ExprList *pList,        /* List to which to append. Might be NULL */
1158b7916a78Sdrh   Expr *pExpr             /* Expression to be appended. Might be NULL */
115917435752Sdrh ){
116017435752Sdrh   sqlite3 *db = pParse->db;
1161575fad65Sdrh   assert( db!=0 );
1162a76b5dfcSdrh   if( pList==0 ){
1163575fad65Sdrh     pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
1164a76b5dfcSdrh     if( pList==0 ){
1165d5d56523Sdanielk1977       goto no_mem;
1166a76b5dfcSdrh     }
1167c263f7c4Sdrh     pList->nExpr = 0;
1168575fad65Sdrh     pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
1169d872bb18Sdrh     if( pList->a==0 ) goto no_mem;
1170d872bb18Sdrh   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
1171d5d56523Sdanielk1977     struct ExprList_item *a;
1172d872bb18Sdrh     assert( pList->nExpr>0 );
1173d872bb18Sdrh     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
1174d5d56523Sdanielk1977     if( a==0 ){
1175d5d56523Sdanielk1977       goto no_mem;
1176a76b5dfcSdrh     }
1177d5d56523Sdanielk1977     pList->a = a;
1178a76b5dfcSdrh   }
11794efc4754Sdrh   assert( pList->a!=0 );
1180b7916a78Sdrh   if( 1 ){
11814efc4754Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
11824efc4754Sdrh     memset(pItem, 0, sizeof(*pItem));
1183e94ddc9eSdanielk1977     pItem->pExpr = pExpr;
1184a76b5dfcSdrh   }
1185a76b5dfcSdrh   return pList;
1186d5d56523Sdanielk1977 
1187d5d56523Sdanielk1977 no_mem:
1188d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
1189633e6d57Sdrh   sqlite3ExprDelete(db, pExpr);
1190633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1191d5d56523Sdanielk1977   return 0;
1192a76b5dfcSdrh }
1193a76b5dfcSdrh 
1194a76b5dfcSdrh /*
1195bc622bc0Sdrh ** Set the sort order for the last element on the given ExprList.
1196bc622bc0Sdrh */
1197bc622bc0Sdrh void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1198bc622bc0Sdrh   if( p==0 ) return;
1199bc622bc0Sdrh   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1200bc622bc0Sdrh   assert( p->nExpr>0 );
1201bc622bc0Sdrh   if( iSortOrder<0 ){
1202bc622bc0Sdrh     assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1203bc622bc0Sdrh     return;
1204bc622bc0Sdrh   }
1205bc622bc0Sdrh   p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
1206bc622bc0Sdrh }
1207bc622bc0Sdrh 
1208bc622bc0Sdrh /*
1209b7916a78Sdrh ** Set the ExprList.a[].zName element of the most recently added item
1210b7916a78Sdrh ** on the expression list.
1211b7916a78Sdrh **
1212b7916a78Sdrh ** pList might be NULL following an OOM error.  But pName should never be
1213b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1214b7916a78Sdrh ** is set.
1215b7916a78Sdrh */
1216b7916a78Sdrh void sqlite3ExprListSetName(
1217b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1218b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1219b7916a78Sdrh   Token *pName,           /* Name to be added */
1220b7916a78Sdrh   int dequote             /* True to cause the name to be dequoted */
1221b7916a78Sdrh ){
1222b7916a78Sdrh   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1223b7916a78Sdrh   if( pList ){
1224b7916a78Sdrh     struct ExprList_item *pItem;
1225b7916a78Sdrh     assert( pList->nExpr>0 );
1226b7916a78Sdrh     pItem = &pList->a[pList->nExpr-1];
1227b7916a78Sdrh     assert( pItem->zName==0 );
1228b7916a78Sdrh     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1229b7916a78Sdrh     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
1230b7916a78Sdrh   }
1231b7916a78Sdrh }
1232b7916a78Sdrh 
1233b7916a78Sdrh /*
1234b7916a78Sdrh ** Set the ExprList.a[].zSpan element of the most recently added item
1235b7916a78Sdrh ** on the expression list.
1236b7916a78Sdrh **
1237b7916a78Sdrh ** pList might be NULL following an OOM error.  But pSpan should never be
1238b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1239b7916a78Sdrh ** is set.
1240b7916a78Sdrh */
1241b7916a78Sdrh void sqlite3ExprListSetSpan(
1242b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1243b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1244b7916a78Sdrh   ExprSpan *pSpan         /* The span to be added */
1245b7916a78Sdrh ){
1246b7916a78Sdrh   sqlite3 *db = pParse->db;
1247b7916a78Sdrh   assert( pList!=0 || db->mallocFailed!=0 );
1248b7916a78Sdrh   if( pList ){
1249b7916a78Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1250b7916a78Sdrh     assert( pList->nExpr>0 );
1251b7916a78Sdrh     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1252b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1253b7916a78Sdrh     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1254cf697396Sshane                                     (int)(pSpan->zEnd - pSpan->zStart));
1255b7916a78Sdrh   }
1256b7916a78Sdrh }
1257b7916a78Sdrh 
1258b7916a78Sdrh /*
12597a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
12607a15a4beSdanielk1977 ** leave an error message in pParse.
12617a15a4beSdanielk1977 */
12627a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
12637a15a4beSdanielk1977   Parse *pParse,
12647a15a4beSdanielk1977   ExprList *pEList,
12657a15a4beSdanielk1977   const char *zObject
12667a15a4beSdanielk1977 ){
1267b1a6c3c1Sdrh   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1268c5499befSdrh   testcase( pEList && pEList->nExpr==mx );
1269c5499befSdrh   testcase( pEList && pEList->nExpr==mx+1 );
1270b1a6c3c1Sdrh   if( pEList && pEList->nExpr>mx ){
12717a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
12727a15a4beSdanielk1977   }
12737a15a4beSdanielk1977 }
12747a15a4beSdanielk1977 
12757a15a4beSdanielk1977 /*
1276a76b5dfcSdrh ** Delete an entire expression list.
1277a76b5dfcSdrh */
1278633e6d57Sdrh void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1279a76b5dfcSdrh   int i;
1280be5c89acSdrh   struct ExprList_item *pItem;
1281a76b5dfcSdrh   if( pList==0 ) return;
1282d872bb18Sdrh   assert( pList->a!=0 || pList->nExpr==0 );
1283be5c89acSdrh   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1284633e6d57Sdrh     sqlite3ExprDelete(db, pItem->pExpr);
1285633e6d57Sdrh     sqlite3DbFree(db, pItem->zName);
1286b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1287a76b5dfcSdrh   }
1288633e6d57Sdrh   sqlite3DbFree(db, pList->a);
1289633e6d57Sdrh   sqlite3DbFree(db, pList);
1290a76b5dfcSdrh }
1291a76b5dfcSdrh 
1292a76b5dfcSdrh /*
12932308ed38Sdrh ** Return the bitwise-OR of all Expr.flags fields in the given
12942308ed38Sdrh ** ExprList.
1295885a5b03Sdrh */
12962308ed38Sdrh u32 sqlite3ExprListFlags(const ExprList *pList){
1297885a5b03Sdrh   int i;
12982308ed38Sdrh   u32 m = 0;
12992308ed38Sdrh   if( pList ){
1300885a5b03Sdrh     for(i=0; i<pList->nExpr; i++){
1301d0c73053Sdrh        Expr *pExpr = pList->a[i].pExpr;
1302de845c2fSdrh        assert( pExpr!=0 );
1303de845c2fSdrh        m |= pExpr->flags;
1304885a5b03Sdrh     }
13052308ed38Sdrh   }
13062308ed38Sdrh   return m;
1307885a5b03Sdrh }
1308885a5b03Sdrh 
1309885a5b03Sdrh /*
1310059b2d50Sdrh ** These routines are Walker callbacks used to check expressions to
1311059b2d50Sdrh ** see if they are "constant" for some definition of constant.  The
1312059b2d50Sdrh ** Walker.eCode value determines the type of "constant" we are looking
1313059b2d50Sdrh ** for.
131473b211abSdrh **
13157d10d5a6Sdrh ** These callback routines are used to implement the following:
1316626a879aSdrh **
1317059b2d50Sdrh **     sqlite3ExprIsConstant()                  pWalker->eCode==1
1318059b2d50Sdrh **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
1319fcb9f4f3Sdrh **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
1320059b2d50Sdrh **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
132187abf5c0Sdrh **
1322059b2d50Sdrh ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1323059b2d50Sdrh ** is found to not be a constant.
132487abf5c0Sdrh **
1325feada2dfSdrh ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
1326059b2d50Sdrh ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
1327059b2d50Sdrh ** an existing schema and 4 when processing a new statement.  A bound
1328feada2dfSdrh ** parameter raises an error for new statements, but is silently converted
1329feada2dfSdrh ** to NULL for existing schemas.  This allows sqlite_master tables that
1330feada2dfSdrh ** contain a bound parameter because they were generated by older versions
1331feada2dfSdrh ** of SQLite to be parsed by newer versions of SQLite without raising a
1332feada2dfSdrh ** malformed schema error.
1333626a879aSdrh */
13347d10d5a6Sdrh static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1335626a879aSdrh 
1336059b2d50Sdrh   /* If pWalker->eCode is 2 then any term of the expression that comes from
1337059b2d50Sdrh   ** the ON or USING clauses of a left join disqualifies the expression
13380a168377Sdrh   ** from being considered constant. */
1339059b2d50Sdrh   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1340059b2d50Sdrh     pWalker->eCode = 0;
13417d10d5a6Sdrh     return WRC_Abort;
13420a168377Sdrh   }
13430a168377Sdrh 
1344626a879aSdrh   switch( pExpr->op ){
1345eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
1346059b2d50Sdrh     ** and either pWalker->eCode==4 or 5 or the function has the
1347059b2d50Sdrh     ** SQLITE_FUNC_CONST flag. */
1348eb55bd2fSdrh     case TK_FUNCTION:
134963f84573Sdrh       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
1350b1fba286Sdrh         return WRC_Continue;
1351059b2d50Sdrh       }else{
1352059b2d50Sdrh         pWalker->eCode = 0;
1353059b2d50Sdrh         return WRC_Abort;
1354b1fba286Sdrh       }
1355626a879aSdrh     case TK_ID:
1356626a879aSdrh     case TK_COLUMN:
1357626a879aSdrh     case TK_AGG_FUNCTION:
135813449892Sdrh     case TK_AGG_COLUMN:
1359c5499befSdrh       testcase( pExpr->op==TK_ID );
1360c5499befSdrh       testcase( pExpr->op==TK_COLUMN );
1361c5499befSdrh       testcase( pExpr->op==TK_AGG_FUNCTION );
1362c5499befSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1363059b2d50Sdrh       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1364059b2d50Sdrh         return WRC_Continue;
1365059b2d50Sdrh       }else{
1366059b2d50Sdrh         pWalker->eCode = 0;
13677d10d5a6Sdrh         return WRC_Abort;
1368059b2d50Sdrh       }
1369feada2dfSdrh     case TK_VARIABLE:
1370059b2d50Sdrh       if( pWalker->eCode==5 ){
1371feada2dfSdrh         /* Silently convert bound parameters that appear inside of CREATE
1372feada2dfSdrh         ** statements into a NULL when parsing the CREATE statement text out
1373feada2dfSdrh         ** of the sqlite_master table */
1374feada2dfSdrh         pExpr->op = TK_NULL;
1375059b2d50Sdrh       }else if( pWalker->eCode==4 ){
1376feada2dfSdrh         /* A bound parameter in a CREATE statement that originates from
1377feada2dfSdrh         ** sqlite3_prepare() causes an error */
1378059b2d50Sdrh         pWalker->eCode = 0;
1379feada2dfSdrh         return WRC_Abort;
1380feada2dfSdrh       }
1381feada2dfSdrh       /* Fall through */
1382626a879aSdrh     default:
1383b74b1017Sdrh       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1384b74b1017Sdrh       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
13857d10d5a6Sdrh       return WRC_Continue;
1386626a879aSdrh   }
1387626a879aSdrh }
138862c14b34Sdanielk1977 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
138962c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
1390059b2d50Sdrh   pWalker->eCode = 0;
13917d10d5a6Sdrh   return WRC_Abort;
13927d10d5a6Sdrh }
1393059b2d50Sdrh static int exprIsConst(Expr *p, int initFlag, int iCur){
13947d10d5a6Sdrh   Walker w;
1395aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
1396059b2d50Sdrh   w.eCode = initFlag;
13977d10d5a6Sdrh   w.xExprCallback = exprNodeIsConstant;
13987d10d5a6Sdrh   w.xSelectCallback = selectNodeIsConstant;
1399059b2d50Sdrh   w.u.iCur = iCur;
14007d10d5a6Sdrh   sqlite3WalkExpr(&w, p);
1401059b2d50Sdrh   return w.eCode;
14027d10d5a6Sdrh }
1403626a879aSdrh 
1404626a879aSdrh /*
1405059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1406eb55bd2fSdrh ** and 0 if it involves variables or function calls.
14072398937bSdrh **
14082398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
14092398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
14102398937bSdrh ** a constant.
1411fef5208cSdrh */
14124adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
1413059b2d50Sdrh   return exprIsConst(p, 1, 0);
1414fef5208cSdrh }
1415fef5208cSdrh 
1416fef5208cSdrh /*
1417059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
14180a168377Sdrh ** that does no originate from the ON or USING clauses of a join.
14190a168377Sdrh ** Return 0 if it involves variables or function calls or terms from
14200a168377Sdrh ** an ON or USING clause.
14210a168377Sdrh */
14220a168377Sdrh int sqlite3ExprIsConstantNotJoin(Expr *p){
1423059b2d50Sdrh   return exprIsConst(p, 2, 0);
14240a168377Sdrh }
14250a168377Sdrh 
14260a168377Sdrh /*
1427fcb9f4f3Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1428059b2d50Sdrh ** for any single row of the table with cursor iCur.  In other words, the
1429059b2d50Sdrh ** expression must not refer to any non-deterministic function nor any
1430059b2d50Sdrh ** table other than iCur.
1431059b2d50Sdrh */
1432059b2d50Sdrh int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1433059b2d50Sdrh   return exprIsConst(p, 3, iCur);
1434059b2d50Sdrh }
1435059b2d50Sdrh 
1436059b2d50Sdrh /*
1437059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1438eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
1439eb55bd2fSdrh ** are any variables.
1440eb55bd2fSdrh **
1441eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
1442eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
1443eb55bd2fSdrh ** a constant.
1444eb55bd2fSdrh */
1445feada2dfSdrh int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1446feada2dfSdrh   assert( isInit==0 || isInit==1 );
1447059b2d50Sdrh   return exprIsConst(p, 4+isInit, 0);
1448eb55bd2fSdrh }
1449eb55bd2fSdrh 
14505b88bc4bSdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS
14515b88bc4bSdrh /*
14525b88bc4bSdrh ** Walk an expression tree.  Return 1 if the expression contains a
14535b88bc4bSdrh ** subquery of some kind.  Return 0 if there are no subqueries.
14545b88bc4bSdrh */
14555b88bc4bSdrh int sqlite3ExprContainsSubquery(Expr *p){
14565b88bc4bSdrh   Walker w;
14575b88bc4bSdrh   memset(&w, 0, sizeof(w));
1458bec2476aSdrh   w.eCode = 1;
14595b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
14605b88bc4bSdrh   w.xSelectCallback = selectNodeIsConstant;
14615b88bc4bSdrh   sqlite3WalkExpr(&w, p);
146207194bffSdrh   return w.eCode==0;
14635b88bc4bSdrh }
14645b88bc4bSdrh #endif
14655b88bc4bSdrh 
1466eb55bd2fSdrh /*
146773b211abSdrh ** If the expression p codes a constant integer that is small enough
1468202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
1469202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
1470202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1471e4de1febSdrh */
14724adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
147392b01d53Sdrh   int rc = 0;
1474cd92e84dSdrh 
1475cd92e84dSdrh   /* If an expression is an integer literal that fits in a signed 32-bit
1476cd92e84dSdrh   ** integer, then the EP_IntValue flag will have already been set */
1477cd92e84dSdrh   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1478cd92e84dSdrh            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1479cd92e84dSdrh 
148092b01d53Sdrh   if( p->flags & EP_IntValue ){
148133e619fcSdrh     *pValue = p->u.iValue;
1482e4de1febSdrh     return 1;
1483e4de1febSdrh   }
148492b01d53Sdrh   switch( p->op ){
14854b59ab5eSdrh     case TK_UPLUS: {
148692b01d53Sdrh       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1487f6e369a1Sdrh       break;
14884b59ab5eSdrh     }
1489e4de1febSdrh     case TK_UMINUS: {
1490e4de1febSdrh       int v;
14914adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1492f6418891Smistachkin         assert( v!=(-2147483647-1) );
1493e4de1febSdrh         *pValue = -v;
149492b01d53Sdrh         rc = 1;
1495e4de1febSdrh       }
1496e4de1febSdrh       break;
1497e4de1febSdrh     }
1498e4de1febSdrh     default: break;
1499e4de1febSdrh   }
150092b01d53Sdrh   return rc;
1501e4de1febSdrh }
1502e4de1febSdrh 
1503e4de1febSdrh /*
1504039fc32eSdrh ** Return FALSE if there is no chance that the expression can be NULL.
1505039fc32eSdrh **
1506039fc32eSdrh ** If the expression might be NULL or if the expression is too complex
1507039fc32eSdrh ** to tell return TRUE.
1508039fc32eSdrh **
1509039fc32eSdrh ** This routine is used as an optimization, to skip OP_IsNull opcodes
1510039fc32eSdrh ** when we know that a value cannot be NULL.  Hence, a false positive
1511039fc32eSdrh ** (returning TRUE when in fact the expression can never be NULL) might
1512039fc32eSdrh ** be a small performance hit but is otherwise harmless.  On the other
1513039fc32eSdrh ** hand, a false negative (returning FALSE when the result could be NULL)
1514039fc32eSdrh ** will likely result in an incorrect answer.  So when in doubt, return
1515039fc32eSdrh ** TRUE.
1516039fc32eSdrh */
1517039fc32eSdrh int sqlite3ExprCanBeNull(const Expr *p){
1518039fc32eSdrh   u8 op;
1519cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1520039fc32eSdrh   op = p->op;
1521039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
1522039fc32eSdrh   switch( op ){
1523039fc32eSdrh     case TK_INTEGER:
1524039fc32eSdrh     case TK_STRING:
1525039fc32eSdrh     case TK_FLOAT:
1526039fc32eSdrh     case TK_BLOB:
1527039fc32eSdrh       return 0;
15287248a8b2Sdrh     case TK_COLUMN:
15297248a8b2Sdrh       assert( p->pTab!=0 );
153072673a24Sdrh       return ExprHasProperty(p, EP_CanBeNull) ||
153172673a24Sdrh              (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
1532039fc32eSdrh     default:
1533039fc32eSdrh       return 1;
1534039fc32eSdrh   }
1535039fc32eSdrh }
1536039fc32eSdrh 
1537039fc32eSdrh /*
1538039fc32eSdrh ** Return TRUE if the given expression is a constant which would be
1539039fc32eSdrh ** unchanged by OP_Affinity with the affinity given in the second
1540039fc32eSdrh ** argument.
1541039fc32eSdrh **
1542039fc32eSdrh ** This routine is used to determine if the OP_Affinity operation
1543039fc32eSdrh ** can be omitted.  When in doubt return FALSE.  A false negative
1544039fc32eSdrh ** is harmless.  A false positive, however, can result in the wrong
1545039fc32eSdrh ** answer.
1546039fc32eSdrh */
1547039fc32eSdrh int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1548039fc32eSdrh   u8 op;
154905883a34Sdrh   if( aff==SQLITE_AFF_BLOB ) return 1;
1550cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1551039fc32eSdrh   op = p->op;
1552039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
1553039fc32eSdrh   switch( op ){
1554039fc32eSdrh     case TK_INTEGER: {
1555039fc32eSdrh       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1556039fc32eSdrh     }
1557039fc32eSdrh     case TK_FLOAT: {
1558039fc32eSdrh       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1559039fc32eSdrh     }
1560039fc32eSdrh     case TK_STRING: {
1561039fc32eSdrh       return aff==SQLITE_AFF_TEXT;
1562039fc32eSdrh     }
1563039fc32eSdrh     case TK_BLOB: {
1564039fc32eSdrh       return 1;
1565039fc32eSdrh     }
15662f2855b6Sdrh     case TK_COLUMN: {
156788376ca7Sdrh       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
156888376ca7Sdrh       return p->iColumn<0
15692f2855b6Sdrh           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
15702f2855b6Sdrh     }
1571039fc32eSdrh     default: {
1572039fc32eSdrh       return 0;
1573039fc32eSdrh     }
1574039fc32eSdrh   }
1575039fc32eSdrh }
1576039fc32eSdrh 
1577039fc32eSdrh /*
1578c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
1579c4a3c779Sdrh */
15804adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
15814adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
15824adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
15834adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1584c4a3c779Sdrh   return 0;
1585c4a3c779Sdrh }
1586c4a3c779Sdrh 
15879a96b668Sdanielk1977 /*
158869c355bdSdrh ** pX is the RHS of an IN operator.  If pX is a SELECT statement
158969c355bdSdrh ** that can be simplified to a direct table access, then return
159069c355bdSdrh ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
159169c355bdSdrh ** or if the SELECT statement needs to be manifested into a transient
159269c355bdSdrh ** table, then return NULL.
1593b287f4b6Sdrh */
1594b287f4b6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
159569c355bdSdrh static Select *isCandidateForInOpt(Expr *pX){
159669c355bdSdrh   Select *p;
1597b287f4b6Sdrh   SrcList *pSrc;
1598b287f4b6Sdrh   ExprList *pEList;
159969c355bdSdrh   Expr *pRes;
1600b287f4b6Sdrh   Table *pTab;
160169c355bdSdrh   if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
160269c355bdSdrh   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
160369c355bdSdrh   p = pX->x.pSelect;
1604b287f4b6Sdrh   if( p->pPrior ) return 0;              /* Not a compound SELECT */
16057d10d5a6Sdrh   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1606b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1607b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
16087d10d5a6Sdrh     return 0; /* No DISTINCT keyword and no aggregate functions */
16097d10d5a6Sdrh   }
1610b74b1017Sdrh   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
1611b287f4b6Sdrh   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
1612b74b1017Sdrh   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
1613b287f4b6Sdrh   if( p->pWhere ) return 0;              /* Has no WHERE clause */
1614b287f4b6Sdrh   pSrc = p->pSrc;
1615d1fa7bcaSdrh   assert( pSrc!=0 );
1616d1fa7bcaSdrh   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
1617b74b1017Sdrh   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
1618b287f4b6Sdrh   pTab = pSrc->a[0].pTab;
161969c355bdSdrh   assert( pTab!=0 );
1620b74b1017Sdrh   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
1621b287f4b6Sdrh   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
1622b287f4b6Sdrh   pEList = p->pEList;
1623b287f4b6Sdrh   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
162490730c9eSdrh   pRes = pEList->a[0].pExpr;
162590730c9eSdrh   if( pRes->op!=TK_COLUMN ) return 0;    /* Result is a column */
162669c355bdSdrh   assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
162769c355bdSdrh   return p;
1628b287f4b6Sdrh }
1629b287f4b6Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
1630b287f4b6Sdrh 
1631b287f4b6Sdrh /*
16321d8cb21fSdan ** Code an OP_Once instruction and allocate space for its flag. Return the
16331d8cb21fSdan ** address of the new instruction.
16341d8cb21fSdan */
16351d8cb21fSdan int sqlite3CodeOnce(Parse *pParse){
16361d8cb21fSdan   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
16371d8cb21fSdan   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
16381d8cb21fSdan }
16391d8cb21fSdan 
16401d8cb21fSdan /*
16414c259e9fSdrh ** Generate code that checks the left-most column of index table iCur to see if
16424c259e9fSdrh ** it contains any NULL entries.  Cause the register at regHasNull to be set
16436be515ebSdrh ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
16446be515ebSdrh ** to be set to NULL if iCur contains one or more NULL values.
16456be515ebSdrh */
16466be515ebSdrh static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
1647728e0f91Sdrh   int addr1;
16486be515ebSdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
1649728e0f91Sdrh   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
16506be515ebSdrh   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
16516be515ebSdrh   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
16524c259e9fSdrh   VdbeComment((v, "first_entry_in(%d)", iCur));
1653728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
16546be515ebSdrh }
16556be515ebSdrh 
1656bb53ecb1Sdrh 
1657bb53ecb1Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1658bb53ecb1Sdrh /*
1659bb53ecb1Sdrh ** The argument is an IN operator with a list (not a subquery) on the
1660bb53ecb1Sdrh ** right-hand side.  Return TRUE if that list is constant.
1661bb53ecb1Sdrh */
1662bb53ecb1Sdrh static int sqlite3InRhsIsConstant(Expr *pIn){
1663bb53ecb1Sdrh   Expr *pLHS;
1664bb53ecb1Sdrh   int res;
1665bb53ecb1Sdrh   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
1666bb53ecb1Sdrh   pLHS = pIn->pLeft;
1667bb53ecb1Sdrh   pIn->pLeft = 0;
1668bb53ecb1Sdrh   res = sqlite3ExprIsConstant(pIn);
1669bb53ecb1Sdrh   pIn->pLeft = pLHS;
1670bb53ecb1Sdrh   return res;
1671bb53ecb1Sdrh }
1672bb53ecb1Sdrh #endif
1673bb53ecb1Sdrh 
16746be515ebSdrh /*
16759a96b668Sdanielk1977 ** This function is used by the implementation of the IN (...) operator.
1676d4305ca6Sdrh ** The pX parameter is the expression on the RHS of the IN operator, which
1677d4305ca6Sdrh ** might be either a list of expressions or a subquery.
16789a96b668Sdanielk1977 **
1679d4305ca6Sdrh ** The job of this routine is to find or create a b-tree object that can
1680d4305ca6Sdrh ** be used either to test for membership in the RHS set or to iterate through
1681d4305ca6Sdrh ** all members of the RHS set, skipping duplicates.
1682d4305ca6Sdrh **
16833a85625dSdrh ** A cursor is opened on the b-tree object that is the RHS of the IN operator
1684d4305ca6Sdrh ** and pX->iTable is set to the index of that cursor.
1685d4305ca6Sdrh **
1686b74b1017Sdrh ** The returned value of this function indicates the b-tree type, as follows:
16879a96b668Sdanielk1977 **
16889a96b668Sdanielk1977 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
16891ccce449Sdrh **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
16901ccce449Sdrh **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
16919a96b668Sdanielk1977 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
16929a96b668Sdanielk1977 **                         populated epheremal table.
1693bb53ecb1Sdrh **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
1694bb53ecb1Sdrh **                         implemented as a sequence of comparisons.
16959a96b668Sdanielk1977 **
1696d4305ca6Sdrh ** An existing b-tree might be used if the RHS expression pX is a simple
1697d4305ca6Sdrh ** subquery such as:
16989a96b668Sdanielk1977 **
16999a96b668Sdanielk1977 **     SELECT <column> FROM <table>
17009a96b668Sdanielk1977 **
1701d4305ca6Sdrh ** If the RHS of the IN operator is a list or a more complex subquery, then
1702d4305ca6Sdrh ** an ephemeral table might need to be generated from the RHS and then
170360ec914cSpeter.d.reid ** pX->iTable made to point to the ephemeral table instead of an
1704d4305ca6Sdrh ** existing table.
1705d4305ca6Sdrh **
17063a85625dSdrh ** The inFlags parameter must contain exactly one of the bits
17073a85625dSdrh ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
17083a85625dSdrh ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
17093a85625dSdrh ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
17103a85625dSdrh ** IN index will be used to loop over all values of the RHS of the
17113a85625dSdrh ** IN operator.
17123a85625dSdrh **
17133a85625dSdrh ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
17143a85625dSdrh ** through the set members) then the b-tree must not contain duplicates.
17153a85625dSdrh ** An epheremal table must be used unless the selected <column> is guaranteed
17169a96b668Sdanielk1977 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
1717b74b1017Sdrh ** has a UNIQUE constraint or UNIQUE index.
17180cdc022eSdanielk1977 **
17193a85625dSdrh ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
17203a85625dSdrh ** for fast set membership tests) then an epheremal table must
17210cdc022eSdanielk1977 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
17220cdc022eSdanielk1977 ** be found with <column> as its left-most column.
17230cdc022eSdanielk1977 **
1724bb53ecb1Sdrh ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
1725bb53ecb1Sdrh ** if the RHS of the IN operator is a list (not a subquery) then this
1726bb53ecb1Sdrh ** routine might decide that creating an ephemeral b-tree for membership
1727bb53ecb1Sdrh ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
1728bb53ecb1Sdrh ** calling routine should implement the IN operator using a sequence
1729bb53ecb1Sdrh ** of Eq or Ne comparison operations.
1730bb53ecb1Sdrh **
1731b74b1017Sdrh ** When the b-tree is being used for membership tests, the calling function
17323a85625dSdrh ** might need to know whether or not the RHS side of the IN operator
1733e21a6e1dSdrh ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
17343a85625dSdrh ** if there is any chance that the (...) might contain a NULL value at
17350cdc022eSdanielk1977 ** runtime, then a register is allocated and the register number written
1736e21a6e1dSdrh ** to *prRhsHasNull. If there is no chance that the (...) contains a
1737e21a6e1dSdrh ** NULL value, then *prRhsHasNull is left unchanged.
17380cdc022eSdanielk1977 **
1739e21a6e1dSdrh ** If a register is allocated and its location stored in *prRhsHasNull, then
17406be515ebSdrh ** the value in that register will be NULL if the b-tree contains one or more
17416be515ebSdrh ** NULL values, and it will be some non-NULL value if the b-tree contains no
17426be515ebSdrh ** NULL values.
17439a96b668Sdanielk1977 */
1744284f4acaSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
1745e21a6e1dSdrh int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
1746b74b1017Sdrh   Select *p;                            /* SELECT to the right of IN operator */
1747b74b1017Sdrh   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
1748b74b1017Sdrh   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
17493a85625dSdrh   int mustBeUnique;                     /* True if RHS must be unique */
1750b8475df8Sdrh   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
17519a96b668Sdanielk1977 
17521450bc6eSdrh   assert( pX->op==TK_IN );
17533a85625dSdrh   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
17541450bc6eSdrh 
1755b74b1017Sdrh   /* Check to see if an existing table or index can be used to
1756b74b1017Sdrh   ** satisfy the query.  This is preferable to generating a new
1757b74b1017Sdrh   ** ephemeral table.
17589a96b668Sdanielk1977   */
175969c355bdSdrh   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
1760e1fb65a0Sdanielk1977     sqlite3 *db = pParse->db;              /* Database connection */
1761b07028f7Sdrh     Table *pTab;                           /* Table <table>. */
1762b07028f7Sdrh     Expr *pExpr;                           /* Expression <column> */
1763bbbdc83bSdrh     i16 iCol;                              /* Index of column <column> */
1764bbbdc83bSdrh     i16 iDb;                               /* Database idx for pTab */
1765e1fb65a0Sdanielk1977 
1766b07028f7Sdrh     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
1767b07028f7Sdrh     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
1768b07028f7Sdrh     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
1769b07028f7Sdrh     pTab = p->pSrc->a[0].pTab;
1770b07028f7Sdrh     pExpr = p->pEList->a[0].pExpr;
1771bbbdc83bSdrh     iCol = (i16)pExpr->iColumn;
1772b07028f7Sdrh 
1773b22f7c83Sdrh     /* Code an OP_Transaction and OP_TableLock for <table>. */
1774e1fb65a0Sdanielk1977     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1775e1fb65a0Sdanielk1977     sqlite3CodeVerifySchema(pParse, iDb);
1776e1fb65a0Sdanielk1977     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
17779a96b668Sdanielk1977 
17789a96b668Sdanielk1977     /* This function is only called from two places. In both cases the vdbe
17799a96b668Sdanielk1977     ** has already been allocated. So assume sqlite3GetVdbe() is always
17809a96b668Sdanielk1977     ** successful here.
17819a96b668Sdanielk1977     */
17829a96b668Sdanielk1977     assert(v);
17839a96b668Sdanielk1977     if( iCol<0 ){
17847d176105Sdrh       int iAddr = sqlite3CodeOnce(pParse);
17857d176105Sdrh       VdbeCoverage(v);
17869a96b668Sdanielk1977 
17879a96b668Sdanielk1977       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
17889a96b668Sdanielk1977       eType = IN_INDEX_ROWID;
17899a96b668Sdanielk1977 
17909a96b668Sdanielk1977       sqlite3VdbeJumpHere(v, iAddr);
17919a96b668Sdanielk1977     }else{
1792e1fb65a0Sdanielk1977       Index *pIdx;                         /* Iterator variable */
1793e1fb65a0Sdanielk1977 
17949a96b668Sdanielk1977       /* The collation sequence used by the comparison. If an index is to
17959a96b668Sdanielk1977       ** be used in place of a temp-table, it must be ordered according
1796e1fb65a0Sdanielk1977       ** to this collation sequence.  */
17979a96b668Sdanielk1977       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
17989a96b668Sdanielk1977 
17999a96b668Sdanielk1977       /* Check that the affinity that will be used to perform the
18009a96b668Sdanielk1977       ** comparison is the same as the affinity of the column. If
18019a96b668Sdanielk1977       ** it is not, it is not possible to use any index.
18029a96b668Sdanielk1977       */
1803dbaee5e3Sdrh       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
18049a96b668Sdanielk1977 
18059a96b668Sdanielk1977       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
18069a96b668Sdanielk1977         if( (pIdx->aiColumn[0]==iCol)
1807b74b1017Sdrh          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
18085f1d1d9cSdrh          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
18099a96b668Sdanielk1977         ){
18107d176105Sdrh           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
18112ec2fb22Sdrh           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
18122ec2fb22Sdrh           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1813207872a4Sdanielk1977           VdbeComment((v, "%s", pIdx->zName));
18141ccce449Sdrh           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
18151ccce449Sdrh           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
18169a96b668Sdanielk1977 
1817e21a6e1dSdrh           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
1818e21a6e1dSdrh             *prRhsHasNull = ++pParse->nMem;
18196be515ebSdrh             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
18200cdc022eSdanielk1977           }
1821552fd454Sdrh           sqlite3VdbeJumpHere(v, iAddr);
18229a96b668Sdanielk1977         }
18239a96b668Sdanielk1977       }
18249a96b668Sdanielk1977     }
18259a96b668Sdanielk1977   }
18269a96b668Sdanielk1977 
1827bb53ecb1Sdrh   /* If no preexisting index is available for the IN clause
1828bb53ecb1Sdrh   ** and IN_INDEX_NOOP is an allowed reply
1829bb53ecb1Sdrh   ** and the RHS of the IN operator is a list, not a subquery
1830bb53ecb1Sdrh   ** and the RHS is not contant or has two or fewer terms,
183160ec914cSpeter.d.reid   ** then it is not worth creating an ephemeral table to evaluate
1832bb53ecb1Sdrh   ** the IN operator so return IN_INDEX_NOOP.
1833bb53ecb1Sdrh   */
1834bb53ecb1Sdrh   if( eType==0
1835bb53ecb1Sdrh    && (inFlags & IN_INDEX_NOOP_OK)
1836bb53ecb1Sdrh    && !ExprHasProperty(pX, EP_xIsSelect)
1837bb53ecb1Sdrh    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
1838bb53ecb1Sdrh   ){
1839bb53ecb1Sdrh     eType = IN_INDEX_NOOP;
1840bb53ecb1Sdrh   }
1841bb53ecb1Sdrh 
1842bb53ecb1Sdrh 
18439a96b668Sdanielk1977   if( eType==0 ){
18444387006cSdrh     /* Could not find an existing table or index to use as the RHS b-tree.
1845b74b1017Sdrh     ** We will have to generate an ephemeral table to do the job.
1846b74b1017Sdrh     */
18478e23daf3Sdrh     u32 savedNQueryLoop = pParse->nQueryLoop;
18480cdc022eSdanielk1977     int rMayHaveNull = 0;
184941a05b7bSdanielk1977     eType = IN_INDEX_EPH;
18503a85625dSdrh     if( inFlags & IN_INDEX_LOOP ){
18514a5acf8eSdrh       pParse->nQueryLoop = 0;
1852c5cd1249Sdrh       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
185341a05b7bSdanielk1977         eType = IN_INDEX_ROWID;
18540cdc022eSdanielk1977       }
1855e21a6e1dSdrh     }else if( prRhsHasNull ){
1856e21a6e1dSdrh       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
1857cf4d38aaSdrh     }
185841a05b7bSdanielk1977     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
1859cf4d38aaSdrh     pParse->nQueryLoop = savedNQueryLoop;
18609a96b668Sdanielk1977   }else{
18619a96b668Sdanielk1977     pX->iTable = iTab;
18629a96b668Sdanielk1977   }
18639a96b668Sdanielk1977   return eType;
18649a96b668Sdanielk1977 }
1865284f4acaSdanielk1977 #endif
1866626a879aSdrh 
1867626a879aSdrh /*
1868d4187c71Sdrh ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
1869d4187c71Sdrh ** or IN operators.  Examples:
1870626a879aSdrh **
18719cbe6352Sdrh **     (SELECT a FROM b)          -- subquery
18729cbe6352Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
18739cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
18749cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
1875fef5208cSdrh **
18769cbe6352Sdrh ** The pExpr parameter describes the expression that contains the IN
18779cbe6352Sdrh ** operator or subquery.
187841a05b7bSdanielk1977 **
187941a05b7bSdanielk1977 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
188041a05b7bSdanielk1977 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
188141a05b7bSdanielk1977 ** to some integer key column of a table B-Tree. In this case, use an
188241a05b7bSdanielk1977 ** intkey B-Tree to store the set of IN(...) values instead of the usual
188341a05b7bSdanielk1977 ** (slower) variable length keys B-Tree.
1884fd773cf9Sdrh **
1885fd773cf9Sdrh ** If rMayHaveNull is non-zero, that means that the operation is an IN
1886fd773cf9Sdrh ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
18873a85625dSdrh ** All this routine does is initialize the register given by rMayHaveNull
18883a85625dSdrh ** to NULL.  Calling routines will take care of changing this register
18893a85625dSdrh ** value to non-NULL if the RHS is NULL-free.
18901450bc6eSdrh **
18911450bc6eSdrh ** For a SELECT or EXISTS operator, return the register that holds the
18921450bc6eSdrh ** result.  For IN operators or if an error occurs, the return value is 0.
1893cce7d176Sdrh */
189451522cd3Sdrh #ifndef SQLITE_OMIT_SUBQUERY
18951450bc6eSdrh int sqlite3CodeSubselect(
1896fd773cf9Sdrh   Parse *pParse,          /* Parsing context */
1897fd773cf9Sdrh   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
18986be515ebSdrh   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
1899fd773cf9Sdrh   int isRowid             /* If true, LHS of IN operator is a rowid */
190041a05b7bSdanielk1977 ){
19016be515ebSdrh   int jmpIfDynamic = -1;                      /* One-time test address */
19021450bc6eSdrh   int rReg = 0;                           /* Register storing resulting */
1903b3bce662Sdanielk1977   Vdbe *v = sqlite3GetVdbe(pParse);
19041450bc6eSdrh   if( NEVER(v==0) ) return 0;
1905ceea3321Sdrh   sqlite3ExprCachePush(pParse);
1906fc976065Sdanielk1977 
190757dbd7b3Sdrh   /* This code must be run in its entirety every time it is encountered
190857dbd7b3Sdrh   ** if any of the following is true:
190957dbd7b3Sdrh   **
191057dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
191157dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
191257dbd7b3Sdrh   **    *  We are inside a trigger
191357dbd7b3Sdrh   **
191457dbd7b3Sdrh   ** If all of the above are false, then we can run this code just once
191557dbd7b3Sdrh   ** save the results, and reuse the same result on subsequent invocations.
1916b3bce662Sdanielk1977   */
1917c5cd1249Sdrh   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
19186be515ebSdrh     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
1919b3bce662Sdanielk1977   }
1920b3bce662Sdanielk1977 
19214a07e3dbSdan #ifndef SQLITE_OMIT_EXPLAIN
19224a07e3dbSdan   if( pParse->explain==2 ){
192362aaa6caSdrh     char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
192462aaa6caSdrh         jmpIfDynamic>=0?"":"CORRELATED ",
192562aaa6caSdrh         pExpr->op==TK_IN?"LIST":"SCALAR",
192662aaa6caSdrh         pParse->iNextSelectId
19274a07e3dbSdan     );
19284a07e3dbSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
19294a07e3dbSdan   }
19304a07e3dbSdan #endif
19314a07e3dbSdan 
1932cce7d176Sdrh   switch( pExpr->op ){
1933fef5208cSdrh     case TK_IN: {
1934d4187c71Sdrh       char affinity;              /* Affinity of the LHS of the IN */
1935b9bb7c18Sdrh       int addr;                   /* Address of OP_OpenEphemeral instruction */
1936d4187c71Sdrh       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
1937323df790Sdrh       KeyInfo *pKeyInfo = 0;      /* Key information */
1938d3d39e93Sdrh 
193941a05b7bSdanielk1977       affinity = sqlite3ExprAffinity(pLeft);
1940e014a838Sdanielk1977 
1941e014a838Sdanielk1977       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
19428cff69dfSdrh       ** expression it is handled the same way.  An ephemeral table is
1943e014a838Sdanielk1977       ** filled with single-field index keys representing the results
1944e014a838Sdanielk1977       ** from the SELECT or the <exprlist>.
1945fef5208cSdrh       **
1946e014a838Sdanielk1977       ** If the 'x' expression is a column value, or the SELECT...
1947e014a838Sdanielk1977       ** statement returns a column value, then the affinity of that
1948e014a838Sdanielk1977       ** column is used to build the index keys. If both 'x' and the
1949e014a838Sdanielk1977       ** SELECT... statement are columns, then numeric affinity is used
1950e014a838Sdanielk1977       ** if either column has NUMERIC or INTEGER affinity. If neither
1951e014a838Sdanielk1977       ** 'x' nor the SELECT... statement are columns, then numeric affinity
1952e014a838Sdanielk1977       ** is used.
1953fef5208cSdrh       */
1954832508b7Sdrh       pExpr->iTable = pParse->nTab++;
195541a05b7bSdanielk1977       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
1956ad124329Sdrh       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
1957e014a838Sdanielk1977 
19586ab3a2ecSdanielk1977       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1959e014a838Sdanielk1977         /* Case 1:     expr IN (SELECT ...)
1960e014a838Sdanielk1977         **
1961e014a838Sdanielk1977         ** Generate code to write the results of the select into the temporary
1962e014a838Sdanielk1977         ** table allocated and opened above.
1963e014a838Sdanielk1977         */
19644387006cSdrh         Select *pSelect = pExpr->x.pSelect;
19651013c932Sdrh         SelectDest dest;
1966be5c89acSdrh         ExprList *pEList;
19671013c932Sdrh 
196841a05b7bSdanielk1977         assert( !isRowid );
19691013c932Sdrh         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
19702b596da8Sdrh         dest.affSdst = (u8)affinity;
1971e014a838Sdanielk1977         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
19724387006cSdrh         pSelect->iLimit = 0;
19734387006cSdrh         testcase( pSelect->selFlags & SF_Distinct );
1974812ea833Sdrh         testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
19754387006cSdrh         if( sqlite3Select(pParse, pSelect, &dest) ){
19762ec2fb22Sdrh           sqlite3KeyInfoUnref(pKeyInfo);
19771450bc6eSdrh           return 0;
197894ccde58Sdrh         }
19794387006cSdrh         pEList = pSelect->pEList;
1980812ea833Sdrh         assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
19813535ec3eSdrh         assert( pEList!=0 );
19823535ec3eSdrh         assert( pEList->nExpr>0 );
19832ec2fb22Sdrh         assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
1984323df790Sdrh         pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1985be5c89acSdrh                                                          pEList->a[0].pExpr);
1986a7d2db17Sdrh       }else if( ALWAYS(pExpr->x.pList!=0) ){
1987fef5208cSdrh         /* Case 2:     expr IN (exprlist)
1988fef5208cSdrh         **
1989e014a838Sdanielk1977         ** For each expression, build an index key from the evaluation and
1990e014a838Sdanielk1977         ** store it in the temporary table. If <expr> is a column, then use
1991e014a838Sdanielk1977         ** that columns affinity when building index keys. If <expr> is not
1992e014a838Sdanielk1977         ** a column, use numeric affinity.
1993fef5208cSdrh         */
1994e014a838Sdanielk1977         int i;
19956ab3a2ecSdanielk1977         ExprList *pList = pExpr->x.pList;
199657dbd7b3Sdrh         struct ExprList_item *pItem;
1997ecc31805Sdrh         int r1, r2, r3;
199857dbd7b3Sdrh 
1999e014a838Sdanielk1977         if( !affinity ){
200005883a34Sdrh           affinity = SQLITE_AFF_BLOB;
2001e014a838Sdanielk1977         }
2002323df790Sdrh         if( pKeyInfo ){
20032ec2fb22Sdrh           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2004323df790Sdrh           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2005323df790Sdrh         }
2006e014a838Sdanielk1977 
2007e014a838Sdanielk1977         /* Loop through each expression in <exprlist>. */
20082d401ab8Sdrh         r1 = sqlite3GetTempReg(pParse);
20092d401ab8Sdrh         r2 = sqlite3GetTempReg(pParse);
201037e08081Sdrh         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
201157dbd7b3Sdrh         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
201257dbd7b3Sdrh           Expr *pE2 = pItem->pExpr;
2013e05c929bSdrh           int iValToIns;
2014e014a838Sdanielk1977 
201557dbd7b3Sdrh           /* If the expression is not constant then we will need to
201657dbd7b3Sdrh           ** disable the test that was generated above that makes sure
201757dbd7b3Sdrh           ** this code only executes once.  Because for a non-constant
201857dbd7b3Sdrh           ** expression we need to rerun this code each time.
201957dbd7b3Sdrh           */
20206be515ebSdrh           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
20216be515ebSdrh             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
20226be515ebSdrh             jmpIfDynamic = -1;
20234794b980Sdrh           }
2024e014a838Sdanielk1977 
2025e014a838Sdanielk1977           /* Evaluate the expression and insert it into the temp table */
2026e05c929bSdrh           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2027e05c929bSdrh             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
2028e05c929bSdrh           }else{
2029ecc31805Sdrh             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
203041a05b7bSdanielk1977             if( isRowid ){
2031e05c929bSdrh               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2032e05c929bSdrh                                 sqlite3VdbeCurrentAddr(v)+2);
2033688852abSdrh               VdbeCoverage(v);
203441a05b7bSdanielk1977               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
203541a05b7bSdanielk1977             }else{
2036ecc31805Sdrh               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
20373c31fc23Sdrh               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
20382d401ab8Sdrh               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2039fef5208cSdrh             }
204041a05b7bSdanielk1977           }
2041e05c929bSdrh         }
20422d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r1);
20432d401ab8Sdrh         sqlite3ReleaseTempReg(pParse, r2);
2044fef5208cSdrh       }
2045323df790Sdrh       if( pKeyInfo ){
20462ec2fb22Sdrh         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
204741a05b7bSdanielk1977       }
2048b3bce662Sdanielk1977       break;
2049fef5208cSdrh     }
2050fef5208cSdrh 
205151522cd3Sdrh     case TK_EXISTS:
2052fd773cf9Sdrh     case TK_SELECT:
2053fd773cf9Sdrh     default: {
2054fd773cf9Sdrh       /* If this has to be a scalar SELECT.  Generate code to put the
2055fef5208cSdrh       ** value of this select in a memory cell and record the number
2056fd773cf9Sdrh       ** of the memory cell in iColumn.  If this is an EXISTS, write
2057fd773cf9Sdrh       ** an integer 0 (not exists) or 1 (exists) into a memory cell
2058fd773cf9Sdrh       ** and record that memory cell in iColumn.
2059fef5208cSdrh       */
2060fd773cf9Sdrh       Select *pSel;                         /* SELECT statement to encode */
2061fd773cf9Sdrh       SelectDest dest;                      /* How to deal with SELECt result */
20621398ad36Sdrh 
2063cf697396Sshane       testcase( pExpr->op==TK_EXISTS );
2064cf697396Sshane       testcase( pExpr->op==TK_SELECT );
2065cf697396Sshane       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
2066cf697396Sshane 
20676ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
20686ab3a2ecSdanielk1977       pSel = pExpr->x.pSelect;
20691013c932Sdrh       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
207051522cd3Sdrh       if( pExpr->op==TK_SELECT ){
20716c8c8ce0Sdanielk1977         dest.eDest = SRT_Mem;
207253932ce8Sdrh         dest.iSdst = dest.iSDParm;
20732b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
2074d4e70ebdSdrh         VdbeComment((v, "Init subquery result"));
207551522cd3Sdrh       }else{
20766c8c8ce0Sdanielk1977         dest.eDest = SRT_Exists;
20772b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
2078d4e70ebdSdrh         VdbeComment((v, "Init EXISTS result"));
207951522cd3Sdrh       }
2080633e6d57Sdrh       sqlite3ExprDelete(pParse->db, pSel->pLimit);
2081094430ebSdrh       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2082094430ebSdrh                                   &sqlite3IntTokens[1]);
208348b5b041Sdrh       pSel->iLimit = 0;
2084772460fdSdrh       pSel->selFlags &= ~SF_MultiValue;
20857d10d5a6Sdrh       if( sqlite3Select(pParse, pSel, &dest) ){
20861450bc6eSdrh         return 0;
208794ccde58Sdrh       }
20882b596da8Sdrh       rReg = dest.iSDParm;
2089ebb6a65dSdrh       ExprSetVVAProperty(pExpr, EP_NoReduce);
2090b3bce662Sdanielk1977       break;
209119a775c2Sdrh     }
2092cce7d176Sdrh   }
2093b3bce662Sdanielk1977 
20946be515ebSdrh   if( rHasNullFlag ){
20956be515ebSdrh     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
2096b3bce662Sdanielk1977   }
20976be515ebSdrh 
20986be515ebSdrh   if( jmpIfDynamic>=0 ){
20996be515ebSdrh     sqlite3VdbeJumpHere(v, jmpIfDynamic);
2100b3bce662Sdanielk1977   }
2101d2490904Sdrh   sqlite3ExprCachePop(pParse);
2102fc976065Sdanielk1977 
21031450bc6eSdrh   return rReg;
2104cce7d176Sdrh }
210551522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
2106cce7d176Sdrh 
2107e3365e6cSdrh #ifndef SQLITE_OMIT_SUBQUERY
2108e3365e6cSdrh /*
2109e3365e6cSdrh ** Generate code for an IN expression.
2110e3365e6cSdrh **
2111e3365e6cSdrh **      x IN (SELECT ...)
2112e3365e6cSdrh **      x IN (value, value, ...)
2113e3365e6cSdrh **
2114e3365e6cSdrh ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
2115e3365e6cSdrh ** is an array of zero or more values.  The expression is true if the LHS is
2116e3365e6cSdrh ** contained within the RHS.  The value of the expression is unknown (NULL)
2117e3365e6cSdrh ** if the LHS is NULL or if the LHS is not contained within the RHS and the
2118e3365e6cSdrh ** RHS contains one or more NULL values.
2119e3365e6cSdrh **
21206be515ebSdrh ** This routine generates code that jumps to destIfFalse if the LHS is not
2121e3365e6cSdrh ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
2122e3365e6cSdrh ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
2123e3365e6cSdrh ** within the RHS then fall through.
2124e3365e6cSdrh */
2125e3365e6cSdrh static void sqlite3ExprCodeIN(
2126e3365e6cSdrh   Parse *pParse,        /* Parsing and code generating context */
2127e3365e6cSdrh   Expr *pExpr,          /* The IN expression */
2128e3365e6cSdrh   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
2129e3365e6cSdrh   int destIfNull        /* Jump here if the results are unknown due to NULLs */
2130e3365e6cSdrh ){
2131e3365e6cSdrh   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
2132e3365e6cSdrh   char affinity;        /* Comparison affinity to use */
2133e3365e6cSdrh   int eType;            /* Type of the RHS */
2134e3365e6cSdrh   int r1;               /* Temporary use register */
2135e3365e6cSdrh   Vdbe *v;              /* Statement under construction */
2136e3365e6cSdrh 
2137e3365e6cSdrh   /* Compute the RHS.   After this step, the table with cursor
2138e3365e6cSdrh   ** pExpr->iTable will contains the values that make up the RHS.
2139e3365e6cSdrh   */
2140e3365e6cSdrh   v = pParse->pVdbe;
2141e3365e6cSdrh   assert( v!=0 );       /* OOM detected prior to this routine */
2142e3365e6cSdrh   VdbeNoopComment((v, "begin IN expr"));
2143bb53ecb1Sdrh   eType = sqlite3FindInIndex(pParse, pExpr,
2144bb53ecb1Sdrh                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
21453a85625dSdrh                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
2146e3365e6cSdrh 
2147e3365e6cSdrh   /* Figure out the affinity to use to create a key from the results
2148e3365e6cSdrh   ** of the expression. affinityStr stores a static string suitable for
2149e3365e6cSdrh   ** P4 of OP_MakeRecord.
2150e3365e6cSdrh   */
2151e3365e6cSdrh   affinity = comparisonAffinity(pExpr);
2152e3365e6cSdrh 
2153e3365e6cSdrh   /* Code the LHS, the <expr> from "<expr> IN (...)".
2154e3365e6cSdrh   */
2155e3365e6cSdrh   sqlite3ExprCachePush(pParse);
2156e3365e6cSdrh   r1 = sqlite3GetTempReg(pParse);
2157e3365e6cSdrh   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
2158e3365e6cSdrh 
2159bb53ecb1Sdrh   /* If sqlite3FindInIndex() did not find or create an index that is
2160bb53ecb1Sdrh   ** suitable for evaluating the IN operator, then evaluate using a
2161bb53ecb1Sdrh   ** sequence of comparisons.
2162bb53ecb1Sdrh   */
2163bb53ecb1Sdrh   if( eType==IN_INDEX_NOOP ){
2164bb53ecb1Sdrh     ExprList *pList = pExpr->x.pList;
2165bb53ecb1Sdrh     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2166bb53ecb1Sdrh     int labelOk = sqlite3VdbeMakeLabel(v);
2167bb53ecb1Sdrh     int r2, regToFree;
2168bb53ecb1Sdrh     int regCkNull = 0;
2169bb53ecb1Sdrh     int ii;
2170bb53ecb1Sdrh     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2171bb53ecb1Sdrh     if( destIfNull!=destIfFalse ){
2172bb53ecb1Sdrh       regCkNull = sqlite3GetTempReg(pParse);
2173a976979bSdrh       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
2174bb53ecb1Sdrh     }
2175bb53ecb1Sdrh     for(ii=0; ii<pList->nExpr; ii++){
2176bb53ecb1Sdrh       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
2177a976979bSdrh       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
2178bb53ecb1Sdrh         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2179bb53ecb1Sdrh       }
2180bb53ecb1Sdrh       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2181bb53ecb1Sdrh         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
21824336b0e6Sdrh                           (void*)pColl, P4_COLLSEQ);
21834336b0e6Sdrh         VdbeCoverageIf(v, ii<pList->nExpr-1);
21844336b0e6Sdrh         VdbeCoverageIf(v, ii==pList->nExpr-1);
2185bb53ecb1Sdrh         sqlite3VdbeChangeP5(v, affinity);
2186bb53ecb1Sdrh       }else{
2187bb53ecb1Sdrh         assert( destIfNull==destIfFalse );
2188bb53ecb1Sdrh         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2189bb53ecb1Sdrh                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
2190bb53ecb1Sdrh         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
2191bb53ecb1Sdrh       }
2192bb53ecb1Sdrh       sqlite3ReleaseTempReg(pParse, regToFree);
2193bb53ecb1Sdrh     }
2194bb53ecb1Sdrh     if( regCkNull ){
2195bb53ecb1Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
2196076e85f5Sdrh       sqlite3VdbeGoto(v, destIfFalse);
2197bb53ecb1Sdrh     }
2198bb53ecb1Sdrh     sqlite3VdbeResolveLabel(v, labelOk);
2199bb53ecb1Sdrh     sqlite3ReleaseTempReg(pParse, regCkNull);
2200bb53ecb1Sdrh   }else{
2201bb53ecb1Sdrh 
2202094430ebSdrh     /* If the LHS is NULL, then the result is either false or NULL depending
2203094430ebSdrh     ** on whether the RHS is empty or not, respectively.
2204094430ebSdrh     */
22057248a8b2Sdrh     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
2206094430ebSdrh       if( destIfNull==destIfFalse ){
2207094430ebSdrh         /* Shortcut for the common case where the false and NULL outcomes are
2208094430ebSdrh         ** the same. */
2209688852abSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
2210094430ebSdrh       }else{
2211688852abSdrh         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2212094430ebSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2213688852abSdrh         VdbeCoverage(v);
2214076e85f5Sdrh         sqlite3VdbeGoto(v, destIfNull);
2215094430ebSdrh         sqlite3VdbeJumpHere(v, addr1);
2216094430ebSdrh       }
22177248a8b2Sdrh     }
2218e3365e6cSdrh 
2219e3365e6cSdrh     if( eType==IN_INDEX_ROWID ){
2220e3365e6cSdrh       /* In this case, the RHS is the ROWID of table b-tree
2221e3365e6cSdrh       */
2222688852abSdrh       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
2223e3365e6cSdrh       sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
2224688852abSdrh       VdbeCoverage(v);
2225e3365e6cSdrh     }else{
2226e3365e6cSdrh       /* In this case, the RHS is an index b-tree.
2227e3365e6cSdrh       */
22288cff69dfSdrh       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
2229e3365e6cSdrh 
2230e3365e6cSdrh       /* If the set membership test fails, then the result of the
2231e3365e6cSdrh       ** "x IN (...)" expression must be either 0 or NULL. If the set
2232e3365e6cSdrh       ** contains no NULL values, then the result is 0. If the set
2233e3365e6cSdrh       ** contains one or more NULL values, then the result of the
2234e3365e6cSdrh       ** expression is also NULL.
2235e3365e6cSdrh       */
2236e80c9b9aSdrh       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
2237e80c9b9aSdrh       if( rRhsHasNull==0 ){
2238e3365e6cSdrh         /* This branch runs if it is known at compile time that the RHS
2239e3365e6cSdrh         ** cannot contain NULL values. This happens as the result
2240e3365e6cSdrh         ** of a "NOT NULL" constraint in the database schema.
2241e3365e6cSdrh         **
2242e3365e6cSdrh         ** Also run this branch if NULL is equivalent to FALSE
2243e3365e6cSdrh         ** for this particular IN operator.
2244e3365e6cSdrh         */
22458cff69dfSdrh         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
2246688852abSdrh         VdbeCoverage(v);
2247e3365e6cSdrh       }else{
2248e3365e6cSdrh         /* In this branch, the RHS of the IN might contain a NULL and
2249e3365e6cSdrh         ** the presence of a NULL on the RHS makes a difference in the
2250e3365e6cSdrh         ** outcome.
2251e3365e6cSdrh         */
2252728e0f91Sdrh         int addr1;
2253e3365e6cSdrh 
2254e3365e6cSdrh         /* First check to see if the LHS is contained in the RHS.  If so,
22556be515ebSdrh         ** then the answer is TRUE the presence of NULLs in the RHS does
22566be515ebSdrh         ** not matter.  If the LHS is not contained in the RHS, then the
22576be515ebSdrh         ** answer is NULL if the RHS contains NULLs and the answer is
22586be515ebSdrh         ** FALSE if the RHS is NULL-free.
2259e3365e6cSdrh         */
2260728e0f91Sdrh         addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
2261688852abSdrh         VdbeCoverage(v);
22626be515ebSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2263552fd454Sdrh         VdbeCoverage(v);
2264076e85f5Sdrh         sqlite3VdbeGoto(v, destIfFalse);
2265728e0f91Sdrh         sqlite3VdbeJumpHere(v, addr1);
2266e3365e6cSdrh       }
2267e3365e6cSdrh     }
2268bb53ecb1Sdrh   }
2269e3365e6cSdrh   sqlite3ReleaseTempReg(pParse, r1);
2270d2490904Sdrh   sqlite3ExprCachePop(pParse);
2271e3365e6cSdrh   VdbeComment((v, "end IN expr"));
2272e3365e6cSdrh }
2273e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
2274e3365e6cSdrh 
227513573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2276598f1340Sdrh /*
2277598f1340Sdrh ** Generate an instruction that will put the floating point
22789cbf3425Sdrh ** value described by z[0..n-1] into register iMem.
22790cf19ed8Sdrh **
22800cf19ed8Sdrh ** The z[] string will probably not be zero-terminated.  But the
22810cf19ed8Sdrh ** z[n] character is guaranteed to be something that does not look
22820cf19ed8Sdrh ** like the continuation of the number.
2283598f1340Sdrh */
2284b7916a78Sdrh static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
2285fd773cf9Sdrh   if( ALWAYS(z!=0) ){
2286598f1340Sdrh     double value;
22879339da1fSdrh     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
2288d0015161Sdrh     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2289598f1340Sdrh     if( negateFlag ) value = -value;
229097bae794Sdrh     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
2291598f1340Sdrh   }
2292598f1340Sdrh }
229313573c71Sdrh #endif
2294598f1340Sdrh 
2295598f1340Sdrh 
2296598f1340Sdrh /*
2297fec19aadSdrh ** Generate an instruction that will put the integer describe by
22989cbf3425Sdrh ** text z[0..n-1] into register iMem.
22990cf19ed8Sdrh **
23005f1d6b61Sshaneh ** Expr.u.zToken is always UTF8 and zero-terminated.
2301fec19aadSdrh */
230213573c71Sdrh static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
230313573c71Sdrh   Vdbe *v = pParse->pVdbe;
230492b01d53Sdrh   if( pExpr->flags & EP_IntValue ){
230533e619fcSdrh     int i = pExpr->u.iValue;
2306d50ffc41Sdrh     assert( i>=0 );
230792b01d53Sdrh     if( negFlag ) i = -i;
230892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
2309fd773cf9Sdrh   }else{
23105f1d6b61Sshaneh     int c;
23115f1d6b61Sshaneh     i64 value;
2312fd773cf9Sdrh     const char *z = pExpr->u.zToken;
2313fd773cf9Sdrh     assert( z!=0 );
23149296c18aSdrh     c = sqlite3DecOrHexToI64(z, &value);
23155f1d6b61Sshaneh     if( c==0 || (c==2 && negFlag) ){
2316158b9cb9Sdrh       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
231797bae794Sdrh       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
2318fec19aadSdrh     }else{
231913573c71Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
232013573c71Sdrh       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
232113573c71Sdrh #else
23221b7ddc59Sdrh #ifndef SQLITE_OMIT_HEX_INTEGER
23239296c18aSdrh       if( sqlite3_strnicmp(z,"0x",2)==0 ){
23249296c18aSdrh         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
23251b7ddc59Sdrh       }else
23261b7ddc59Sdrh #endif
23271b7ddc59Sdrh       {
2328b7916a78Sdrh         codeReal(v, z, negFlag, iMem);
23299296c18aSdrh       }
233013573c71Sdrh #endif
2331fec19aadSdrh     }
2332fec19aadSdrh   }
2333c9cf901dSdanielk1977 }
2334fec19aadSdrh 
2335ceea3321Sdrh /*
2336ceea3321Sdrh ** Clear a cache entry.
2337ceea3321Sdrh */
2338ceea3321Sdrh static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2339ceea3321Sdrh   if( p->tempReg ){
2340ceea3321Sdrh     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2341ceea3321Sdrh       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2342ceea3321Sdrh     }
2343ceea3321Sdrh     p->tempReg = 0;
2344ceea3321Sdrh   }
2345ceea3321Sdrh }
2346ceea3321Sdrh 
2347ceea3321Sdrh 
2348ceea3321Sdrh /*
2349ceea3321Sdrh ** Record in the column cache that a particular column from a
2350ceea3321Sdrh ** particular table is stored in a particular register.
2351ceea3321Sdrh */
2352ceea3321Sdrh void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2353ceea3321Sdrh   int i;
2354ceea3321Sdrh   int minLru;
2355ceea3321Sdrh   int idxLru;
2356ceea3321Sdrh   struct yColCache *p;
2357ceea3321Sdrh 
2358ce8f53d4Sdan   /* Unless an error has occurred, register numbers are always positive. */
2359ce8f53d4Sdan   assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
236020411ea7Sdrh   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
236120411ea7Sdrh 
2362b6da74ebSdrh   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
2363b6da74ebSdrh   ** for testing only - to verify that SQLite always gets the same answer
2364b6da74ebSdrh   ** with and without the column cache.
2365b6da74ebSdrh   */
23667e5418e4Sdrh   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
2367b6da74ebSdrh 
236827ee406eSdrh   /* First replace any existing entry.
236927ee406eSdrh   **
237027ee406eSdrh   ** Actually, the way the column cache is currently used, we are guaranteed
237127ee406eSdrh   ** that the object will never already be in cache.  Verify this guarantee.
237227ee406eSdrh   */
237327ee406eSdrh #ifndef NDEBUG
2374ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
237527ee406eSdrh     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
2376ceea3321Sdrh   }
237727ee406eSdrh #endif
2378ceea3321Sdrh 
2379ceea3321Sdrh   /* Find an empty slot and replace it */
2380ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2381ceea3321Sdrh     if( p->iReg==0 ){
2382ceea3321Sdrh       p->iLevel = pParse->iCacheLevel;
2383ceea3321Sdrh       p->iTable = iTab;
2384ceea3321Sdrh       p->iColumn = iCol;
2385ceea3321Sdrh       p->iReg = iReg;
2386ceea3321Sdrh       p->tempReg = 0;
2387ceea3321Sdrh       p->lru = pParse->iCacheCnt++;
2388ceea3321Sdrh       return;
2389ceea3321Sdrh     }
2390ceea3321Sdrh   }
2391ceea3321Sdrh 
2392ceea3321Sdrh   /* Replace the last recently used */
2393ceea3321Sdrh   minLru = 0x7fffffff;
2394ceea3321Sdrh   idxLru = -1;
2395ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2396ceea3321Sdrh     if( p->lru<minLru ){
2397ceea3321Sdrh       idxLru = i;
2398ceea3321Sdrh       minLru = p->lru;
2399ceea3321Sdrh     }
2400ceea3321Sdrh   }
240120411ea7Sdrh   if( ALWAYS(idxLru>=0) ){
2402ceea3321Sdrh     p = &pParse->aColCache[idxLru];
2403ceea3321Sdrh     p->iLevel = pParse->iCacheLevel;
2404ceea3321Sdrh     p->iTable = iTab;
2405ceea3321Sdrh     p->iColumn = iCol;
2406ceea3321Sdrh     p->iReg = iReg;
2407ceea3321Sdrh     p->tempReg = 0;
2408ceea3321Sdrh     p->lru = pParse->iCacheCnt++;
2409ceea3321Sdrh     return;
2410ceea3321Sdrh   }
2411ceea3321Sdrh }
2412ceea3321Sdrh 
2413ceea3321Sdrh /*
2414f49f3523Sdrh ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2415f49f3523Sdrh ** Purge the range of registers from the column cache.
2416ceea3321Sdrh */
2417f49f3523Sdrh void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
2418ceea3321Sdrh   int i;
2419f49f3523Sdrh   int iLast = iReg + nReg - 1;
2420ceea3321Sdrh   struct yColCache *p;
2421ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2422f49f3523Sdrh     int r = p->iReg;
2423f49f3523Sdrh     if( r>=iReg && r<=iLast ){
2424ceea3321Sdrh       cacheEntryClear(pParse, p);
2425ceea3321Sdrh       p->iReg = 0;
2426ceea3321Sdrh     }
2427ceea3321Sdrh   }
2428ceea3321Sdrh }
2429ceea3321Sdrh 
2430ceea3321Sdrh /*
2431ceea3321Sdrh ** Remember the current column cache context.  Any new entries added
2432ceea3321Sdrh ** added to the column cache after this call are removed when the
2433ceea3321Sdrh ** corresponding pop occurs.
2434ceea3321Sdrh */
2435ceea3321Sdrh void sqlite3ExprCachePush(Parse *pParse){
2436ceea3321Sdrh   pParse->iCacheLevel++;
24379ac7962aSdrh #ifdef SQLITE_DEBUG
24389ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
24399ac7962aSdrh     printf("PUSH to %d\n", pParse->iCacheLevel);
24409ac7962aSdrh   }
24419ac7962aSdrh #endif
2442ceea3321Sdrh }
2443ceea3321Sdrh 
2444ceea3321Sdrh /*
2445ceea3321Sdrh ** Remove from the column cache any entries that were added since the
2446d2490904Sdrh ** the previous sqlite3ExprCachePush operation.  In other words, restore
2447d2490904Sdrh ** the cache to the state it was in prior the most recent Push.
2448ceea3321Sdrh */
2449d2490904Sdrh void sqlite3ExprCachePop(Parse *pParse){
2450ceea3321Sdrh   int i;
2451ceea3321Sdrh   struct yColCache *p;
2452d2490904Sdrh   assert( pParse->iCacheLevel>=1 );
2453d2490904Sdrh   pParse->iCacheLevel--;
24549ac7962aSdrh #ifdef SQLITE_DEBUG
24559ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
24569ac7962aSdrh     printf("POP  to %d\n", pParse->iCacheLevel);
24579ac7962aSdrh   }
24589ac7962aSdrh #endif
2459ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2460ceea3321Sdrh     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2461ceea3321Sdrh       cacheEntryClear(pParse, p);
2462ceea3321Sdrh       p->iReg = 0;
2463ceea3321Sdrh     }
2464ceea3321Sdrh   }
2465ceea3321Sdrh }
2466945498f3Sdrh 
2467945498f3Sdrh /*
24685cd79239Sdrh ** When a cached column is reused, make sure that its register is
24695cd79239Sdrh ** no longer available as a temp register.  ticket #3879:  that same
24705cd79239Sdrh ** register might be in the cache in multiple places, so be sure to
24715cd79239Sdrh ** get them all.
24725cd79239Sdrh */
24735cd79239Sdrh static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
24745cd79239Sdrh   int i;
24755cd79239Sdrh   struct yColCache *p;
24765cd79239Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
24775cd79239Sdrh     if( p->iReg==iReg ){
24785cd79239Sdrh       p->tempReg = 0;
24795cd79239Sdrh     }
24805cd79239Sdrh   }
24815cd79239Sdrh }
24825cd79239Sdrh 
24831f9ca2c8Sdrh /* Generate code that will load into register regOut a value that is
24841f9ca2c8Sdrh ** appropriate for the iIdxCol-th column of index pIdx.
24851f9ca2c8Sdrh */
24861f9ca2c8Sdrh void sqlite3ExprCodeLoadIndexColumn(
24871f9ca2c8Sdrh   Parse *pParse,  /* The parsing context */
24881f9ca2c8Sdrh   Index *pIdx,    /* The index whose column is to be loaded */
24891f9ca2c8Sdrh   int iTabCur,    /* Cursor pointing to a table row */
24901f9ca2c8Sdrh   int iIdxCol,    /* The column of the index to be loaded */
24911f9ca2c8Sdrh   int regOut      /* Store the index column value in this register */
24921f9ca2c8Sdrh ){
24931f9ca2c8Sdrh   i16 iTabCol = pIdx->aiColumn[iIdxCol];
24944b92f98cSdrh   if( iTabCol==XN_EXPR ){
24951f9ca2c8Sdrh     assert( pIdx->aColExpr );
24961f9ca2c8Sdrh     assert( pIdx->aColExpr->nExpr>iIdxCol );
24971f9ca2c8Sdrh     pParse->iSelfTab = iTabCur;
24981c75c9d7Sdrh     sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
24994b92f98cSdrh   }else{
25004b92f98cSdrh     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
25014b92f98cSdrh                                     iTabCol, regOut);
25024b92f98cSdrh   }
25031f9ca2c8Sdrh }
25041f9ca2c8Sdrh 
25055cd79239Sdrh /*
25065c092e8aSdrh ** Generate code to extract the value of the iCol-th column of a table.
25075c092e8aSdrh */
25085c092e8aSdrh void sqlite3ExprCodeGetColumnOfTable(
25095c092e8aSdrh   Vdbe *v,        /* The VDBE under construction */
25105c092e8aSdrh   Table *pTab,    /* The table containing the value */
2511313619f5Sdrh   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
25125c092e8aSdrh   int iCol,       /* Index of the column to extract */
2513313619f5Sdrh   int regOut      /* Extract the value into this register */
25145c092e8aSdrh ){
25155c092e8aSdrh   if( iCol<0 || iCol==pTab->iPKey ){
25165c092e8aSdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
25175c092e8aSdrh   }else{
25185c092e8aSdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
2519ee0ec8e1Sdrh     int x = iCol;
2520ee0ec8e1Sdrh     if( !HasRowid(pTab) ){
2521ee0ec8e1Sdrh       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
2522ee0ec8e1Sdrh     }
2523ee0ec8e1Sdrh     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
25245c092e8aSdrh   }
25255c092e8aSdrh   if( iCol>=0 ){
25265c092e8aSdrh     sqlite3ColumnDefault(v, pTab, iCol, regOut);
25275c092e8aSdrh   }
25285c092e8aSdrh }
25295c092e8aSdrh 
25305c092e8aSdrh /*
2531945498f3Sdrh ** Generate code that will extract the iColumn-th column from
2532ce78bc6eSdrh ** table pTab and store the column value in a register.
2533ce78bc6eSdrh **
2534ce78bc6eSdrh ** An effort is made to store the column value in register iReg.  This
2535ce78bc6eSdrh ** is not garanteeed for GetColumn() - the result can be stored in
2536ce78bc6eSdrh ** any register.  But the result is guaranteed to land in register iReg
2537ce78bc6eSdrh ** for GetColumnToReg().
2538e55cbd72Sdrh **
2539e55cbd72Sdrh ** There must be an open cursor to pTab in iTable when this routine
2540e55cbd72Sdrh ** is called.  If iColumn<0 then code is generated that extracts the rowid.
2541945498f3Sdrh */
2542e55cbd72Sdrh int sqlite3ExprCodeGetColumn(
2543e55cbd72Sdrh   Parse *pParse,   /* Parsing and code generating context */
25442133d822Sdrh   Table *pTab,     /* Description of the table we are reading from */
25452133d822Sdrh   int iColumn,     /* Index of the table column */
25462133d822Sdrh   int iTable,      /* The cursor pointing to the table */
2547a748fdccSdrh   int iReg,        /* Store results here */
2548ce78bc6eSdrh   u8 p5            /* P5 value for OP_Column + FLAGS */
25492133d822Sdrh ){
2550e55cbd72Sdrh   Vdbe *v = pParse->pVdbe;
2551e55cbd72Sdrh   int i;
2552da250ea5Sdrh   struct yColCache *p;
2553e55cbd72Sdrh 
2554ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2555b6da74ebSdrh     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
2556ceea3321Sdrh       p->lru = pParse->iCacheCnt++;
25575cd79239Sdrh       sqlite3ExprCachePinRegister(pParse, p->iReg);
2558da250ea5Sdrh       return p->iReg;
2559e55cbd72Sdrh     }
2560e55cbd72Sdrh   }
2561e55cbd72Sdrh   assert( v!=0 );
25625c092e8aSdrh   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
2563a748fdccSdrh   if( p5 ){
2564a748fdccSdrh     sqlite3VdbeChangeP5(v, p5);
2565a748fdccSdrh   }else{
2566ceea3321Sdrh     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2567a748fdccSdrh   }
2568e55cbd72Sdrh   return iReg;
2569e55cbd72Sdrh }
2570ce78bc6eSdrh void sqlite3ExprCodeGetColumnToReg(
2571ce78bc6eSdrh   Parse *pParse,   /* Parsing and code generating context */
2572ce78bc6eSdrh   Table *pTab,     /* Description of the table we are reading from */
2573ce78bc6eSdrh   int iColumn,     /* Index of the table column */
2574ce78bc6eSdrh   int iTable,      /* The cursor pointing to the table */
2575ce78bc6eSdrh   int iReg         /* Store results here */
2576ce78bc6eSdrh ){
2577ce78bc6eSdrh   int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
2578ce78bc6eSdrh   if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
2579ce78bc6eSdrh }
2580ce78bc6eSdrh 
2581e55cbd72Sdrh 
2582e55cbd72Sdrh /*
2583ceea3321Sdrh ** Clear all column cache entries.
2584e55cbd72Sdrh */
2585ceea3321Sdrh void sqlite3ExprCacheClear(Parse *pParse){
2586e55cbd72Sdrh   int i;
2587ceea3321Sdrh   struct yColCache *p;
2588ceea3321Sdrh 
25899ac7962aSdrh #if SQLITE_DEBUG
25909ac7962aSdrh   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
25919ac7962aSdrh     printf("CLEAR\n");
25929ac7962aSdrh   }
25939ac7962aSdrh #endif
2594ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2595ceea3321Sdrh     if( p->iReg ){
2596ceea3321Sdrh       cacheEntryClear(pParse, p);
2597ceea3321Sdrh       p->iReg = 0;
2598e55cbd72Sdrh     }
2599da250ea5Sdrh   }
2600da250ea5Sdrh }
2601e55cbd72Sdrh 
2602e55cbd72Sdrh /*
2603da250ea5Sdrh ** Record the fact that an affinity change has occurred on iCount
2604da250ea5Sdrh ** registers starting with iStart.
2605e55cbd72Sdrh */
2606da250ea5Sdrh void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2607f49f3523Sdrh   sqlite3ExprCacheRemove(pParse, iStart, iCount);
2608e55cbd72Sdrh }
2609e55cbd72Sdrh 
2610e55cbd72Sdrh /*
2611b21e7c70Sdrh ** Generate code to move content from registers iFrom...iFrom+nReg-1
2612b21e7c70Sdrh ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
2613e55cbd72Sdrh */
2614b21e7c70Sdrh void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
2615e8e4af76Sdrh   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
2616079a3072Sdrh   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
2617236241aeSdrh   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
2618945498f3Sdrh }
2619945498f3Sdrh 
2620f49f3523Sdrh #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
262192b01d53Sdrh /*
2622652fbf55Sdrh ** Return true if any register in the range iFrom..iTo (inclusive)
2623652fbf55Sdrh ** is used as part of the column cache.
2624f49f3523Sdrh **
2625f49f3523Sdrh ** This routine is used within assert() and testcase() macros only
2626f49f3523Sdrh ** and does not appear in a normal build.
2627652fbf55Sdrh */
2628652fbf55Sdrh static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2629652fbf55Sdrh   int i;
2630ceea3321Sdrh   struct yColCache *p;
2631ceea3321Sdrh   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2632ceea3321Sdrh     int r = p->iReg;
2633f49f3523Sdrh     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
2634652fbf55Sdrh   }
2635652fbf55Sdrh   return 0;
2636652fbf55Sdrh }
2637f49f3523Sdrh #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
2638652fbf55Sdrh 
2639652fbf55Sdrh /*
2640a4c3c87eSdrh ** Convert an expression node to a TK_REGISTER
2641a4c3c87eSdrh */
2642a4c3c87eSdrh static void exprToRegister(Expr *p, int iReg){
2643a4c3c87eSdrh   p->op2 = p->op;
2644a4c3c87eSdrh   p->op = TK_REGISTER;
2645a4c3c87eSdrh   p->iTable = iReg;
2646a4c3c87eSdrh   ExprClearProperty(p, EP_Skip);
2647a4c3c87eSdrh }
2648a4c3c87eSdrh 
2649a4c3c87eSdrh /*
2650cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
26512dcef11bSdrh ** expression.  Attempt to store the results in register "target".
26522dcef11bSdrh ** Return the register where results are stored.
2653389a1adbSdrh **
26548b213899Sdrh ** With this routine, there is no guarantee that results will
26552dcef11bSdrh ** be stored in target.  The result might be stored in some other
26562dcef11bSdrh ** register if it is convenient to do so.  The calling function
26572dcef11bSdrh ** must check the return code and move the results to the desired
26582dcef11bSdrh ** register.
2659cce7d176Sdrh */
2660678ccce8Sdrh int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
26612dcef11bSdrh   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
26622dcef11bSdrh   int op;                   /* The opcode being coded */
26632dcef11bSdrh   int inReg = target;       /* Results stored in register inReg */
26642dcef11bSdrh   int regFree1 = 0;         /* If non-zero free this temporary register */
26652dcef11bSdrh   int regFree2 = 0;         /* If non-zero free this temporary register */
2666678ccce8Sdrh   int r1, r2, r3, r4;       /* Various register numbers */
266720411ea7Sdrh   sqlite3 *db = pParse->db; /* The database connection */
266810d1edf0Sdrh   Expr tempX;               /* Temporary expression node */
2669ffe07b2dSdrh 
26709cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
267120411ea7Sdrh   if( v==0 ){
267220411ea7Sdrh     assert( pParse->db->mallocFailed );
267320411ea7Sdrh     return 0;
267420411ea7Sdrh   }
2675389a1adbSdrh 
2676389a1adbSdrh   if( pExpr==0 ){
2677389a1adbSdrh     op = TK_NULL;
2678389a1adbSdrh   }else{
2679f2bc013cSdrh     op = pExpr->op;
2680389a1adbSdrh   }
2681f2bc013cSdrh   switch( op ){
268213449892Sdrh     case TK_AGG_COLUMN: {
268313449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
268413449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
268513449892Sdrh       if( !pAggInfo->directMode ){
26869de221dfSdrh         assert( pCol->iMem>0 );
26879de221dfSdrh         inReg = pCol->iMem;
268813449892Sdrh         break;
268913449892Sdrh       }else if( pAggInfo->useSortingIdx ){
26905134d135Sdan         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
2691389a1adbSdrh                               pCol->iSorterColumn, target);
269213449892Sdrh         break;
269313449892Sdrh       }
269413449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
269513449892Sdrh     }
2696967e8b73Sdrh     case TK_COLUMN: {
2697b2b9d3d7Sdrh       int iTab = pExpr->iTable;
2698b2b9d3d7Sdrh       if( iTab<0 ){
2699b2b9d3d7Sdrh         if( pParse->ckBase>0 ){
2700b2b9d3d7Sdrh           /* Generating CHECK constraints or inserting into partial index */
2701aa9b8963Sdrh           inReg = pExpr->iColumn + pParse->ckBase;
2702b2b9d3d7Sdrh           break;
2703c4a3c779Sdrh         }else{
27041f9ca2c8Sdrh           /* Coding an expression that is part of an index where column names
27051f9ca2c8Sdrh           ** in the index refer to the table to which the index belongs */
27061f9ca2c8Sdrh           iTab = pParse->iSelfTab;
27072282792aSdrh         }
2708b2b9d3d7Sdrh       }
2709b2b9d3d7Sdrh       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2710b2b9d3d7Sdrh                                pExpr->iColumn, iTab, target,
2711b2b9d3d7Sdrh                                pExpr->op2);
2712cce7d176Sdrh       break;
2713cce7d176Sdrh     }
2714cce7d176Sdrh     case TK_INTEGER: {
271513573c71Sdrh       codeInteger(pParse, pExpr, 0, target);
2716fec19aadSdrh       break;
271751e9a445Sdrh     }
271813573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2719598f1340Sdrh     case TK_FLOAT: {
272033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
272133e619fcSdrh       codeReal(v, pExpr->u.zToken, 0, target);
2722598f1340Sdrh       break;
2723598f1340Sdrh     }
272413573c71Sdrh #endif
2725fec19aadSdrh     case TK_STRING: {
272633e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
2727076e85f5Sdrh       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
2728cce7d176Sdrh       break;
2729cce7d176Sdrh     }
2730f0863fe5Sdrh     case TK_NULL: {
27319de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2732f0863fe5Sdrh       break;
2733f0863fe5Sdrh     }
27345338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
2735c572ef7fSdanielk1977     case TK_BLOB: {
27366c8c6cecSdrh       int n;
27376c8c6cecSdrh       const char *z;
2738ca48c90fSdrh       char *zBlob;
273933e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
274033e619fcSdrh       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
274133e619fcSdrh       assert( pExpr->u.zToken[1]=='\'' );
274233e619fcSdrh       z = &pExpr->u.zToken[2];
2743b7916a78Sdrh       n = sqlite3Strlen30(z) - 1;
2744b7916a78Sdrh       assert( z[n]=='\'' );
2745ca48c90fSdrh       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2746ca48c90fSdrh       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2747c572ef7fSdanielk1977       break;
2748c572ef7fSdanielk1977     }
27495338a5f7Sdanielk1977 #endif
275050457896Sdrh     case TK_VARIABLE: {
275133e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
275233e619fcSdrh       assert( pExpr->u.zToken!=0 );
275333e619fcSdrh       assert( pExpr->u.zToken[0]!=0 );
2754eaf52d88Sdrh       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
275533e619fcSdrh       if( pExpr->u.zToken[1]!=0 ){
275604e9eeadSdrh         assert( pExpr->u.zToken[0]=='?'
275704e9eeadSdrh              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
275804e9eeadSdrh         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
2759895d7472Sdrh       }
276050457896Sdrh       break;
276150457896Sdrh     }
27624e0cff60Sdrh     case TK_REGISTER: {
27639de221dfSdrh       inReg = pExpr->iTable;
27644e0cff60Sdrh       break;
27654e0cff60Sdrh     }
2766487e262fSdrh #ifndef SQLITE_OMIT_CAST
2767487e262fSdrh     case TK_CAST: {
2768487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
27692dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
27701735fa88Sdrh       if( inReg!=target ){
27711735fa88Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
27721735fa88Sdrh         inReg = target;
27731735fa88Sdrh       }
27744169e430Sdrh       sqlite3VdbeAddOp2(v, OP_Cast, target,
27754169e430Sdrh                         sqlite3AffinityType(pExpr->u.zToken, 0));
2776c5499befSdrh       testcase( usedAsColumnCache(pParse, inReg, inReg) );
2777b3843a82Sdrh       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
2778487e262fSdrh       break;
2779487e262fSdrh     }
2780487e262fSdrh #endif /* SQLITE_OMIT_CAST */
2781c9b84a1fSdrh     case TK_LT:
2782c9b84a1fSdrh     case TK_LE:
2783c9b84a1fSdrh     case TK_GT:
2784c9b84a1fSdrh     case TK_GE:
2785c9b84a1fSdrh     case TK_NE:
2786c9b84a1fSdrh     case TK_EQ: {
2787b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2788b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
278935573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
279035573356Sdrh                   r1, r2, inReg, SQLITE_STOREP2);
27917d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
27927d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
27937d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
27947d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
27957d176105Sdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
27967d176105Sdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
2797c5499befSdrh       testcase( regFree1==0 );
2798c5499befSdrh       testcase( regFree2==0 );
2799a37cdde0Sdanielk1977       break;
2800c9b84a1fSdrh     }
28016a2fe093Sdrh     case TK_IS:
28026a2fe093Sdrh     case TK_ISNOT: {
28036a2fe093Sdrh       testcase( op==TK_IS );
28046a2fe093Sdrh       testcase( op==TK_ISNOT );
2805b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2806b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
28076a2fe093Sdrh       op = (op==TK_IS) ? TK_EQ : TK_NE;
28086a2fe093Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
28096a2fe093Sdrh                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
28107d176105Sdrh       VdbeCoverageIf(v, op==TK_EQ);
28117d176105Sdrh       VdbeCoverageIf(v, op==TK_NE);
28126a2fe093Sdrh       testcase( regFree1==0 );
28136a2fe093Sdrh       testcase( regFree2==0 );
28146a2fe093Sdrh       break;
28156a2fe093Sdrh     }
2816cce7d176Sdrh     case TK_AND:
2817cce7d176Sdrh     case TK_OR:
2818cce7d176Sdrh     case TK_PLUS:
2819cce7d176Sdrh     case TK_STAR:
2820cce7d176Sdrh     case TK_MINUS:
2821bf4133cbSdrh     case TK_REM:
2822bf4133cbSdrh     case TK_BITAND:
2823bf4133cbSdrh     case TK_BITOR:
282417c40294Sdrh     case TK_SLASH:
2825bf4133cbSdrh     case TK_LSHIFT:
2826855eb1cfSdrh     case TK_RSHIFT:
28270040077dSdrh     case TK_CONCAT: {
28287d176105Sdrh       assert( TK_AND==OP_And );            testcase( op==TK_AND );
28297d176105Sdrh       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
28307d176105Sdrh       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
28317d176105Sdrh       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
28327d176105Sdrh       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
28337d176105Sdrh       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
28347d176105Sdrh       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
28357d176105Sdrh       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
28367d176105Sdrh       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
28377d176105Sdrh       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
28387d176105Sdrh       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
28392dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
28402dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
28415b6afba9Sdrh       sqlite3VdbeAddOp3(v, op, r2, r1, target);
2842c5499befSdrh       testcase( regFree1==0 );
2843c5499befSdrh       testcase( regFree2==0 );
28440040077dSdrh       break;
28450040077dSdrh     }
2846cce7d176Sdrh     case TK_UMINUS: {
2847fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
2848fec19aadSdrh       assert( pLeft );
284913573c71Sdrh       if( pLeft->op==TK_INTEGER ){
285013573c71Sdrh         codeInteger(pParse, pLeft, 1, target);
285113573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
285213573c71Sdrh       }else if( pLeft->op==TK_FLOAT ){
285333e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
285433e619fcSdrh         codeReal(v, pLeft->u.zToken, 1, target);
285513573c71Sdrh #endif
28563c84ddffSdrh       }else{
285710d1edf0Sdrh         tempX.op = TK_INTEGER;
285810d1edf0Sdrh         tempX.flags = EP_IntValue|EP_TokenOnly;
285910d1edf0Sdrh         tempX.u.iValue = 0;
286010d1edf0Sdrh         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
2861e55cbd72Sdrh         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
28622dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
2863c5499befSdrh         testcase( regFree2==0 );
28643c84ddffSdrh       }
28659de221dfSdrh       inReg = target;
28666e142f54Sdrh       break;
28676e142f54Sdrh     }
2868bf4133cbSdrh     case TK_BITNOT:
28696e142f54Sdrh     case TK_NOT: {
28707d176105Sdrh       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
28717d176105Sdrh       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
2872e99fa2afSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2873e99fa2afSdrh       testcase( regFree1==0 );
2874e99fa2afSdrh       inReg = target;
2875e99fa2afSdrh       sqlite3VdbeAddOp2(v, op, r1, inReg);
2876cce7d176Sdrh       break;
2877cce7d176Sdrh     }
2878cce7d176Sdrh     case TK_ISNULL:
2879cce7d176Sdrh     case TK_NOTNULL: {
28806a288a33Sdrh       int addr;
28817d176105Sdrh       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
28827d176105Sdrh       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
28839de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
28842dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2885c5499befSdrh       testcase( regFree1==0 );
28862dcef11bSdrh       addr = sqlite3VdbeAddOp1(v, op, r1);
28877d176105Sdrh       VdbeCoverageIf(v, op==TK_ISNULL);
28887d176105Sdrh       VdbeCoverageIf(v, op==TK_NOTNULL);
2889a976979bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
28906a288a33Sdrh       sqlite3VdbeJumpHere(v, addr);
2891a37cdde0Sdanielk1977       break;
2892f2bc013cSdrh     }
28932282792aSdrh     case TK_AGG_FUNCTION: {
289413449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
28957e56e711Sdrh       if( pInfo==0 ){
289633e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
289733e619fcSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
28987e56e711Sdrh       }else{
28999de221dfSdrh         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
29007e56e711Sdrh       }
29012282792aSdrh       break;
29022282792aSdrh     }
2903cce7d176Sdrh     case TK_FUNCTION: {
290412ffee8cSdrh       ExprList *pFarg;       /* List of function arguments */
290512ffee8cSdrh       int nFarg;             /* Number of function arguments */
290612ffee8cSdrh       FuncDef *pDef;         /* The function definition object */
290712ffee8cSdrh       const char *zId;       /* The function name */
2908693e6719Sdrh       u32 constMask = 0;     /* Mask of function arguments that are constant */
290912ffee8cSdrh       int i;                 /* Loop counter */
291012ffee8cSdrh       u8 enc = ENC(db);      /* The text encoding used by this database */
291112ffee8cSdrh       CollSeq *pColl = 0;    /* A collating sequence */
291217435752Sdrh 
29136ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2914c5cd1249Sdrh       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
291512ffee8cSdrh         pFarg = 0;
291612ffee8cSdrh       }else{
291712ffee8cSdrh         pFarg = pExpr->x.pList;
291812ffee8cSdrh       }
291912ffee8cSdrh       nFarg = pFarg ? pFarg->nExpr : 0;
292033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
292133e619fcSdrh       zId = pExpr->u.zToken;
292280738d9cSdrh       pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
29232d80151fSdrh       if( pDef==0 || pDef->xFinalize!=0 ){
292480738d9cSdrh         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
2925feb306f5Sdrh         break;
2926feb306f5Sdrh       }
2927ae6bb957Sdrh 
2928ae6bb957Sdrh       /* Attempt a direct implementation of the built-in COALESCE() and
292960ec914cSpeter.d.reid       ** IFNULL() functions.  This avoids unnecessary evaluation of
2930ae6bb957Sdrh       ** arguments past the first non-NULL argument.
2931ae6bb957Sdrh       */
2932d36e1041Sdrh       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
2933ae6bb957Sdrh         int endCoalesce = sqlite3VdbeMakeLabel(v);
2934ae6bb957Sdrh         assert( nFarg>=2 );
2935ae6bb957Sdrh         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
2936ae6bb957Sdrh         for(i=1; i<nFarg; i++){
2937ae6bb957Sdrh           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
2938688852abSdrh           VdbeCoverage(v);
2939f49f3523Sdrh           sqlite3ExprCacheRemove(pParse, target, 1);
2940ae6bb957Sdrh           sqlite3ExprCachePush(pParse);
2941ae6bb957Sdrh           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
2942d2490904Sdrh           sqlite3ExprCachePop(pParse);
2943ae6bb957Sdrh         }
2944ae6bb957Sdrh         sqlite3VdbeResolveLabel(v, endCoalesce);
2945ae6bb957Sdrh         break;
2946ae6bb957Sdrh       }
2947ae6bb957Sdrh 
2948cca9f3d2Sdrh       /* The UNLIKELY() function is a no-op.  The result is the value
2949cca9f3d2Sdrh       ** of the first argument.
2950cca9f3d2Sdrh       */
2951cca9f3d2Sdrh       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
2952cca9f3d2Sdrh         assert( nFarg>=1 );
29535f02ab09Sdrh         inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
2954cca9f3d2Sdrh         break;
2955cca9f3d2Sdrh       }
2956ae6bb957Sdrh 
2957d1a01edaSdrh       for(i=0; i<nFarg; i++){
2958d1a01edaSdrh         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
2959693e6719Sdrh           testcase( i==31 );
2960693e6719Sdrh           constMask |= MASKBIT32(i);
2961d1a01edaSdrh         }
2962d1a01edaSdrh         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
2963d1a01edaSdrh           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
2964d1a01edaSdrh         }
2965d1a01edaSdrh       }
296612ffee8cSdrh       if( pFarg ){
2967d1a01edaSdrh         if( constMask ){
2968d1a01edaSdrh           r1 = pParse->nMem+1;
2969d1a01edaSdrh           pParse->nMem += nFarg;
2970d1a01edaSdrh         }else{
297112ffee8cSdrh           r1 = sqlite3GetTempRange(pParse, nFarg);
2972d1a01edaSdrh         }
2973a748fdccSdrh 
2974a748fdccSdrh         /* For length() and typeof() functions with a column argument,
2975a748fdccSdrh         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
2976a748fdccSdrh         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
2977a748fdccSdrh         ** loading.
2978a748fdccSdrh         */
2979d36e1041Sdrh         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
29804e245a4cSdrh           u8 exprOp;
2981a748fdccSdrh           assert( nFarg==1 );
2982a748fdccSdrh           assert( pFarg->a[0].pExpr!=0 );
29834e245a4cSdrh           exprOp = pFarg->a[0].pExpr->op;
29844e245a4cSdrh           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
2985a748fdccSdrh             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
2986a748fdccSdrh             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
2987b1fba286Sdrh             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
2988b1fba286Sdrh             pFarg->a[0].pExpr->op2 =
2989b1fba286Sdrh                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
2990a748fdccSdrh           }
2991a748fdccSdrh         }
2992a748fdccSdrh 
2993d7d385ddSdrh         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
29945579d59fSdrh         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
2995d1a01edaSdrh                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
2996d2490904Sdrh         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
2997892d3179Sdrh       }else{
299812ffee8cSdrh         r1 = 0;
2999892d3179Sdrh       }
3000b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
3001a43fa227Sdrh       /* Possibly overload the function if the first argument is
3002a43fa227Sdrh       ** a virtual table column.
3003a43fa227Sdrh       **
3004a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3005a43fa227Sdrh       ** second argument, not the first, as the argument to test to
3006a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
3007a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
3008a43fa227Sdrh       ** control overloading) ends up as the second argument to the
3009a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
3010a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
3011a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
3012a43fa227Sdrh       */
301312ffee8cSdrh       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
301412ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
301512ffee8cSdrh       }else if( nFarg>0 ){
301612ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
3017b7f6f68fSdrh       }
3018b7f6f68fSdrh #endif
3019d36e1041Sdrh       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
30208b213899Sdrh         if( !pColl ) pColl = db->pDfltColl;
302166a5167bSdrh         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
3022682f68b0Sdanielk1977       }
30239c7c913cSdrh       sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
302466a5167bSdrh                         (char*)pDef, P4_FUNCDEF);
302512ffee8cSdrh       sqlite3VdbeChangeP5(v, (u8)nFarg);
3026d1a01edaSdrh       if( nFarg && constMask==0 ){
302712ffee8cSdrh         sqlite3ReleaseTempRange(pParse, r1, nFarg);
30282dcef11bSdrh       }
30296ec2733bSdrh       break;
30306ec2733bSdrh     }
3031fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
3032fe2093d7Sdrh     case TK_EXISTS:
303319a775c2Sdrh     case TK_SELECT: {
3034c5499befSdrh       testcase( op==TK_EXISTS );
3035c5499befSdrh       testcase( op==TK_SELECT );
30361450bc6eSdrh       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
303719a775c2Sdrh       break;
303819a775c2Sdrh     }
3039fef5208cSdrh     case TK_IN: {
3040e3365e6cSdrh       int destIfFalse = sqlite3VdbeMakeLabel(v);
3041e3365e6cSdrh       int destIfNull = sqlite3VdbeMakeLabel(v);
3042e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3043e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
304466ba23ceSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3045e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
3046e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3047e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfNull);
3048fef5208cSdrh       break;
3049fef5208cSdrh     }
3050e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
3051e3365e6cSdrh 
3052e3365e6cSdrh 
30532dcef11bSdrh     /*
30542dcef11bSdrh     **    x BETWEEN y AND z
30552dcef11bSdrh     **
30562dcef11bSdrh     ** This is equivalent to
30572dcef11bSdrh     **
30582dcef11bSdrh     **    x>=y AND x<=z
30592dcef11bSdrh     **
30602dcef11bSdrh     ** X is stored in pExpr->pLeft.
30612dcef11bSdrh     ** Y is stored in pExpr->pList->a[0].pExpr.
30622dcef11bSdrh     ** Z is stored in pExpr->pList->a[1].pExpr.
30632dcef11bSdrh     */
3064fef5208cSdrh     case TK_BETWEEN: {
3065be5c89acSdrh       Expr *pLeft = pExpr->pLeft;
30666ab3a2ecSdanielk1977       struct ExprList_item *pLItem = pExpr->x.pList->a;
3067be5c89acSdrh       Expr *pRight = pLItem->pExpr;
306835573356Sdrh 
3069b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3070b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
3071c5499befSdrh       testcase( regFree1==0 );
3072c5499befSdrh       testcase( regFree2==0 );
30732dcef11bSdrh       r3 = sqlite3GetTempReg(pParse);
3074678ccce8Sdrh       r4 = sqlite3GetTempReg(pParse);
307535573356Sdrh       codeCompare(pParse, pLeft, pRight, OP_Ge,
30767d176105Sdrh                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
3077be5c89acSdrh       pLItem++;
3078be5c89acSdrh       pRight = pLItem->pExpr;
30792dcef11bSdrh       sqlite3ReleaseTempReg(pParse, regFree2);
30802dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
3081c5499befSdrh       testcase( regFree2==0 );
3082678ccce8Sdrh       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
3083688852abSdrh       VdbeCoverage(v);
3084678ccce8Sdrh       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
30852dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r3);
3086678ccce8Sdrh       sqlite3ReleaseTempReg(pParse, r4);
3087fef5208cSdrh       break;
3088fef5208cSdrh     }
308994fa9c41Sdrh     case TK_SPAN:
3090ae80ddeaSdrh     case TK_COLLATE:
30914f07e5fbSdrh     case TK_UPLUS: {
30922dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3093a2e00042Sdrh       break;
3094a2e00042Sdrh     }
30952dcef11bSdrh 
3096165921a7Sdan     case TK_TRIGGER: {
309765a7cd16Sdan       /* If the opcode is TK_TRIGGER, then the expression is a reference
309865a7cd16Sdan       ** to a column in the new.* or old.* pseudo-tables available to
309965a7cd16Sdan       ** trigger programs. In this case Expr.iTable is set to 1 for the
310065a7cd16Sdan       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
310165a7cd16Sdan       ** is set to the column of the pseudo-table to read, or to -1 to
310265a7cd16Sdan       ** read the rowid field.
310365a7cd16Sdan       **
310465a7cd16Sdan       ** The expression is implemented using an OP_Param opcode. The p1
310565a7cd16Sdan       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
310665a7cd16Sdan       ** to reference another column of the old.* pseudo-table, where
310765a7cd16Sdan       ** i is the index of the column. For a new.rowid reference, p1 is
310865a7cd16Sdan       ** set to (n+1), where n is the number of columns in each pseudo-table.
310965a7cd16Sdan       ** For a reference to any other column in the new.* pseudo-table, p1
311065a7cd16Sdan       ** is set to (n+2+i), where n and i are as defined previously. For
311165a7cd16Sdan       ** example, if the table on which triggers are being fired is
311265a7cd16Sdan       ** declared as:
311365a7cd16Sdan       **
311465a7cd16Sdan       **   CREATE TABLE t1(a, b);
311565a7cd16Sdan       **
311665a7cd16Sdan       ** Then p1 is interpreted as follows:
311765a7cd16Sdan       **
311865a7cd16Sdan       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
311965a7cd16Sdan       **   p1==1   ->    old.a         p1==4   ->    new.a
312065a7cd16Sdan       **   p1==2   ->    old.b         p1==5   ->    new.b
312165a7cd16Sdan       */
31222832ad42Sdan       Table *pTab = pExpr->pTab;
312365a7cd16Sdan       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
312465a7cd16Sdan 
312565a7cd16Sdan       assert( pExpr->iTable==0 || pExpr->iTable==1 );
312665a7cd16Sdan       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
312765a7cd16Sdan       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
312865a7cd16Sdan       assert( p1>=0 && p1<(pTab->nCol*2+2) );
312965a7cd16Sdan 
313065a7cd16Sdan       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
313176d462eeSdan       VdbeComment((v, "%s.%s -> $%d",
3132165921a7Sdan         (pExpr->iTable ? "new" : "old"),
313376d462eeSdan         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
313476d462eeSdan         target
3135165921a7Sdan       ));
313665a7cd16Sdan 
313744dbca83Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
313865a7cd16Sdan       /* If the column has REAL affinity, it may currently be stored as an
3139113762a2Sdrh       ** integer. Use OP_RealAffinity to make sure it is really real.
3140113762a2Sdrh       **
3141113762a2Sdrh       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3142113762a2Sdrh       ** floating point when extracting it from the record.  */
31432832ad42Sdan       if( pExpr->iColumn>=0
31442832ad42Sdan        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
31452832ad42Sdan       ){
31462832ad42Sdan         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
31472832ad42Sdan       }
314844dbca83Sdrh #endif
3149165921a7Sdan       break;
3150165921a7Sdan     }
3151165921a7Sdan 
3152165921a7Sdan 
31532dcef11bSdrh     /*
31542dcef11bSdrh     ** Form A:
31552dcef11bSdrh     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
31562dcef11bSdrh     **
31572dcef11bSdrh     ** Form B:
31582dcef11bSdrh     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
31592dcef11bSdrh     **
31602dcef11bSdrh     ** Form A is can be transformed into the equivalent form B as follows:
31612dcef11bSdrh     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
31622dcef11bSdrh     **        WHEN x=eN THEN rN ELSE y END
31632dcef11bSdrh     **
31642dcef11bSdrh     ** X (if it exists) is in pExpr->pLeft.
3165c5cd1249Sdrh     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3166c5cd1249Sdrh     ** odd.  The Y is also optional.  If the number of elements in x.pList
3167c5cd1249Sdrh     ** is even, then Y is omitted and the "otherwise" result is NULL.
31682dcef11bSdrh     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
31692dcef11bSdrh     **
31702dcef11bSdrh     ** The result of the expression is the Ri for the first matching Ei,
31712dcef11bSdrh     ** or if there is no matching Ei, the ELSE term Y, or if there is
31722dcef11bSdrh     ** no ELSE term, NULL.
31732dcef11bSdrh     */
317433cd4909Sdrh     default: assert( op==TK_CASE ); {
31752dcef11bSdrh       int endLabel;                     /* GOTO label for end of CASE stmt */
31762dcef11bSdrh       int nextCase;                     /* GOTO label for next WHEN clause */
31772dcef11bSdrh       int nExpr;                        /* 2x number of WHEN terms */
31782dcef11bSdrh       int i;                            /* Loop counter */
31792dcef11bSdrh       ExprList *pEList;                 /* List of WHEN terms */
31802dcef11bSdrh       struct ExprList_item *aListelem;  /* Array of WHEN terms */
31812dcef11bSdrh       Expr opCompare;                   /* The X==Ei expression */
31822dcef11bSdrh       Expr *pX;                         /* The X expression */
31831bd10f8aSdrh       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
3184ceea3321Sdrh       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
318517a7f8ddSdrh 
31866ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
31876ab3a2ecSdanielk1977       assert(pExpr->x.pList->nExpr > 0);
31886ab3a2ecSdanielk1977       pEList = pExpr->x.pList;
3189be5c89acSdrh       aListelem = pEList->a;
3190be5c89acSdrh       nExpr = pEList->nExpr;
31912dcef11bSdrh       endLabel = sqlite3VdbeMakeLabel(v);
31922dcef11bSdrh       if( (pX = pExpr->pLeft)!=0 ){
319310d1edf0Sdrh         tempX = *pX;
319433cd4909Sdrh         testcase( pX->op==TK_COLUMN );
319510d1edf0Sdrh         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
3196c5499befSdrh         testcase( regFree1==0 );
31972dcef11bSdrh         opCompare.op = TK_EQ;
319810d1edf0Sdrh         opCompare.pLeft = &tempX;
31992dcef11bSdrh         pTest = &opCompare;
32008b1db07fSdrh         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
32018b1db07fSdrh         ** The value in regFree1 might get SCopy-ed into the file result.
32028b1db07fSdrh         ** So make sure that the regFree1 register is not reused for other
32038b1db07fSdrh         ** purposes and possibly overwritten.  */
32048b1db07fSdrh         regFree1 = 0;
3205cce7d176Sdrh       }
3206c5cd1249Sdrh       for(i=0; i<nExpr-1; i=i+2){
3207ceea3321Sdrh         sqlite3ExprCachePush(pParse);
32082dcef11bSdrh         if( pX ){
32091bd10f8aSdrh           assert( pTest!=0 );
32102dcef11bSdrh           opCompare.pRight = aListelem[i].pExpr;
3211f5905aa7Sdrh         }else{
32122dcef11bSdrh           pTest = aListelem[i].pExpr;
321317a7f8ddSdrh         }
32142dcef11bSdrh         nextCase = sqlite3VdbeMakeLabel(v);
321533cd4909Sdrh         testcase( pTest->op==TK_COLUMN );
32162dcef11bSdrh         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
3217c5499befSdrh         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
32189de221dfSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
3219076e85f5Sdrh         sqlite3VdbeGoto(v, endLabel);
3220d2490904Sdrh         sqlite3ExprCachePop(pParse);
32212dcef11bSdrh         sqlite3VdbeResolveLabel(v, nextCase);
3222f570f011Sdrh       }
3223c5cd1249Sdrh       if( (nExpr&1)!=0 ){
3224ceea3321Sdrh         sqlite3ExprCachePush(pParse);
3225c5cd1249Sdrh         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
3226d2490904Sdrh         sqlite3ExprCachePop(pParse);
322717a7f8ddSdrh       }else{
32289de221dfSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
322917a7f8ddSdrh       }
3230c1f4a19bSdanielk1977       assert( db->mallocFailed || pParse->nErr>0
3231c1f4a19bSdanielk1977            || pParse->iCacheLevel==iCacheLevel );
32322dcef11bSdrh       sqlite3VdbeResolveLabel(v, endLabel);
32336f34903eSdanielk1977       break;
32346f34903eSdanielk1977     }
32355338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
32366f34903eSdanielk1977     case TK_RAISE: {
3237165921a7Sdan       assert( pExpr->affinity==OE_Rollback
3238165921a7Sdan            || pExpr->affinity==OE_Abort
3239165921a7Sdan            || pExpr->affinity==OE_Fail
3240165921a7Sdan            || pExpr->affinity==OE_Ignore
3241165921a7Sdan       );
3242e0af83acSdan       if( !pParse->pTriggerTab ){
3243e0af83acSdan         sqlite3ErrorMsg(pParse,
3244e0af83acSdan                        "RAISE() may only be used within a trigger-program");
3245e0af83acSdan         return 0;
3246e0af83acSdan       }
3247e0af83acSdan       if( pExpr->affinity==OE_Abort ){
3248e0af83acSdan         sqlite3MayAbort(pParse);
3249e0af83acSdan       }
325033e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3251e0af83acSdan       if( pExpr->affinity==OE_Ignore ){
3252e0af83acSdan         sqlite3VdbeAddOp4(
3253e0af83acSdan             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
3254688852abSdrh         VdbeCoverage(v);
3255e0af83acSdan       }else{
3256433dccfbSdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
3257f9c8ce3cSdrh                               pExpr->affinity, pExpr->u.zToken, 0, 0);
3258e0af83acSdan       }
3259e0af83acSdan 
3260ffe07b2dSdrh       break;
326117a7f8ddSdrh     }
32625338a5f7Sdanielk1977 #endif
3263ffe07b2dSdrh   }
32642dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
32652dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
32662dcef11bSdrh   return inReg;
32675b6afba9Sdrh }
32682dcef11bSdrh 
32692dcef11bSdrh /*
3270d1a01edaSdrh ** Factor out the code of the given expression to initialization time.
3271d1a01edaSdrh */
3272d673cddaSdrh void sqlite3ExprCodeAtInit(
3273d673cddaSdrh   Parse *pParse,    /* Parsing context */
3274d673cddaSdrh   Expr *pExpr,      /* The expression to code when the VDBE initializes */
3275d673cddaSdrh   int regDest,      /* Store the value in this register */
3276d673cddaSdrh   u8 reusable       /* True if this expression is reusable */
3277d673cddaSdrh ){
3278d1a01edaSdrh   ExprList *p;
3279d9f158e7Sdrh   assert( ConstFactorOk(pParse) );
3280d1a01edaSdrh   p = pParse->pConstExpr;
3281d1a01edaSdrh   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3282d1a01edaSdrh   p = sqlite3ExprListAppend(pParse, p, pExpr);
3283d673cddaSdrh   if( p ){
3284d673cddaSdrh      struct ExprList_item *pItem = &p->a[p->nExpr-1];
3285d673cddaSdrh      pItem->u.iConstExprReg = regDest;
3286d673cddaSdrh      pItem->reusable = reusable;
3287d673cddaSdrh   }
3288d1a01edaSdrh   pParse->pConstExpr = p;
3289d1a01edaSdrh }
3290d1a01edaSdrh 
3291d1a01edaSdrh /*
32922dcef11bSdrh ** Generate code to evaluate an expression and store the results
32932dcef11bSdrh ** into a register.  Return the register number where the results
32942dcef11bSdrh ** are stored.
32952dcef11bSdrh **
32962dcef11bSdrh ** If the register is a temporary register that can be deallocated,
3297678ccce8Sdrh ** then write its number into *pReg.  If the result register is not
32982dcef11bSdrh ** a temporary, then set *pReg to zero.
3299f30a969bSdrh **
3300f30a969bSdrh ** If pExpr is a constant, then this routine might generate this
3301f30a969bSdrh ** code to fill the register in the initialization section of the
3302f30a969bSdrh ** VDBE program, in order to factor it out of the evaluation loop.
33032dcef11bSdrh */
33042dcef11bSdrh int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
3305f30a969bSdrh   int r2;
3306f30a969bSdrh   pExpr = sqlite3ExprSkipCollate(pExpr);
3307d9f158e7Sdrh   if( ConstFactorOk(pParse)
3308f30a969bSdrh    && pExpr->op!=TK_REGISTER
3309f30a969bSdrh    && sqlite3ExprIsConstantNotJoin(pExpr)
3310f30a969bSdrh   ){
3311f30a969bSdrh     ExprList *p = pParse->pConstExpr;
3312f30a969bSdrh     int i;
3313f30a969bSdrh     *pReg  = 0;
3314f30a969bSdrh     if( p ){
3315d673cddaSdrh       struct ExprList_item *pItem;
3316d673cddaSdrh       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3317d673cddaSdrh         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3318d673cddaSdrh           return pItem->u.iConstExprReg;
3319f30a969bSdrh         }
3320f30a969bSdrh       }
3321f30a969bSdrh     }
3322f30a969bSdrh     r2 = ++pParse->nMem;
3323d673cddaSdrh     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
3324f30a969bSdrh   }else{
33252dcef11bSdrh     int r1 = sqlite3GetTempReg(pParse);
3326f30a969bSdrh     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
33272dcef11bSdrh     if( r2==r1 ){
33282dcef11bSdrh       *pReg = r1;
33292dcef11bSdrh     }else{
33302dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r1);
33312dcef11bSdrh       *pReg = 0;
33322dcef11bSdrh     }
3333f30a969bSdrh   }
33342dcef11bSdrh   return r2;
33352dcef11bSdrh }
33362dcef11bSdrh 
33372dcef11bSdrh /*
33382dcef11bSdrh ** Generate code that will evaluate expression pExpr and store the
33392dcef11bSdrh ** results in register target.  The results are guaranteed to appear
33402dcef11bSdrh ** in register target.
33412dcef11bSdrh */
334205a86c5cSdrh void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
33439cbf3425Sdrh   int inReg;
33449cbf3425Sdrh 
33459cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
3346ebc16717Sdrh   if( pExpr && pExpr->op==TK_REGISTER ){
3347ebc16717Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3348ebc16717Sdrh   }else{
33499cbf3425Sdrh     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
33501c75c9d7Sdrh     assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
33510e359b30Sdrh     if( inReg!=target && pParse->pVdbe ){
33529cbf3425Sdrh       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
335317a7f8ddSdrh     }
3354ebc16717Sdrh   }
3355cce7d176Sdrh }
3356cce7d176Sdrh 
3357cce7d176Sdrh /*
33581c75c9d7Sdrh ** Make a transient copy of expression pExpr and then code it using
33591c75c9d7Sdrh ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
33601c75c9d7Sdrh ** except that the input expression is guaranteed to be unchanged.
33611c75c9d7Sdrh */
33621c75c9d7Sdrh void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
33631c75c9d7Sdrh   sqlite3 *db = pParse->db;
33641c75c9d7Sdrh   pExpr = sqlite3ExprDup(db, pExpr, 0);
33651c75c9d7Sdrh   if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
33661c75c9d7Sdrh   sqlite3ExprDelete(db, pExpr);
33671c75c9d7Sdrh }
33681c75c9d7Sdrh 
33691c75c9d7Sdrh /*
337005a86c5cSdrh ** Generate code that will evaluate expression pExpr and store the
337105a86c5cSdrh ** results in register target.  The results are guaranteed to appear
337205a86c5cSdrh ** in register target.  If the expression is constant, then this routine
337305a86c5cSdrh ** might choose to code the expression at initialization time.
337405a86c5cSdrh */
337505a86c5cSdrh void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
337605a86c5cSdrh   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
337705a86c5cSdrh     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
337805a86c5cSdrh   }else{
337905a86c5cSdrh     sqlite3ExprCode(pParse, pExpr, target);
338005a86c5cSdrh   }
3381cce7d176Sdrh }
3382cce7d176Sdrh 
3383cce7d176Sdrh /*
338460ec914cSpeter.d.reid ** Generate code that evaluates the given expression and puts the result
3385de4fcfddSdrh ** in register target.
338625303780Sdrh **
33872dcef11bSdrh ** Also make a copy of the expression results into another "cache" register
33882dcef11bSdrh ** and modify the expression so that the next time it is evaluated,
33892dcef11bSdrh ** the result is a copy of the cache register.
33902dcef11bSdrh **
33912dcef11bSdrh ** This routine is used for expressions that are used multiple
33922dcef11bSdrh ** times.  They are evaluated once and the results of the expression
33932dcef11bSdrh ** are reused.
339425303780Sdrh */
339505a86c5cSdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
339625303780Sdrh   Vdbe *v = pParse->pVdbe;
339725303780Sdrh   int iMem;
339805a86c5cSdrh 
339905a86c5cSdrh   assert( target>0 );
340005a86c5cSdrh   assert( pExpr->op!=TK_REGISTER );
340105a86c5cSdrh   sqlite3ExprCode(pParse, pExpr, target);
34022dcef11bSdrh   iMem = ++pParse->nMem;
340305a86c5cSdrh   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
3404a4c3c87eSdrh   exprToRegister(pExpr, iMem);
340525303780Sdrh }
34067e02e5e6Sdrh 
3407678ccce8Sdrh /*
3408268380caSdrh ** Generate code that pushes the value of every element of the given
34099cbf3425Sdrh ** expression list into a sequence of registers beginning at target.
3410268380caSdrh **
3411892d3179Sdrh ** Return the number of elements evaluated.
3412d1a01edaSdrh **
3413d1a01edaSdrh ** The SQLITE_ECEL_DUP flag prevents the arguments from being
3414d1a01edaSdrh ** filled using OP_SCopy.  OP_Copy must be used instead.
3415d1a01edaSdrh **
3416d1a01edaSdrh ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
3417d1a01edaSdrh ** factored out into initialization code.
3418b0df9634Sdrh **
3419b0df9634Sdrh ** The SQLITE_ECEL_REF flag means that expressions in the list with
3420b0df9634Sdrh ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
3421b0df9634Sdrh ** in registers at srcReg, and so the value can be copied from there.
3422268380caSdrh */
34234adee20fSdanielk1977 int sqlite3ExprCodeExprList(
3424268380caSdrh   Parse *pParse,     /* Parsing context */
3425389a1adbSdrh   ExprList *pList,   /* The expression list to be coded */
3426191b54cbSdrh   int target,        /* Where to write results */
34275579d59fSdrh   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
3428d1a01edaSdrh   u8 flags           /* SQLITE_ECEL_* flags */
3429268380caSdrh ){
3430268380caSdrh   struct ExprList_item *pItem;
34315579d59fSdrh   int i, j, n;
3432d1a01edaSdrh   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
34335579d59fSdrh   Vdbe *v = pParse->pVdbe;
34349d8b3072Sdrh   assert( pList!=0 );
34359cbf3425Sdrh   assert( target>0 );
3436d81a142bSdrh   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
3437268380caSdrh   n = pList->nExpr;
3438d9f158e7Sdrh   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
3439191b54cbSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
34407445ffe2Sdrh     Expr *pExpr = pItem->pExpr;
34415579d59fSdrh     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
34425579d59fSdrh       sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
34435579d59fSdrh     }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
3444d673cddaSdrh       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
3445d1a01edaSdrh     }else{
34467445ffe2Sdrh       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
3447746fd9ccSdrh       if( inReg!=target+i ){
34484eded604Sdrh         VdbeOp *pOp;
34494eded604Sdrh         if( copyOp==OP_Copy
34504eded604Sdrh          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
34514eded604Sdrh          && pOp->p1+pOp->p3+1==inReg
34524eded604Sdrh          && pOp->p2+pOp->p3+1==target+i
34534eded604Sdrh         ){
34544eded604Sdrh           pOp->p3++;
34554eded604Sdrh         }else{
34564eded604Sdrh           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
34574eded604Sdrh         }
3458d1a01edaSdrh       }
3459d176611bSdrh     }
3460268380caSdrh   }
3461f9b596ebSdrh   return n;
3462268380caSdrh }
3463268380caSdrh 
3464268380caSdrh /*
346536c563a2Sdrh ** Generate code for a BETWEEN operator.
346636c563a2Sdrh **
346736c563a2Sdrh **    x BETWEEN y AND z
346836c563a2Sdrh **
346936c563a2Sdrh ** The above is equivalent to
347036c563a2Sdrh **
347136c563a2Sdrh **    x>=y AND x<=z
347236c563a2Sdrh **
347336c563a2Sdrh ** Code it as such, taking care to do the common subexpression
347460ec914cSpeter.d.reid ** elimination of x.
347536c563a2Sdrh */
347636c563a2Sdrh static void exprCodeBetween(
347736c563a2Sdrh   Parse *pParse,    /* Parsing and code generating context */
347836c563a2Sdrh   Expr *pExpr,      /* The BETWEEN expression */
347936c563a2Sdrh   int dest,         /* Jump here if the jump is taken */
348036c563a2Sdrh   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
348136c563a2Sdrh   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
348236c563a2Sdrh ){
348336c563a2Sdrh   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
348436c563a2Sdrh   Expr compLeft;    /* The  x>=y  term */
348536c563a2Sdrh   Expr compRight;   /* The  x<=z  term */
348636c563a2Sdrh   Expr exprX;       /* The  x  subexpression */
348736c563a2Sdrh   int regFree1 = 0; /* Temporary use register */
348836c563a2Sdrh 
348936c563a2Sdrh   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
349036c563a2Sdrh   exprX = *pExpr->pLeft;
349136c563a2Sdrh   exprAnd.op = TK_AND;
349236c563a2Sdrh   exprAnd.pLeft = &compLeft;
349336c563a2Sdrh   exprAnd.pRight = &compRight;
349436c563a2Sdrh   compLeft.op = TK_GE;
349536c563a2Sdrh   compLeft.pLeft = &exprX;
349636c563a2Sdrh   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
349736c563a2Sdrh   compRight.op = TK_LE;
349836c563a2Sdrh   compRight.pLeft = &exprX;
349936c563a2Sdrh   compRight.pRight = pExpr->x.pList->a[1].pExpr;
3500a4c3c87eSdrh   exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
350136c563a2Sdrh   if( jumpIfTrue ){
350236c563a2Sdrh     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
350336c563a2Sdrh   }else{
350436c563a2Sdrh     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
350536c563a2Sdrh   }
350636c563a2Sdrh   sqlite3ReleaseTempReg(pParse, regFree1);
350736c563a2Sdrh 
350836c563a2Sdrh   /* Ensure adequate test coverage */
350936c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
351036c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
351136c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
351236c563a2Sdrh   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
351336c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
351436c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
351536c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
351636c563a2Sdrh   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
351736c563a2Sdrh }
351836c563a2Sdrh 
351936c563a2Sdrh /*
3520cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
3521cce7d176Sdrh ** to the label "dest" if the expression is true but execution
3522cce7d176Sdrh ** continues straight thru if the expression is false.
3523f5905aa7Sdrh **
3524f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
352535573356Sdrh ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
3526f2bc013cSdrh **
3527f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
3528f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3529f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
3530f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
3531f2bc013cSdrh ** below verify that the numbers are aligned correctly.
3532cce7d176Sdrh */
35334adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3534cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3535cce7d176Sdrh   int op = 0;
35362dcef11bSdrh   int regFree1 = 0;
35372dcef11bSdrh   int regFree2 = 0;
35382dcef11bSdrh   int r1, r2;
35392dcef11bSdrh 
354035573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
354148864df9Smistachkin   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
354233cd4909Sdrh   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
3543f2bc013cSdrh   op = pExpr->op;
3544f2bc013cSdrh   switch( op ){
3545cce7d176Sdrh     case TK_AND: {
35464adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3547c5499befSdrh       testcase( jumpIfNull==0 );
354835573356Sdrh       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
354954e2adb5Sdrh       sqlite3ExprCachePush(pParse);
35504adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
35514adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3552d2490904Sdrh       sqlite3ExprCachePop(pParse);
3553cce7d176Sdrh       break;
3554cce7d176Sdrh     }
3555cce7d176Sdrh     case TK_OR: {
3556c5499befSdrh       testcase( jumpIfNull==0 );
35574adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
355854e2adb5Sdrh       sqlite3ExprCachePush(pParse);
35594adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3560d2490904Sdrh       sqlite3ExprCachePop(pParse);
3561cce7d176Sdrh       break;
3562cce7d176Sdrh     }
3563cce7d176Sdrh     case TK_NOT: {
3564c5499befSdrh       testcase( jumpIfNull==0 );
35654adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3566cce7d176Sdrh       break;
3567cce7d176Sdrh     }
3568de845c2fSdrh     case TK_IS:
3569de845c2fSdrh     case TK_ISNOT:
3570de845c2fSdrh       testcase( op==TK_IS );
3571de845c2fSdrh       testcase( op==TK_ISNOT );
3572de845c2fSdrh       op = (op==TK_IS) ? TK_EQ : TK_NE;
3573de845c2fSdrh       jumpIfNull = SQLITE_NULLEQ;
3574de845c2fSdrh       /* Fall thru */
3575cce7d176Sdrh     case TK_LT:
3576cce7d176Sdrh     case TK_LE:
3577cce7d176Sdrh     case TK_GT:
3578cce7d176Sdrh     case TK_GE:
3579cce7d176Sdrh     case TK_NE:
35800ac65892Sdrh     case TK_EQ: {
3581c5499befSdrh       testcase( jumpIfNull==0 );
3582b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3583b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
358435573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
35852dcef11bSdrh                   r1, r2, dest, jumpIfNull);
35867d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
35877d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
35887d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
35897d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3590de845c2fSdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
3591de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
3592de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
3593de845c2fSdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
3594de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
3595de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
35966a2fe093Sdrh       testcase( regFree1==0 );
35976a2fe093Sdrh       testcase( regFree2==0 );
35986a2fe093Sdrh       break;
35996a2fe093Sdrh     }
3600cce7d176Sdrh     case TK_ISNULL:
3601cce7d176Sdrh     case TK_NOTNULL: {
36027d176105Sdrh       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
36037d176105Sdrh       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
36042dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
36052dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
36067d176105Sdrh       VdbeCoverageIf(v, op==TK_ISNULL);
36077d176105Sdrh       VdbeCoverageIf(v, op==TK_NOTNULL);
3608c5499befSdrh       testcase( regFree1==0 );
3609cce7d176Sdrh       break;
3610cce7d176Sdrh     }
3611fef5208cSdrh     case TK_BETWEEN: {
36125c03f30aSdrh       testcase( jumpIfNull==0 );
361336c563a2Sdrh       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
3614fef5208cSdrh       break;
3615fef5208cSdrh     }
3616bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
3617e3365e6cSdrh     case TK_IN: {
3618e3365e6cSdrh       int destIfFalse = sqlite3VdbeMakeLabel(v);
3619e3365e6cSdrh       int destIfNull = jumpIfNull ? dest : destIfFalse;
3620e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3621076e85f5Sdrh       sqlite3VdbeGoto(v, dest);
3622e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
3623e3365e6cSdrh       break;
3624e3365e6cSdrh     }
3625bb201344Sshaneh #endif
3626cce7d176Sdrh     default: {
3627991a1985Sdrh       if( exprAlwaysTrue(pExpr) ){
3628076e85f5Sdrh         sqlite3VdbeGoto(v, dest);
3629991a1985Sdrh       }else if( exprAlwaysFalse(pExpr) ){
3630991a1985Sdrh         /* No-op */
3631991a1985Sdrh       }else{
36322dcef11bSdrh         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
36332dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
3634688852abSdrh         VdbeCoverage(v);
3635c5499befSdrh         testcase( regFree1==0 );
3636c5499befSdrh         testcase( jumpIfNull==0 );
3637991a1985Sdrh       }
3638cce7d176Sdrh       break;
3639cce7d176Sdrh     }
3640cce7d176Sdrh   }
36412dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
36422dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3643cce7d176Sdrh }
3644cce7d176Sdrh 
3645cce7d176Sdrh /*
364666b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
3647cce7d176Sdrh ** to the label "dest" if the expression is false but execution
3648cce7d176Sdrh ** continues straight thru if the expression is true.
3649f5905aa7Sdrh **
3650f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
365135573356Sdrh ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
365235573356Sdrh ** is 0.
3653cce7d176Sdrh */
36544adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3655cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
3656cce7d176Sdrh   int op = 0;
36572dcef11bSdrh   int regFree1 = 0;
36582dcef11bSdrh   int regFree2 = 0;
36592dcef11bSdrh   int r1, r2;
36602dcef11bSdrh 
366135573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
366248864df9Smistachkin   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
366333cd4909Sdrh   if( pExpr==0 )    return;
3664f2bc013cSdrh 
3665f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
3666f2bc013cSdrh   **
3667f2bc013cSdrh   **       pExpr->op            op
3668f2bc013cSdrh   **       ---------          ----------
3669f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
3670f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
3671f2bc013cSdrh   **       TK_NE              OP_Eq
3672f2bc013cSdrh   **       TK_EQ              OP_Ne
3673f2bc013cSdrh   **       TK_GT              OP_Le
3674f2bc013cSdrh   **       TK_LE              OP_Gt
3675f2bc013cSdrh   **       TK_GE              OP_Lt
3676f2bc013cSdrh   **       TK_LT              OP_Ge
3677f2bc013cSdrh   **
3678f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
3679f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
3680f2bc013cSdrh   ** can compute the mapping above using the following expression.
3681f2bc013cSdrh   ** Assert()s verify that the computation is correct.
3682f2bc013cSdrh   */
3683f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3684f2bc013cSdrh 
3685f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
3686f2bc013cSdrh   */
3687f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3688f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3689f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
3690f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
3691f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
3692f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
3693f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
3694f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
3695f2bc013cSdrh 
3696cce7d176Sdrh   switch( pExpr->op ){
3697cce7d176Sdrh     case TK_AND: {
3698c5499befSdrh       testcase( jumpIfNull==0 );
36994adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
370054e2adb5Sdrh       sqlite3ExprCachePush(pParse);
37014adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3702d2490904Sdrh       sqlite3ExprCachePop(pParse);
3703cce7d176Sdrh       break;
3704cce7d176Sdrh     }
3705cce7d176Sdrh     case TK_OR: {
37064adee20fSdanielk1977       int d2 = sqlite3VdbeMakeLabel(v);
3707c5499befSdrh       testcase( jumpIfNull==0 );
370835573356Sdrh       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
370954e2adb5Sdrh       sqlite3ExprCachePush(pParse);
37104adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
37114adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, d2);
3712d2490904Sdrh       sqlite3ExprCachePop(pParse);
3713cce7d176Sdrh       break;
3714cce7d176Sdrh     }
3715cce7d176Sdrh     case TK_NOT: {
37165c03f30aSdrh       testcase( jumpIfNull==0 );
37174adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3718cce7d176Sdrh       break;
3719cce7d176Sdrh     }
3720de845c2fSdrh     case TK_IS:
3721de845c2fSdrh     case TK_ISNOT:
3722de845c2fSdrh       testcase( pExpr->op==TK_IS );
3723de845c2fSdrh       testcase( pExpr->op==TK_ISNOT );
3724de845c2fSdrh       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
3725de845c2fSdrh       jumpIfNull = SQLITE_NULLEQ;
3726de845c2fSdrh       /* Fall thru */
3727cce7d176Sdrh     case TK_LT:
3728cce7d176Sdrh     case TK_LE:
3729cce7d176Sdrh     case TK_GT:
3730cce7d176Sdrh     case TK_GE:
3731cce7d176Sdrh     case TK_NE:
3732cce7d176Sdrh     case TK_EQ: {
3733c5499befSdrh       testcase( jumpIfNull==0 );
3734b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3735b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
373635573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
37372dcef11bSdrh                   r1, r2, dest, jumpIfNull);
37387d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
37397d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
37407d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
37417d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3742de845c2fSdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
3743de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
3744de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
3745de845c2fSdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
3746de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
3747de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
37486a2fe093Sdrh       testcase( regFree1==0 );
37496a2fe093Sdrh       testcase( regFree2==0 );
37506a2fe093Sdrh       break;
37516a2fe093Sdrh     }
3752cce7d176Sdrh     case TK_ISNULL:
3753cce7d176Sdrh     case TK_NOTNULL: {
37542dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
37552dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
37567d176105Sdrh       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
37577d176105Sdrh       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
3758c5499befSdrh       testcase( regFree1==0 );
3759cce7d176Sdrh       break;
3760cce7d176Sdrh     }
3761fef5208cSdrh     case TK_BETWEEN: {
37625c03f30aSdrh       testcase( jumpIfNull==0 );
376336c563a2Sdrh       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
3764fef5208cSdrh       break;
3765fef5208cSdrh     }
3766bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
3767e3365e6cSdrh     case TK_IN: {
3768e3365e6cSdrh       if( jumpIfNull ){
3769e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
3770e3365e6cSdrh       }else{
3771e3365e6cSdrh         int destIfNull = sqlite3VdbeMakeLabel(v);
3772e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
3773e3365e6cSdrh         sqlite3VdbeResolveLabel(v, destIfNull);
3774e3365e6cSdrh       }
3775e3365e6cSdrh       break;
3776e3365e6cSdrh     }
3777bb201344Sshaneh #endif
3778cce7d176Sdrh     default: {
3779991a1985Sdrh       if( exprAlwaysFalse(pExpr) ){
3780076e85f5Sdrh         sqlite3VdbeGoto(v, dest);
3781991a1985Sdrh       }else if( exprAlwaysTrue(pExpr) ){
3782991a1985Sdrh         /* no-op */
3783991a1985Sdrh       }else{
37842dcef11bSdrh         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
37852dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
3786688852abSdrh         VdbeCoverage(v);
3787c5499befSdrh         testcase( regFree1==0 );
3788c5499befSdrh         testcase( jumpIfNull==0 );
3789991a1985Sdrh       }
3790cce7d176Sdrh       break;
3791cce7d176Sdrh     }
3792cce7d176Sdrh   }
37932dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
37942dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
3795cce7d176Sdrh }
37962282792aSdrh 
37972282792aSdrh /*
379872bc8208Sdrh ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
379972bc8208Sdrh ** code generation, and that copy is deleted after code generation. This
380072bc8208Sdrh ** ensures that the original pExpr is unchanged.
380172bc8208Sdrh */
380272bc8208Sdrh void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
380372bc8208Sdrh   sqlite3 *db = pParse->db;
380472bc8208Sdrh   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
380572bc8208Sdrh   if( db->mallocFailed==0 ){
380672bc8208Sdrh     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
380772bc8208Sdrh   }
380872bc8208Sdrh   sqlite3ExprDelete(db, pCopy);
380972bc8208Sdrh }
381072bc8208Sdrh 
381172bc8208Sdrh 
381272bc8208Sdrh /*
38131d9da70aSdrh ** Do a deep comparison of two expression trees.  Return 0 if the two
38141d9da70aSdrh ** expressions are completely identical.  Return 1 if they differ only
38151d9da70aSdrh ** by a COLLATE operator at the top level.  Return 2 if there are differences
38161d9da70aSdrh ** other than the top-level COLLATE operator.
3817d40aab0eSdrh **
3818619a1305Sdrh ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
3819619a1305Sdrh ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
3820619a1305Sdrh **
382166518ca7Sdrh ** The pA side might be using TK_REGISTER.  If that is the case and pB is
382266518ca7Sdrh ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
382366518ca7Sdrh **
38241d9da70aSdrh ** Sometimes this routine will return 2 even if the two expressions
3825d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
38261d9da70aSdrh ** identical, we return 2 just to be safe.  So if this routine
38271d9da70aSdrh ** returns 2, then you do not really know for certain if the two
38281d9da70aSdrh ** expressions are the same.  But if you get a 0 or 1 return, then you
3829d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
38301d9da70aSdrh ** this routine is used, it does not hurt to get an extra 2 - that
3831d40aab0eSdrh ** just might result in some slightly slower code.  But returning
38321d9da70aSdrh ** an incorrect 0 or 1 could lead to a malfunction.
38332282792aSdrh */
3834619a1305Sdrh int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
383510d1edf0Sdrh   u32 combinedFlags;
38364b202ae2Sdanielk1977   if( pA==0 || pB==0 ){
38371d9da70aSdrh     return pB==pA ? 0 : 2;
38382282792aSdrh   }
383910d1edf0Sdrh   combinedFlags = pA->flags | pB->flags;
384010d1edf0Sdrh   if( combinedFlags & EP_IntValue ){
384110d1edf0Sdrh     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
384210d1edf0Sdrh       return 0;
384310d1edf0Sdrh     }
38441d9da70aSdrh     return 2;
38456ab3a2ecSdanielk1977   }
3846c2acc4e4Sdrh   if( pA->op!=pB->op ){
3847619a1305Sdrh     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
3848ae80ddeaSdrh       return 1;
3849ae80ddeaSdrh     }
3850619a1305Sdrh     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
3851ae80ddeaSdrh       return 1;
3852ae80ddeaSdrh     }
3853ae80ddeaSdrh     return 2;
3854ae80ddeaSdrh   }
38552edc5fd7Sdrh   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
3856390b88a4Sdrh     if( pA->op==TK_FUNCTION ){
3857390b88a4Sdrh       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
3858390b88a4Sdrh     }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
385910d1edf0Sdrh       return pA->op==TK_COLLATE ? 1 : 2;
386010d1edf0Sdrh     }
386110d1edf0Sdrh   }
386210d1edf0Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
386385f8aa79Sdrh   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
386410d1edf0Sdrh     if( combinedFlags & EP_xIsSelect ) return 2;
3865619a1305Sdrh     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
3866619a1305Sdrh     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
3867619a1305Sdrh     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
38687693c42fSdrh     if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
3869619a1305Sdrh       if( pA->iColumn!=pB->iColumn ) return 2;
387066518ca7Sdrh       if( pA->iTable!=pB->iTable
387185f8aa79Sdrh        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
38721d9da70aSdrh     }
38731d9da70aSdrh   }
38742646da7eSdrh   return 0;
38752646da7eSdrh }
38762282792aSdrh 
38778c6f666bSdrh /*
38788c6f666bSdrh ** Compare two ExprList objects.  Return 0 if they are identical and
38798c6f666bSdrh ** non-zero if they differ in any way.
38808c6f666bSdrh **
3881619a1305Sdrh ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
3882619a1305Sdrh ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
3883619a1305Sdrh **
38848c6f666bSdrh ** This routine might return non-zero for equivalent ExprLists.  The
38858c6f666bSdrh ** only consequence will be disabled optimizations.  But this routine
38868c6f666bSdrh ** must never return 0 if the two ExprList objects are different, or
38878c6f666bSdrh ** a malfunction will result.
38888c6f666bSdrh **
38898c6f666bSdrh ** Two NULL pointers are considered to be the same.  But a NULL pointer
38908c6f666bSdrh ** always differs from a non-NULL pointer.
38918c6f666bSdrh */
3892619a1305Sdrh int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
38938c6f666bSdrh   int i;
38948c6f666bSdrh   if( pA==0 && pB==0 ) return 0;
38958c6f666bSdrh   if( pA==0 || pB==0 ) return 1;
38968c6f666bSdrh   if( pA->nExpr!=pB->nExpr ) return 1;
38978c6f666bSdrh   for(i=0; i<pA->nExpr; i++){
38988c6f666bSdrh     Expr *pExprA = pA->a[i].pExpr;
38998c6f666bSdrh     Expr *pExprB = pB->a[i].pExpr;
39008c6f666bSdrh     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
3901619a1305Sdrh     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
39028c6f666bSdrh   }
39038c6f666bSdrh   return 0;
39048c6f666bSdrh }
390513449892Sdrh 
39062282792aSdrh /*
39074bd5f73fSdrh ** Return true if we can prove the pE2 will always be true if pE1 is
39084bd5f73fSdrh ** true.  Return false if we cannot complete the proof or if pE2 might
39094bd5f73fSdrh ** be false.  Examples:
39104bd5f73fSdrh **
3911619a1305Sdrh **     pE1: x==5       pE2: x==5             Result: true
39124bd5f73fSdrh **     pE1: x>0        pE2: x==5             Result: false
3913619a1305Sdrh **     pE1: x=21       pE2: x=21 OR y=43     Result: true
39144bd5f73fSdrh **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
3915619a1305Sdrh **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
3916619a1305Sdrh **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
3917619a1305Sdrh **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
39184bd5f73fSdrh **
39194bd5f73fSdrh ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
39204bd5f73fSdrh ** Expr.iTable<0 then assume a table number given by iTab.
39214bd5f73fSdrh **
39224bd5f73fSdrh ** When in doubt, return false.  Returning true might give a performance
39234bd5f73fSdrh ** improvement.  Returning false might cause a performance reduction, but
39244bd5f73fSdrh ** it will always give the correct answer and is hence always safe.
39254bd5f73fSdrh */
39264bd5f73fSdrh int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
3927619a1305Sdrh   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
3928619a1305Sdrh     return 1;
3929619a1305Sdrh   }
3930619a1305Sdrh   if( pE2->op==TK_OR
3931619a1305Sdrh    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
3932619a1305Sdrh              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
3933619a1305Sdrh   ){
3934619a1305Sdrh     return 1;
3935619a1305Sdrh   }
3936619a1305Sdrh   if( pE2->op==TK_NOTNULL
3937619a1305Sdrh    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
3938619a1305Sdrh    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
3939619a1305Sdrh   ){
3940619a1305Sdrh     return 1;
3941619a1305Sdrh   }
3942619a1305Sdrh   return 0;
39434bd5f73fSdrh }
39444bd5f73fSdrh 
39454bd5f73fSdrh /*
3946030796dfSdrh ** An instance of the following structure is used by the tree walker
3947030796dfSdrh ** to count references to table columns in the arguments of an
3948ed551b95Sdrh ** aggregate function, in order to implement the
3949ed551b95Sdrh ** sqlite3FunctionThisSrc() routine.
3950374fdce4Sdrh */
3951030796dfSdrh struct SrcCount {
3952030796dfSdrh   SrcList *pSrc;   /* One particular FROM clause in a nested query */
3953030796dfSdrh   int nThis;       /* Number of references to columns in pSrcList */
3954030796dfSdrh   int nOther;      /* Number of references to columns in other FROM clauses */
3955030796dfSdrh };
3956030796dfSdrh 
3957030796dfSdrh /*
3958030796dfSdrh ** Count the number of references to columns.
3959030796dfSdrh */
3960030796dfSdrh static int exprSrcCount(Walker *pWalker, Expr *pExpr){
3961fb0a6081Sdrh   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
3962fb0a6081Sdrh   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
3963fb0a6081Sdrh   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
3964fb0a6081Sdrh   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
3965fb0a6081Sdrh   ** NEVER() will need to be removed. */
3966fb0a6081Sdrh   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
3967374fdce4Sdrh     int i;
3968030796dfSdrh     struct SrcCount *p = pWalker->u.pSrcCount;
3969030796dfSdrh     SrcList *pSrc = p->pSrc;
3970655814d2Sdrh     int nSrc = pSrc ? pSrc->nSrc : 0;
3971655814d2Sdrh     for(i=0; i<nSrc; i++){
3972030796dfSdrh       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
3973374fdce4Sdrh     }
3974655814d2Sdrh     if( i<nSrc ){
3975030796dfSdrh       p->nThis++;
3976374fdce4Sdrh     }else{
3977030796dfSdrh       p->nOther++;
3978374fdce4Sdrh     }
3979374fdce4Sdrh   }
3980030796dfSdrh   return WRC_Continue;
3981030796dfSdrh }
3982374fdce4Sdrh 
3983374fdce4Sdrh /*
3984030796dfSdrh ** Determine if any of the arguments to the pExpr Function reference
3985030796dfSdrh ** pSrcList.  Return true if they do.  Also return true if the function
3986030796dfSdrh ** has no arguments or has only constant arguments.  Return false if pExpr
3987030796dfSdrh ** references columns but not columns of tables found in pSrcList.
3988374fdce4Sdrh */
3989030796dfSdrh int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
3990374fdce4Sdrh   Walker w;
3991030796dfSdrh   struct SrcCount cnt;
3992374fdce4Sdrh   assert( pExpr->op==TK_AGG_FUNCTION );
3993374fdce4Sdrh   memset(&w, 0, sizeof(w));
3994030796dfSdrh   w.xExprCallback = exprSrcCount;
3995030796dfSdrh   w.u.pSrcCount = &cnt;
3996030796dfSdrh   cnt.pSrc = pSrcList;
3997030796dfSdrh   cnt.nThis = 0;
3998030796dfSdrh   cnt.nOther = 0;
3999030796dfSdrh   sqlite3WalkExprList(&w, pExpr->x.pList);
4000030796dfSdrh   return cnt.nThis>0 || cnt.nOther==0;
4001374fdce4Sdrh }
4002374fdce4Sdrh 
4003374fdce4Sdrh /*
400413449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
400513449892Sdrh ** the new element.  Return a negative number if malloc fails.
40062282792aSdrh */
400717435752Sdrh static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
400813449892Sdrh   int i;
4009cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
401017435752Sdrh        db,
4011cf643729Sdrh        pInfo->aCol,
4012cf643729Sdrh        sizeof(pInfo->aCol[0]),
4013cf643729Sdrh        &pInfo->nColumn,
4014cf643729Sdrh        &i
4015cf643729Sdrh   );
401613449892Sdrh   return i;
40172282792aSdrh }
401813449892Sdrh 
401913449892Sdrh /*
402013449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
402113449892Sdrh ** the new element.  Return a negative number if malloc fails.
402213449892Sdrh */
402317435752Sdrh static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
402413449892Sdrh   int i;
4025cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
402617435752Sdrh        db,
4027cf643729Sdrh        pInfo->aFunc,
4028cf643729Sdrh        sizeof(pInfo->aFunc[0]),
4029cf643729Sdrh        &pInfo->nFunc,
4030cf643729Sdrh        &i
4031cf643729Sdrh   );
403213449892Sdrh   return i;
40332282792aSdrh }
40342282792aSdrh 
40352282792aSdrh /*
40367d10d5a6Sdrh ** This is the xExprCallback for a tree walker.  It is used to
40377d10d5a6Sdrh ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
4038626a879aSdrh ** for additional information.
40392282792aSdrh */
40407d10d5a6Sdrh static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
40412282792aSdrh   int i;
40427d10d5a6Sdrh   NameContext *pNC = pWalker->u.pNC;
4043a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
4044a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
404513449892Sdrh   AggInfo *pAggInfo = pNC->pAggInfo;
404613449892Sdrh 
40472282792aSdrh   switch( pExpr->op ){
404889c69d00Sdrh     case TK_AGG_COLUMN:
4049967e8b73Sdrh     case TK_COLUMN: {
40508b213899Sdrh       testcase( pExpr->op==TK_AGG_COLUMN );
40518b213899Sdrh       testcase( pExpr->op==TK_COLUMN );
405213449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
405313449892Sdrh       ** clause of the aggregate query */
405420bc393cSdrh       if( ALWAYS(pSrcList!=0) ){
405513449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
405613449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
405713449892Sdrh           struct AggInfo_col *pCol;
4058c5cd1249Sdrh           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
405913449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
406013449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
406113449892Sdrh             ** that is in the FROM clause of the aggregate query.
406213449892Sdrh             **
406313449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
406413449892Sdrh             ** is not an entry there already.
406513449892Sdrh             */
40667f906d63Sdrh             int k;
406713449892Sdrh             pCol = pAggInfo->aCol;
40687f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
406913449892Sdrh               if( pCol->iTable==pExpr->iTable &&
407013449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
40712282792aSdrh                 break;
40722282792aSdrh               }
40732282792aSdrh             }
40741e536953Sdanielk1977             if( (k>=pAggInfo->nColumn)
40751e536953Sdanielk1977              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
40761e536953Sdanielk1977             ){
40777f906d63Sdrh               pCol = &pAggInfo->aCol[k];
40780817d0dfSdanielk1977               pCol->pTab = pExpr->pTab;
407913449892Sdrh               pCol->iTable = pExpr->iTable;
408013449892Sdrh               pCol->iColumn = pExpr->iColumn;
40810a07c107Sdrh               pCol->iMem = ++pParse->nMem;
408213449892Sdrh               pCol->iSorterColumn = -1;
40835774b806Sdrh               pCol->pExpr = pExpr;
408413449892Sdrh               if( pAggInfo->pGroupBy ){
408513449892Sdrh                 int j, n;
408613449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
408713449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
408813449892Sdrh                 n = pGB->nExpr;
408913449892Sdrh                 for(j=0; j<n; j++, pTerm++){
409013449892Sdrh                   Expr *pE = pTerm->pExpr;
409113449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
409213449892Sdrh                       pE->iColumn==pExpr->iColumn ){
409313449892Sdrh                     pCol->iSorterColumn = j;
409413449892Sdrh                     break;
40952282792aSdrh                   }
409613449892Sdrh                 }
409713449892Sdrh               }
409813449892Sdrh               if( pCol->iSorterColumn<0 ){
409913449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
410013449892Sdrh               }
410113449892Sdrh             }
410213449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
410313449892Sdrh             ** because it was there before or because we just created it).
410413449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
410513449892Sdrh             ** pAggInfo->aCol[] entry.
410613449892Sdrh             */
4107ebb6a65dSdrh             ExprSetVVAProperty(pExpr, EP_NoReduce);
410813449892Sdrh             pExpr->pAggInfo = pAggInfo;
410913449892Sdrh             pExpr->op = TK_AGG_COLUMN;
4110cf697396Sshane             pExpr->iAgg = (i16)k;
411113449892Sdrh             break;
411213449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
411313449892Sdrh         } /* end loop over pSrcList */
4114a58fdfb1Sdanielk1977       }
41157d10d5a6Sdrh       return WRC_Prune;
41162282792aSdrh     }
41172282792aSdrh     case TK_AGG_FUNCTION: {
41183a8c4be7Sdrh       if( (pNC->ncFlags & NC_InAggFunc)==0
4119ed551b95Sdrh        && pWalker->walkerDepth==pExpr->op2
41203a8c4be7Sdrh       ){
412113449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
412213449892Sdrh         ** function that is already in the pAggInfo structure
412313449892Sdrh         */
412413449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
412513449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
4126619a1305Sdrh           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
41272282792aSdrh             break;
41282282792aSdrh           }
41292282792aSdrh         }
413013449892Sdrh         if( i>=pAggInfo->nFunc ){
413113449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
413213449892Sdrh           */
413314db2665Sdanielk1977           u8 enc = ENC(pParse->db);
41341e536953Sdanielk1977           i = addAggInfoFunc(pParse->db, pAggInfo);
413513449892Sdrh           if( i>=0 ){
41366ab3a2ecSdanielk1977             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
413713449892Sdrh             pItem = &pAggInfo->aFunc[i];
413813449892Sdrh             pItem->pExpr = pExpr;
41390a07c107Sdrh             pItem->iMem = ++pParse->nMem;
414033e619fcSdrh             assert( !ExprHasProperty(pExpr, EP_IntValue) );
414113449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
414280738d9cSdrh                    pExpr->u.zToken,
41436ab3a2ecSdanielk1977                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
4144fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
4145fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
4146fd357974Sdrh             }else{
4147fd357974Sdrh               pItem->iDistinct = -1;
4148fd357974Sdrh             }
41492282792aSdrh           }
415013449892Sdrh         }
415113449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
415213449892Sdrh         */
4153c5cd1249Sdrh         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
4154ebb6a65dSdrh         ExprSetVVAProperty(pExpr, EP_NoReduce);
4155cf697396Sshane         pExpr->iAgg = (i16)i;
415613449892Sdrh         pExpr->pAggInfo = pAggInfo;
41573a8c4be7Sdrh         return WRC_Prune;
41586e83a57fSdrh       }else{
41596e83a57fSdrh         return WRC_Continue;
41606e83a57fSdrh       }
41612282792aSdrh     }
4162a58fdfb1Sdanielk1977   }
41637d10d5a6Sdrh   return WRC_Continue;
41647d10d5a6Sdrh }
41657d10d5a6Sdrh static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
4166d5a336efSdrh   UNUSED_PARAMETER(pWalker);
4167d5a336efSdrh   UNUSED_PARAMETER(pSelect);
41687d10d5a6Sdrh   return WRC_Continue;
4169a58fdfb1Sdanielk1977 }
4170626a879aSdrh 
4171626a879aSdrh /*
4172e8abb4caSdrh ** Analyze the pExpr expression looking for aggregate functions and
4173e8abb4caSdrh ** for variables that need to be added to AggInfo object that pNC->pAggInfo
4174e8abb4caSdrh ** points to.  Additional entries are made on the AggInfo object as
4175e8abb4caSdrh ** necessary.
4176626a879aSdrh **
4177626a879aSdrh ** This routine should only be called after the expression has been
41787d10d5a6Sdrh ** analyzed by sqlite3ResolveExprNames().
4179626a879aSdrh */
4180d2b3e23bSdrh void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
41817d10d5a6Sdrh   Walker w;
4182374fdce4Sdrh   memset(&w, 0, sizeof(w));
41837d10d5a6Sdrh   w.xExprCallback = analyzeAggregate;
41847d10d5a6Sdrh   w.xSelectCallback = analyzeAggregatesInSelect;
41857d10d5a6Sdrh   w.u.pNC = pNC;
418620bc393cSdrh   assert( pNC->pSrcList!=0 );
41877d10d5a6Sdrh   sqlite3WalkExpr(&w, pExpr);
41882282792aSdrh }
41895d9a4af9Sdrh 
41905d9a4af9Sdrh /*
41915d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
41925d9a4af9Sdrh ** expression list.  Return the number of errors.
41935d9a4af9Sdrh **
41945d9a4af9Sdrh ** If an error is found, the analysis is cut short.
41955d9a4af9Sdrh */
4196d2b3e23bSdrh void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
41975d9a4af9Sdrh   struct ExprList_item *pItem;
41985d9a4af9Sdrh   int i;
41995d9a4af9Sdrh   if( pList ){
4200d2b3e23bSdrh     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4201d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
42025d9a4af9Sdrh     }
42035d9a4af9Sdrh   }
42045d9a4af9Sdrh }
4205892d3179Sdrh 
4206892d3179Sdrh /*
4207ceea3321Sdrh ** Allocate a single new register for use to hold some intermediate result.
4208892d3179Sdrh */
4209892d3179Sdrh int sqlite3GetTempReg(Parse *pParse){
4210e55cbd72Sdrh   if( pParse->nTempReg==0 ){
4211892d3179Sdrh     return ++pParse->nMem;
4212892d3179Sdrh   }
42132f425f6bSdanielk1977   return pParse->aTempReg[--pParse->nTempReg];
4214892d3179Sdrh }
4215ceea3321Sdrh 
4216ceea3321Sdrh /*
4217ceea3321Sdrh ** Deallocate a register, making available for reuse for some other
4218ceea3321Sdrh ** purpose.
4219ceea3321Sdrh **
4220ceea3321Sdrh ** If a register is currently being used by the column cache, then
422160ec914cSpeter.d.reid ** the deallocation is deferred until the column cache line that uses
4222ceea3321Sdrh ** the register becomes stale.
4223ceea3321Sdrh */
4224892d3179Sdrh void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
42252dcef11bSdrh   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
4226ceea3321Sdrh     int i;
4227ceea3321Sdrh     struct yColCache *p;
4228ceea3321Sdrh     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4229ceea3321Sdrh       if( p->iReg==iReg ){
4230ceea3321Sdrh         p->tempReg = 1;
4231ceea3321Sdrh         return;
4232ceea3321Sdrh       }
4233ceea3321Sdrh     }
4234892d3179Sdrh     pParse->aTempReg[pParse->nTempReg++] = iReg;
4235892d3179Sdrh   }
4236892d3179Sdrh }
4237892d3179Sdrh 
4238892d3179Sdrh /*
4239892d3179Sdrh ** Allocate or deallocate a block of nReg consecutive registers
4240892d3179Sdrh */
4241892d3179Sdrh int sqlite3GetTempRange(Parse *pParse, int nReg){
4242e55cbd72Sdrh   int i, n;
4243892d3179Sdrh   i = pParse->iRangeReg;
4244e55cbd72Sdrh   n = pParse->nRangeReg;
4245f49f3523Sdrh   if( nReg<=n ){
4246f49f3523Sdrh     assert( !usedAsColumnCache(pParse, i, i+n-1) );
4247892d3179Sdrh     pParse->iRangeReg += nReg;
4248892d3179Sdrh     pParse->nRangeReg -= nReg;
4249892d3179Sdrh   }else{
4250892d3179Sdrh     i = pParse->nMem+1;
4251892d3179Sdrh     pParse->nMem += nReg;
4252892d3179Sdrh   }
4253892d3179Sdrh   return i;
4254892d3179Sdrh }
4255892d3179Sdrh void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
4256f49f3523Sdrh   sqlite3ExprCacheRemove(pParse, iReg, nReg);
4257892d3179Sdrh   if( nReg>pParse->nRangeReg ){
4258892d3179Sdrh     pParse->nRangeReg = nReg;
4259892d3179Sdrh     pParse->iRangeReg = iReg;
4260892d3179Sdrh   }
4261892d3179Sdrh }
4262cdc69557Sdrh 
4263cdc69557Sdrh /*
4264cdc69557Sdrh ** Mark all temporary registers as being unavailable for reuse.
4265cdc69557Sdrh */
4266cdc69557Sdrh void sqlite3ClearTempRegCache(Parse *pParse){
4267cdc69557Sdrh   pParse->nTempReg = 0;
4268cdc69557Sdrh   pParse->nRangeReg = 0;
4269cdc69557Sdrh }
4270bb9b5f26Sdrh 
4271bb9b5f26Sdrh /*
4272bb9b5f26Sdrh ** Validate that no temporary register falls within the range of
4273bb9b5f26Sdrh ** iFirst..iLast, inclusive.  This routine is only call from within assert()
4274bb9b5f26Sdrh ** statements.
4275bb9b5f26Sdrh */
4276bb9b5f26Sdrh #ifdef SQLITE_DEBUG
4277bb9b5f26Sdrh int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
4278bb9b5f26Sdrh   int i;
4279bb9b5f26Sdrh   if( pParse->nRangeReg>0
4280bb9b5f26Sdrh    && pParse->iRangeReg+pParse->nRangeReg<iLast
4281bb9b5f26Sdrh    && pParse->iRangeReg>=iFirst
4282bb9b5f26Sdrh   ){
4283bb9b5f26Sdrh      return 0;
4284bb9b5f26Sdrh   }
4285bb9b5f26Sdrh   for(i=0; i<pParse->nTempReg; i++){
4286bb9b5f26Sdrh     if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
4287bb9b5f26Sdrh       return 0;
4288bb9b5f26Sdrh     }
4289bb9b5f26Sdrh   }
4290bb9b5f26Sdrh   return 1;
4291bb9b5f26Sdrh }
4292bb9b5f26Sdrh #endif /* SQLITE_DEBUG */
4293