xref: /sqlite-3.40.0/src/expr.c (revision a7d6db6a)
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 
1712abf408Sdrh /* Forward declarations */
1812abf408Sdrh static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
1912abf408Sdrh static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
2012abf408Sdrh 
210dfa4f6fSdrh /*
220dfa4f6fSdrh ** Return the affinity character for a single column of a table.
230dfa4f6fSdrh */
240dfa4f6fSdrh char sqlite3TableColumnAffinity(Table *pTab, int iCol){
250dfa4f6fSdrh   assert( iCol<pTab->nCol );
260dfa4f6fSdrh   return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
270dfa4f6fSdrh }
2812abf408Sdrh 
29e014a838Sdanielk1977 /*
30e014a838Sdanielk1977 ** Return the 'affinity' of the expression pExpr if any.
31e014a838Sdanielk1977 **
32e014a838Sdanielk1977 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33e014a838Sdanielk1977 ** or a sub-select with a column as the return value, then the
34e014a838Sdanielk1977 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35e014a838Sdanielk1977 ** indicating no affinity for the expression.
36e014a838Sdanielk1977 **
3760ec914cSpeter.d.reid ** i.e. the WHERE clause expressions in the following statements all
38e014a838Sdanielk1977 ** have an affinity:
39e014a838Sdanielk1977 **
40e014a838Sdanielk1977 ** CREATE TABLE t1(a);
41e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE a;
42e014a838Sdanielk1977 ** SELECT a AS b FROM t1 WHERE b;
43e014a838Sdanielk1977 ** SELECT * FROM t1 WHERE (select a from t1);
44e014a838Sdanielk1977 */
45bf3b721fSdanielk1977 char sqlite3ExprAffinity(Expr *pExpr){
46580c8c18Sdrh   int op;
479bec6fb3Smistachkin   if( pExpr->flags & EP_Generic ) return 0;
48*a7d6db6aSdrh   while( ExprHasProperty(pExpr, EP_Skip) ){
49*a7d6db6aSdrh     assert( pExpr->op==TK_COLLATE );
50*a7d6db6aSdrh     pExpr = pExpr->pLeft;
51*a7d6db6aSdrh     assert( pExpr!=0 );
52*a7d6db6aSdrh   }
53580c8c18Sdrh   op = pExpr->op;
54487e262fSdrh   if( op==TK_SELECT ){
556ab3a2ecSdanielk1977     assert( pExpr->flags&EP_xIsSelect );
566ab3a2ecSdanielk1977     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
57a37cdde0Sdanielk1977   }
58db45bd5eSdrh   if( op==TK_REGISTER ) op = pExpr->op2;
59487e262fSdrh #ifndef SQLITE_OMIT_CAST
60487e262fSdrh   if( op==TK_CAST ){
6133e619fcSdrh     assert( !ExprHasProperty(pExpr, EP_IntValue) );
62fdaac671Sdrh     return sqlite3AffinityType(pExpr->u.zToken, 0);
63487e262fSdrh   }
64487e262fSdrh #endif
65eda079cdSdrh   if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
66eda079cdSdrh     return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
677d10d5a6Sdrh   }
6880aa5453Sdan   if( op==TK_SELECT_COLUMN ){
6980aa5453Sdan     assert( pExpr->pLeft->flags&EP_xIsSelect );
7080aa5453Sdan     return sqlite3ExprAffinity(
7180aa5453Sdan         pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
7280aa5453Sdan     );
7380aa5453Sdan   }
74a37cdde0Sdanielk1977   return pExpr->affinity;
75a37cdde0Sdanielk1977 }
76a37cdde0Sdanielk1977 
7753db1458Sdrh /*
788b4c40d8Sdrh ** Set the collating sequence for expression pExpr to be the collating
79ae80ddeaSdrh ** sequence named by pToken.   Return a pointer to a new Expr node that
80ae80ddeaSdrh ** implements the COLLATE operator.
810a8a406eSdrh **
820a8a406eSdrh ** If a memory allocation error occurs, that fact is recorded in pParse->db
830a8a406eSdrh ** and the pExpr parameter is returned unchanged.
848b4c40d8Sdrh */
854ef7efadSdrh Expr *sqlite3ExprAddCollateToken(
864ef7efadSdrh   Parse *pParse,           /* Parsing context */
874ef7efadSdrh   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
8880103fc6Sdan   const Token *pCollName,  /* Name of collating sequence */
8980103fc6Sdan   int dequote              /* True to dequote pCollName */
904ef7efadSdrh ){
910a8a406eSdrh   if( pCollName->n>0 ){
9280103fc6Sdan     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
93ae80ddeaSdrh     if( pNew ){
94ae80ddeaSdrh       pNew->pLeft = pExpr;
95a4c3c87eSdrh       pNew->flags |= EP_Collate|EP_Skip;
960a8a406eSdrh       pExpr = pNew;
97ae80ddeaSdrh     }
980a8a406eSdrh   }
990a8a406eSdrh   return pExpr;
1000a8a406eSdrh }
1010a8a406eSdrh Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
1020a8a406eSdrh   Token s;
103261d8a51Sdrh   assert( zC!=0 );
10440aced5cSdrh   sqlite3TokenInit(&s, (char*)zC);
10580103fc6Sdan   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
1060a8a406eSdrh }
1070a8a406eSdrh 
1080a8a406eSdrh /*
1090b8d255cSdrh ** Skip over any TK_COLLATE operators and any unlikely()
110a4c3c87eSdrh ** or likelihood() function at the root of an expression.
1110a8a406eSdrh */
1120a8a406eSdrh Expr *sqlite3ExprSkipCollate(Expr *pExpr){
113*a7d6db6aSdrh   while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
114a4c3c87eSdrh     if( ExprHasProperty(pExpr, EP_Unlikely) ){
115cca9f3d2Sdrh       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
116cca9f3d2Sdrh       assert( pExpr->x.pList->nExpr>0 );
117a4c3c87eSdrh       assert( pExpr->op==TK_FUNCTION );
118cca9f3d2Sdrh       pExpr = pExpr->x.pList->a[0].pExpr;
119cca9f3d2Sdrh     }else{
1200b8d255cSdrh       assert( pExpr->op==TK_COLLATE );
121d91eba96Sdrh       pExpr = pExpr->pLeft;
122cca9f3d2Sdrh     }
123d91eba96Sdrh   }
1240a8a406eSdrh   return pExpr;
1258b4c40d8Sdrh }
1268b4c40d8Sdrh 
1278b4c40d8Sdrh /*
128ae80ddeaSdrh ** Return the collation sequence for the expression pExpr. If
129ae80ddeaSdrh ** there is no defined collating sequence, return NULL.
130ae80ddeaSdrh **
13170efa84dSdrh ** See also: sqlite3ExprNNCollSeq()
13270efa84dSdrh **
13370efa84dSdrh ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
13470efa84dSdrh ** default collation if pExpr has no defined collation.
13570efa84dSdrh **
136ae80ddeaSdrh ** The collating sequence might be determined by a COLLATE operator
137ae80ddeaSdrh ** or by the presence of a column with a defined collating sequence.
138ae80ddeaSdrh ** COLLATE operators take first precedence.  Left operands take
139ae80ddeaSdrh ** precedence over right operands.
1400202b29eSdanielk1977 */
1417cedc8d4Sdanielk1977 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
142ae80ddeaSdrh   sqlite3 *db = pParse->db;
1437cedc8d4Sdanielk1977   CollSeq *pColl = 0;
1447d10d5a6Sdrh   Expr *p = pExpr;
145261d8a51Sdrh   while( p ){
146ae80ddeaSdrh     int op = p->op;
147fbb24d10Sdrh     if( p->flags & EP_Generic ) break;
148cb0e04f9Sdrh     if( op==TK_REGISTER ) op = p->op2;
149cb0e04f9Sdrh     if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
150eda079cdSdrh      && p->y.pTab!=0
151ae80ddeaSdrh     ){
152eda079cdSdrh       /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
1537d10d5a6Sdrh       ** a TK_COLUMN but was previously evaluated and cached in a register */
1547d10d5a6Sdrh       int j = p->iColumn;
1557d10d5a6Sdrh       if( j>=0 ){
156eda079cdSdrh         const char *zColl = p->y.pTab->aCol[j].zColl;
157c4a64facSdrh         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
1580202b29eSdanielk1977       }
1597d10d5a6Sdrh       break;
1607d10d5a6Sdrh     }
161e081d73cSdrh     if( op==TK_CAST || op==TK_UPLUS ){
162e081d73cSdrh       p = p->pLeft;
163e081d73cSdrh       continue;
164e081d73cSdrh     }
165cb0e04f9Sdrh     if( op==TK_COLLATE ){
166e081d73cSdrh       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
167e081d73cSdrh       break;
168e081d73cSdrh     }
169ae80ddeaSdrh     if( p->flags & EP_Collate ){
1702308ed38Sdrh       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
1717d10d5a6Sdrh         p = p->pLeft;
172ae80ddeaSdrh       }else{
1732308ed38Sdrh         Expr *pNext  = p->pRight;
1746728cd91Sdrh         /* The Expr.x union is never used at the same time as Expr.pRight */
1756728cd91Sdrh         assert( p->x.pList==0 || p->pRight==0 );
1766728cd91Sdrh         /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
1776728cd91Sdrh         ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
1786728cd91Sdrh         ** least one EP_Collate. Thus the following two ALWAYS. */
1796728cd91Sdrh         if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
1802308ed38Sdrh           int i;
1816728cd91Sdrh           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
1822308ed38Sdrh             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
1832308ed38Sdrh               pNext = p->x.pList->a[i].pExpr;
1842308ed38Sdrh               break;
1852308ed38Sdrh             }
1862308ed38Sdrh           }
1872308ed38Sdrh         }
1882308ed38Sdrh         p = pNext;
189ae80ddeaSdrh       }
190ae80ddeaSdrh     }else{
191ae80ddeaSdrh       break;
192ae80ddeaSdrh     }
1930202b29eSdanielk1977   }
1947cedc8d4Sdanielk1977   if( sqlite3CheckCollSeq(pParse, pColl) ){
1957cedc8d4Sdanielk1977     pColl = 0;
1967cedc8d4Sdanielk1977   }
1977cedc8d4Sdanielk1977   return pColl;
1980202b29eSdanielk1977 }
1990202b29eSdanielk1977 
2000202b29eSdanielk1977 /*
20170efa84dSdrh ** Return the collation sequence for the expression pExpr. If
20270efa84dSdrh ** there is no defined collating sequence, return a pointer to the
20370efa84dSdrh ** defautl collation sequence.
20470efa84dSdrh **
20570efa84dSdrh ** See also: sqlite3ExprCollSeq()
20670efa84dSdrh **
20770efa84dSdrh ** The sqlite3ExprCollSeq() routine works the same except that it
20870efa84dSdrh ** returns NULL if there is no defined collation.
20970efa84dSdrh */
21070efa84dSdrh CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
21170efa84dSdrh   CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
21270efa84dSdrh   if( p==0 ) p = pParse->db->pDfltColl;
21370efa84dSdrh   assert( p!=0 );
21470efa84dSdrh   return p;
21570efa84dSdrh }
21670efa84dSdrh 
21770efa84dSdrh /*
21870efa84dSdrh ** Return TRUE if the two expressions have equivalent collating sequences.
21970efa84dSdrh */
22070efa84dSdrh int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
22170efa84dSdrh   CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
22270efa84dSdrh   CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
22370efa84dSdrh   return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
22470efa84dSdrh }
22570efa84dSdrh 
22670efa84dSdrh /*
227626a879aSdrh ** pExpr is an operand of a comparison operator.  aff2 is the
228626a879aSdrh ** type affinity of the other operand.  This routine returns the
22953db1458Sdrh ** type affinity that should be used for the comparison operator.
23053db1458Sdrh */
231e014a838Sdanielk1977 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
232bf3b721fSdanielk1977   char aff1 = sqlite3ExprAffinity(pExpr);
233e014a838Sdanielk1977   if( aff1 && aff2 ){
2348df447f0Sdrh     /* Both sides of the comparison are columns. If one has numeric
2358df447f0Sdrh     ** affinity, use that. Otherwise use no affinity.
236e014a838Sdanielk1977     */
2378a51256cSdrh     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
238e014a838Sdanielk1977       return SQLITE_AFF_NUMERIC;
239e014a838Sdanielk1977     }else{
24005883a34Sdrh       return SQLITE_AFF_BLOB;
241e014a838Sdanielk1977     }
242e014a838Sdanielk1977   }else if( !aff1 && !aff2 ){
2435f6a87b3Sdrh     /* Neither side of the comparison is a column.  Compare the
2445f6a87b3Sdrh     ** results directly.
245e014a838Sdanielk1977     */
24605883a34Sdrh     return SQLITE_AFF_BLOB;
247e014a838Sdanielk1977   }else{
248e014a838Sdanielk1977     /* One side is a column, the other is not. Use the columns affinity. */
249fe05af87Sdrh     assert( aff1==0 || aff2==0 );
250e014a838Sdanielk1977     return (aff1 + aff2);
251e014a838Sdanielk1977   }
252e014a838Sdanielk1977 }
253e014a838Sdanielk1977 
25453db1458Sdrh /*
25553db1458Sdrh ** pExpr is a comparison operator.  Return the type affinity that should
25653db1458Sdrh ** be applied to both operands prior to doing the comparison.
25753db1458Sdrh */
258e014a838Sdanielk1977 static char comparisonAffinity(Expr *pExpr){
259e014a838Sdanielk1977   char aff;
260e014a838Sdanielk1977   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
261e014a838Sdanielk1977           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
2626a2fe093Sdrh           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
263e014a838Sdanielk1977   assert( pExpr->pLeft );
264bf3b721fSdanielk1977   aff = sqlite3ExprAffinity(pExpr->pLeft);
265e014a838Sdanielk1977   if( pExpr->pRight ){
266e014a838Sdanielk1977     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
2676ab3a2ecSdanielk1977   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2686ab3a2ecSdanielk1977     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
26913ac46eeSdrh   }else if( aff==0 ){
27005883a34Sdrh     aff = SQLITE_AFF_BLOB;
271e014a838Sdanielk1977   }
272e014a838Sdanielk1977   return aff;
273e014a838Sdanielk1977 }
274e014a838Sdanielk1977 
275e014a838Sdanielk1977 /*
276e014a838Sdanielk1977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
277e014a838Sdanielk1977 ** idx_affinity is the affinity of an indexed column. Return true
278e014a838Sdanielk1977 ** if the index with affinity idx_affinity may be used to implement
279e014a838Sdanielk1977 ** the comparison in pExpr.
280e014a838Sdanielk1977 */
281e014a838Sdanielk1977 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
282e014a838Sdanielk1977   char aff = comparisonAffinity(pExpr);
2838a51256cSdrh   switch( aff ){
28405883a34Sdrh     case SQLITE_AFF_BLOB:
2858a51256cSdrh       return 1;
2868a51256cSdrh     case SQLITE_AFF_TEXT:
2878a51256cSdrh       return idx_affinity==SQLITE_AFF_TEXT;
2888a51256cSdrh     default:
2898a51256cSdrh       return sqlite3IsNumericAffinity(idx_affinity);
2908a51256cSdrh   }
291e014a838Sdanielk1977 }
292e014a838Sdanielk1977 
293a37cdde0Sdanielk1977 /*
29435573356Sdrh ** Return the P5 value that should be used for a binary comparison
295a37cdde0Sdanielk1977 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
296a37cdde0Sdanielk1977 */
29735573356Sdrh static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
29835573356Sdrh   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
2991bd10f8aSdrh   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
30035573356Sdrh   return aff;
301a37cdde0Sdanielk1977 }
302a37cdde0Sdanielk1977 
303a2e00042Sdrh /*
3040202b29eSdanielk1977 ** Return a pointer to the collation sequence that should be used by
3050202b29eSdanielk1977 ** a binary comparison operator comparing pLeft and pRight.
3060202b29eSdanielk1977 **
3070202b29eSdanielk1977 ** If the left hand expression has a collating sequence type, then it is
3080202b29eSdanielk1977 ** used. Otherwise the collation sequence for the right hand expression
3090202b29eSdanielk1977 ** is used, or the default (BINARY) if neither expression has a collating
3100202b29eSdanielk1977 ** type.
311bcbb04e5Sdanielk1977 **
312bcbb04e5Sdanielk1977 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
313bcbb04e5Sdanielk1977 ** it is not considered.
3140202b29eSdanielk1977 */
315bcbb04e5Sdanielk1977 CollSeq *sqlite3BinaryCompareCollSeq(
316bcbb04e5Sdanielk1977   Parse *pParse,
317bcbb04e5Sdanielk1977   Expr *pLeft,
318bcbb04e5Sdanielk1977   Expr *pRight
319bcbb04e5Sdanielk1977 ){
320ec41ddacSdrh   CollSeq *pColl;
321ec41ddacSdrh   assert( pLeft );
322ae80ddeaSdrh   if( pLeft->flags & EP_Collate ){
323ae80ddeaSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
324ae80ddeaSdrh   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
325ae80ddeaSdrh     pColl = sqlite3ExprCollSeq(pParse, pRight);
326ec41ddacSdrh   }else{
327ec41ddacSdrh     pColl = sqlite3ExprCollSeq(pParse, pLeft);
3280202b29eSdanielk1977     if( !pColl ){
3297cedc8d4Sdanielk1977       pColl = sqlite3ExprCollSeq(pParse, pRight);
3300202b29eSdanielk1977     }
331ec41ddacSdrh   }
3320202b29eSdanielk1977   return pColl;
3330202b29eSdanielk1977 }
3340202b29eSdanielk1977 
3350202b29eSdanielk1977 /*
336be5c89acSdrh ** Generate code for a comparison operator.
337be5c89acSdrh */
338be5c89acSdrh static int codeCompare(
339be5c89acSdrh   Parse *pParse,    /* The parsing (and code generating) context */
340be5c89acSdrh   Expr *pLeft,      /* The left operand */
341be5c89acSdrh   Expr *pRight,     /* The right operand */
342be5c89acSdrh   int opcode,       /* The comparison opcode */
34335573356Sdrh   int in1, int in2, /* Register holding operands */
344be5c89acSdrh   int dest,         /* Jump here if true.  */
345be5c89acSdrh   int jumpIfNull    /* If true, jump if either operand is NULL */
346be5c89acSdrh ){
34735573356Sdrh   int p5;
34835573356Sdrh   int addr;
34935573356Sdrh   CollSeq *p4;
35035573356Sdrh 
35135573356Sdrh   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
35235573356Sdrh   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
35335573356Sdrh   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
35435573356Sdrh                            (void*)p4, P4_COLLSEQ);
3551bd10f8aSdrh   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
35635573356Sdrh   return addr;
357be5c89acSdrh }
358be5c89acSdrh 
359cfbb5e82Sdan /*
360870a0705Sdan ** Return true if expression pExpr is a vector, or false otherwise.
361d832da7fSdrh **
362d832da7fSdrh ** A vector is defined as any expression that results in two or more
363d832da7fSdrh ** columns of result.  Every TK_VECTOR node is an vector because the
364d832da7fSdrh ** parser will not generate a TK_VECTOR with fewer than two entries.
365d832da7fSdrh ** But a TK_SELECT might be either a vector or a scalar. It is only
366d832da7fSdrh ** considered a vector if it has two or more result columns.
367870a0705Sdan */
368870a0705Sdan int sqlite3ExprIsVector(Expr *pExpr){
36976dbe7a8Sdrh   return sqlite3ExprVectorSize(pExpr)>1;
370870a0705Sdan }
371870a0705Sdan 
372870a0705Sdan /*
373cfbb5e82Sdan ** If the expression passed as the only argument is of type TK_VECTOR
374cfbb5e82Sdan ** return the number of expressions in the vector. Or, if the expression
375cfbb5e82Sdan ** is a sub-select, return the number of columns in the sub-select. For
376cfbb5e82Sdan ** any other type of expression, return 1.
377cfbb5e82Sdan */
37871c57db0Sdan int sqlite3ExprVectorSize(Expr *pExpr){
37912abf408Sdrh   u8 op = pExpr->op;
38012abf408Sdrh   if( op==TK_REGISTER ) op = pExpr->op2;
38112abf408Sdrh   if( op==TK_VECTOR ){
38271c57db0Sdan     return pExpr->x.pList->nExpr;
38312abf408Sdrh   }else if( op==TK_SELECT ){
38476dbe7a8Sdrh     return pExpr->x.pSelect->pEList->nExpr;
38576dbe7a8Sdrh   }else{
38676dbe7a8Sdrh     return 1;
38776dbe7a8Sdrh   }
38871c57db0Sdan }
38971c57db0Sdan 
390ba00e30aSdan /*
391fc7f27b9Sdrh ** Return a pointer to a subexpression of pVector that is the i-th
392fc7f27b9Sdrh ** column of the vector (numbered starting with 0).  The caller must
393fc7f27b9Sdrh ** ensure that i is within range.
394fc7f27b9Sdrh **
39576dbe7a8Sdrh ** If pVector is really a scalar (and "scalar" here includes subqueries
39676dbe7a8Sdrh ** that return a single column!) then return pVector unmodified.
39776dbe7a8Sdrh **
398fc7f27b9Sdrh ** pVector retains ownership of the returned subexpression.
399fc7f27b9Sdrh **
400fc7f27b9Sdrh ** If the vector is a (SELECT ...) then the expression returned is
40176dbe7a8Sdrh ** just the expression for the i-th term of the result set, and may
40276dbe7a8Sdrh ** not be ready for evaluation because the table cursor has not yet
40376dbe7a8Sdrh ** been positioned.
404ba00e30aSdan */
405fc7f27b9Sdrh Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
406870a0705Sdan   assert( i<sqlite3ExprVectorSize(pVector) );
407870a0705Sdan   if( sqlite3ExprIsVector(pVector) ){
4089f24b53dSdrh     assert( pVector->op2==0 || pVector->op==TK_REGISTER );
4099f24b53dSdrh     if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
41071c57db0Sdan       return pVector->x.pSelect->pEList->a[i].pExpr;
411870a0705Sdan     }else{
41271c57db0Sdan       return pVector->x.pList->a[i].pExpr;
41371c57db0Sdan     }
414870a0705Sdan   }
415870a0705Sdan   return pVector;
416870a0705Sdan }
417fc7f27b9Sdrh 
418fc7f27b9Sdrh /*
419fc7f27b9Sdrh ** Compute and return a new Expr object which when passed to
420fc7f27b9Sdrh ** sqlite3ExprCode() will generate all necessary code to compute
421fc7f27b9Sdrh ** the iField-th column of the vector expression pVector.
422fc7f27b9Sdrh **
4238762ec19Sdrh ** It is ok for pVector to be a scalar (as long as iField==0).
4248762ec19Sdrh ** In that case, this routine works like sqlite3ExprDup().
4258762ec19Sdrh **
426fc7f27b9Sdrh ** The caller owns the returned Expr object and is responsible for
427fc7f27b9Sdrh ** ensuring that the returned value eventually gets freed.
428fc7f27b9Sdrh **
4298762ec19Sdrh ** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
430fad0e70cSdan ** then the returned object will reference pVector and so pVector must remain
4318762ec19Sdrh ** valid for the life of the returned object.  If pVector is a TK_VECTOR
4328762ec19Sdrh ** or a scalar expression, then it can be deleted as soon as this routine
43376dbe7a8Sdrh ** returns.
4348762ec19Sdrh **
4358762ec19Sdrh ** A trick to cause a TK_SELECT pVector to be deleted together with
4368762ec19Sdrh ** the returned Expr object is to attach the pVector to the pRight field
4378762ec19Sdrh ** of the returned TK_SELECT_COLUMN Expr object.
438fc7f27b9Sdrh */
439fc7f27b9Sdrh Expr *sqlite3ExprForVectorField(
440fc7f27b9Sdrh   Parse *pParse,       /* Parsing context */
441fc7f27b9Sdrh   Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
442a1251bc4Sdrh   int iField           /* Which column of the vector to return */
443fc7f27b9Sdrh ){
444fc7f27b9Sdrh   Expr *pRet;
445a1251bc4Sdrh   if( pVector->op==TK_SELECT ){
446a1251bc4Sdrh     assert( pVector->flags & EP_xIsSelect );
447fc7f27b9Sdrh     /* The TK_SELECT_COLUMN Expr node:
448fc7f27b9Sdrh     **
449966e2911Sdrh     ** pLeft:           pVector containing TK_SELECT.  Not deleted.
4508762ec19Sdrh     ** pRight:          not used.  But recursively deleted.
451fc7f27b9Sdrh     ** iColumn:         Index of a column in pVector
452966e2911Sdrh     ** iTable:          0 or the number of columns on the LHS of an assignment
453fc7f27b9Sdrh     ** pLeft->iTable:   First in an array of register holding result, or 0
454fc7f27b9Sdrh     **                  if the result is not yet computed.
455fc7f27b9Sdrh     **
456fc7f27b9Sdrh     ** sqlite3ExprDelete() specifically skips the recursive delete of
457fc7f27b9Sdrh     ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
4588762ec19Sdrh     ** can be attached to pRight to cause this node to take ownership of
4598762ec19Sdrh     ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
4608762ec19Sdrh     ** with the same pLeft pointer to the pVector, but only one of them
4618762ec19Sdrh     ** will own the pVector.
462fc7f27b9Sdrh     */
463abfd35eaSdrh     pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
4648bd0d58eSdrh     if( pRet ){
4658bd0d58eSdrh       pRet->iColumn = iField;
4668bd0d58eSdrh       pRet->pLeft = pVector;
4678bd0d58eSdrh     }
468fc7f27b9Sdrh     assert( pRet==0 || pRet->iTable==0 );
469fc7f27b9Sdrh   }else{
470a1251bc4Sdrh     if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
471a1251bc4Sdrh     pRet = sqlite3ExprDup(pParse->db, pVector, 0);
472dfb5c963Sdan     sqlite3RenameTokenRemap(pParse, pRet, pVector);
473fc7f27b9Sdrh   }
474fc7f27b9Sdrh   return pRet;
475fc7f27b9Sdrh }
47671c57db0Sdan 
4775c288b92Sdan /*
4785c288b92Sdan ** If expression pExpr is of type TK_SELECT, generate code to evaluate
4795c288b92Sdan ** it. Return the register in which the result is stored (or, if the
4805c288b92Sdan ** sub-select returns more than one column, the first in an array
4815c288b92Sdan ** of registers in which the result is stored).
4825c288b92Sdan **
4835c288b92Sdan ** If pExpr is not a TK_SELECT expression, return 0.
4845c288b92Sdan */
4855c288b92Sdan static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
4868da209b1Sdan   int reg = 0;
487f9b2e05cSdan #ifndef SQLITE_OMIT_SUBQUERY
4885c288b92Sdan   if( pExpr->op==TK_SELECT ){
48985bcdce2Sdrh     reg = sqlite3CodeSubselect(pParse, pExpr);
4908da209b1Sdan   }
491f9b2e05cSdan #endif
4928da209b1Sdan   return reg;
4938da209b1Sdan }
4948da209b1Sdan 
4955c288b92Sdan /*
4965c288b92Sdan ** Argument pVector points to a vector expression - either a TK_VECTOR
497870a0705Sdan ** or TK_SELECT that returns more than one column. This function returns
498870a0705Sdan ** the register number of a register that contains the value of
499870a0705Sdan ** element iField of the vector.
500870a0705Sdan **
501870a0705Sdan ** If pVector is a TK_SELECT expression, then code for it must have
502870a0705Sdan ** already been generated using the exprCodeSubselect() routine. In this
503870a0705Sdan ** case parameter regSelect should be the first in an array of registers
504870a0705Sdan ** containing the results of the sub-select.
505870a0705Sdan **
506870a0705Sdan ** If pVector is of type TK_VECTOR, then code for the requested field
507870a0705Sdan ** is generated. In this case (*pRegFree) may be set to the number of
508870a0705Sdan ** a temporary register to be freed by the caller before returning.
5095c288b92Sdan **
5105c288b92Sdan ** Before returning, output parameter (*ppExpr) is set to point to the
5115c288b92Sdan ** Expr object corresponding to element iElem of the vector.
5125c288b92Sdan */
5135c288b92Sdan static int exprVectorRegister(
5145c288b92Sdan   Parse *pParse,                  /* Parse context */
5155c288b92Sdan   Expr *pVector,                  /* Vector to extract element from */
516870a0705Sdan   int iField,                     /* Field to extract from pVector */
5175c288b92Sdan   int regSelect,                  /* First in array of registers */
5185c288b92Sdan   Expr **ppExpr,                  /* OUT: Expression element */
5195c288b92Sdan   int *pRegFree                   /* OUT: Temp register to free */
5205c288b92Sdan ){
52112abf408Sdrh   u8 op = pVector->op;
522c1bcd9ccSdrh   assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
52312abf408Sdrh   if( op==TK_REGISTER ){
52412abf408Sdrh     *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
52512abf408Sdrh     return pVector->iTable+iField;
52612abf408Sdrh   }
52712abf408Sdrh   if( op==TK_SELECT ){
528870a0705Sdan     *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
529870a0705Sdan      return regSelect+iField;
5305c288b92Sdan   }
531870a0705Sdan   *ppExpr = pVector->x.pList->a[iField].pExpr;
5325c288b92Sdan   return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
5335c288b92Sdan }
5345c288b92Sdan 
5355c288b92Sdan /*
5365c288b92Sdan ** Expression pExpr is a comparison between two vector values. Compute
53779752b6eSdrh ** the result of the comparison (1, 0, or NULL) and write that
53879752b6eSdrh ** result into register dest.
53979752b6eSdrh **
54079752b6eSdrh ** The caller must satisfy the following preconditions:
54179752b6eSdrh **
54279752b6eSdrh **    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
54379752b6eSdrh **    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
54479752b6eSdrh **    otherwise:                op==pExpr->op and p5==0
5455c288b92Sdan */
54679752b6eSdrh static void codeVectorCompare(
54779752b6eSdrh   Parse *pParse,        /* Code generator context */
54879752b6eSdrh   Expr *pExpr,          /* The comparison operation */
54979752b6eSdrh   int dest,             /* Write results into this register */
55079752b6eSdrh   u8 op,                /* Comparison operator */
55179752b6eSdrh   u8 p5                 /* SQLITE_NULLEQ or zero */
55279752b6eSdrh ){
55371c57db0Sdan   Vdbe *v = pParse->pVdbe;
55471c57db0Sdan   Expr *pLeft = pExpr->pLeft;
55571c57db0Sdan   Expr *pRight = pExpr->pRight;
55671c57db0Sdan   int nLeft = sqlite3ExprVectorSize(pLeft);
55771c57db0Sdan   int i;
55871c57db0Sdan   int regLeft = 0;
55971c57db0Sdan   int regRight = 0;
56079752b6eSdrh   u8 opx = op;
561ec4ccdbcSdrh   int addrDone = sqlite3VdbeMakeLabel(pParse);
56271c57db0Sdan 
563245ce62eSdrh   if( nLeft!=sqlite3ExprVectorSize(pRight) ){
564245ce62eSdrh     sqlite3ErrorMsg(pParse, "row value misused");
565245ce62eSdrh     return;
566245ce62eSdrh   }
56771c57db0Sdan   assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
56871c57db0Sdan        || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
56971c57db0Sdan        || pExpr->op==TK_LT || pExpr->op==TK_GT
57071c57db0Sdan        || pExpr->op==TK_LE || pExpr->op==TK_GE
57171c57db0Sdan   );
57279752b6eSdrh   assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
57379752b6eSdrh             || (pExpr->op==TK_ISNOT && op==TK_NE) );
57479752b6eSdrh   assert( p5==0 || pExpr->op!=op );
57579752b6eSdrh   assert( p5==SQLITE_NULLEQ || pExpr->op==op );
57671c57db0Sdan 
57779752b6eSdrh   p5 |= SQLITE_STOREP2;
57879752b6eSdrh   if( opx==TK_LE ) opx = TK_LT;
57979752b6eSdrh   if( opx==TK_GE ) opx = TK_GT;
5805c288b92Sdan 
5815c288b92Sdan   regLeft = exprCodeSubselect(pParse, pLeft);
5825c288b92Sdan   regRight = exprCodeSubselect(pParse, pRight);
5835c288b92Sdan 
584321e828dSdrh   for(i=0; 1 /*Loop exits by "break"*/; i++){
5855c288b92Sdan     int regFree1 = 0, regFree2 = 0;
5865c288b92Sdan     Expr *pL, *pR;
5875c288b92Sdan     int r1, r2;
588321e828dSdrh     assert( i>=0 && i<nLeft );
5895c288b92Sdan     r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
5905c288b92Sdan     r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
59179752b6eSdrh     codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
59279752b6eSdrh     testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
59379752b6eSdrh     testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
59479752b6eSdrh     testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
59579752b6eSdrh     testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
59679752b6eSdrh     testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
59779752b6eSdrh     testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
59871c57db0Sdan     sqlite3ReleaseTempReg(pParse, regFree1);
59971c57db0Sdan     sqlite3ReleaseTempReg(pParse, regFree2);
60079752b6eSdrh     if( i==nLeft-1 ){
60179752b6eSdrh       break;
60271c57db0Sdan     }
60379752b6eSdrh     if( opx==TK_EQ ){
60479752b6eSdrh       sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
60579752b6eSdrh       p5 |= SQLITE_KEEPNULL;
60679752b6eSdrh     }else if( opx==TK_NE ){
60779752b6eSdrh       sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
60879752b6eSdrh       p5 |= SQLITE_KEEPNULL;
609a2f62925Sdrh     }else{
610a2f62925Sdrh       assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
611a2f62925Sdrh       sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
61279752b6eSdrh       VdbeCoverageIf(v, op==TK_LT);
61379752b6eSdrh       VdbeCoverageIf(v, op==TK_GT);
61479752b6eSdrh       VdbeCoverageIf(v, op==TK_LE);
61579752b6eSdrh       VdbeCoverageIf(v, op==TK_GE);
61679752b6eSdrh       if( i==nLeft-2 ) opx = op;
61771c57db0Sdan     }
61879752b6eSdrh   }
61979752b6eSdrh   sqlite3VdbeResolveLabel(v, addrDone);
62079752b6eSdrh }
62171c57db0Sdan 
6224b5255acSdanielk1977 #if SQLITE_MAX_EXPR_DEPTH>0
6234b5255acSdanielk1977 /*
6244b5255acSdanielk1977 ** Check that argument nHeight is less than or equal to the maximum
6254b5255acSdanielk1977 ** expression depth allowed. If it is not, leave an error message in
6264b5255acSdanielk1977 ** pParse.
6274b5255acSdanielk1977 */
6287d10d5a6Sdrh int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
6294b5255acSdanielk1977   int rc = SQLITE_OK;
6304b5255acSdanielk1977   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
6314b5255acSdanielk1977   if( nHeight>mxHeight ){
6324b5255acSdanielk1977     sqlite3ErrorMsg(pParse,
6334b5255acSdanielk1977        "Expression tree is too large (maximum depth %d)", mxHeight
6344b5255acSdanielk1977     );
6354b5255acSdanielk1977     rc = SQLITE_ERROR;
6364b5255acSdanielk1977   }
6374b5255acSdanielk1977   return rc;
6384b5255acSdanielk1977 }
6394b5255acSdanielk1977 
6404b5255acSdanielk1977 /* The following three functions, heightOfExpr(), heightOfExprList()
6414b5255acSdanielk1977 ** and heightOfSelect(), are used to determine the maximum height
6424b5255acSdanielk1977 ** of any expression tree referenced by the structure passed as the
6434b5255acSdanielk1977 ** first argument.
6444b5255acSdanielk1977 **
6454b5255acSdanielk1977 ** If this maximum height is greater than the current value pointed
6464b5255acSdanielk1977 ** to by pnHeight, the second parameter, then set *pnHeight to that
6474b5255acSdanielk1977 ** value.
6484b5255acSdanielk1977 */
6494b5255acSdanielk1977 static void heightOfExpr(Expr *p, int *pnHeight){
6504b5255acSdanielk1977   if( p ){
6514b5255acSdanielk1977     if( p->nHeight>*pnHeight ){
6524b5255acSdanielk1977       *pnHeight = p->nHeight;
6534b5255acSdanielk1977     }
6544b5255acSdanielk1977   }
6554b5255acSdanielk1977 }
6564b5255acSdanielk1977 static void heightOfExprList(ExprList *p, int *pnHeight){
6574b5255acSdanielk1977   if( p ){
6584b5255acSdanielk1977     int i;
6594b5255acSdanielk1977     for(i=0; i<p->nExpr; i++){
6604b5255acSdanielk1977       heightOfExpr(p->a[i].pExpr, pnHeight);
6614b5255acSdanielk1977     }
6624b5255acSdanielk1977   }
6634b5255acSdanielk1977 }
6641a3a3086Sdan static void heightOfSelect(Select *pSelect, int *pnHeight){
6651a3a3086Sdan   Select *p;
6661a3a3086Sdan   for(p=pSelect; p; p=p->pPrior){
6674b5255acSdanielk1977     heightOfExpr(p->pWhere, pnHeight);
6684b5255acSdanielk1977     heightOfExpr(p->pHaving, pnHeight);
6694b5255acSdanielk1977     heightOfExpr(p->pLimit, pnHeight);
6704b5255acSdanielk1977     heightOfExprList(p->pEList, pnHeight);
6714b5255acSdanielk1977     heightOfExprList(p->pGroupBy, pnHeight);
6724b5255acSdanielk1977     heightOfExprList(p->pOrderBy, pnHeight);
6734b5255acSdanielk1977   }
6744b5255acSdanielk1977 }
6754b5255acSdanielk1977 
6764b5255acSdanielk1977 /*
6774b5255acSdanielk1977 ** Set the Expr.nHeight variable in the structure passed as an
6784b5255acSdanielk1977 ** argument. An expression with no children, Expr.pList or
6794b5255acSdanielk1977 ** Expr.pSelect member has a height of 1. Any other expression
6804b5255acSdanielk1977 ** has a height equal to the maximum height of any other
6814b5255acSdanielk1977 ** referenced Expr plus one.
6822308ed38Sdrh **
6832308ed38Sdrh ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
6842308ed38Sdrh ** if appropriate.
6854b5255acSdanielk1977 */
6864b5255acSdanielk1977 static void exprSetHeight(Expr *p){
6874b5255acSdanielk1977   int nHeight = 0;
6884b5255acSdanielk1977   heightOfExpr(p->pLeft, &nHeight);
6894b5255acSdanielk1977   heightOfExpr(p->pRight, &nHeight);
6906ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_xIsSelect) ){
6916ab3a2ecSdanielk1977     heightOfSelect(p->x.pSelect, &nHeight);
6922308ed38Sdrh   }else if( p->x.pList ){
6936ab3a2ecSdanielk1977     heightOfExprList(p->x.pList, &nHeight);
6942308ed38Sdrh     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
6956ab3a2ecSdanielk1977   }
6964b5255acSdanielk1977   p->nHeight = nHeight + 1;
6974b5255acSdanielk1977 }
6984b5255acSdanielk1977 
6994b5255acSdanielk1977 /*
7004b5255acSdanielk1977 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
7014b5255acSdanielk1977 ** the height is greater than the maximum allowed expression depth,
7024b5255acSdanielk1977 ** leave an error in pParse.
7032308ed38Sdrh **
7042308ed38Sdrh ** Also propagate all EP_Propagate flags from the Expr.x.pList into
7052308ed38Sdrh ** Expr.flags.
7064b5255acSdanielk1977 */
7072308ed38Sdrh void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
70874893a4cSdrh   if( pParse->nErr ) return;
7094b5255acSdanielk1977   exprSetHeight(p);
7107d10d5a6Sdrh   sqlite3ExprCheckHeight(pParse, p->nHeight);
7114b5255acSdanielk1977 }
7124b5255acSdanielk1977 
7134b5255acSdanielk1977 /*
7144b5255acSdanielk1977 ** Return the maximum height of any expression tree referenced
7154b5255acSdanielk1977 ** by the select statement passed as an argument.
7164b5255acSdanielk1977 */
7174b5255acSdanielk1977 int sqlite3SelectExprHeight(Select *p){
7184b5255acSdanielk1977   int nHeight = 0;
7194b5255acSdanielk1977   heightOfSelect(p, &nHeight);
7204b5255acSdanielk1977   return nHeight;
7214b5255acSdanielk1977 }
7222308ed38Sdrh #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
7232308ed38Sdrh /*
7242308ed38Sdrh ** Propagate all EP_Propagate flags from the Expr.x.pList into
7252308ed38Sdrh ** Expr.flags.
7262308ed38Sdrh */
7272308ed38Sdrh void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
7282308ed38Sdrh   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
7292308ed38Sdrh     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
7302308ed38Sdrh   }
7312308ed38Sdrh }
7324b5255acSdanielk1977 #define exprSetHeight(y)
7334b5255acSdanielk1977 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
7344b5255acSdanielk1977 
735be5c89acSdrh /*
736b7916a78Sdrh ** This routine is the core allocator for Expr nodes.
737b7916a78Sdrh **
738a76b5dfcSdrh ** Construct a new expression node and return a pointer to it.  Memory
739b7916a78Sdrh ** for this node and for the pToken argument is a single allocation
740b7916a78Sdrh ** obtained from sqlite3DbMalloc().  The calling function
741a76b5dfcSdrh ** is responsible for making sure the node eventually gets freed.
742b7916a78Sdrh **
743b7916a78Sdrh ** If dequote is true, then the token (if it exists) is dequoted.
744e792b5b4Sdrh ** If dequote is false, no dequoting is performed.  The deQuote
745b7916a78Sdrh ** parameter is ignored if pToken is NULL or if the token does not
746b7916a78Sdrh ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
747b7916a78Sdrh ** then the EP_DblQuoted flag is set on the expression node.
74833e619fcSdrh **
74933e619fcSdrh ** Special case:  If op==TK_INTEGER and pToken points to a string that
75033e619fcSdrh ** can be translated into a 32-bit integer, then the token is not
75133e619fcSdrh ** stored in u.zToken.  Instead, the integer values is written
75233e619fcSdrh ** into u.iValue and the EP_IntValue flag is set.  No extra storage
75333e619fcSdrh ** is allocated to hold the integer text and the dequote flag is ignored.
754a76b5dfcSdrh */
755b7916a78Sdrh Expr *sqlite3ExprAlloc(
756cca8a4adSdrh   sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
75717435752Sdrh   int op,                 /* Expression opcode */
758b7916a78Sdrh   const Token *pToken,    /* Token argument.  Might be NULL */
759b7916a78Sdrh   int dequote             /* True to dequote */
76017435752Sdrh ){
761a76b5dfcSdrh   Expr *pNew;
76233e619fcSdrh   int nExtra = 0;
763cf697396Sshane   int iValue = 0;
764b7916a78Sdrh 
765575fad65Sdrh   assert( db!=0 );
766b7916a78Sdrh   if( pToken ){
76733e619fcSdrh     if( op!=TK_INTEGER || pToken->z==0
76833e619fcSdrh           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
769b7916a78Sdrh       nExtra = pToken->n+1;
770d50ffc41Sdrh       assert( iValue>=0 );
77133e619fcSdrh     }
772a76b5dfcSdrh   }
773575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
774b7916a78Sdrh   if( pNew ){
775ca3862dcSdrh     memset(pNew, 0, sizeof(Expr));
7761bd10f8aSdrh     pNew->op = (u8)op;
777a58fdfb1Sdanielk1977     pNew->iAgg = -1;
778a76b5dfcSdrh     if( pToken ){
77933e619fcSdrh       if( nExtra==0 ){
780ad31727fSdrh         pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
78133e619fcSdrh         pNew->u.iValue = iValue;
78233e619fcSdrh       }else{
78333e619fcSdrh         pNew->u.zToken = (char*)&pNew[1];
784b07028f7Sdrh         assert( pToken->z!=0 || pToken->n==0 );
785b07028f7Sdrh         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
78633e619fcSdrh         pNew->u.zToken[pToken->n] = 0;
787244b9d6eSdrh         if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
78851d35b0fSdrh           sqlite3DequoteExpr(pNew);
789a34001c9Sdrh         }
790a34001c9Sdrh       }
79133e619fcSdrh     }
792b7916a78Sdrh #if SQLITE_MAX_EXPR_DEPTH>0
793b7916a78Sdrh     pNew->nHeight = 1;
794b7916a78Sdrh #endif
795a34001c9Sdrh   }
796a76b5dfcSdrh   return pNew;
797a76b5dfcSdrh }
798a76b5dfcSdrh 
799a76b5dfcSdrh /*
800b7916a78Sdrh ** Allocate a new expression node from a zero-terminated token that has
801b7916a78Sdrh ** already been dequoted.
802b7916a78Sdrh */
803b7916a78Sdrh Expr *sqlite3Expr(
804b7916a78Sdrh   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
805b7916a78Sdrh   int op,                 /* Expression opcode */
806b7916a78Sdrh   const char *zToken      /* Token argument.  Might be NULL */
807b7916a78Sdrh ){
808b7916a78Sdrh   Token x;
809b7916a78Sdrh   x.z = zToken;
810b40f06c6Sdrh   x.n = sqlite3Strlen30(zToken);
811b7916a78Sdrh   return sqlite3ExprAlloc(db, op, &x, 0);
812b7916a78Sdrh }
813b7916a78Sdrh 
814b7916a78Sdrh /*
815b7916a78Sdrh ** Attach subtrees pLeft and pRight to the Expr node pRoot.
816b7916a78Sdrh **
817b7916a78Sdrh ** If pRoot==NULL that means that a memory allocation error has occurred.
818b7916a78Sdrh ** In that case, delete the subtrees pLeft and pRight.
819b7916a78Sdrh */
820b7916a78Sdrh void sqlite3ExprAttachSubtrees(
821b7916a78Sdrh   sqlite3 *db,
822b7916a78Sdrh   Expr *pRoot,
823b7916a78Sdrh   Expr *pLeft,
824b7916a78Sdrh   Expr *pRight
825b7916a78Sdrh ){
826b7916a78Sdrh   if( pRoot==0 ){
827b7916a78Sdrh     assert( db->mallocFailed );
828b7916a78Sdrh     sqlite3ExprDelete(db, pLeft);
829b7916a78Sdrh     sqlite3ExprDelete(db, pRight);
830b7916a78Sdrh   }else{
831b7916a78Sdrh     if( pRight ){
832b7916a78Sdrh       pRoot->pRight = pRight;
833885a5b03Sdrh       pRoot->flags |= EP_Propagate & pRight->flags;
834b7916a78Sdrh     }
835b7916a78Sdrh     if( pLeft ){
836b7916a78Sdrh       pRoot->pLeft = pLeft;
837885a5b03Sdrh       pRoot->flags |= EP_Propagate & pLeft->flags;
838b7916a78Sdrh     }
839b7916a78Sdrh     exprSetHeight(pRoot);
840b7916a78Sdrh   }
841b7916a78Sdrh }
842b7916a78Sdrh 
843b7916a78Sdrh /*
84460ec914cSpeter.d.reid ** Allocate an Expr node which joins as many as two subtrees.
845b7916a78Sdrh **
846bf664469Sdrh ** One or both of the subtrees can be NULL.  Return a pointer to the new
847bf664469Sdrh ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
848bf664469Sdrh ** free the subtrees and return NULL.
849206f3d96Sdrh */
85017435752Sdrh Expr *sqlite3PExpr(
85117435752Sdrh   Parse *pParse,          /* Parsing context */
85217435752Sdrh   int op,                 /* Expression opcode */
85317435752Sdrh   Expr *pLeft,            /* Left operand */
854abfd35eaSdrh   Expr *pRight            /* Right operand */
85517435752Sdrh ){
8565fb52caaSdrh   Expr *p;
857abfd35eaSdrh   p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
858abfd35eaSdrh   if( p ){
859abfd35eaSdrh     memset(p, 0, sizeof(Expr));
860f1722baaSdrh     p->op = op & 0xff;
861abfd35eaSdrh     p->iAgg = -1;
862b7916a78Sdrh     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
8632b359bdbSdan     sqlite3ExprCheckHeight(pParse, p->nHeight);
864d5c851c1Sdrh   }else{
865d5c851c1Sdrh     sqlite3ExprDelete(pParse->db, pLeft);
866d5c851c1Sdrh     sqlite3ExprDelete(pParse->db, pRight);
8672b359bdbSdan   }
8684e0cff60Sdrh   return p;
8694e0cff60Sdrh }
8704e0cff60Sdrh 
8714e0cff60Sdrh /*
87208de4f79Sdrh ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
87308de4f79Sdrh ** do a memory allocation failure) then delete the pSelect object.
87408de4f79Sdrh */
87508de4f79Sdrh void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
87608de4f79Sdrh   if( pExpr ){
87708de4f79Sdrh     pExpr->x.pSelect = pSelect;
87808de4f79Sdrh     ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
87908de4f79Sdrh     sqlite3ExprSetHeightAndFlags(pParse, pExpr);
88008de4f79Sdrh   }else{
88108de4f79Sdrh     assert( pParse->db->mallocFailed );
88208de4f79Sdrh     sqlite3SelectDelete(pParse->db, pSelect);
88308de4f79Sdrh   }
88408de4f79Sdrh }
88508de4f79Sdrh 
88608de4f79Sdrh 
88708de4f79Sdrh /*
88891bb0eedSdrh ** Join two expressions using an AND operator.  If either expression is
88991bb0eedSdrh ** NULL, then just return the other expression.
8905fb52caaSdrh **
8915fb52caaSdrh ** If one side or the other of the AND is known to be false, then instead
8925fb52caaSdrh ** of returning an AND expression, just return a constant expression with
8935fb52caaSdrh ** a value of false.
89491bb0eedSdrh */
895d5c851c1Sdrh Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
896d5c851c1Sdrh   sqlite3 *db = pParse->db;
89791bb0eedSdrh   if( pLeft==0  ){
89891bb0eedSdrh     return pRight;
89991bb0eedSdrh   }else if( pRight==0 ){
90091bb0eedSdrh     return pLeft;
901ad31727fSdrh   }else if( ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight) ){
9028e34e406Sdrh     sqlite3ExprUnmapAndDelete(pParse, pLeft);
9038e34e406Sdrh     sqlite3ExprUnmapAndDelete(pParse, pRight);
9045fb52caaSdrh     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
90591bb0eedSdrh   }else{
906d5c851c1Sdrh     return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
907a76b5dfcSdrh   }
908a76b5dfcSdrh }
909a76b5dfcSdrh 
910a76b5dfcSdrh /*
911a76b5dfcSdrh ** Construct a new expression node for a function with multiple
912a76b5dfcSdrh ** arguments.
913a76b5dfcSdrh */
914954733b3Sdrh Expr *sqlite3ExprFunction(
915954733b3Sdrh   Parse *pParse,        /* Parsing context */
916954733b3Sdrh   ExprList *pList,      /* Argument list */
917954733b3Sdrh   Token *pToken,        /* Name of the function */
918954733b3Sdrh   int eDistinct         /* SF_Distinct or SF_ALL or 0 */
919954733b3Sdrh ){
920a76b5dfcSdrh   Expr *pNew;
921633e6d57Sdrh   sqlite3 *db = pParse->db;
9224b202ae2Sdanielk1977   assert( pToken );
923b7916a78Sdrh   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
924a76b5dfcSdrh   if( pNew==0 ){
925d9da78a2Sdrh     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
926a76b5dfcSdrh     return 0;
927a76b5dfcSdrh   }
928954733b3Sdrh   if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
929954733b3Sdrh     sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
930954733b3Sdrh   }
9316ab3a2ecSdanielk1977   pNew->x.pList = pList;
932fca23557Sdrh   ExprSetProperty(pNew, EP_HasFunc);
9336ab3a2ecSdanielk1977   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
9342308ed38Sdrh   sqlite3ExprSetHeightAndFlags(pParse, pNew);
935954733b3Sdrh   if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
936a76b5dfcSdrh   return pNew;
937a76b5dfcSdrh }
938a76b5dfcSdrh 
939a76b5dfcSdrh /*
940fa6bc000Sdrh ** Assign a variable number to an expression that encodes a wildcard
941fa6bc000Sdrh ** in the original SQL statement.
942fa6bc000Sdrh **
943fa6bc000Sdrh ** Wildcards consisting of a single "?" are assigned the next sequential
944fa6bc000Sdrh ** variable number.
945fa6bc000Sdrh **
946fa6bc000Sdrh ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
9479bf755ccSdrh ** sure "nnn" is not too big to avoid a denial of service attack when
948fa6bc000Sdrh ** the SQL statement comes from an external source.
949fa6bc000Sdrh **
95051f49f17Sdrh ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
951fa6bc000Sdrh ** as the previous instance of the same wildcard.  Or if this is the first
95260ec914cSpeter.d.reid ** instance of the wildcard, the next sequential variable number is
953fa6bc000Sdrh ** assigned.
954fa6bc000Sdrh */
955de25a88cSdrh void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
95617435752Sdrh   sqlite3 *db = pParse->db;
957b7916a78Sdrh   const char *z;
958f326d66dSdrh   ynVar x;
95917435752Sdrh 
960fa6bc000Sdrh   if( pExpr==0 ) return;
961c5cd1249Sdrh   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
96233e619fcSdrh   z = pExpr->u.zToken;
963b7916a78Sdrh   assert( z!=0 );
964b7916a78Sdrh   assert( z[0]!=0 );
965b1ed717fSmistachkin   assert( n==(u32)sqlite3Strlen30(z) );
966b7916a78Sdrh   if( z[1]==0 ){
967fa6bc000Sdrh     /* Wildcard of the form "?".  Assign the next variable number */
968b7916a78Sdrh     assert( z[0]=='?' );
969f326d66dSdrh     x = (ynVar)(++pParse->nVar);
970124c0b49Sdrh   }else{
971f326d66dSdrh     int doAdd = 0;
972124c0b49Sdrh     if( z[0]=='?' ){
973fa6bc000Sdrh       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
974fa6bc000Sdrh       ** use it as the variable number */
975c8d735aeSdan       i64 i;
97618814dfbSdrh       int bOk;
97718814dfbSdrh       if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
97818814dfbSdrh         i = z[1]-'0';  /* The common case of ?N for a single digit N */
97918814dfbSdrh         bOk = 1;
98018814dfbSdrh       }else{
98118814dfbSdrh         bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
98218814dfbSdrh       }
983c5499befSdrh       testcase( i==0 );
984c5499befSdrh       testcase( i==1 );
985c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
986c5499befSdrh       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
987c8d735aeSdan       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
988fa6bc000Sdrh         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
989bb4957f8Sdrh             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
990c9b39288Sdrh         return;
991fa6bc000Sdrh       }
9928e74e7baSdrh       x = (ynVar)i;
993f326d66dSdrh       if( x>pParse->nVar ){
994f326d66dSdrh         pParse->nVar = (int)x;
995f326d66dSdrh         doAdd = 1;
996f326d66dSdrh       }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
997f326d66dSdrh         doAdd = 1;
998fa6bc000Sdrh       }
999fa6bc000Sdrh     }else{
100051f49f17Sdrh       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
1001fa6bc000Sdrh       ** number as the prior appearance of the same name, or if the name
1002fa6bc000Sdrh       ** has never appeared before, reuse the same variable number
1003fa6bc000Sdrh       */
10049bf755ccSdrh       x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
10059bf755ccSdrh       if( x==0 ){
10069bf755ccSdrh         x = (ynVar)(++pParse->nVar);
1007f326d66dSdrh         doAdd = 1;
1008f326d66dSdrh       }
1009f326d66dSdrh     }
1010f326d66dSdrh     if( doAdd ){
10119bf755ccSdrh       pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1012fa6bc000Sdrh     }
1013fa6bc000Sdrh   }
1014c9b39288Sdrh   pExpr->iColumn = x;
1015f326d66dSdrh   if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1016832b2664Sdanielk1977     sqlite3ErrorMsg(pParse, "too many SQL variables");
1017832b2664Sdanielk1977   }
1018fa6bc000Sdrh }
1019fa6bc000Sdrh 
1020fa6bc000Sdrh /*
1021f6963f99Sdan ** Recursively delete an expression tree.
1022a2e00042Sdrh */
10234f0010b1Sdrh static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
10244f0010b1Sdrh   assert( p!=0 );
1025d50ffc41Sdrh   /* Sanity check: Assert that the IntValue is non-negative if it exists */
1026d50ffc41Sdrh   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
1027eda079cdSdrh 
1028eda079cdSdrh   assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
1029eda079cdSdrh   assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
1030eda079cdSdrh           || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
1031209bc522Sdrh #ifdef SQLITE_DEBUG
1032209bc522Sdrh   if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1033209bc522Sdrh     assert( p->pLeft==0 );
1034209bc522Sdrh     assert( p->pRight==0 );
1035209bc522Sdrh     assert( p->x.pSelect==0 );
1036209bc522Sdrh   }
1037209bc522Sdrh #endif
1038209bc522Sdrh   if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1039c5cd1249Sdrh     /* The Expr.x union is never used at the same time as Expr.pRight */
1040c5cd1249Sdrh     assert( p->x.pList==0 || p->pRight==0 );
10414910a76dSdrh     if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1042d1086679Sdrh     if( p->pRight ){
1043d1086679Sdrh       sqlite3ExprDeleteNN(db, p->pRight);
1044d1086679Sdrh     }else if( ExprHasProperty(p, EP_xIsSelect) ){
10456ab3a2ecSdanielk1977       sqlite3SelectDelete(db, p->x.pSelect);
10466ab3a2ecSdanielk1977     }else{
10476ab3a2ecSdanielk1977       sqlite3ExprListDelete(db, p->x.pList);
10486ab3a2ecSdanielk1977     }
1049eda079cdSdrh     if( ExprHasProperty(p, EP_WinFunc) ){
1050eda079cdSdrh       assert( p->op==TK_FUNCTION );
1051eda079cdSdrh       sqlite3WindowDelete(db, p->y.pWin);
105286fb6e17Sdan     }
10536ab3a2ecSdanielk1977   }
1054209bc522Sdrh   if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
105533e619fcSdrh   if( !ExprHasProperty(p, EP_Static) ){
1056dbd6a7dcSdrh     sqlite3DbFreeNN(db, p);
1057a2e00042Sdrh   }
105833e619fcSdrh }
10594f0010b1Sdrh void sqlite3ExprDelete(sqlite3 *db, Expr *p){
10604f0010b1Sdrh   if( p ) sqlite3ExprDeleteNN(db, p);
10614f0010b1Sdrh }
1062a2e00042Sdrh 
10638e34e406Sdrh /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
10648e34e406Sdrh ** expression.
10658e34e406Sdrh */
10668e34e406Sdrh void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
10678e34e406Sdrh   if( p ){
10688e34e406Sdrh     if( IN_RENAME_OBJECT ){
10698e34e406Sdrh       sqlite3RenameExprUnmap(pParse, p);
10708e34e406Sdrh     }
10718e34e406Sdrh     sqlite3ExprDeleteNN(pParse->db, p);
10728e34e406Sdrh   }
10738e34e406Sdrh }
10748e34e406Sdrh 
1075d2687b77Sdrh /*
10766ab3a2ecSdanielk1977 ** Return the number of bytes allocated for the expression structure
10776ab3a2ecSdanielk1977 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
10786ab3a2ecSdanielk1977 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
10796ab3a2ecSdanielk1977 */
10806ab3a2ecSdanielk1977 static int exprStructSize(Expr *p){
10816ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
10826ab3a2ecSdanielk1977   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
10836ab3a2ecSdanielk1977   return EXPR_FULLSIZE;
10846ab3a2ecSdanielk1977 }
10856ab3a2ecSdanielk1977 
10866ab3a2ecSdanielk1977 /*
1087a8e05761Sdrh ** Copy the complete content of an Expr node, taking care not to read
1088a8e05761Sdrh ** past the end of the structure for a reduced-size version of the source
1089a8e05761Sdrh ** Expr.
1090a8e05761Sdrh */
1091a8e05761Sdrh static void exprNodeCopy(Expr *pDest, Expr *pSrc){
1092a8e05761Sdrh   memset(pDest, 0, sizeof(Expr));
1093a8e05761Sdrh   memcpy(pDest, pSrc, exprStructSize(pSrc));
1094a8e05761Sdrh }
1095a8e05761Sdrh 
1096a8e05761Sdrh /*
109733e619fcSdrh ** The dupedExpr*Size() routines each return the number of bytes required
109833e619fcSdrh ** to store a copy of an expression or expression tree.  They differ in
109933e619fcSdrh ** how much of the tree is measured.
110033e619fcSdrh **
110133e619fcSdrh **     dupedExprStructSize()     Size of only the Expr structure
110233e619fcSdrh **     dupedExprNodeSize()       Size of Expr + space for token
110333e619fcSdrh **     dupedExprSize()           Expr + token + subtree components
110433e619fcSdrh **
110533e619fcSdrh ***************************************************************************
110633e619fcSdrh **
110733e619fcSdrh ** The dupedExprStructSize() function returns two values OR-ed together:
110833e619fcSdrh ** (1) the space required for a copy of the Expr structure only and
110933e619fcSdrh ** (2) the EP_xxx flags that indicate what the structure size should be.
111033e619fcSdrh ** The return values is always one of:
111133e619fcSdrh **
111233e619fcSdrh **      EXPR_FULLSIZE
111333e619fcSdrh **      EXPR_REDUCEDSIZE   | EP_Reduced
111433e619fcSdrh **      EXPR_TOKENONLYSIZE | EP_TokenOnly
111533e619fcSdrh **
111633e619fcSdrh ** The size of the structure can be found by masking the return value
111733e619fcSdrh ** of this routine with 0xfff.  The flags can be found by masking the
111833e619fcSdrh ** return value with EP_Reduced|EP_TokenOnly.
111933e619fcSdrh **
112033e619fcSdrh ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
112133e619fcSdrh ** (unreduced) Expr objects as they or originally constructed by the parser.
112233e619fcSdrh ** During expression analysis, extra information is computed and moved into
1123c95f38d4Sdan ** later parts of the Expr object and that extra information might get chopped
112433e619fcSdrh ** off if the expression is reduced.  Note also that it does not work to
112560ec914cSpeter.d.reid ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
112633e619fcSdrh ** to reduce a pristine expression tree from the parser.  The implementation
112733e619fcSdrh ** of dupedExprStructSize() contain multiple assert() statements that attempt
112833e619fcSdrh ** to enforce this constraint.
11296ab3a2ecSdanielk1977 */
11306ab3a2ecSdanielk1977 static int dupedExprStructSize(Expr *p, int flags){
11316ab3a2ecSdanielk1977   int nSize;
113233e619fcSdrh   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1133aecd8021Sdrh   assert( EXPR_FULLSIZE<=0xfff );
1134aecd8021Sdrh   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
113567a9b8edSdan   if( 0==flags || p->op==TK_SELECT_COLUMN
113667a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
1137eda079cdSdrh    || ExprHasProperty(p, EP_WinFunc)
113867a9b8edSdan #endif
113967a9b8edSdan   ){
11406ab3a2ecSdanielk1977     nSize = EXPR_FULLSIZE;
11416ab3a2ecSdanielk1977   }else{
1142c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
114333e619fcSdrh     assert( !ExprHasProperty(p, EP_FromJoin) );
1144c5cd1249Sdrh     assert( !ExprHasProperty(p, EP_MemToken) );
1145ebb6a65dSdrh     assert( !ExprHasProperty(p, EP_NoReduce) );
1146aecd8021Sdrh     if( p->pLeft || p->x.pList ){
114733e619fcSdrh       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
114833e619fcSdrh     }else{
1149aecd8021Sdrh       assert( p->pRight==0 );
115033e619fcSdrh       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
115133e619fcSdrh     }
11526ab3a2ecSdanielk1977   }
11536ab3a2ecSdanielk1977   return nSize;
11546ab3a2ecSdanielk1977 }
11556ab3a2ecSdanielk1977 
11566ab3a2ecSdanielk1977 /*
115733e619fcSdrh ** This function returns the space in bytes required to store the copy
115833e619fcSdrh ** of the Expr structure and a copy of the Expr.u.zToken string (if that
115933e619fcSdrh ** string is defined.)
11606ab3a2ecSdanielk1977 */
11616ab3a2ecSdanielk1977 static int dupedExprNodeSize(Expr *p, int flags){
116233e619fcSdrh   int nByte = dupedExprStructSize(p, flags) & 0xfff;
116333e619fcSdrh   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
11647301e774Sdrh     nByte += sqlite3Strlen30NN(p->u.zToken)+1;
11656ab3a2ecSdanielk1977   }
1166bc73971dSdanielk1977   return ROUND8(nByte);
11676ab3a2ecSdanielk1977 }
11686ab3a2ecSdanielk1977 
11696ab3a2ecSdanielk1977 /*
11706ab3a2ecSdanielk1977 ** Return the number of bytes required to create a duplicate of the
11716ab3a2ecSdanielk1977 ** expression passed as the first argument. The second argument is a
11726ab3a2ecSdanielk1977 ** mask containing EXPRDUP_XXX flags.
11736ab3a2ecSdanielk1977 **
11746ab3a2ecSdanielk1977 ** The value returned includes space to create a copy of the Expr struct
117533e619fcSdrh ** itself and the buffer referred to by Expr.u.zToken, if any.
11766ab3a2ecSdanielk1977 **
11776ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
11786ab3a2ecSdanielk1977 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
11796ab3a2ecSdanielk1977 ** and Expr.pRight variables (but not for any structures pointed to or
11806ab3a2ecSdanielk1977 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
11816ab3a2ecSdanielk1977 */
11826ab3a2ecSdanielk1977 static int dupedExprSize(Expr *p, int flags){
11836ab3a2ecSdanielk1977   int nByte = 0;
11846ab3a2ecSdanielk1977   if( p ){
11856ab3a2ecSdanielk1977     nByte = dupedExprNodeSize(p, flags);
11866ab3a2ecSdanielk1977     if( flags&EXPRDUP_REDUCE ){
1187b7916a78Sdrh       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
11886ab3a2ecSdanielk1977     }
11896ab3a2ecSdanielk1977   }
11906ab3a2ecSdanielk1977   return nByte;
11916ab3a2ecSdanielk1977 }
11926ab3a2ecSdanielk1977 
11936ab3a2ecSdanielk1977 /*
11946ab3a2ecSdanielk1977 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
11956ab3a2ecSdanielk1977 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
119633e619fcSdrh ** to store the copy of expression p, the copies of p->u.zToken
11976ab3a2ecSdanielk1977 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
119860ec914cSpeter.d.reid ** if any. Before returning, *pzBuffer is set to the first byte past the
11996ab3a2ecSdanielk1977 ** portion of the buffer copied into by this function.
12006ab3a2ecSdanielk1977 */
12013c19469cSdrh static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
12023c19469cSdrh   Expr *pNew;           /* Value to return */
12033c19469cSdrh   u8 *zAlloc;           /* Memory space from which to build Expr object */
12043c19469cSdrh   u32 staticFlag;       /* EP_Static if space not obtained from malloc */
12056ab3a2ecSdanielk1977 
12063c19469cSdrh   assert( db!=0 );
12073c19469cSdrh   assert( p );
12083c19469cSdrh   assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
12093c19469cSdrh   assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
12106ab3a2ecSdanielk1977 
12116ab3a2ecSdanielk1977   /* Figure out where to write the new Expr structure. */
12126ab3a2ecSdanielk1977   if( pzBuffer ){
12136ab3a2ecSdanielk1977     zAlloc = *pzBuffer;
121433e619fcSdrh     staticFlag = EP_Static;
12156ab3a2ecSdanielk1977   }else{
12163c19469cSdrh     zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
12173c19469cSdrh     staticFlag = 0;
12186ab3a2ecSdanielk1977   }
12196ab3a2ecSdanielk1977   pNew = (Expr *)zAlloc;
12206ab3a2ecSdanielk1977 
12216ab3a2ecSdanielk1977   if( pNew ){
12226ab3a2ecSdanielk1977     /* Set nNewSize to the size allocated for the structure pointed to
12236ab3a2ecSdanielk1977     ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
12246ab3a2ecSdanielk1977     ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
122533e619fcSdrh     ** by the copy of the p->u.zToken string (if any).
12266ab3a2ecSdanielk1977     */
12273c19469cSdrh     const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
122833e619fcSdrh     const int nNewSize = nStructSize & 0xfff;
122933e619fcSdrh     int nToken;
123033e619fcSdrh     if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
123133e619fcSdrh       nToken = sqlite3Strlen30(p->u.zToken) + 1;
123233e619fcSdrh     }else{
123333e619fcSdrh       nToken = 0;
123433e619fcSdrh     }
12353c19469cSdrh     if( dupFlags ){
12366ab3a2ecSdanielk1977       assert( ExprHasProperty(p, EP_Reduced)==0 );
12376ab3a2ecSdanielk1977       memcpy(zAlloc, p, nNewSize);
12386ab3a2ecSdanielk1977     }else{
12393e6a1411Sdan       u32 nSize = (u32)exprStructSize(p);
12406ab3a2ecSdanielk1977       memcpy(zAlloc, p, nSize);
124172ea29d7Sdrh       if( nSize<EXPR_FULLSIZE ){
12426ab3a2ecSdanielk1977         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
12436ab3a2ecSdanielk1977       }
124472ea29d7Sdrh     }
12456ab3a2ecSdanielk1977 
124633e619fcSdrh     /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1247c5cd1249Sdrh     pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
124833e619fcSdrh     pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
124933e619fcSdrh     pNew->flags |= staticFlag;
12506ab3a2ecSdanielk1977 
125133e619fcSdrh     /* Copy the p->u.zToken string, if any. */
12526ab3a2ecSdanielk1977     if( nToken ){
125333e619fcSdrh       char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
125433e619fcSdrh       memcpy(zToken, p->u.zToken, nToken);
12556ab3a2ecSdanielk1977     }
12566ab3a2ecSdanielk1977 
1257209bc522Sdrh     if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
12586ab3a2ecSdanielk1977       /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
12596ab3a2ecSdanielk1977       if( ExprHasProperty(p, EP_xIsSelect) ){
12603c19469cSdrh         pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
12616ab3a2ecSdanielk1977       }else{
12623c19469cSdrh         pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
12636ab3a2ecSdanielk1977       }
12646ab3a2ecSdanielk1977     }
12656ab3a2ecSdanielk1977 
12666ab3a2ecSdanielk1977     /* Fill in pNew->pLeft and pNew->pRight. */
126753988068Sdrh     if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
12683c19469cSdrh       zAlloc += dupedExprNodeSize(p, dupFlags);
1269209bc522Sdrh       if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
12703c19469cSdrh         pNew->pLeft = p->pLeft ?
12713c19469cSdrh                       exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
12723c19469cSdrh         pNew->pRight = p->pRight ?
12733c19469cSdrh                        exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
12746ab3a2ecSdanielk1977       }
127567a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
1276eda079cdSdrh       if( ExprHasProperty(p, EP_WinFunc) ){
1277eda079cdSdrh         pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1278eda079cdSdrh         assert( ExprHasProperty(pNew, EP_WinFunc) );
1279e2f781b9Sdan       }
128067a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
128153988068Sdrh       if( pzBuffer ){
128253988068Sdrh         *pzBuffer = zAlloc;
128353988068Sdrh       }
128453988068Sdrh     }else{
1285209bc522Sdrh       if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
12869854260bSdrh         if( pNew->op==TK_SELECT_COLUMN ){
12879854260bSdrh           pNew->pLeft = p->pLeft;
128847073f62Sdrh           assert( p->iColumn==0 || p->pRight==0 );
128947073f62Sdrh           assert( p->pRight==0  || p->pRight==p->pLeft );
12909854260bSdrh         }else{
12916ab3a2ecSdanielk1977           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
12929854260bSdrh         }
12936ab3a2ecSdanielk1977         pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
12946ab3a2ecSdanielk1977       }
12956ab3a2ecSdanielk1977     }
12966ab3a2ecSdanielk1977   }
12976ab3a2ecSdanielk1977   return pNew;
12986ab3a2ecSdanielk1977 }
12996ab3a2ecSdanielk1977 
13006ab3a2ecSdanielk1977 /*
1301bfe31e7fSdan ** Create and return a deep copy of the object passed as the second
1302bfe31e7fSdan ** argument. If an OOM condition is encountered, NULL is returned
1303bfe31e7fSdan ** and the db->mallocFailed flag set.
1304bfe31e7fSdan */
1305eede6a53Sdan #ifndef SQLITE_OMIT_CTE
1306bfe31e7fSdan static With *withDup(sqlite3 *db, With *p){
13074e9119d9Sdan   With *pRet = 0;
13084e9119d9Sdan   if( p ){
1309d4de9f7bSdrh     sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
13104e9119d9Sdan     pRet = sqlite3DbMallocZero(db, nByte);
13114e9119d9Sdan     if( pRet ){
13124e9119d9Sdan       int i;
13134e9119d9Sdan       pRet->nCte = p->nCte;
13144e9119d9Sdan       for(i=0; i<p->nCte; i++){
13154e9119d9Sdan         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
13164e9119d9Sdan         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
13174e9119d9Sdan         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
13184e9119d9Sdan       }
13194e9119d9Sdan     }
13204e9119d9Sdan   }
13214e9119d9Sdan   return pRet;
13224e9119d9Sdan }
1323eede6a53Sdan #else
1324eede6a53Sdan # define withDup(x,y) 0
1325eede6a53Sdan #endif
13264e9119d9Sdan 
1327a8389975Sdrh #ifndef SQLITE_OMIT_WINDOWFUNC
1328a8389975Sdrh /*
1329a8389975Sdrh ** The gatherSelectWindows() procedure and its helper routine
1330a8389975Sdrh ** gatherSelectWindowsCallback() are used to scan all the expressions
1331a8389975Sdrh ** an a newly duplicated SELECT statement and gather all of the Window
1332a8389975Sdrh ** objects found there, assembling them onto the linked list at Select->pWin.
1333a8389975Sdrh */
1334a8389975Sdrh static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1335a8389975Sdrh   if( pExpr->op==TK_FUNCTION && pExpr->y.pWin!=0 ){
1336a8389975Sdrh     assert( ExprHasProperty(pExpr, EP_WinFunc) );
1337a8389975Sdrh     pExpr->y.pWin->pNextWin = pWalker->u.pSelect->pWin;
1338a8389975Sdrh     pWalker->u.pSelect->pWin = pExpr->y.pWin;
1339a8389975Sdrh   }
1340a8389975Sdrh   return WRC_Continue;
1341a8389975Sdrh }
1342a37b6a5eSdrh static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1343a37b6a5eSdrh   return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1344a37b6a5eSdrh }
1345a8389975Sdrh static void gatherSelectWindows(Select *p){
1346a8389975Sdrh   Walker w;
1347a8389975Sdrh   w.xExprCallback = gatherSelectWindowsCallback;
1348a37b6a5eSdrh   w.xSelectCallback = gatherSelectWindowsSelectCallback;
1349a37b6a5eSdrh   w.xSelectCallback2 = 0;
13509c46c66cSdrh   w.pParse = 0;
1351a8389975Sdrh   w.u.pSelect = p;
1352a37b6a5eSdrh   sqlite3WalkSelect(&w, p);
1353a8389975Sdrh }
1354a8389975Sdrh #endif
1355a8389975Sdrh 
1356a8389975Sdrh 
1357a76b5dfcSdrh /*
1358ff78bd2fSdrh ** The following group of routines make deep copies of expressions,
1359ff78bd2fSdrh ** expression lists, ID lists, and select statements.  The copies can
1360ff78bd2fSdrh ** be deleted (by being passed to their respective ...Delete() routines)
1361ff78bd2fSdrh ** without effecting the originals.
1362ff78bd2fSdrh **
13634adee20fSdanielk1977 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
13644adee20fSdanielk1977 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1365ad3cab52Sdrh ** by subsequent calls to sqlite*ListAppend() routines.
1366ff78bd2fSdrh **
1367ad3cab52Sdrh ** Any tables that the SrcList might point to are not duplicated.
13686ab3a2ecSdanielk1977 **
1369b7916a78Sdrh ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
13706ab3a2ecSdanielk1977 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
13716ab3a2ecSdanielk1977 ** truncated version of the usual Expr structure that will be stored as
13726ab3a2ecSdanielk1977 ** part of the in-memory representation of the database schema.
1373ff78bd2fSdrh */
13746ab3a2ecSdanielk1977 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
137572ea29d7Sdrh   assert( flags==0 || flags==EXPRDUP_REDUCE );
13763c19469cSdrh   return p ? exprDup(db, p, flags, 0) : 0;
1377ff78bd2fSdrh }
13786ab3a2ecSdanielk1977 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
1379ff78bd2fSdrh   ExprList *pNew;
1380145716b3Sdrh   struct ExprList_item *pItem, *pOldItem;
1381ff78bd2fSdrh   int i;
1382b163748eSdrh   Expr *pPriorSelectCol = 0;
1383575fad65Sdrh   assert( db!=0 );
1384ff78bd2fSdrh   if( p==0 ) return 0;
138597258194Sdrh   pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1386ff78bd2fSdrh   if( pNew==0 ) return 0;
1387a19543feSdrh   pNew->nExpr = p->nExpr;
138843606175Sdrh   pItem = pNew->a;
1389145716b3Sdrh   pOldItem = p->a;
1390145716b3Sdrh   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
13916ab3a2ecSdanielk1977     Expr *pOldExpr = pOldItem->pExpr;
139247073f62Sdrh     Expr *pNewExpr;
1393b5526ea6Sdrh     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
139447073f62Sdrh     if( pOldExpr
139547073f62Sdrh      && pOldExpr->op==TK_SELECT_COLUMN
139647073f62Sdrh      && (pNewExpr = pItem->pExpr)!=0
139747073f62Sdrh     ){
139847073f62Sdrh       assert( pNewExpr->iColumn==0 || i>0 );
139947073f62Sdrh       if( pNewExpr->iColumn==0 ){
140047073f62Sdrh         assert( pOldExpr->pLeft==pOldExpr->pRight );
1401b163748eSdrh         pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
1402b163748eSdrh       }else{
1403b163748eSdrh         assert( i>0 );
1404b163748eSdrh         assert( pItem[-1].pExpr!=0 );
1405b163748eSdrh         assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
1406b163748eSdrh         assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
1407b163748eSdrh         pNewExpr->pLeft = pPriorSelectCol;
140847073f62Sdrh       }
140947073f62Sdrh     }
141017435752Sdrh     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1411b7916a78Sdrh     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
1412145716b3Sdrh     pItem->sortOrder = pOldItem->sortOrder;
14133e7bc9caSdrh     pItem->done = 0;
14142c036cffSdrh     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
141524e25d32Sdan     pItem->bSorterRef = pOldItem->bSorterRef;
1416c2acc4e4Sdrh     pItem->u = pOldItem->u;
1417ff78bd2fSdrh   }
1418ff78bd2fSdrh   return pNew;
1419ff78bd2fSdrh }
142093758c8dSdanielk1977 
142193758c8dSdanielk1977 /*
142293758c8dSdanielk1977 ** If cursors, triggers, views and subqueries are all omitted from
142393758c8dSdanielk1977 ** the build, then none of the following routines, except for
142493758c8dSdanielk1977 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
142593758c8dSdanielk1977 ** called with a NULL argument.
142693758c8dSdanielk1977 */
14276a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
14286a67fe8eSdanielk1977  || !defined(SQLITE_OMIT_SUBQUERY)
14296ab3a2ecSdanielk1977 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1430ad3cab52Sdrh   SrcList *pNew;
1431ad3cab52Sdrh   int i;
1432113088ecSdrh   int nByte;
1433575fad65Sdrh   assert( db!=0 );
1434ad3cab52Sdrh   if( p==0 ) return 0;
1435113088ecSdrh   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1436575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, nByte );
1437ad3cab52Sdrh   if( pNew==0 ) return 0;
14384305d103Sdrh   pNew->nSrc = pNew->nAlloc = p->nSrc;
1439ad3cab52Sdrh   for(i=0; i<p->nSrc; i++){
14404efc4754Sdrh     struct SrcList_item *pNewItem = &pNew->a[i];
14414efc4754Sdrh     struct SrcList_item *pOldItem = &p->a[i];
1442ed8a3bb1Sdrh     Table *pTab;
144341fb5cd1Sdan     pNewItem->pSchema = pOldItem->pSchema;
144417435752Sdrh     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
144517435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
144617435752Sdrh     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
14478a48b9c0Sdrh     pNewItem->fg = pOldItem->fg;
14484efc4754Sdrh     pNewItem->iCursor = pOldItem->iCursor;
14495b6a9ed4Sdrh     pNewItem->addrFillSub = pOldItem->addrFillSub;
14505b6a9ed4Sdrh     pNewItem->regReturn = pOldItem->regReturn;
14518a48b9c0Sdrh     if( pNewItem->fg.isIndexedBy ){
14528a48b9c0Sdrh       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
14538a48b9c0Sdrh     }
14548a48b9c0Sdrh     pNewItem->pIBIndex = pOldItem->pIBIndex;
14558a48b9c0Sdrh     if( pNewItem->fg.isTabFunc ){
14568a48b9c0Sdrh       pNewItem->u1.pFuncArg =
14578a48b9c0Sdrh           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
14588a48b9c0Sdrh     }
1459ed8a3bb1Sdrh     pTab = pNewItem->pTab = pOldItem->pTab;
1460ed8a3bb1Sdrh     if( pTab ){
146179df7782Sdrh       pTab->nTabRef++;
1462a1cb183dSdanielk1977     }
14636ab3a2ecSdanielk1977     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
14646ab3a2ecSdanielk1977     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
146517435752Sdrh     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
14666c18b6e0Sdanielk1977     pNewItem->colUsed = pOldItem->colUsed;
1467ad3cab52Sdrh   }
1468ad3cab52Sdrh   return pNew;
1469ad3cab52Sdrh }
147017435752Sdrh IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1471ff78bd2fSdrh   IdList *pNew;
1472ff78bd2fSdrh   int i;
1473575fad65Sdrh   assert( db!=0 );
1474ff78bd2fSdrh   if( p==0 ) return 0;
1475575fad65Sdrh   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1476ff78bd2fSdrh   if( pNew==0 ) return 0;
14776c535158Sdrh   pNew->nId = p->nId;
1478575fad65Sdrh   pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
1479d5d56523Sdanielk1977   if( pNew->a==0 ){
1480dbd6a7dcSdrh     sqlite3DbFreeNN(db, pNew);
1481d5d56523Sdanielk1977     return 0;
1482d5d56523Sdanielk1977   }
14836c535158Sdrh   /* Note that because the size of the allocation for p->a[] is not
14846c535158Sdrh   ** necessarily a power of two, sqlite3IdListAppend() may not be called
14856c535158Sdrh   ** on the duplicate created by this function. */
1486ff78bd2fSdrh   for(i=0; i<p->nId; i++){
14874efc4754Sdrh     struct IdList_item *pNewItem = &pNew->a[i];
14884efc4754Sdrh     struct IdList_item *pOldItem = &p->a[i];
148917435752Sdrh     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
14904efc4754Sdrh     pNewItem->idx = pOldItem->idx;
1491ff78bd2fSdrh   }
1492ff78bd2fSdrh   return pNew;
1493ff78bd2fSdrh }
1494a7466205Sdan Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
1495a7466205Sdan   Select *pRet = 0;
1496a7466205Sdan   Select *pNext = 0;
1497a7466205Sdan   Select **pp = &pRet;
1498a7466205Sdan   Select *p;
1499a7466205Sdan 
1500575fad65Sdrh   assert( db!=0 );
1501a7466205Sdan   for(p=pDup; p; p=p->pPrior){
1502a7466205Sdan     Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1503a7466205Sdan     if( pNew==0 ) break;
1504b7916a78Sdrh     pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
15056ab3a2ecSdanielk1977     pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
15066ab3a2ecSdanielk1977     pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
15076ab3a2ecSdanielk1977     pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
15086ab3a2ecSdanielk1977     pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
15096ab3a2ecSdanielk1977     pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1510ff78bd2fSdrh     pNew->op = p->op;
1511a7466205Sdan     pNew->pNext = pNext;
1512a7466205Sdan     pNew->pPrior = 0;
15136ab3a2ecSdanielk1977     pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
151492b01d53Sdrh     pNew->iLimit = 0;
151592b01d53Sdrh     pNew->iOffset = 0;
15167d10d5a6Sdrh     pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1517b9bb7c18Sdrh     pNew->addrOpenEphm[0] = -1;
1518b9bb7c18Sdrh     pNew->addrOpenEphm[1] = -1;
1519ec2da854Sdrh     pNew->nSelectRow = p->nSelectRow;
15204e9119d9Sdan     pNew->pWith = withDup(db, p->pWith);
152167a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
15222e362f97Sdan     pNew->pWin = 0;
1523c95f38d4Sdan     pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1524a8389975Sdrh     if( p->pWin ) gatherSelectWindows(pNew);
152567a9b8edSdan #endif
1526fef37760Sdrh     pNew->selId = p->selId;
1527a7466205Sdan     *pp = pNew;
1528a7466205Sdan     pp = &pNew->pPrior;
1529a7466205Sdan     pNext = pNew;
1530a7466205Sdan   }
1531a7466205Sdan 
1532a7466205Sdan   return pRet;
1533ff78bd2fSdrh }
153493758c8dSdanielk1977 #else
15356ab3a2ecSdanielk1977 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
153693758c8dSdanielk1977   assert( p==0 );
153793758c8dSdanielk1977   return 0;
153893758c8dSdanielk1977 }
153993758c8dSdanielk1977 #endif
1540ff78bd2fSdrh 
1541ff78bd2fSdrh 
1542ff78bd2fSdrh /*
1543a76b5dfcSdrh ** Add a new element to the end of an expression list.  If pList is
1544a76b5dfcSdrh ** initially NULL, then create a new expression list.
1545b7916a78Sdrh **
1546a19543feSdrh ** The pList argument must be either NULL or a pointer to an ExprList
1547a19543feSdrh ** obtained from a prior call to sqlite3ExprListAppend().  This routine
1548a19543feSdrh ** may not be used with an ExprList obtained from sqlite3ExprListDup().
1549a19543feSdrh ** Reason:  This routine assumes that the number of slots in pList->a[]
1550a19543feSdrh ** is a power of two.  That is true for sqlite3ExprListAppend() returns
1551a19543feSdrh ** but is not necessarily true from the return value of sqlite3ExprListDup().
1552a19543feSdrh **
1553b7916a78Sdrh ** If a memory allocation error occurs, the entire list is freed and
1554b7916a78Sdrh ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1555b7916a78Sdrh ** that the new entry was successfully appended.
1556a76b5dfcSdrh */
155717435752Sdrh ExprList *sqlite3ExprListAppend(
155817435752Sdrh   Parse *pParse,          /* Parsing context */
155917435752Sdrh   ExprList *pList,        /* List to which to append. Might be NULL */
1560b7916a78Sdrh   Expr *pExpr             /* Expression to be appended. Might be NULL */
156117435752Sdrh ){
156243606175Sdrh   struct ExprList_item *pItem;
156317435752Sdrh   sqlite3 *db = pParse->db;
1564575fad65Sdrh   assert( db!=0 );
1565a76b5dfcSdrh   if( pList==0 ){
1566575fad65Sdrh     pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
1567a76b5dfcSdrh     if( pList==0 ){
1568d5d56523Sdanielk1977       goto no_mem;
1569a76b5dfcSdrh     }
1570c263f7c4Sdrh     pList->nExpr = 0;
1571a19543feSdrh   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
157243606175Sdrh     ExprList *pNew;
157343606175Sdrh     pNew = sqlite3DbRealloc(db, pList,
15740aa3231fSdrh          sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
157543606175Sdrh     if( pNew==0 ){
1576d5d56523Sdanielk1977       goto no_mem;
1577a76b5dfcSdrh     }
157843606175Sdrh     pList = pNew;
1579a76b5dfcSdrh   }
158043606175Sdrh   pItem = &pList->a[pList->nExpr++];
1581a8b9793cSdrh   assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
1582a8b9793cSdrh   assert( offsetof(struct ExprList_item,pExpr)==0 );
1583a8b9793cSdrh   memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
1584e94ddc9eSdanielk1977   pItem->pExpr = pExpr;
1585a76b5dfcSdrh   return pList;
1586d5d56523Sdanielk1977 
1587d5d56523Sdanielk1977 no_mem:
1588d5d56523Sdanielk1977   /* Avoid leaking memory if malloc has failed. */
1589633e6d57Sdrh   sqlite3ExprDelete(db, pExpr);
1590633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1591d5d56523Sdanielk1977   return 0;
1592a76b5dfcSdrh }
1593a76b5dfcSdrh 
1594a76b5dfcSdrh /*
15958762ec19Sdrh ** pColumns and pExpr form a vector assignment which is part of the SET
15968762ec19Sdrh ** clause of an UPDATE statement.  Like this:
1597a1251bc4Sdrh **
1598a1251bc4Sdrh **        (a,b,c) = (expr1,expr2,expr3)
1599a1251bc4Sdrh ** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
1600a1251bc4Sdrh **
1601a1251bc4Sdrh ** For each term of the vector assignment, append new entries to the
1602b67343d0Sdrh ** expression list pList.  In the case of a subquery on the RHS, append
1603a1251bc4Sdrh ** TK_SELECT_COLUMN expressions.
1604a1251bc4Sdrh */
1605a1251bc4Sdrh ExprList *sqlite3ExprListAppendVector(
1606a1251bc4Sdrh   Parse *pParse,         /* Parsing context */
1607a1251bc4Sdrh   ExprList *pList,       /* List to which to append. Might be NULL */
1608a1251bc4Sdrh   IdList *pColumns,      /* List of names of LHS of the assignment */
1609a1251bc4Sdrh   Expr *pExpr            /* Vector expression to be appended. Might be NULL */
1610a1251bc4Sdrh ){
1611a1251bc4Sdrh   sqlite3 *db = pParse->db;
1612a1251bc4Sdrh   int n;
1613a1251bc4Sdrh   int i;
161466860af3Sdrh   int iFirst = pList ? pList->nExpr : 0;
1615321e828dSdrh   /* pColumns can only be NULL due to an OOM but an OOM will cause an
1616321e828dSdrh   ** exit prior to this routine being invoked */
1617321e828dSdrh   if( NEVER(pColumns==0) ) goto vector_append_error;
1618a1251bc4Sdrh   if( pExpr==0 ) goto vector_append_error;
1619966e2911Sdrh 
1620966e2911Sdrh   /* If the RHS is a vector, then we can immediately check to see that
1621966e2911Sdrh   ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
1622966e2911Sdrh   ** wildcards ("*") in the result set of the SELECT must be expanded before
1623966e2911Sdrh   ** we can do the size check, so defer the size check until code generation.
1624966e2911Sdrh   */
1625966e2911Sdrh   if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
1626a1251bc4Sdrh     sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1627a1251bc4Sdrh                     pColumns->nId, n);
1628a1251bc4Sdrh     goto vector_append_error;
1629a1251bc4Sdrh   }
1630966e2911Sdrh 
1631966e2911Sdrh   for(i=0; i<pColumns->nId; i++){
1632a1251bc4Sdrh     Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1633a1251bc4Sdrh     pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1634a1251bc4Sdrh     if( pList ){
163566860af3Sdrh       assert( pList->nExpr==iFirst+i+1 );
1636a1251bc4Sdrh       pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1637a1251bc4Sdrh       pColumns->a[i].zName = 0;
1638a1251bc4Sdrh     }
1639a1251bc4Sdrh   }
1640966e2911Sdrh 
1641ffe28059Sdrh   if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
1642966e2911Sdrh     Expr *pFirst = pList->a[iFirst].pExpr;
1643f4dd26c5Sdrh     assert( pFirst!=0 );
1644966e2911Sdrh     assert( pFirst->op==TK_SELECT_COLUMN );
1645966e2911Sdrh 
1646966e2911Sdrh     /* Store the SELECT statement in pRight so it will be deleted when
1647966e2911Sdrh     ** sqlite3ExprListDelete() is called */
1648966e2911Sdrh     pFirst->pRight = pExpr;
1649a1251bc4Sdrh     pExpr = 0;
1650966e2911Sdrh 
1651966e2911Sdrh     /* Remember the size of the LHS in iTable so that we can check that
1652966e2911Sdrh     ** the RHS and LHS sizes match during code generation. */
1653966e2911Sdrh     pFirst->iTable = pColumns->nId;
1654a1251bc4Sdrh   }
1655a1251bc4Sdrh 
1656a1251bc4Sdrh vector_append_error:
16578e34e406Sdrh   sqlite3ExprUnmapAndDelete(pParse, pExpr);
1658a1251bc4Sdrh   sqlite3IdListDelete(db, pColumns);
1659a1251bc4Sdrh   return pList;
1660a1251bc4Sdrh }
1661a1251bc4Sdrh 
1662a1251bc4Sdrh /*
1663bc622bc0Sdrh ** Set the sort order for the last element on the given ExprList.
1664bc622bc0Sdrh */
1665bc622bc0Sdrh void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1666bc622bc0Sdrh   if( p==0 ) return;
1667bc622bc0Sdrh   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1668bc622bc0Sdrh   assert( p->nExpr>0 );
1669bc622bc0Sdrh   if( iSortOrder<0 ){
1670bc622bc0Sdrh     assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1671bc622bc0Sdrh     return;
1672bc622bc0Sdrh   }
1673bc622bc0Sdrh   p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
1674bc622bc0Sdrh }
1675bc622bc0Sdrh 
1676bc622bc0Sdrh /*
1677b7916a78Sdrh ** Set the ExprList.a[].zName element of the most recently added item
1678b7916a78Sdrh ** on the expression list.
1679b7916a78Sdrh **
1680b7916a78Sdrh ** pList might be NULL following an OOM error.  But pName should never be
1681b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1682b7916a78Sdrh ** is set.
1683b7916a78Sdrh */
1684b7916a78Sdrh void sqlite3ExprListSetName(
1685b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1686b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
1687b7916a78Sdrh   Token *pName,           /* Name to be added */
1688b7916a78Sdrh   int dequote             /* True to cause the name to be dequoted */
1689b7916a78Sdrh ){
1690b7916a78Sdrh   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1691b7916a78Sdrh   if( pList ){
1692b7916a78Sdrh     struct ExprList_item *pItem;
1693b7916a78Sdrh     assert( pList->nExpr>0 );
1694b7916a78Sdrh     pItem = &pList->a[pList->nExpr-1];
1695b7916a78Sdrh     assert( pItem->zName==0 );
1696b7916a78Sdrh     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1697244b9d6eSdrh     if( dequote ) sqlite3Dequote(pItem->zName);
1698c9461eccSdan     if( IN_RENAME_OBJECT ){
169907e95233Sdan       sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
17005be60c55Sdan     }
1701b7916a78Sdrh   }
1702b7916a78Sdrh }
1703b7916a78Sdrh 
1704b7916a78Sdrh /*
1705b7916a78Sdrh ** Set the ExprList.a[].zSpan element of the most recently added item
1706b7916a78Sdrh ** on the expression list.
1707b7916a78Sdrh **
1708b7916a78Sdrh ** pList might be NULL following an OOM error.  But pSpan should never be
1709b7916a78Sdrh ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1710b7916a78Sdrh ** is set.
1711b7916a78Sdrh */
1712b7916a78Sdrh void sqlite3ExprListSetSpan(
1713b7916a78Sdrh   Parse *pParse,          /* Parsing context */
1714b7916a78Sdrh   ExprList *pList,        /* List to which to add the span. */
17151be266baSdrh   const char *zStart,     /* Start of the span */
17161be266baSdrh   const char *zEnd        /* End of the span */
1717b7916a78Sdrh ){
1718b7916a78Sdrh   sqlite3 *db = pParse->db;
1719b7916a78Sdrh   assert( pList!=0 || db->mallocFailed!=0 );
1720b7916a78Sdrh   if( pList ){
1721b7916a78Sdrh     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1722b7916a78Sdrh     assert( pList->nExpr>0 );
1723b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
17249b2e0435Sdrh     pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
1725b7916a78Sdrh   }
1726b7916a78Sdrh }
1727b7916a78Sdrh 
1728b7916a78Sdrh /*
17297a15a4beSdanielk1977 ** If the expression list pEList contains more than iLimit elements,
17307a15a4beSdanielk1977 ** leave an error message in pParse.
17317a15a4beSdanielk1977 */
17327a15a4beSdanielk1977 void sqlite3ExprListCheckLength(
17337a15a4beSdanielk1977   Parse *pParse,
17347a15a4beSdanielk1977   ExprList *pEList,
17357a15a4beSdanielk1977   const char *zObject
17367a15a4beSdanielk1977 ){
1737b1a6c3c1Sdrh   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1738c5499befSdrh   testcase( pEList && pEList->nExpr==mx );
1739c5499befSdrh   testcase( pEList && pEList->nExpr==mx+1 );
1740b1a6c3c1Sdrh   if( pEList && pEList->nExpr>mx ){
17417a15a4beSdanielk1977     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
17427a15a4beSdanielk1977   }
17437a15a4beSdanielk1977 }
17447a15a4beSdanielk1977 
17457a15a4beSdanielk1977 /*
1746a76b5dfcSdrh ** Delete an entire expression list.
1747a76b5dfcSdrh */
1748affa855cSdrh static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
1749ac48b751Sdrh   int i = pList->nExpr;
1750ac48b751Sdrh   struct ExprList_item *pItem =  pList->a;
1751ac48b751Sdrh   assert( pList->nExpr>0 );
1752ac48b751Sdrh   do{
1753633e6d57Sdrh     sqlite3ExprDelete(db, pItem->pExpr);
1754633e6d57Sdrh     sqlite3DbFree(db, pItem->zName);
1755b7916a78Sdrh     sqlite3DbFree(db, pItem->zSpan);
1756ac48b751Sdrh     pItem++;
1757ac48b751Sdrh   }while( --i>0 );
1758dbd6a7dcSdrh   sqlite3DbFreeNN(db, pList);
1759a76b5dfcSdrh }
1760affa855cSdrh void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1761affa855cSdrh   if( pList ) exprListDeleteNN(db, pList);
1762affa855cSdrh }
1763a76b5dfcSdrh 
1764a76b5dfcSdrh /*
17652308ed38Sdrh ** Return the bitwise-OR of all Expr.flags fields in the given
17662308ed38Sdrh ** ExprList.
1767885a5b03Sdrh */
17682308ed38Sdrh u32 sqlite3ExprListFlags(const ExprList *pList){
1769885a5b03Sdrh   int i;
17702308ed38Sdrh   u32 m = 0;
1771508e2d00Sdrh   assert( pList!=0 );
1772885a5b03Sdrh   for(i=0; i<pList->nExpr; i++){
1773d0c73053Sdrh      Expr *pExpr = pList->a[i].pExpr;
1774de845c2fSdrh      assert( pExpr!=0 );
1775de845c2fSdrh      m |= pExpr->flags;
1776885a5b03Sdrh   }
17772308ed38Sdrh   return m;
1778885a5b03Sdrh }
1779885a5b03Sdrh 
1780885a5b03Sdrh /*
17817e6f980bSdrh ** This is a SELECT-node callback for the expression walker that
17827e6f980bSdrh ** always "fails".  By "fail" in this case, we mean set
17837e6f980bSdrh ** pWalker->eCode to zero and abort.
17847e6f980bSdrh **
17857e6f980bSdrh ** This callback is used by multiple expression walkers.
17867e6f980bSdrh */
17877e6f980bSdrh int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
17887e6f980bSdrh   UNUSED_PARAMETER(NotUsed);
17897e6f980bSdrh   pWalker->eCode = 0;
17907e6f980bSdrh   return WRC_Abort;
17917e6f980bSdrh }
17927e6f980bSdrh 
17937e6f980bSdrh /*
1794171d16bbSdrh ** If the input expression is an ID with the name "true" or "false"
179596acafbeSdrh ** then convert it into an TK_TRUEFALSE term.  Return non-zero if
179696acafbeSdrh ** the conversion happened, and zero if the expression is unaltered.
1797171d16bbSdrh */
1798171d16bbSdrh int sqlite3ExprIdToTrueFalse(Expr *pExpr){
1799171d16bbSdrh   assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
180051d35b0fSdrh   if( !ExprHasProperty(pExpr, EP_Quoted)
180151d35b0fSdrh    && (sqlite3StrICmp(pExpr->u.zToken, "true")==0
180251d35b0fSdrh        || sqlite3StrICmp(pExpr->u.zToken, "false")==0)
1803171d16bbSdrh   ){
1804171d16bbSdrh     pExpr->op = TK_TRUEFALSE;
1805ad31727fSdrh     ExprSetProperty(pExpr, pExpr->u.zToken[4]==0 ? EP_IsTrue : EP_IsFalse);
1806171d16bbSdrh     return 1;
1807171d16bbSdrh   }
1808171d16bbSdrh   return 0;
1809171d16bbSdrh }
1810171d16bbSdrh 
181143c4ac8bSdrh /*
181296acafbeSdrh ** The argument must be a TK_TRUEFALSE Expr node.  Return 1 if it is TRUE
181343c4ac8bSdrh ** and 0 if it is FALSE.
181443c4ac8bSdrh */
181596acafbeSdrh int sqlite3ExprTruthValue(const Expr *pExpr){
181643c4ac8bSdrh   assert( pExpr->op==TK_TRUEFALSE );
181743c4ac8bSdrh   assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
181843c4ac8bSdrh        || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
181943c4ac8bSdrh   return pExpr->u.zToken[4]==0;
182043c4ac8bSdrh }
182143c4ac8bSdrh 
182217180fcaSdrh /*
182317180fcaSdrh ** If pExpr is an AND or OR expression, try to simplify it by eliminating
182417180fcaSdrh ** terms that are always true or false.  Return the simplified expression.
182517180fcaSdrh ** Or return the original expression if no simplification is possible.
182617180fcaSdrh **
182717180fcaSdrh ** Examples:
182817180fcaSdrh **
182917180fcaSdrh **     (x<10) AND true                =>   (x<10)
183017180fcaSdrh **     (x<10) AND false               =>   false
183117180fcaSdrh **     (x<10) AND (y=22 OR false)     =>   (x<10) AND (y=22)
183217180fcaSdrh **     (x<10) AND (y=22 OR true)      =>   (x<10)
183317180fcaSdrh **     (y=22) OR true                 =>   true
183417180fcaSdrh */
183517180fcaSdrh Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
183617180fcaSdrh   assert( pExpr!=0 );
183717180fcaSdrh   if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
183817180fcaSdrh     Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
183917180fcaSdrh     Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
184017180fcaSdrh     if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
184117180fcaSdrh       pExpr = pExpr->op==TK_AND ? pRight : pLeft;
184217180fcaSdrh     }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
184317180fcaSdrh       pExpr = pExpr->op==TK_AND ? pLeft : pRight;
184417180fcaSdrh     }
184517180fcaSdrh   }
184617180fcaSdrh   return pExpr;
184717180fcaSdrh }
184817180fcaSdrh 
1849171d16bbSdrh 
1850171d16bbSdrh /*
1851059b2d50Sdrh ** These routines are Walker callbacks used to check expressions to
1852059b2d50Sdrh ** see if they are "constant" for some definition of constant.  The
1853059b2d50Sdrh ** Walker.eCode value determines the type of "constant" we are looking
1854059b2d50Sdrh ** for.
185573b211abSdrh **
18567d10d5a6Sdrh ** These callback routines are used to implement the following:
1857626a879aSdrh **
1858059b2d50Sdrh **     sqlite3ExprIsConstant()                  pWalker->eCode==1
1859059b2d50Sdrh **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
1860fcb9f4f3Sdrh **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
1861059b2d50Sdrh **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
186287abf5c0Sdrh **
1863059b2d50Sdrh ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1864059b2d50Sdrh ** is found to not be a constant.
186587abf5c0Sdrh **
1866feada2dfSdrh ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
1867059b2d50Sdrh ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
1868059b2d50Sdrh ** an existing schema and 4 when processing a new statement.  A bound
1869feada2dfSdrh ** parameter raises an error for new statements, but is silently converted
1870feada2dfSdrh ** to NULL for existing schemas.  This allows sqlite_master tables that
1871feada2dfSdrh ** contain a bound parameter because they were generated by older versions
1872feada2dfSdrh ** of SQLite to be parsed by newer versions of SQLite without raising a
1873feada2dfSdrh ** malformed schema error.
1874626a879aSdrh */
18757d10d5a6Sdrh static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1876626a879aSdrh 
1877059b2d50Sdrh   /* If pWalker->eCode is 2 then any term of the expression that comes from
1878059b2d50Sdrh   ** the ON or USING clauses of a left join disqualifies the expression
18790a168377Sdrh   ** from being considered constant. */
1880059b2d50Sdrh   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1881059b2d50Sdrh     pWalker->eCode = 0;
18827d10d5a6Sdrh     return WRC_Abort;
18830a168377Sdrh   }
18840a168377Sdrh 
1885626a879aSdrh   switch( pExpr->op ){
1886eb55bd2fSdrh     /* Consider functions to be constant if all their arguments are constant
1887059b2d50Sdrh     ** and either pWalker->eCode==4 or 5 or the function has the
1888059b2d50Sdrh     ** SQLITE_FUNC_CONST flag. */
1889eb55bd2fSdrh     case TK_FUNCTION:
189063f84573Sdrh       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
1891b1fba286Sdrh         return WRC_Continue;
1892059b2d50Sdrh       }else{
1893059b2d50Sdrh         pWalker->eCode = 0;
1894059b2d50Sdrh         return WRC_Abort;
1895b1fba286Sdrh       }
1896626a879aSdrh     case TK_ID:
1897171d16bbSdrh       /* Convert "true" or "false" in a DEFAULT clause into the
1898171d16bbSdrh       ** appropriate TK_TRUEFALSE operator */
1899e39ef31cSdrh       if( sqlite3ExprIdToTrueFalse(pExpr) ){
1900171d16bbSdrh         return WRC_Prune;
1901171d16bbSdrh       }
1902171d16bbSdrh       /* Fall thru */
1903626a879aSdrh     case TK_COLUMN:
1904626a879aSdrh     case TK_AGG_FUNCTION:
190513449892Sdrh     case TK_AGG_COLUMN:
1906c5499befSdrh       testcase( pExpr->op==TK_ID );
1907c5499befSdrh       testcase( pExpr->op==TK_COLUMN );
1908c5499befSdrh       testcase( pExpr->op==TK_AGG_FUNCTION );
1909c5499befSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
191007aded63Sdrh       if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
1911efad2e23Sdrh         return WRC_Continue;
1912efad2e23Sdrh       }
1913059b2d50Sdrh       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1914059b2d50Sdrh         return WRC_Continue;
1915f43ce0b4Sdrh       }
1916f43ce0b4Sdrh       /* Fall through */
1917f43ce0b4Sdrh     case TK_IF_NULL_ROW:
19186e341b93Sdrh     case TK_REGISTER:
19199916048bSdrh       testcase( pExpr->op==TK_REGISTER );
1920f43ce0b4Sdrh       testcase( pExpr->op==TK_IF_NULL_ROW );
1921059b2d50Sdrh       pWalker->eCode = 0;
19227d10d5a6Sdrh       return WRC_Abort;
1923feada2dfSdrh     case TK_VARIABLE:
1924059b2d50Sdrh       if( pWalker->eCode==5 ){
1925feada2dfSdrh         /* Silently convert bound parameters that appear inside of CREATE
1926feada2dfSdrh         ** statements into a NULL when parsing the CREATE statement text out
1927feada2dfSdrh         ** of the sqlite_master table */
1928feada2dfSdrh         pExpr->op = TK_NULL;
1929059b2d50Sdrh       }else if( pWalker->eCode==4 ){
1930feada2dfSdrh         /* A bound parameter in a CREATE statement that originates from
1931feada2dfSdrh         ** sqlite3_prepare() causes an error */
1932059b2d50Sdrh         pWalker->eCode = 0;
1933feada2dfSdrh         return WRC_Abort;
1934feada2dfSdrh       }
1935feada2dfSdrh       /* Fall through */
1936626a879aSdrh     default:
19376e341b93Sdrh       testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
19386e341b93Sdrh       testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
19397d10d5a6Sdrh       return WRC_Continue;
1940626a879aSdrh   }
1941626a879aSdrh }
1942059b2d50Sdrh static int exprIsConst(Expr *p, int initFlag, int iCur){
19437d10d5a6Sdrh   Walker w;
1944059b2d50Sdrh   w.eCode = initFlag;
19457d10d5a6Sdrh   w.xExprCallback = exprNodeIsConstant;
19467e6f980bSdrh   w.xSelectCallback = sqlite3SelectWalkFail;
1947979dd1beSdrh #ifdef SQLITE_DEBUG
1948979dd1beSdrh   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
1949979dd1beSdrh #endif
1950059b2d50Sdrh   w.u.iCur = iCur;
19517d10d5a6Sdrh   sqlite3WalkExpr(&w, p);
1952059b2d50Sdrh   return w.eCode;
19537d10d5a6Sdrh }
1954626a879aSdrh 
1955626a879aSdrh /*
1956059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1957eb55bd2fSdrh ** and 0 if it involves variables or function calls.
19582398937bSdrh **
19592398937bSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
19602398937bSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
19612398937bSdrh ** a constant.
1962fef5208cSdrh */
19634adee20fSdanielk1977 int sqlite3ExprIsConstant(Expr *p){
1964059b2d50Sdrh   return exprIsConst(p, 1, 0);
1965fef5208cSdrh }
1966fef5208cSdrh 
1967fef5208cSdrh /*
196807aded63Sdrh ** Walk an expression tree.  Return non-zero if
196907aded63Sdrh **
197007aded63Sdrh **   (1) the expression is constant, and
197107aded63Sdrh **   (2) the expression does originate in the ON or USING clause
197207aded63Sdrh **       of a LEFT JOIN, and
197307aded63Sdrh **   (3) the expression does not contain any EP_FixedCol TK_COLUMN
197407aded63Sdrh **       operands created by the constant propagation optimization.
197507aded63Sdrh **
197607aded63Sdrh ** When this routine returns true, it indicates that the expression
197707aded63Sdrh ** can be added to the pParse->pConstExpr list and evaluated once when
197807aded63Sdrh ** the prepared statement starts up.  See sqlite3ExprCodeAtInit().
19790a168377Sdrh */
19800a168377Sdrh int sqlite3ExprIsConstantNotJoin(Expr *p){
1981059b2d50Sdrh   return exprIsConst(p, 2, 0);
19820a168377Sdrh }
19830a168377Sdrh 
19840a168377Sdrh /*
1985fcb9f4f3Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
1986059b2d50Sdrh ** for any single row of the table with cursor iCur.  In other words, the
1987059b2d50Sdrh ** expression must not refer to any non-deterministic function nor any
1988059b2d50Sdrh ** table other than iCur.
1989059b2d50Sdrh */
1990059b2d50Sdrh int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1991059b2d50Sdrh   return exprIsConst(p, 3, iCur);
1992059b2d50Sdrh }
1993059b2d50Sdrh 
1994ab31a845Sdan 
1995ab31a845Sdan /*
1996ab31a845Sdan ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
1997ab31a845Sdan */
1998ab31a845Sdan static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
1999ab31a845Sdan   ExprList *pGroupBy = pWalker->u.pGroupBy;
2000ab31a845Sdan   int i;
2001ab31a845Sdan 
2002ab31a845Sdan   /* Check if pExpr is identical to any GROUP BY term. If so, consider
2003ab31a845Sdan   ** it constant.  */
2004ab31a845Sdan   for(i=0; i<pGroupBy->nExpr; i++){
2005ab31a845Sdan     Expr *p = pGroupBy->a[i].pExpr;
20065aa550cfSdan     if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
200770efa84dSdrh       CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2008efad2e23Sdrh       if( sqlite3IsBinary(pColl) ){
2009ab31a845Sdan         return WRC_Prune;
2010ab31a845Sdan       }
2011ab31a845Sdan     }
2012ab31a845Sdan   }
2013ab31a845Sdan 
2014ab31a845Sdan   /* Check if pExpr is a sub-select. If so, consider it variable. */
2015ab31a845Sdan   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2016ab31a845Sdan     pWalker->eCode = 0;
2017ab31a845Sdan     return WRC_Abort;
2018ab31a845Sdan   }
2019ab31a845Sdan 
2020ab31a845Sdan   return exprNodeIsConstant(pWalker, pExpr);
2021ab31a845Sdan }
2022ab31a845Sdan 
2023ab31a845Sdan /*
2024ab31a845Sdan ** Walk the expression tree passed as the first argument. Return non-zero
2025ab31a845Sdan ** if the expression consists entirely of constants or copies of terms
2026ab31a845Sdan ** in pGroupBy that sort with the BINARY collation sequence.
2027ab314001Sdrh **
2028ab314001Sdrh ** This routine is used to determine if a term of the HAVING clause can
2029ab314001Sdrh ** be promoted into the WHERE clause.  In order for such a promotion to work,
2030ab314001Sdrh ** the value of the HAVING clause term must be the same for all members of
2031ab314001Sdrh ** a "group".  The requirement that the GROUP BY term must be BINARY
2032ab314001Sdrh ** assumes that no other collating sequence will have a finer-grained
2033ab314001Sdrh ** grouping than binary.  In other words (A=B COLLATE binary) implies
2034ab314001Sdrh ** A=B in every other collating sequence.  The requirement that the
2035ab314001Sdrh ** GROUP BY be BINARY is stricter than necessary.  It would also work
2036ab314001Sdrh ** to promote HAVING clauses that use the same alternative collating
2037ab314001Sdrh ** sequence as the GROUP BY term, but that is much harder to check,
2038ab314001Sdrh ** alternative collating sequences are uncommon, and this is only an
2039ab314001Sdrh ** optimization, so we take the easy way out and simply require the
2040ab314001Sdrh ** GROUP BY to use the BINARY collating sequence.
2041ab31a845Sdan */
2042ab31a845Sdan int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2043ab31a845Sdan   Walker w;
2044ab31a845Sdan   w.eCode = 1;
2045ab31a845Sdan   w.xExprCallback = exprNodeIsConstantOrGroupBy;
2046979dd1beSdrh   w.xSelectCallback = 0;
2047ab31a845Sdan   w.u.pGroupBy = pGroupBy;
2048ab31a845Sdan   w.pParse = pParse;
2049ab31a845Sdan   sqlite3WalkExpr(&w, p);
2050ab31a845Sdan   return w.eCode;
2051ab31a845Sdan }
2052ab31a845Sdan 
2053059b2d50Sdrh /*
2054059b2d50Sdrh ** Walk an expression tree.  Return non-zero if the expression is constant
2055eb55bd2fSdrh ** or a function call with constant arguments.  Return and 0 if there
2056eb55bd2fSdrh ** are any variables.
2057eb55bd2fSdrh **
2058eb55bd2fSdrh ** For the purposes of this function, a double-quoted string (ex: "abc")
2059eb55bd2fSdrh ** is considered a variable but a single-quoted string (ex: 'abc') is
2060eb55bd2fSdrh ** a constant.
2061eb55bd2fSdrh */
2062feada2dfSdrh int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2063feada2dfSdrh   assert( isInit==0 || isInit==1 );
2064059b2d50Sdrh   return exprIsConst(p, 4+isInit, 0);
2065eb55bd2fSdrh }
2066eb55bd2fSdrh 
20675b88bc4bSdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS
20685b88bc4bSdrh /*
20695b88bc4bSdrh ** Walk an expression tree.  Return 1 if the expression contains a
20705b88bc4bSdrh ** subquery of some kind.  Return 0 if there are no subqueries.
20715b88bc4bSdrh */
20725b88bc4bSdrh int sqlite3ExprContainsSubquery(Expr *p){
20735b88bc4bSdrh   Walker w;
2074bec2476aSdrh   w.eCode = 1;
20755b88bc4bSdrh   w.xExprCallback = sqlite3ExprWalkNoop;
20767e6f980bSdrh   w.xSelectCallback = sqlite3SelectWalkFail;
2077979dd1beSdrh #ifdef SQLITE_DEBUG
2078979dd1beSdrh   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2079979dd1beSdrh #endif
20805b88bc4bSdrh   sqlite3WalkExpr(&w, p);
208107194bffSdrh   return w.eCode==0;
20825b88bc4bSdrh }
20835b88bc4bSdrh #endif
20845b88bc4bSdrh 
2085eb55bd2fSdrh /*
208673b211abSdrh ** If the expression p codes a constant integer that is small enough
2087202b2df7Sdrh ** to fit in a 32-bit integer, return 1 and put the value of the integer
2088202b2df7Sdrh ** in *pValue.  If the expression is not an integer or if it is too big
2089202b2df7Sdrh ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2090e4de1febSdrh */
20914adee20fSdanielk1977 int sqlite3ExprIsInteger(Expr *p, int *pValue){
209292b01d53Sdrh   int rc = 0;
20931d2d71a0Sdrh   if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */
2094cd92e84dSdrh 
2095cd92e84dSdrh   /* If an expression is an integer literal that fits in a signed 32-bit
2096cd92e84dSdrh   ** integer, then the EP_IntValue flag will have already been set */
2097cd92e84dSdrh   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2098cd92e84dSdrh            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2099cd92e84dSdrh 
210092b01d53Sdrh   if( p->flags & EP_IntValue ){
210133e619fcSdrh     *pValue = p->u.iValue;
2102e4de1febSdrh     return 1;
2103e4de1febSdrh   }
210492b01d53Sdrh   switch( p->op ){
21054b59ab5eSdrh     case TK_UPLUS: {
210692b01d53Sdrh       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
2107f6e369a1Sdrh       break;
21084b59ab5eSdrh     }
2109e4de1febSdrh     case TK_UMINUS: {
2110e4de1febSdrh       int v;
21114adee20fSdanielk1977       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
2112f6418891Smistachkin         assert( v!=(-2147483647-1) );
2113e4de1febSdrh         *pValue = -v;
211492b01d53Sdrh         rc = 1;
2115e4de1febSdrh       }
2116e4de1febSdrh       break;
2117e4de1febSdrh     }
2118e4de1febSdrh     default: break;
2119e4de1febSdrh   }
212092b01d53Sdrh   return rc;
2121e4de1febSdrh }
2122e4de1febSdrh 
2123e4de1febSdrh /*
2124039fc32eSdrh ** Return FALSE if there is no chance that the expression can be NULL.
2125039fc32eSdrh **
2126039fc32eSdrh ** If the expression might be NULL or if the expression is too complex
2127039fc32eSdrh ** to tell return TRUE.
2128039fc32eSdrh **
2129039fc32eSdrh ** This routine is used as an optimization, to skip OP_IsNull opcodes
2130039fc32eSdrh ** when we know that a value cannot be NULL.  Hence, a false positive
2131039fc32eSdrh ** (returning TRUE when in fact the expression can never be NULL) might
2132039fc32eSdrh ** be a small performance hit but is otherwise harmless.  On the other
2133039fc32eSdrh ** hand, a false negative (returning FALSE when the result could be NULL)
2134039fc32eSdrh ** will likely result in an incorrect answer.  So when in doubt, return
2135039fc32eSdrh ** TRUE.
2136039fc32eSdrh */
2137039fc32eSdrh int sqlite3ExprCanBeNull(const Expr *p){
2138039fc32eSdrh   u8 op;
21399bfb0794Sdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
21409bfb0794Sdrh     p = p->pLeft;
21419bfb0794Sdrh   }
2142039fc32eSdrh   op = p->op;
2143039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
2144039fc32eSdrh   switch( op ){
2145039fc32eSdrh     case TK_INTEGER:
2146039fc32eSdrh     case TK_STRING:
2147039fc32eSdrh     case TK_FLOAT:
2148039fc32eSdrh     case TK_BLOB:
2149039fc32eSdrh       return 0;
21507248a8b2Sdrh     case TK_COLUMN:
215172673a24Sdrh       return ExprHasProperty(p, EP_CanBeNull) ||
2152eda079cdSdrh              p->y.pTab==0 ||  /* Reference to column of index on expression */
2153eda079cdSdrh              (p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
2154039fc32eSdrh     default:
2155039fc32eSdrh       return 1;
2156039fc32eSdrh   }
2157039fc32eSdrh }
2158039fc32eSdrh 
2159039fc32eSdrh /*
2160039fc32eSdrh ** Return TRUE if the given expression is a constant which would be
2161039fc32eSdrh ** unchanged by OP_Affinity with the affinity given in the second
2162039fc32eSdrh ** argument.
2163039fc32eSdrh **
2164039fc32eSdrh ** This routine is used to determine if the OP_Affinity operation
2165039fc32eSdrh ** can be omitted.  When in doubt return FALSE.  A false negative
2166039fc32eSdrh ** is harmless.  A false positive, however, can result in the wrong
2167039fc32eSdrh ** answer.
2168039fc32eSdrh */
2169039fc32eSdrh int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2170039fc32eSdrh   u8 op;
217105883a34Sdrh   if( aff==SQLITE_AFF_BLOB ) return 1;
2172cd7f457eSdrh   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
2173039fc32eSdrh   op = p->op;
2174039fc32eSdrh   if( op==TK_REGISTER ) op = p->op2;
2175039fc32eSdrh   switch( op ){
2176039fc32eSdrh     case TK_INTEGER: {
2177039fc32eSdrh       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
2178039fc32eSdrh     }
2179039fc32eSdrh     case TK_FLOAT: {
2180039fc32eSdrh       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
2181039fc32eSdrh     }
2182039fc32eSdrh     case TK_STRING: {
2183039fc32eSdrh       return aff==SQLITE_AFF_TEXT;
2184039fc32eSdrh     }
2185039fc32eSdrh     case TK_BLOB: {
2186039fc32eSdrh       return 1;
2187039fc32eSdrh     }
21882f2855b6Sdrh     case TK_COLUMN: {
218988376ca7Sdrh       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
219088376ca7Sdrh       return p->iColumn<0
21912f2855b6Sdrh           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
21922f2855b6Sdrh     }
2193039fc32eSdrh     default: {
2194039fc32eSdrh       return 0;
2195039fc32eSdrh     }
2196039fc32eSdrh   }
2197039fc32eSdrh }
2198039fc32eSdrh 
2199039fc32eSdrh /*
2200c4a3c779Sdrh ** Return TRUE if the given string is a row-id column name.
2201c4a3c779Sdrh */
22024adee20fSdanielk1977 int sqlite3IsRowid(const char *z){
22034adee20fSdanielk1977   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
22044adee20fSdanielk1977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
22054adee20fSdanielk1977   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2206c4a3c779Sdrh   return 0;
2207c4a3c779Sdrh }
2208c4a3c779Sdrh 
22099a96b668Sdanielk1977 /*
221069c355bdSdrh ** pX is the RHS of an IN operator.  If pX is a SELECT statement
221169c355bdSdrh ** that can be simplified to a direct table access, then return
221269c355bdSdrh ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
221369c355bdSdrh ** or if the SELECT statement needs to be manifested into a transient
221469c355bdSdrh ** table, then return NULL.
2215b287f4b6Sdrh */
2216b287f4b6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
22177b35a77bSdan static Select *isCandidateForInOpt(Expr *pX){
221869c355bdSdrh   Select *p;
2219b287f4b6Sdrh   SrcList *pSrc;
2220b287f4b6Sdrh   ExprList *pEList;
2221b287f4b6Sdrh   Table *pTab;
2222cfbb5e82Sdan   int i;
222369c355bdSdrh   if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
222469c355bdSdrh   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
222569c355bdSdrh   p = pX->x.pSelect;
2226b287f4b6Sdrh   if( p->pPrior ) return 0;              /* Not a compound SELECT */
22277d10d5a6Sdrh   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2228b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2229b74b1017Sdrh     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
22307d10d5a6Sdrh     return 0; /* No DISTINCT keyword and no aggregate functions */
22317d10d5a6Sdrh   }
2232b74b1017Sdrh   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
2233b287f4b6Sdrh   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
2234b287f4b6Sdrh   if( p->pWhere ) return 0;              /* Has no WHERE clause */
2235b287f4b6Sdrh   pSrc = p->pSrc;
2236d1fa7bcaSdrh   assert( pSrc!=0 );
2237d1fa7bcaSdrh   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
2238b74b1017Sdrh   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
2239b287f4b6Sdrh   pTab = pSrc->a[0].pTab;
224069c355bdSdrh   assert( pTab!=0 );
2241b74b1017Sdrh   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
2242b287f4b6Sdrh   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
2243b287f4b6Sdrh   pEList = p->pEList;
2244ac6b47d1Sdrh   assert( pEList!=0 );
22457b35a77bSdan   /* All SELECT results must be columns. */
2246cfbb5e82Sdan   for(i=0; i<pEList->nExpr; i++){
2247cfbb5e82Sdan     Expr *pRes = pEList->a[i].pExpr;
2248cfbb5e82Sdan     if( pRes->op!=TK_COLUMN ) return 0;
224969c355bdSdrh     assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
2250cfbb5e82Sdan   }
225169c355bdSdrh   return p;
2252b287f4b6Sdrh }
2253b287f4b6Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
2254b287f4b6Sdrh 
2255f9b2e05cSdan #ifndef SQLITE_OMIT_SUBQUERY
22561d8cb21fSdan /*
22574c259e9fSdrh ** Generate code that checks the left-most column of index table iCur to see if
22584c259e9fSdrh ** it contains any NULL entries.  Cause the register at regHasNull to be set
22596be515ebSdrh ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
22606be515ebSdrh ** to be set to NULL if iCur contains one or more NULL values.
22616be515ebSdrh */
22626be515ebSdrh static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2263728e0f91Sdrh   int addr1;
22646be515ebSdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2265728e0f91Sdrh   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
22666be515ebSdrh   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
22676be515ebSdrh   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
22684c259e9fSdrh   VdbeComment((v, "first_entry_in(%d)", iCur));
2269728e0f91Sdrh   sqlite3VdbeJumpHere(v, addr1);
22706be515ebSdrh }
2271f9b2e05cSdan #endif
22726be515ebSdrh 
2273bb53ecb1Sdrh 
2274bb53ecb1Sdrh #ifndef SQLITE_OMIT_SUBQUERY
2275bb53ecb1Sdrh /*
2276bb53ecb1Sdrh ** The argument is an IN operator with a list (not a subquery) on the
2277bb53ecb1Sdrh ** right-hand side.  Return TRUE if that list is constant.
2278bb53ecb1Sdrh */
2279bb53ecb1Sdrh static int sqlite3InRhsIsConstant(Expr *pIn){
2280bb53ecb1Sdrh   Expr *pLHS;
2281bb53ecb1Sdrh   int res;
2282bb53ecb1Sdrh   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2283bb53ecb1Sdrh   pLHS = pIn->pLeft;
2284bb53ecb1Sdrh   pIn->pLeft = 0;
2285bb53ecb1Sdrh   res = sqlite3ExprIsConstant(pIn);
2286bb53ecb1Sdrh   pIn->pLeft = pLHS;
2287bb53ecb1Sdrh   return res;
2288bb53ecb1Sdrh }
2289bb53ecb1Sdrh #endif
2290bb53ecb1Sdrh 
22916be515ebSdrh /*
22929a96b668Sdanielk1977 ** This function is used by the implementation of the IN (...) operator.
2293d4305ca6Sdrh ** The pX parameter is the expression on the RHS of the IN operator, which
2294d4305ca6Sdrh ** might be either a list of expressions or a subquery.
22959a96b668Sdanielk1977 **
2296d4305ca6Sdrh ** The job of this routine is to find or create a b-tree object that can
2297d4305ca6Sdrh ** be used either to test for membership in the RHS set or to iterate through
2298d4305ca6Sdrh ** all members of the RHS set, skipping duplicates.
2299d4305ca6Sdrh **
23003a85625dSdrh ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2301d4305ca6Sdrh ** and pX->iTable is set to the index of that cursor.
2302d4305ca6Sdrh **
2303b74b1017Sdrh ** The returned value of this function indicates the b-tree type, as follows:
23049a96b668Sdanielk1977 **
23059a96b668Sdanielk1977 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
23061ccce449Sdrh **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
23071ccce449Sdrh **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
23089a96b668Sdanielk1977 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
23099a96b668Sdanielk1977 **                         populated epheremal table.
2310bb53ecb1Sdrh **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
2311bb53ecb1Sdrh **                         implemented as a sequence of comparisons.
23129a96b668Sdanielk1977 **
2313d4305ca6Sdrh ** An existing b-tree might be used if the RHS expression pX is a simple
2314d4305ca6Sdrh ** subquery such as:
23159a96b668Sdanielk1977 **
2316553168c7Sdan **     SELECT <column1>, <column2>... FROM <table>
23179a96b668Sdanielk1977 **
2318d4305ca6Sdrh ** If the RHS of the IN operator is a list or a more complex subquery, then
2319d4305ca6Sdrh ** an ephemeral table might need to be generated from the RHS and then
232060ec914cSpeter.d.reid ** pX->iTable made to point to the ephemeral table instead of an
2321d4305ca6Sdrh ** existing table.
2322d4305ca6Sdrh **
23237fc0ba0fSdrh ** The inFlags parameter must contain, at a minimum, one of the bits
23247fc0ba0fSdrh ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both.  If inFlags contains
23257fc0ba0fSdrh ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
23267fc0ba0fSdrh ** membership test.  When the IN_INDEX_LOOP bit is set, the IN index will
23277fc0ba0fSdrh ** be used to loop over all values of the RHS of the IN operator.
23283a85625dSdrh **
23293a85625dSdrh ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
23303a85625dSdrh ** through the set members) then the b-tree must not contain duplicates.
23317fc0ba0fSdrh ** An epheremal table will be created unless the selected columns are guaranteed
2332553168c7Sdan ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2333553168c7Sdan ** a UNIQUE constraint or index.
23340cdc022eSdanielk1977 **
23353a85625dSdrh ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
23363a85625dSdrh ** for fast set membership tests) then an epheremal table must
2337553168c7Sdan ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2338553168c7Sdan ** index can be found with the specified <columns> as its left-most.
23390cdc022eSdanielk1977 **
2340bb53ecb1Sdrh ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2341bb53ecb1Sdrh ** if the RHS of the IN operator is a list (not a subquery) then this
2342bb53ecb1Sdrh ** routine might decide that creating an ephemeral b-tree for membership
2343bb53ecb1Sdrh ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
2344bb53ecb1Sdrh ** calling routine should implement the IN operator using a sequence
2345bb53ecb1Sdrh ** of Eq or Ne comparison operations.
2346bb53ecb1Sdrh **
2347b74b1017Sdrh ** When the b-tree is being used for membership tests, the calling function
23483a85625dSdrh ** might need to know whether or not the RHS side of the IN operator
2349e21a6e1dSdrh ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
23503a85625dSdrh ** if there is any chance that the (...) might contain a NULL value at
23510cdc022eSdanielk1977 ** runtime, then a register is allocated and the register number written
2352e21a6e1dSdrh ** to *prRhsHasNull. If there is no chance that the (...) contains a
2353e21a6e1dSdrh ** NULL value, then *prRhsHasNull is left unchanged.
23540cdc022eSdanielk1977 **
2355e21a6e1dSdrh ** If a register is allocated and its location stored in *prRhsHasNull, then
23566be515ebSdrh ** the value in that register will be NULL if the b-tree contains one or more
23576be515ebSdrh ** NULL values, and it will be some non-NULL value if the b-tree contains no
23586be515ebSdrh ** NULL values.
2359553168c7Sdan **
2360553168c7Sdan ** If the aiMap parameter is not NULL, it must point to an array containing
2361553168c7Sdan ** one element for each column returned by the SELECT statement on the RHS
2362553168c7Sdan ** of the IN(...) operator. The i'th entry of the array is populated with the
2363553168c7Sdan ** offset of the index column that matches the i'th column returned by the
2364553168c7Sdan ** SELECT. For example, if the expression and selected index are:
2365553168c7Sdan **
2366553168c7Sdan **   (?,?,?) IN (SELECT a, b, c FROM t1)
2367553168c7Sdan **   CREATE INDEX i1 ON t1(b, c, a);
2368553168c7Sdan **
2369553168c7Sdan ** then aiMap[] is populated with {2, 0, 1}.
23709a96b668Sdanielk1977 */
2371284f4acaSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
2372ba00e30aSdan int sqlite3FindInIndex(
23736fc8f364Sdrh   Parse *pParse,             /* Parsing context */
23746fc8f364Sdrh   Expr *pX,                  /* The right-hand side (RHS) of the IN operator */
23756fc8f364Sdrh   u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
23766fc8f364Sdrh   int *prRhsHasNull,         /* Register holding NULL status.  See notes */
23772c04131cSdrh   int *aiMap,                /* Mapping from Index fields to RHS fields */
23782c04131cSdrh   int *piTab                 /* OUT: index to use */
2379ba00e30aSdan ){
2380b74b1017Sdrh   Select *p;                            /* SELECT to the right of IN operator */
2381b74b1017Sdrh   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
2382b74b1017Sdrh   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
23833a85625dSdrh   int mustBeUnique;                     /* True if RHS must be unique */
2384b8475df8Sdrh   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
23859a96b668Sdanielk1977 
23861450bc6eSdrh   assert( pX->op==TK_IN );
23873a85625dSdrh   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
23881450bc6eSdrh 
23897b35a77bSdan   /* If the RHS of this IN(...) operator is a SELECT, and if it matters
23907b35a77bSdan   ** whether or not the SELECT result contains NULL values, check whether
2391870a0705Sdan   ** or not NULL is actually possible (it may not be, for example, due
23927b35a77bSdan   ** to NOT NULL constraints in the schema). If no NULL values are possible,
2393870a0705Sdan   ** set prRhsHasNull to 0 before continuing.  */
23947b35a77bSdan   if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
23957b35a77bSdan     int i;
23967b35a77bSdan     ExprList *pEList = pX->x.pSelect->pEList;
23977b35a77bSdan     for(i=0; i<pEList->nExpr; i++){
23987b35a77bSdan       if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
23997b35a77bSdan     }
24007b35a77bSdan     if( i==pEList->nExpr ){
24017b35a77bSdan       prRhsHasNull = 0;
24027b35a77bSdan     }
24037b35a77bSdan   }
24047b35a77bSdan 
2405b74b1017Sdrh   /* Check to see if an existing table or index can be used to
2406b74b1017Sdrh   ** satisfy the query.  This is preferable to generating a new
24077b35a77bSdan   ** ephemeral table.  */
24087b35a77bSdan   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
2409e1fb65a0Sdanielk1977     sqlite3 *db = pParse->db;              /* Database connection */
2410b07028f7Sdrh     Table *pTab;                           /* Table <table>. */
2411ba00e30aSdan     i16 iDb;                               /* Database idx for pTab */
2412cfbb5e82Sdan     ExprList *pEList = p->pEList;
2413cfbb5e82Sdan     int nExpr = pEList->nExpr;
2414e1fb65a0Sdanielk1977 
2415b07028f7Sdrh     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
2416b07028f7Sdrh     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2417b07028f7Sdrh     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
2418b07028f7Sdrh     pTab = p->pSrc->a[0].pTab;
2419b07028f7Sdrh 
2420b22f7c83Sdrh     /* Code an OP_Transaction and OP_TableLock for <table>. */
2421e1fb65a0Sdanielk1977     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2422e1fb65a0Sdanielk1977     sqlite3CodeVerifySchema(pParse, iDb);
2423e1fb65a0Sdanielk1977     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
24249a96b668Sdanielk1977 
2425a84a283dSdrh     assert(v);  /* sqlite3GetVdbe() has always been previously called */
2426cfbb5e82Sdan     if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
242762659b2aSdrh       /* The "x IN (SELECT rowid FROM table)" case */
2428511f9e8dSdrh       int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
24297d176105Sdrh       VdbeCoverage(v);
24309a96b668Sdanielk1977 
24319a96b668Sdanielk1977       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
24329a96b668Sdanielk1977       eType = IN_INDEX_ROWID;
2433d8852095Sdrh       ExplainQueryPlan((pParse, 0,
2434d8852095Sdrh             "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
24359a96b668Sdanielk1977       sqlite3VdbeJumpHere(v, iAddr);
24369a96b668Sdanielk1977     }else{
2437e1fb65a0Sdanielk1977       Index *pIdx;                         /* Iterator variable */
2438cfbb5e82Sdan       int affinity_ok = 1;
2439cfbb5e82Sdan       int i;
2440cfbb5e82Sdan 
2441cfbb5e82Sdan       /* Check that the affinity that will be used to perform each
244262659b2aSdrh       ** comparison is the same as the affinity of each column in table
244362659b2aSdrh       ** on the RHS of the IN operator.  If it not, it is not possible to
244462659b2aSdrh       ** use any index of the RHS table.  */
2445cfbb5e82Sdan       for(i=0; i<nExpr && affinity_ok; i++){
2446fc7f27b9Sdrh         Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2447cfbb5e82Sdan         int iCol = pEList->a[i].pExpr->iColumn;
24480dfa4f6fSdrh         char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
2449cfbb5e82Sdan         char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
245062659b2aSdrh         testcase( cmpaff==SQLITE_AFF_BLOB );
245162659b2aSdrh         testcase( cmpaff==SQLITE_AFF_TEXT );
2452cfbb5e82Sdan         switch( cmpaff ){
2453cfbb5e82Sdan           case SQLITE_AFF_BLOB:
2454cfbb5e82Sdan             break;
2455cfbb5e82Sdan           case SQLITE_AFF_TEXT:
245662659b2aSdrh             /* sqlite3CompareAffinity() only returns TEXT if one side or the
245762659b2aSdrh             ** other has no affinity and the other side is TEXT.  Hence,
245862659b2aSdrh             ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
245962659b2aSdrh             ** and for the term on the LHS of the IN to have no affinity. */
246062659b2aSdrh             assert( idxaff==SQLITE_AFF_TEXT );
2461cfbb5e82Sdan             break;
2462cfbb5e82Sdan           default:
2463cfbb5e82Sdan             affinity_ok = sqlite3IsNumericAffinity(idxaff);
2464cfbb5e82Sdan         }
2465cfbb5e82Sdan       }
2466e1fb65a0Sdanielk1977 
2467a84a283dSdrh       if( affinity_ok ){
2468a84a283dSdrh         /* Search for an existing index that will work for this IN operator */
2469a84a283dSdrh         for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2470a84a283dSdrh           Bitmask colUsed;      /* Columns of the index used */
2471a84a283dSdrh           Bitmask mCol;         /* Mask for the current column */
24726fc8f364Sdrh           if( pIdx->nColumn<nExpr ) continue;
2473d4a4a361Sdrh           if( pIdx->pPartIdxWhere!=0 ) continue;
2474a84a283dSdrh           /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2475a84a283dSdrh           ** BITMASK(nExpr) without overflowing */
2476a84a283dSdrh           testcase( pIdx->nColumn==BMS-2 );
2477a84a283dSdrh           testcase( pIdx->nColumn==BMS-1 );
2478a84a283dSdrh           if( pIdx->nColumn>=BMS-1 ) continue;
24796fc8f364Sdrh           if( mustBeUnique ){
24806fc8f364Sdrh             if( pIdx->nKeyCol>nExpr
24816fc8f364Sdrh              ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
24826fc8f364Sdrh             ){
2483a84a283dSdrh               continue;  /* This index is not unique over the IN RHS columns */
2484cfbb5e82Sdan             }
24856fc8f364Sdrh           }
2486cfbb5e82Sdan 
2487a84a283dSdrh           colUsed = 0;   /* Columns of index used so far */
2488cfbb5e82Sdan           for(i=0; i<nExpr; i++){
2489fc7f27b9Sdrh             Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2490cfbb5e82Sdan             Expr *pRhs = pEList->a[i].pExpr;
2491cfbb5e82Sdan             CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2492cfbb5e82Sdan             int j;
2493cfbb5e82Sdan 
24946fc8f364Sdrh             assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
2495cfbb5e82Sdan             for(j=0; j<nExpr; j++){
2496cfbb5e82Sdan               if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2497cfbb5e82Sdan               assert( pIdx->azColl[j] );
2498106526e1Sdrh               if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2499106526e1Sdrh                 continue;
2500106526e1Sdrh               }
2501cfbb5e82Sdan               break;
2502cfbb5e82Sdan             }
2503cfbb5e82Sdan             if( j==nExpr ) break;
2504a84a283dSdrh             mCol = MASKBIT(j);
2505a84a283dSdrh             if( mCol & colUsed ) break; /* Each column used only once */
2506a84a283dSdrh             colUsed |= mCol;
2507ba00e30aSdan             if( aiMap ) aiMap[i] = j;
2508cfbb5e82Sdan           }
2509cfbb5e82Sdan 
2510a84a283dSdrh           assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2511a84a283dSdrh           if( colUsed==(MASKBIT(nExpr)-1) ){
2512a84a283dSdrh             /* If we reach this point, that means the index pIdx is usable */
2513511f9e8dSdrh             int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2514e2ca99c9Sdrh             ExplainQueryPlan((pParse, 0,
2515e2ca99c9Sdrh                               "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
25162ec2fb22Sdrh             sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
25172ec2fb22Sdrh             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2518207872a4Sdanielk1977             VdbeComment((v, "%s", pIdx->zName));
25191ccce449Sdrh             assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
25201ccce449Sdrh             eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
25219a96b668Sdanielk1977 
25227b35a77bSdan             if( prRhsHasNull ){
25233480bfdaSdan #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
2524cfbb5e82Sdan               i64 mask = (1<<nExpr)-1;
25253480bfdaSdan               sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
2526cfbb5e82Sdan                   iTab, 0, 0, (u8*)&mask, P4_INT64);
25273480bfdaSdan #endif
2528b80dbdc2Sdrh               *prRhsHasNull = ++pParse->nMem;
25297b35a77bSdan               if( nExpr==1 ){
25306be515ebSdrh                 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
25310cdc022eSdanielk1977               }
25327b35a77bSdan             }
2533552fd454Sdrh             sqlite3VdbeJumpHere(v, iAddr);
25349a96b668Sdanielk1977           }
2535a84a283dSdrh         } /* End loop over indexes */
2536a84a283dSdrh       } /* End if( affinity_ok ) */
2537a84a283dSdrh     } /* End if not an rowid index */
2538a84a283dSdrh   } /* End attempt to optimize using an index */
25399a96b668Sdanielk1977 
2540bb53ecb1Sdrh   /* If no preexisting index is available for the IN clause
2541bb53ecb1Sdrh   ** and IN_INDEX_NOOP is an allowed reply
2542bb53ecb1Sdrh   ** and the RHS of the IN operator is a list, not a subquery
254371c57db0Sdan   ** and the RHS is not constant or has two or fewer terms,
254460ec914cSpeter.d.reid   ** then it is not worth creating an ephemeral table to evaluate
2545bb53ecb1Sdrh   ** the IN operator so return IN_INDEX_NOOP.
2546bb53ecb1Sdrh   */
2547bb53ecb1Sdrh   if( eType==0
2548bb53ecb1Sdrh    && (inFlags & IN_INDEX_NOOP_OK)
2549bb53ecb1Sdrh    && !ExprHasProperty(pX, EP_xIsSelect)
2550bb53ecb1Sdrh    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2551bb53ecb1Sdrh   ){
2552bb53ecb1Sdrh     eType = IN_INDEX_NOOP;
2553bb53ecb1Sdrh   }
2554bb53ecb1Sdrh 
25559a96b668Sdanielk1977   if( eType==0 ){
25564387006cSdrh     /* Could not find an existing table or index to use as the RHS b-tree.
2557b74b1017Sdrh     ** We will have to generate an ephemeral table to do the job.
2558b74b1017Sdrh     */
25598e23daf3Sdrh     u32 savedNQueryLoop = pParse->nQueryLoop;
25600cdc022eSdanielk1977     int rMayHaveNull = 0;
256141a05b7bSdanielk1977     eType = IN_INDEX_EPH;
25623a85625dSdrh     if( inFlags & IN_INDEX_LOOP ){
25634a5acf8eSdrh       pParse->nQueryLoop = 0;
2564e21a6e1dSdrh     }else if( prRhsHasNull ){
2565e21a6e1dSdrh       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
2566cf4d38aaSdrh     }
256785bcdce2Sdrh     assert( pX->op==TK_IN );
256850ef6716Sdrh     sqlite3CodeRhsOfIN(pParse, pX, iTab);
256985bcdce2Sdrh     if( rMayHaveNull ){
25702c04131cSdrh       sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
257185bcdce2Sdrh     }
2572cf4d38aaSdrh     pParse->nQueryLoop = savedNQueryLoop;
25739a96b668Sdanielk1977   }
2574ba00e30aSdan 
2575ba00e30aSdan   if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2576ba00e30aSdan     int i, n;
2577ba00e30aSdan     n = sqlite3ExprVectorSize(pX->pLeft);
2578ba00e30aSdan     for(i=0; i<n; i++) aiMap[i] = i;
2579ba00e30aSdan   }
25802c04131cSdrh   *piTab = iTab;
25819a96b668Sdanielk1977   return eType;
25829a96b668Sdanielk1977 }
2583284f4acaSdanielk1977 #endif
2584626a879aSdrh 
2585f9b2e05cSdan #ifndef SQLITE_OMIT_SUBQUERY
2586553168c7Sdan /*
2587553168c7Sdan ** Argument pExpr is an (?, ?...) IN(...) expression. This
2588553168c7Sdan ** function allocates and returns a nul-terminated string containing
2589553168c7Sdan ** the affinities to be used for each column of the comparison.
2590553168c7Sdan **
2591553168c7Sdan ** It is the responsibility of the caller to ensure that the returned
2592553168c7Sdan ** string is eventually freed using sqlite3DbFree().
2593553168c7Sdan */
259471c57db0Sdan static char *exprINAffinity(Parse *pParse, Expr *pExpr){
259571c57db0Sdan   Expr *pLeft = pExpr->pLeft;
259671c57db0Sdan   int nVal = sqlite3ExprVectorSize(pLeft);
2597553168c7Sdan   Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
259871c57db0Sdan   char *zRet;
259971c57db0Sdan 
2600553168c7Sdan   assert( pExpr->op==TK_IN );
26015c258dc1Sdrh   zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
260271c57db0Sdan   if( zRet ){
260371c57db0Sdan     int i;
260471c57db0Sdan     for(i=0; i<nVal; i++){
2605fc7f27b9Sdrh       Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
2606553168c7Sdan       char a = sqlite3ExprAffinity(pA);
2607553168c7Sdan       if( pSelect ){
2608553168c7Sdan         zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
260971c57db0Sdan       }else{
2610553168c7Sdan         zRet[i] = a;
261171c57db0Sdan       }
261271c57db0Sdan     }
261371c57db0Sdan     zRet[nVal] = '\0';
261471c57db0Sdan   }
261571c57db0Sdan   return zRet;
261671c57db0Sdan }
2617f9b2e05cSdan #endif
261871c57db0Sdan 
26198da209b1Sdan #ifndef SQLITE_OMIT_SUBQUERY
26208da209b1Sdan /*
26218da209b1Sdan ** Load the Parse object passed as the first argument with an error
26228da209b1Sdan ** message of the form:
26238da209b1Sdan **
26248da209b1Sdan **   "sub-select returns N columns - expected M"
26258da209b1Sdan */
26268da209b1Sdan void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
26278da209b1Sdan   const char *zFmt = "sub-select returns %d columns - expected %d";
26288da209b1Sdan   sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
26298da209b1Sdan }
26308da209b1Sdan #endif
26318da209b1Sdan 
2632626a879aSdrh /*
263344c5604cSdan ** Expression pExpr is a vector that has been used in a context where
263444c5604cSdan ** it is not permitted. If pExpr is a sub-select vector, this routine
263544c5604cSdan ** loads the Parse object with a message of the form:
263644c5604cSdan **
263744c5604cSdan **   "sub-select returns N columns - expected 1"
263844c5604cSdan **
263944c5604cSdan ** Or, if it is a regular scalar vector:
264044c5604cSdan **
264144c5604cSdan **   "row value misused"
264244c5604cSdan */
264344c5604cSdan void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
264444c5604cSdan #ifndef SQLITE_OMIT_SUBQUERY
264544c5604cSdan   if( pExpr->flags & EP_xIsSelect ){
264644c5604cSdan     sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
264744c5604cSdan   }else
264844c5604cSdan #endif
264944c5604cSdan   {
265044c5604cSdan     sqlite3ErrorMsg(pParse, "row value misused");
265144c5604cSdan   }
265244c5604cSdan }
265344c5604cSdan 
265485bcdce2Sdrh #ifndef SQLITE_OMIT_SUBQUERY
265544c5604cSdan /*
265685bcdce2Sdrh ** Generate code that will construct an ephemeral table containing all terms
265785bcdce2Sdrh ** in the RHS of an IN operator.  The IN operator can be in either of two
265885bcdce2Sdrh ** forms:
2659626a879aSdrh **
26609cbe6352Sdrh **     x IN (4,5,11)              -- IN operator with list on right-hand side
26619cbe6352Sdrh **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
2662fef5208cSdrh **
26632c04131cSdrh ** The pExpr parameter is the IN operator.  The cursor number for the
26642c04131cSdrh ** constructed ephermeral table is returned.  The first time the ephemeral
26652c04131cSdrh ** table is computed, the cursor number is also stored in pExpr->iTable,
26662c04131cSdrh ** however the cursor number returned might not be the same, as it might
26672c04131cSdrh ** have been duplicated using OP_OpenDup.
266841a05b7bSdanielk1977 **
266985bcdce2Sdrh ** If the LHS expression ("x" in the examples) is a column value, or
267085bcdce2Sdrh ** the SELECT statement returns a column value, then the affinity of that
267185bcdce2Sdrh ** column is used to build the index keys. If both 'x' and the
267285bcdce2Sdrh ** SELECT... statement are columns, then numeric affinity is used
267385bcdce2Sdrh ** if either column has NUMERIC or INTEGER affinity. If neither
267485bcdce2Sdrh ** 'x' nor the SELECT... statement are columns, then numeric affinity
267585bcdce2Sdrh ** is used.
2676cce7d176Sdrh */
267785bcdce2Sdrh void sqlite3CodeRhsOfIN(
2678fd773cf9Sdrh   Parse *pParse,          /* Parsing context */
267985bcdce2Sdrh   Expr *pExpr,            /* The IN operator */
268050ef6716Sdrh   int iTab                /* Use this cursor number */
268141a05b7bSdanielk1977 ){
26822c04131cSdrh   int addrOnce = 0;           /* Address of the OP_Once instruction at top */
268385bcdce2Sdrh   int addr;                   /* Address of OP_OpenEphemeral instruction */
268485bcdce2Sdrh   Expr *pLeft;                /* the LHS of the IN operator */
268585bcdce2Sdrh   KeyInfo *pKeyInfo = 0;      /* Key information */
268685bcdce2Sdrh   int nVal;                   /* Size of vector pLeft */
268785bcdce2Sdrh   Vdbe *v;                    /* The prepared statement under construction */
2688fc976065Sdanielk1977 
26892c04131cSdrh   v = pParse->pVdbe;
269085bcdce2Sdrh   assert( v!=0 );
269185bcdce2Sdrh 
26922c04131cSdrh   /* The evaluation of the IN must be repeated every time it
269339a11819Sdrh   ** is encountered if any of the following is true:
269457dbd7b3Sdrh   **
269557dbd7b3Sdrh   **    *  The right-hand side is a correlated subquery
269657dbd7b3Sdrh   **    *  The right-hand side is an expression list containing variables
269757dbd7b3Sdrh   **    *  We are inside a trigger
269857dbd7b3Sdrh   **
26992c04131cSdrh   ** If all of the above are false, then we can compute the RHS just once
27002c04131cSdrh   ** and reuse it many names.
2701b3bce662Sdanielk1977   */
2702efb699fcSdrh   if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
27032c04131cSdrh     /* Reuse of the RHS is allowed */
27042c04131cSdrh     /* If this routine has already been coded, but the previous code
27052c04131cSdrh     ** might not have been invoked yet, so invoke it now as a subroutine.
27062c04131cSdrh     */
27072c04131cSdrh     if( ExprHasProperty(pExpr, EP_Subrtn) ){
2708f9231c34Sdrh       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2709bd462bccSdrh       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2710bd462bccSdrh         ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
2711bd462bccSdrh               pExpr->x.pSelect->selId));
2712bd462bccSdrh       }
27132c04131cSdrh       sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
27142c04131cSdrh                         pExpr->y.sub.iAddr);
27152c04131cSdrh       sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
2716f9231c34Sdrh       sqlite3VdbeJumpHere(v, addrOnce);
27172c04131cSdrh       return;
27182c04131cSdrh     }
27192c04131cSdrh 
27202c04131cSdrh     /* Begin coding the subroutine */
27212c04131cSdrh     ExprSetProperty(pExpr, EP_Subrtn);
27222c04131cSdrh     pExpr->y.sub.regReturn = ++pParse->nMem;
27232c04131cSdrh     pExpr->y.sub.iAddr =
27242c04131cSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
27252c04131cSdrh     VdbeComment((v, "return address"));
27262c04131cSdrh 
27272c04131cSdrh     addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2728b3bce662Sdanielk1977   }
2729b3bce662Sdanielk1977 
273085bcdce2Sdrh   /* Check to see if this is a vector IN operator */
273185bcdce2Sdrh   pLeft = pExpr->pLeft;
273271c57db0Sdan   nVal = sqlite3ExprVectorSize(pLeft);
2733e014a838Sdanielk1977 
273485bcdce2Sdrh   /* Construct the ephemeral table that will contain the content of
273585bcdce2Sdrh   ** RHS of the IN operator.
2736fef5208cSdrh   */
27372c04131cSdrh   pExpr->iTable = iTab;
273850ef6716Sdrh   addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
27392c04131cSdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
27402c04131cSdrh   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
27412c04131cSdrh     VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
27422c04131cSdrh   }else{
27432c04131cSdrh     VdbeComment((v, "RHS of IN operator"));
27442c04131cSdrh   }
27452c04131cSdrh #endif
274650ef6716Sdrh   pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
2747e014a838Sdanielk1977 
27486ab3a2ecSdanielk1977   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2749e014a838Sdanielk1977     /* Case 1:     expr IN (SELECT ...)
2750e014a838Sdanielk1977     **
2751e014a838Sdanielk1977     ** Generate code to write the results of the select into the temporary
2752e014a838Sdanielk1977     ** table allocated and opened above.
2753e014a838Sdanielk1977     */
27544387006cSdrh     Select *pSelect = pExpr->x.pSelect;
275571c57db0Sdan     ExprList *pEList = pSelect->pEList;
27561013c932Sdrh 
27572c04131cSdrh     ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
27582c04131cSdrh         addrOnce?"":"CORRELATED ", pSelect->selId
2759e2ca99c9Sdrh     ));
276064bcb8cfSdrh     /* If the LHS and RHS of the IN operator do not match, that
276164bcb8cfSdrh     ** error will have been caught long before we reach this point. */
276264bcb8cfSdrh     if( ALWAYS(pEList->nExpr==nVal) ){
276371c57db0Sdan       SelectDest dest;
276471c57db0Sdan       int i;
2765bd462bccSdrh       sqlite3SelectDestInit(&dest, SRT_Set, iTab);
276671c57db0Sdan       dest.zAffSdst = exprINAffinity(pParse, pExpr);
27674387006cSdrh       pSelect->iLimit = 0;
27684387006cSdrh       testcase( pSelect->selFlags & SF_Distinct );
2769812ea833Sdrh       testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
27704387006cSdrh       if( sqlite3Select(pParse, pSelect, &dest) ){
277171c57db0Sdan         sqlite3DbFree(pParse->db, dest.zAffSdst);
27722ec2fb22Sdrh         sqlite3KeyInfoUnref(pKeyInfo);
277385bcdce2Sdrh         return;
277494ccde58Sdrh       }
277571c57db0Sdan       sqlite3DbFree(pParse->db, dest.zAffSdst);
2776812ea833Sdrh       assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
27773535ec3eSdrh       assert( pEList!=0 );
27783535ec3eSdrh       assert( pEList->nExpr>0 );
27792ec2fb22Sdrh       assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
278071c57db0Sdan       for(i=0; i<nVal; i++){
2781773d3afaSdan         Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
278271c57db0Sdan         pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
278371c57db0Sdan             pParse, p, pEList->a[i].pExpr
278471c57db0Sdan         );
278571c57db0Sdan       }
278671c57db0Sdan     }
2787a7d2db17Sdrh   }else if( ALWAYS(pExpr->x.pList!=0) ){
2788fef5208cSdrh     /* Case 2:     expr IN (exprlist)
2789fef5208cSdrh     **
2790e014a838Sdanielk1977     ** For each expression, build an index key from the evaluation and
2791e014a838Sdanielk1977     ** store it in the temporary table. If <expr> is a column, then use
2792e014a838Sdanielk1977     ** that columns affinity when building index keys. If <expr> is not
2793e014a838Sdanielk1977     ** a column, use numeric affinity.
2794fef5208cSdrh     */
279571c57db0Sdan     char affinity;            /* Affinity of the LHS of the IN */
2796e014a838Sdanielk1977     int i;
27976ab3a2ecSdanielk1977     ExprList *pList = pExpr->x.pList;
279857dbd7b3Sdrh     struct ExprList_item *pItem;
2799ecc31805Sdrh     int r1, r2, r3;
280071c57db0Sdan     affinity = sqlite3ExprAffinity(pLeft);
2801e014a838Sdanielk1977     if( !affinity ){
280205883a34Sdrh       affinity = SQLITE_AFF_BLOB;
2803e014a838Sdanielk1977     }
2804323df790Sdrh     if( pKeyInfo ){
28052ec2fb22Sdrh       assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2806323df790Sdrh       pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2807323df790Sdrh     }
2808e014a838Sdanielk1977 
2809e014a838Sdanielk1977     /* Loop through each expression in <exprlist>. */
28102d401ab8Sdrh     r1 = sqlite3GetTempReg(pParse);
28112d401ab8Sdrh     r2 = sqlite3GetTempReg(pParse);
281257dbd7b3Sdrh     for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
281357dbd7b3Sdrh       Expr *pE2 = pItem->pExpr;
2814e014a838Sdanielk1977 
281557dbd7b3Sdrh       /* If the expression is not constant then we will need to
281657dbd7b3Sdrh       ** disable the test that was generated above that makes sure
281757dbd7b3Sdrh       ** this code only executes once.  Because for a non-constant
281857dbd7b3Sdrh       ** expression we need to rerun this code each time.
281957dbd7b3Sdrh       */
28202c04131cSdrh       if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
28212c04131cSdrh         sqlite3VdbeChangeToNoop(v, addrOnce);
28227ac0e562Sdan         ExprClearProperty(pExpr, EP_Subrtn);
28232c04131cSdrh         addrOnce = 0;
28244794b980Sdrh       }
2825e014a838Sdanielk1977 
2826e014a838Sdanielk1977       /* Evaluate the expression and insert it into the temp table */
2827ecc31805Sdrh       r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2828ecc31805Sdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2829bd462bccSdrh       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r3, 1);
2830fef5208cSdrh     }
28312d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, r1);
28322d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, r2);
2833fef5208cSdrh   }
2834323df790Sdrh   if( pKeyInfo ){
28352ec2fb22Sdrh     sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
283641a05b7bSdanielk1977   }
28372c04131cSdrh   if( addrOnce ){
28382c04131cSdrh     sqlite3VdbeJumpHere(v, addrOnce);
28392c04131cSdrh     /* Subroutine return */
28402c04131cSdrh     sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
28412c04131cSdrh     sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
284285bcdce2Sdrh   }
284385bcdce2Sdrh }
284485bcdce2Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
284585bcdce2Sdrh 
284685bcdce2Sdrh /*
284785bcdce2Sdrh ** Generate code for scalar subqueries used as a subquery expression
284885bcdce2Sdrh ** or EXISTS operator:
284985bcdce2Sdrh **
285085bcdce2Sdrh **     (SELECT a FROM b)          -- subquery
285185bcdce2Sdrh **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
285285bcdce2Sdrh **
285385bcdce2Sdrh ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
285485bcdce2Sdrh **
285585bcdce2Sdrh ** The register that holds the result.  For a multi-column SELECT,
285685bcdce2Sdrh ** the result is stored in a contiguous array of registers and the
285785bcdce2Sdrh ** return value is the register of the left-most result column.
285885bcdce2Sdrh ** Return 0 if an error occurs.
285985bcdce2Sdrh */
286085bcdce2Sdrh #ifndef SQLITE_OMIT_SUBQUERY
286185bcdce2Sdrh int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
28622c04131cSdrh   int addrOnce = 0;           /* Address of OP_Once at top of subroutine */
286385bcdce2Sdrh   int rReg = 0;               /* Register storing resulting */
286485bcdce2Sdrh   Select *pSel;               /* SELECT statement to encode */
286585bcdce2Sdrh   SelectDest dest;            /* How to deal with SELECT result */
286685bcdce2Sdrh   int nReg;                   /* Registers to allocate */
286785bcdce2Sdrh   Expr *pLimit;               /* New limit expression */
28682c04131cSdrh 
28692c04131cSdrh   Vdbe *v = pParse->pVdbe;
287085bcdce2Sdrh   assert( v!=0 );
2871bd462bccSdrh   testcase( pExpr->op==TK_EXISTS );
2872bd462bccSdrh   testcase( pExpr->op==TK_SELECT );
2873bd462bccSdrh   assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
2874bd462bccSdrh   assert( ExprHasProperty(pExpr, EP_xIsSelect) );
2875bd462bccSdrh   pSel = pExpr->x.pSelect;
287685bcdce2Sdrh 
28775198ff57Sdrh   /* The evaluation of the EXISTS/SELECT must be repeated every time it
287885bcdce2Sdrh   ** is encountered if any of the following is true:
287985bcdce2Sdrh   **
288085bcdce2Sdrh   **    *  The right-hand side is a correlated subquery
288185bcdce2Sdrh   **    *  The right-hand side is an expression list containing variables
288285bcdce2Sdrh   **    *  We are inside a trigger
288385bcdce2Sdrh   **
288485bcdce2Sdrh   ** If all of the above are false, then we can run this code just once
288585bcdce2Sdrh   ** save the results, and reuse the same result on subsequent invocations.
288685bcdce2Sdrh   */
288785bcdce2Sdrh   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
28885198ff57Sdrh     /* If this routine has already been coded, then invoke it as a
28895198ff57Sdrh     ** subroutine. */
28905198ff57Sdrh     if( ExprHasProperty(pExpr, EP_Subrtn) ){
2891bd462bccSdrh       ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
28925198ff57Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
28935198ff57Sdrh                         pExpr->y.sub.iAddr);
28945198ff57Sdrh       return pExpr->iTable;
28955198ff57Sdrh     }
28965198ff57Sdrh 
28975198ff57Sdrh     /* Begin coding the subroutine */
28985198ff57Sdrh     ExprSetProperty(pExpr, EP_Subrtn);
28995198ff57Sdrh     pExpr->y.sub.regReturn = ++pParse->nMem;
29005198ff57Sdrh     pExpr->y.sub.iAddr =
29015198ff57Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
29025198ff57Sdrh     VdbeComment((v, "return address"));
29035198ff57Sdrh 
29042c04131cSdrh     addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2905fef5208cSdrh   }
2906fef5208cSdrh 
290785bcdce2Sdrh   /* For a SELECT, generate code to put the values for all columns of
290839a11819Sdrh   ** the first row into an array of registers and return the index of
290939a11819Sdrh   ** the first register.
291039a11819Sdrh   **
291139a11819Sdrh   ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
291239a11819Sdrh   ** into a register and return that register number.
291339a11819Sdrh   **
291439a11819Sdrh   ** In both cases, the query is augmented with "LIMIT 1".  Any
291539a11819Sdrh   ** preexisting limit is discarded in place of the new LIMIT 1.
2916fef5208cSdrh   */
2917bd462bccSdrh   ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
2918bd462bccSdrh         addrOnce?"":"CORRELATED ", pSel->selId));
291971c57db0Sdan   nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
292071c57db0Sdan   sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
292171c57db0Sdan   pParse->nMem += nReg;
292251522cd3Sdrh   if( pExpr->op==TK_SELECT ){
29236c8c8ce0Sdanielk1977     dest.eDest = SRT_Mem;
292453932ce8Sdrh     dest.iSdst = dest.iSDParm;
292571c57db0Sdan     dest.nSdst = nReg;
292671c57db0Sdan     sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
2927d4e70ebdSdrh     VdbeComment((v, "Init subquery result"));
292851522cd3Sdrh   }else{
29296c8c8ce0Sdanielk1977     dest.eDest = SRT_Exists;
29302b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
2931d4e70ebdSdrh     VdbeComment((v, "Init EXISTS result"));
293251522cd3Sdrh   }
29338c0833fbSdrh   pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
29348c0833fbSdrh   if( pSel->pLimit ){
29358c0833fbSdrh     sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
29368c0833fbSdrh     pSel->pLimit->pLeft = pLimit;
29378c0833fbSdrh   }else{
29388c0833fbSdrh     pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
29398c0833fbSdrh   }
294048b5b041Sdrh   pSel->iLimit = 0;
29417d10d5a6Sdrh   if( sqlite3Select(pParse, pSel, &dest) ){
29421450bc6eSdrh     return 0;
294394ccde58Sdrh   }
29442c04131cSdrh   pExpr->iTable = rReg = dest.iSDParm;
2945ebb6a65dSdrh   ExprSetVVAProperty(pExpr, EP_NoReduce);
29462c04131cSdrh   if( addrOnce ){
29472c04131cSdrh     sqlite3VdbeJumpHere(v, addrOnce);
2948fc976065Sdanielk1977 
29492c04131cSdrh     /* Subroutine return */
29502c04131cSdrh     sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
29512c04131cSdrh     sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
29525198ff57Sdrh   }
29532c04131cSdrh 
29541450bc6eSdrh   return rReg;
2955cce7d176Sdrh }
295651522cd3Sdrh #endif /* SQLITE_OMIT_SUBQUERY */
2957cce7d176Sdrh 
2958e3365e6cSdrh #ifndef SQLITE_OMIT_SUBQUERY
2959e3365e6cSdrh /*
29607b35a77bSdan ** Expr pIn is an IN(...) expression. This function checks that the
29617b35a77bSdan ** sub-select on the RHS of the IN() operator has the same number of
29627b35a77bSdan ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
29637b35a77bSdan ** a sub-query, that the LHS is a vector of size 1.
29647b35a77bSdan */
29657b35a77bSdan int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
29667b35a77bSdan   int nVector = sqlite3ExprVectorSize(pIn->pLeft);
29677b35a77bSdan   if( (pIn->flags & EP_xIsSelect) ){
29687b35a77bSdan     if( nVector!=pIn->x.pSelect->pEList->nExpr ){
29697b35a77bSdan       sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
29707b35a77bSdan       return 1;
29717b35a77bSdan     }
29727b35a77bSdan   }else if( nVector!=1 ){
297344c5604cSdan     sqlite3VectorErrorMsg(pParse, pIn->pLeft);
29747b35a77bSdan     return 1;
29757b35a77bSdan   }
29767b35a77bSdan   return 0;
29777b35a77bSdan }
29787b35a77bSdan #endif
29797b35a77bSdan 
29807b35a77bSdan #ifndef SQLITE_OMIT_SUBQUERY
29817b35a77bSdan /*
2982e3365e6cSdrh ** Generate code for an IN expression.
2983e3365e6cSdrh **
2984e3365e6cSdrh **      x IN (SELECT ...)
2985e3365e6cSdrh **      x IN (value, value, ...)
2986e3365e6cSdrh **
2987ecb87ac8Sdrh ** The left-hand side (LHS) is a scalar or vector expression.  The
2988e347d3e8Sdrh ** right-hand side (RHS) is an array of zero or more scalar values, or a
2989e347d3e8Sdrh ** subquery.  If the RHS is a subquery, the number of result columns must
2990e347d3e8Sdrh ** match the number of columns in the vector on the LHS.  If the RHS is
2991e347d3e8Sdrh ** a list of values, the LHS must be a scalar.
2992e347d3e8Sdrh **
2993e347d3e8Sdrh ** The IN operator is true if the LHS value is contained within the RHS.
2994e347d3e8Sdrh ** The result is false if the LHS is definitely not in the RHS.  The
2995e347d3e8Sdrh ** result is NULL if the presence of the LHS in the RHS cannot be
2996e347d3e8Sdrh ** determined due to NULLs.
2997e3365e6cSdrh **
29986be515ebSdrh ** This routine generates code that jumps to destIfFalse if the LHS is not
2999e3365e6cSdrh ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
3000e3365e6cSdrh ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
3001e3365e6cSdrh ** within the RHS then fall through.
3002ecb87ac8Sdrh **
3003ecb87ac8Sdrh ** See the separate in-operator.md documentation file in the canonical
3004ecb87ac8Sdrh ** SQLite source tree for additional information.
3005e3365e6cSdrh */
3006e3365e6cSdrh static void sqlite3ExprCodeIN(
3007e3365e6cSdrh   Parse *pParse,        /* Parsing and code generating context */
3008e3365e6cSdrh   Expr *pExpr,          /* The IN expression */
3009e3365e6cSdrh   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
3010e3365e6cSdrh   int destIfNull        /* Jump here if the results are unknown due to NULLs */
3011e3365e6cSdrh ){
3012e3365e6cSdrh   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
3013e3365e6cSdrh   int eType;            /* Type of the RHS */
3014e347d3e8Sdrh   int rLhs;             /* Register(s) holding the LHS values */
3015e347d3e8Sdrh   int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
3016e3365e6cSdrh   Vdbe *v;              /* Statement under construction */
3017ba00e30aSdan   int *aiMap = 0;       /* Map from vector field to index column */
3018ba00e30aSdan   char *zAff = 0;       /* Affinity string for comparisons */
3019ecb87ac8Sdrh   int nVector;          /* Size of vectors for this IN operator */
302012abf408Sdrh   int iDummy;           /* Dummy parameter to exprCodeVector() */
3021e347d3e8Sdrh   Expr *pLeft;          /* The LHS of the IN operator */
3022ecb87ac8Sdrh   int i;                /* loop counter */
3023e347d3e8Sdrh   int destStep2;        /* Where to jump when NULLs seen in step 2 */
3024e347d3e8Sdrh   int destStep6 = 0;    /* Start of code for Step 6 */
3025e347d3e8Sdrh   int addrTruthOp;      /* Address of opcode that determines the IN is true */
3026e347d3e8Sdrh   int destNotNull;      /* Jump here if a comparison is not true in step 6 */
3027e347d3e8Sdrh   int addrTop;          /* Top of the step-6 loop */
30282c04131cSdrh   int iTab = 0;         /* Index to use */
3029e3365e6cSdrh 
3030e347d3e8Sdrh   pLeft = pExpr->pLeft;
30317b35a77bSdan   if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3032553168c7Sdan   zAff = exprINAffinity(pParse, pExpr);
3033ba00e30aSdan   nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3034ba00e30aSdan   aiMap = (int*)sqlite3DbMallocZero(
3035ba00e30aSdan       pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3036ba00e30aSdan   );
3037e347d3e8Sdrh   if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
30387b35a77bSdan 
3039ba00e30aSdan   /* Attempt to compute the RHS. After this step, if anything other than
30402c04131cSdrh   ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3041ba00e30aSdan   ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3042ba00e30aSdan   ** the RHS has not yet been coded.  */
3043e3365e6cSdrh   v = pParse->pVdbe;
3044e3365e6cSdrh   assert( v!=0 );       /* OOM detected prior to this routine */
3045e3365e6cSdrh   VdbeNoopComment((v, "begin IN expr"));
3046bb53ecb1Sdrh   eType = sqlite3FindInIndex(pParse, pExpr,
3047bb53ecb1Sdrh                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
30482c04131cSdrh                              destIfFalse==destIfNull ? 0 : &rRhsHasNull,
30492c04131cSdrh                              aiMap, &iTab);
3050e3365e6cSdrh 
3051ba00e30aSdan   assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3052ba00e30aSdan        || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3053ba00e30aSdan   );
3054ecb87ac8Sdrh #ifdef SQLITE_DEBUG
3055ecb87ac8Sdrh   /* Confirm that aiMap[] contains nVector integer values between 0 and
3056ecb87ac8Sdrh   ** nVector-1. */
3057ecb87ac8Sdrh   for(i=0; i<nVector; i++){
3058ecb87ac8Sdrh     int j, cnt;
3059ecb87ac8Sdrh     for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3060ecb87ac8Sdrh     assert( cnt==1 );
3061ecb87ac8Sdrh   }
3062ecb87ac8Sdrh #endif
3063e3365e6cSdrh 
3064ba00e30aSdan   /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3065ba00e30aSdan   ** vector, then it is stored in an array of nVector registers starting
3066ba00e30aSdan   ** at r1.
3067e347d3e8Sdrh   **
3068e347d3e8Sdrh   ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3069e347d3e8Sdrh   ** so that the fields are in the same order as an existing index.   The
3070e347d3e8Sdrh   ** aiMap[] array contains a mapping from the original LHS field order to
3071e347d3e8Sdrh   ** the field order that matches the RHS index.
3072e3365e6cSdrh   */
3073e347d3e8Sdrh   rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3074e347d3e8Sdrh   for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3075ecb87ac8Sdrh   if( i==nVector ){
3076e347d3e8Sdrh     /* LHS fields are not reordered */
3077e347d3e8Sdrh     rLhs = rLhsOrig;
3078ecb87ac8Sdrh   }else{
3079ecb87ac8Sdrh     /* Need to reorder the LHS fields according to aiMap */
3080e347d3e8Sdrh     rLhs = sqlite3GetTempRange(pParse, nVector);
3081ba00e30aSdan     for(i=0; i<nVector; i++){
3082e347d3e8Sdrh       sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3083ba00e30aSdan     }
3084ecb87ac8Sdrh   }
3085e3365e6cSdrh 
3086bb53ecb1Sdrh   /* If sqlite3FindInIndex() did not find or create an index that is
3087bb53ecb1Sdrh   ** suitable for evaluating the IN operator, then evaluate using a
3088bb53ecb1Sdrh   ** sequence of comparisons.
3089e347d3e8Sdrh   **
3090e347d3e8Sdrh   ** This is step (1) in the in-operator.md optimized algorithm.
3091bb53ecb1Sdrh   */
3092bb53ecb1Sdrh   if( eType==IN_INDEX_NOOP ){
3093bb53ecb1Sdrh     ExprList *pList = pExpr->x.pList;
3094bb53ecb1Sdrh     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3095ec4ccdbcSdrh     int labelOk = sqlite3VdbeMakeLabel(pParse);
3096bb53ecb1Sdrh     int r2, regToFree;
3097bb53ecb1Sdrh     int regCkNull = 0;
3098bb53ecb1Sdrh     int ii;
3099bb53ecb1Sdrh     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3100bb53ecb1Sdrh     if( destIfNull!=destIfFalse ){
3101bb53ecb1Sdrh       regCkNull = sqlite3GetTempReg(pParse);
3102e347d3e8Sdrh       sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
3103bb53ecb1Sdrh     }
3104bb53ecb1Sdrh     for(ii=0; ii<pList->nExpr; ii++){
3105bb53ecb1Sdrh       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
3106a976979bSdrh       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
3107bb53ecb1Sdrh         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3108bb53ecb1Sdrh       }
3109bb53ecb1Sdrh       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
3110e347d3e8Sdrh         sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
31114336b0e6Sdrh                           (void*)pColl, P4_COLLSEQ);
31124336b0e6Sdrh         VdbeCoverageIf(v, ii<pList->nExpr-1);
31134336b0e6Sdrh         VdbeCoverageIf(v, ii==pList->nExpr-1);
3114ba00e30aSdan         sqlite3VdbeChangeP5(v, zAff[0]);
3115bb53ecb1Sdrh       }else{
3116bb53ecb1Sdrh         assert( destIfNull==destIfFalse );
3117e347d3e8Sdrh         sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
3118bb53ecb1Sdrh                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
3119ba00e30aSdan         sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
3120bb53ecb1Sdrh       }
3121bb53ecb1Sdrh       sqlite3ReleaseTempReg(pParse, regToFree);
3122bb53ecb1Sdrh     }
3123bb53ecb1Sdrh     if( regCkNull ){
3124bb53ecb1Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
3125076e85f5Sdrh       sqlite3VdbeGoto(v, destIfFalse);
3126bb53ecb1Sdrh     }
3127bb53ecb1Sdrh     sqlite3VdbeResolveLabel(v, labelOk);
3128bb53ecb1Sdrh     sqlite3ReleaseTempReg(pParse, regCkNull);
3129e347d3e8Sdrh     goto sqlite3ExprCodeIN_finished;
3130e347d3e8Sdrh   }
3131bb53ecb1Sdrh 
3132e347d3e8Sdrh   /* Step 2: Check to see if the LHS contains any NULL columns.  If the
3133e347d3e8Sdrh   ** LHS does contain NULLs then the result must be either FALSE or NULL.
3134e347d3e8Sdrh   ** We will then skip the binary search of the RHS.
3135e347d3e8Sdrh   */
3136094430ebSdrh   if( destIfNull==destIfFalse ){
3137e347d3e8Sdrh     destStep2 = destIfFalse;
3138e347d3e8Sdrh   }else{
3139ec4ccdbcSdrh     destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
3140e347d3e8Sdrh   }
3141d49fd4e8Sdan   for(i=0; i<nVector; i++){
3142fc7f27b9Sdrh     Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3143d49fd4e8Sdan     if( sqlite3ExprCanBeNull(p) ){
3144e347d3e8Sdrh       sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
3145471b4b92Sdrh       VdbeCoverage(v);
3146d49fd4e8Sdan     }
3147d49fd4e8Sdan   }
3148e3365e6cSdrh 
3149e347d3e8Sdrh   /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
3150e347d3e8Sdrh   ** of the RHS using the LHS as a probe.  If found, the result is
3151e347d3e8Sdrh   ** true.
3152e347d3e8Sdrh   */
3153e3365e6cSdrh   if( eType==IN_INDEX_ROWID ){
3154e347d3e8Sdrh     /* In this case, the RHS is the ROWID of table b-tree and so we also
3155e347d3e8Sdrh     ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
3156e347d3e8Sdrh     ** into a single opcode. */
31572c04131cSdrh     sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
3158688852abSdrh     VdbeCoverage(v);
3159e347d3e8Sdrh     addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
31607b35a77bSdan   }else{
3161e347d3e8Sdrh     sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3162e347d3e8Sdrh     if( destIfFalse==destIfNull ){
3163e347d3e8Sdrh       /* Combine Step 3 and Step 5 into a single opcode */
31642c04131cSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
3165e347d3e8Sdrh                            rLhs, nVector); VdbeCoverage(v);
3166e347d3e8Sdrh       goto sqlite3ExprCodeIN_finished;
3167e347d3e8Sdrh     }
3168e347d3e8Sdrh     /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
31692c04131cSdrh     addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
3170e347d3e8Sdrh                                       rLhs, nVector); VdbeCoverage(v);
3171e347d3e8Sdrh   }
3172ba00e30aSdan 
3173e347d3e8Sdrh   /* Step 4.  If the RHS is known to be non-NULL and we did not find
3174e347d3e8Sdrh   ** an match on the search above, then the result must be FALSE.
3175e347d3e8Sdrh   */
3176e347d3e8Sdrh   if( rRhsHasNull && nVector==1 ){
3177e347d3e8Sdrh     sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3178471b4b92Sdrh     VdbeCoverage(v);
3179e347d3e8Sdrh   }
31807b35a77bSdan 
3181e347d3e8Sdrh   /* Step 5.  If we do not care about the difference between NULL and
3182e347d3e8Sdrh   ** FALSE, then just return false.
3183e347d3e8Sdrh   */
3184e347d3e8Sdrh   if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3185e347d3e8Sdrh 
3186e347d3e8Sdrh   /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
3187e347d3e8Sdrh   ** If any comparison is NULL, then the result is NULL.  If all
3188e347d3e8Sdrh   ** comparisons are FALSE then the final result is FALSE.
3189e347d3e8Sdrh   **
3190e347d3e8Sdrh   ** For a scalar LHS, it is sufficient to check just the first row
3191e347d3e8Sdrh   ** of the RHS.
3192e347d3e8Sdrh   */
3193e347d3e8Sdrh   if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
31942c04131cSdrh   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
3195471b4b92Sdrh   VdbeCoverage(v);
3196e347d3e8Sdrh   if( nVector>1 ){
3197ec4ccdbcSdrh     destNotNull = sqlite3VdbeMakeLabel(pParse);
3198e347d3e8Sdrh   }else{
3199e347d3e8Sdrh     /* For nVector==1, combine steps 6 and 7 by immediately returning
3200e347d3e8Sdrh     ** FALSE if the first comparison is not NULL */
3201e347d3e8Sdrh     destNotNull = destIfFalse;
3202e347d3e8Sdrh   }
3203ba00e30aSdan   for(i=0; i<nVector; i++){
3204ba00e30aSdan     Expr *p;
3205ba00e30aSdan     CollSeq *pColl;
3206e347d3e8Sdrh     int r3 = sqlite3GetTempReg(pParse);
3207fc7f27b9Sdrh     p = sqlite3VectorFieldSubexpr(pLeft, i);
3208ba00e30aSdan     pColl = sqlite3ExprCollSeq(pParse, p);
32092c04131cSdrh     sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
3210e347d3e8Sdrh     sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
321118016ad2Sdrh                       (void*)pColl, P4_COLLSEQ);
3212471b4b92Sdrh     VdbeCoverage(v);
3213e347d3e8Sdrh     sqlite3ReleaseTempReg(pParse, r3);
32147b35a77bSdan   }
32157b35a77bSdan   sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3216e347d3e8Sdrh   if( nVector>1 ){
3217e347d3e8Sdrh     sqlite3VdbeResolveLabel(v, destNotNull);
32182c04131cSdrh     sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
321918016ad2Sdrh     VdbeCoverage(v);
3220e347d3e8Sdrh 
3221e347d3e8Sdrh     /* Step 7:  If we reach this point, we know that the result must
3222e347d3e8Sdrh     ** be false. */
322318016ad2Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
32247b35a77bSdan   }
32257b35a77bSdan 
3226e347d3e8Sdrh   /* Jumps here in order to return true. */
3227e347d3e8Sdrh   sqlite3VdbeJumpHere(v, addrTruthOp);
3228e3365e6cSdrh 
3229e347d3e8Sdrh sqlite3ExprCodeIN_finished:
3230e347d3e8Sdrh   if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
3231ecb87ac8Sdrh   VdbeComment((v, "end IN expr"));
3232e347d3e8Sdrh sqlite3ExprCodeIN_oom_error:
3233ba00e30aSdan   sqlite3DbFree(pParse->db, aiMap);
3234553168c7Sdan   sqlite3DbFree(pParse->db, zAff);
3235e3365e6cSdrh }
3236e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
3237e3365e6cSdrh 
323813573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
3239598f1340Sdrh /*
3240598f1340Sdrh ** Generate an instruction that will put the floating point
32419cbf3425Sdrh ** value described by z[0..n-1] into register iMem.
32420cf19ed8Sdrh **
32430cf19ed8Sdrh ** The z[] string will probably not be zero-terminated.  But the
32440cf19ed8Sdrh ** z[n] character is guaranteed to be something that does not look
32450cf19ed8Sdrh ** like the continuation of the number.
3246598f1340Sdrh */
3247b7916a78Sdrh static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
3248fd773cf9Sdrh   if( ALWAYS(z!=0) ){
3249598f1340Sdrh     double value;
32509339da1fSdrh     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
3251d0015161Sdrh     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3252598f1340Sdrh     if( negateFlag ) value = -value;
325397bae794Sdrh     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
3254598f1340Sdrh   }
3255598f1340Sdrh }
325613573c71Sdrh #endif
3257598f1340Sdrh 
3258598f1340Sdrh 
3259598f1340Sdrh /*
3260fec19aadSdrh ** Generate an instruction that will put the integer describe by
32619cbf3425Sdrh ** text z[0..n-1] into register iMem.
32620cf19ed8Sdrh **
32635f1d6b61Sshaneh ** Expr.u.zToken is always UTF8 and zero-terminated.
3264fec19aadSdrh */
326513573c71Sdrh static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
326613573c71Sdrh   Vdbe *v = pParse->pVdbe;
326792b01d53Sdrh   if( pExpr->flags & EP_IntValue ){
326833e619fcSdrh     int i = pExpr->u.iValue;
3269d50ffc41Sdrh     assert( i>=0 );
327092b01d53Sdrh     if( negFlag ) i = -i;
327192b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3272fd773cf9Sdrh   }else{
32735f1d6b61Sshaneh     int c;
32745f1d6b61Sshaneh     i64 value;
3275fd773cf9Sdrh     const char *z = pExpr->u.zToken;
3276fd773cf9Sdrh     assert( z!=0 );
32779296c18aSdrh     c = sqlite3DecOrHexToI64(z, &value);
327884d4f1a3Sdrh     if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
327913573c71Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
328013573c71Sdrh       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
328113573c71Sdrh #else
32821b7ddc59Sdrh #ifndef SQLITE_OMIT_HEX_INTEGER
32839296c18aSdrh       if( sqlite3_strnicmp(z,"0x",2)==0 ){
328477320ea4Sdrh         sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
32851b7ddc59Sdrh       }else
32861b7ddc59Sdrh #endif
32871b7ddc59Sdrh       {
3288b7916a78Sdrh         codeReal(v, z, negFlag, iMem);
32899296c18aSdrh       }
329013573c71Sdrh #endif
329177320ea4Sdrh     }else{
329284d4f1a3Sdrh       if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
329377320ea4Sdrh       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3294fec19aadSdrh     }
3295fec19aadSdrh   }
3296c9cf901dSdanielk1977 }
3297fec19aadSdrh 
32985cd79239Sdrh 
32991f9ca2c8Sdrh /* Generate code that will load into register regOut a value that is
33001f9ca2c8Sdrh ** appropriate for the iIdxCol-th column of index pIdx.
33011f9ca2c8Sdrh */
33021f9ca2c8Sdrh void sqlite3ExprCodeLoadIndexColumn(
33031f9ca2c8Sdrh   Parse *pParse,  /* The parsing context */
33041f9ca2c8Sdrh   Index *pIdx,    /* The index whose column is to be loaded */
33051f9ca2c8Sdrh   int iTabCur,    /* Cursor pointing to a table row */
33061f9ca2c8Sdrh   int iIdxCol,    /* The column of the index to be loaded */
33071f9ca2c8Sdrh   int regOut      /* Store the index column value in this register */
33081f9ca2c8Sdrh ){
33091f9ca2c8Sdrh   i16 iTabCol = pIdx->aiColumn[iIdxCol];
33104b92f98cSdrh   if( iTabCol==XN_EXPR ){
33111f9ca2c8Sdrh     assert( pIdx->aColExpr );
33121f9ca2c8Sdrh     assert( pIdx->aColExpr->nExpr>iIdxCol );
33133e34eabcSdrh     pParse->iSelfTab = iTabCur + 1;
33141c75c9d7Sdrh     sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
33153e34eabcSdrh     pParse->iSelfTab = 0;
33164b92f98cSdrh   }else{
33174b92f98cSdrh     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
33184b92f98cSdrh                                     iTabCol, regOut);
33194b92f98cSdrh   }
33201f9ca2c8Sdrh }
33211f9ca2c8Sdrh 
33225cd79239Sdrh /*
33235c092e8aSdrh ** Generate code to extract the value of the iCol-th column of a table.
33245c092e8aSdrh */
33255c092e8aSdrh void sqlite3ExprCodeGetColumnOfTable(
33265c092e8aSdrh   Vdbe *v,        /* The VDBE under construction */
33275c092e8aSdrh   Table *pTab,    /* The table containing the value */
3328313619f5Sdrh   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
33295c092e8aSdrh   int iCol,       /* Index of the column to extract */
3330313619f5Sdrh   int regOut      /* Extract the value into this register */
33315c092e8aSdrh ){
3332aca19e19Sdrh   if( pTab==0 ){
3333aca19e19Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
3334aca19e19Sdrh     return;
3335aca19e19Sdrh   }
33365c092e8aSdrh   if( iCol<0 || iCol==pTab->iPKey ){
33375c092e8aSdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
33385c092e8aSdrh   }else{
33395c092e8aSdrh     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
3340ee0ec8e1Sdrh     int x = iCol;
334135db31b2Sdrh     if( !HasRowid(pTab) && !IsVirtual(pTab) ){
3342ee0ec8e1Sdrh       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3343ee0ec8e1Sdrh     }
3344ee0ec8e1Sdrh     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
33455c092e8aSdrh   }
33465c092e8aSdrh   if( iCol>=0 ){
33475c092e8aSdrh     sqlite3ColumnDefault(v, pTab, iCol, regOut);
33485c092e8aSdrh   }
33495c092e8aSdrh }
33505c092e8aSdrh 
33515c092e8aSdrh /*
3352945498f3Sdrh ** Generate code that will extract the iColumn-th column from
33538c607191Sdrh ** table pTab and store the column value in register iReg.
3354e55cbd72Sdrh **
3355e55cbd72Sdrh ** There must be an open cursor to pTab in iTable when this routine
3356e55cbd72Sdrh ** is called.  If iColumn<0 then code is generated that extracts the rowid.
3357945498f3Sdrh */
3358e55cbd72Sdrh int sqlite3ExprCodeGetColumn(
3359e55cbd72Sdrh   Parse *pParse,   /* Parsing and code generating context */
33602133d822Sdrh   Table *pTab,     /* Description of the table we are reading from */
33612133d822Sdrh   int iColumn,     /* Index of the table column */
33622133d822Sdrh   int iTable,      /* The cursor pointing to the table */
3363a748fdccSdrh   int iReg,        /* Store results here */
3364ce78bc6eSdrh   u8 p5            /* P5 value for OP_Column + FLAGS */
33652133d822Sdrh ){
3366e55cbd72Sdrh   Vdbe *v = pParse->pVdbe;
3367e55cbd72Sdrh   assert( v!=0 );
33685c092e8aSdrh   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
3369a748fdccSdrh   if( p5 ){
3370a748fdccSdrh     sqlite3VdbeChangeP5(v, p5);
3371a748fdccSdrh   }
3372e55cbd72Sdrh   return iReg;
3373e55cbd72Sdrh }
3374e55cbd72Sdrh 
3375e55cbd72Sdrh /*
3376b21e7c70Sdrh ** Generate code to move content from registers iFrom...iFrom+nReg-1
337736a5d88dSdrh ** over to iTo..iTo+nReg-1.
3378e55cbd72Sdrh */
3379b21e7c70Sdrh void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
3380e8e4af76Sdrh   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
3381079a3072Sdrh   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
3382945498f3Sdrh }
3383945498f3Sdrh 
3384652fbf55Sdrh /*
338512abf408Sdrh ** Convert a scalar expression node to a TK_REGISTER referencing
338612abf408Sdrh ** register iReg.  The caller must ensure that iReg already contains
338712abf408Sdrh ** the correct value for the expression.
3388a4c3c87eSdrh */
3389a4c3c87eSdrh static void exprToRegister(Expr *p, int iReg){
3390a4c3c87eSdrh   p->op2 = p->op;
3391a4c3c87eSdrh   p->op = TK_REGISTER;
3392a4c3c87eSdrh   p->iTable = iReg;
3393a4c3c87eSdrh   ExprClearProperty(p, EP_Skip);
3394a4c3c87eSdrh }
3395a4c3c87eSdrh 
339612abf408Sdrh /*
339712abf408Sdrh ** Evaluate an expression (either a vector or a scalar expression) and store
339812abf408Sdrh ** the result in continguous temporary registers.  Return the index of
339912abf408Sdrh ** the first register used to store the result.
340012abf408Sdrh **
340112abf408Sdrh ** If the returned result register is a temporary scalar, then also write
340212abf408Sdrh ** that register number into *piFreeable.  If the returned result register
340312abf408Sdrh ** is not a temporary or if the expression is a vector set *piFreeable
340412abf408Sdrh ** to 0.
340512abf408Sdrh */
340612abf408Sdrh static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
340712abf408Sdrh   int iResult;
340812abf408Sdrh   int nResult = sqlite3ExprVectorSize(p);
340912abf408Sdrh   if( nResult==1 ){
341012abf408Sdrh     iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
341112abf408Sdrh   }else{
341212abf408Sdrh     *piFreeable = 0;
341312abf408Sdrh     if( p->op==TK_SELECT ){
3414dd1bb43aSdrh #if SQLITE_OMIT_SUBQUERY
3415dd1bb43aSdrh       iResult = 0;
3416dd1bb43aSdrh #else
341785bcdce2Sdrh       iResult = sqlite3CodeSubselect(pParse, p);
3418dd1bb43aSdrh #endif
341912abf408Sdrh     }else{
342012abf408Sdrh       int i;
342112abf408Sdrh       iResult = pParse->nMem+1;
342212abf408Sdrh       pParse->nMem += nResult;
342312abf408Sdrh       for(i=0; i<nResult; i++){
34244b725240Sdan         sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
342512abf408Sdrh       }
342612abf408Sdrh     }
342712abf408Sdrh   }
342812abf408Sdrh   return iResult;
342912abf408Sdrh }
343012abf408Sdrh 
343171c57db0Sdan 
3432a4c3c87eSdrh /*
3433cce7d176Sdrh ** Generate code into the current Vdbe to evaluate the given
34342dcef11bSdrh ** expression.  Attempt to store the results in register "target".
34352dcef11bSdrh ** Return the register where results are stored.
3436389a1adbSdrh **
34378b213899Sdrh ** With this routine, there is no guarantee that results will
34382dcef11bSdrh ** be stored in target.  The result might be stored in some other
34392dcef11bSdrh ** register if it is convenient to do so.  The calling function
34402dcef11bSdrh ** must check the return code and move the results to the desired
34412dcef11bSdrh ** register.
3442cce7d176Sdrh */
3443678ccce8Sdrh int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
34442dcef11bSdrh   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
34452dcef11bSdrh   int op;                   /* The opcode being coded */
34462dcef11bSdrh   int inReg = target;       /* Results stored in register inReg */
34472dcef11bSdrh   int regFree1 = 0;         /* If non-zero free this temporary register */
34482dcef11bSdrh   int regFree2 = 0;         /* If non-zero free this temporary register */
34497b35a77bSdan   int r1, r2;               /* Various register numbers */
345010d1edf0Sdrh   Expr tempX;               /* Temporary expression node */
345171c57db0Sdan   int p5 = 0;
3452ffe07b2dSdrh 
34539cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
345420411ea7Sdrh   if( v==0 ){
345520411ea7Sdrh     assert( pParse->db->mallocFailed );
345620411ea7Sdrh     return 0;
345720411ea7Sdrh   }
3458389a1adbSdrh 
34591efa8023Sdrh expr_code_doover:
3460389a1adbSdrh   if( pExpr==0 ){
3461389a1adbSdrh     op = TK_NULL;
3462389a1adbSdrh   }else{
3463f2bc013cSdrh     op = pExpr->op;
3464389a1adbSdrh   }
3465f2bc013cSdrh   switch( op ){
346613449892Sdrh     case TK_AGG_COLUMN: {
346713449892Sdrh       AggInfo *pAggInfo = pExpr->pAggInfo;
346813449892Sdrh       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
346913449892Sdrh       if( !pAggInfo->directMode ){
34709de221dfSdrh         assert( pCol->iMem>0 );
3471c332cc30Sdrh         return pCol->iMem;
347213449892Sdrh       }else if( pAggInfo->useSortingIdx ){
34735134d135Sdan         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
3474389a1adbSdrh                               pCol->iSorterColumn, target);
3475c332cc30Sdrh         return target;
347613449892Sdrh       }
347713449892Sdrh       /* Otherwise, fall thru into the TK_COLUMN case */
347813449892Sdrh     }
3479967e8b73Sdrh     case TK_COLUMN: {
3480b2b9d3d7Sdrh       int iTab = pExpr->iTable;
3481efad2e23Sdrh       if( ExprHasProperty(pExpr, EP_FixedCol) ){
3482d98f5324Sdrh         /* This COLUMN expression is really a constant due to WHERE clause
3483d98f5324Sdrh         ** constraints, and that constant is coded by the pExpr->pLeft
3484d98f5324Sdrh         ** expresssion.  However, make sure the constant has the correct
3485d98f5324Sdrh         ** datatype by applying the Affinity of the table column to the
3486d98f5324Sdrh         ** constant.
3487d98f5324Sdrh         */
3488d98f5324Sdrh         int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
3489eda079cdSdrh         int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
3490d98f5324Sdrh         if( aff!=SQLITE_AFF_BLOB ){
3491d98f5324Sdrh           static const char zAff[] = "B\000C\000D\000E";
3492d98f5324Sdrh           assert( SQLITE_AFF_BLOB=='A' );
3493d98f5324Sdrh           assert( SQLITE_AFF_TEXT=='B' );
3494d98f5324Sdrh           if( iReg!=target ){
3495d98f5324Sdrh             sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
3496d98f5324Sdrh             iReg = target;
3497d98f5324Sdrh           }
3498d98f5324Sdrh           sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
3499d98f5324Sdrh                             &zAff[(aff-'B')*2], P4_STATIC);
3500d98f5324Sdrh         }
3501d98f5324Sdrh         return iReg;
3502efad2e23Sdrh       }
3503b2b9d3d7Sdrh       if( iTab<0 ){
35046e97f8ecSdrh         if( pParse->iSelfTab<0 ){
3505b2b9d3d7Sdrh           /* Generating CHECK constraints or inserting into partial index */
35066e97f8ecSdrh           return pExpr->iColumn - pParse->iSelfTab;
3507c4a3c779Sdrh         }else{
35081f9ca2c8Sdrh           /* Coding an expression that is part of an index where column names
35091f9ca2c8Sdrh           ** in the index refer to the table to which the index belongs */
35103e34eabcSdrh           iTab = pParse->iSelfTab - 1;
35112282792aSdrh         }
3512b2b9d3d7Sdrh       }
3513eda079cdSdrh       return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
3514b2b9d3d7Sdrh                                pExpr->iColumn, iTab, target,
3515b2b9d3d7Sdrh                                pExpr->op2);
3516cce7d176Sdrh     }
3517cce7d176Sdrh     case TK_INTEGER: {
351813573c71Sdrh       codeInteger(pParse, pExpr, 0, target);
3519c332cc30Sdrh       return target;
352051e9a445Sdrh     }
35218abed7b9Sdrh     case TK_TRUEFALSE: {
352296acafbeSdrh       sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
3523007c843bSdrh       return target;
3524007c843bSdrh     }
352513573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
3526598f1340Sdrh     case TK_FLOAT: {
352733e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
352833e619fcSdrh       codeReal(v, pExpr->u.zToken, 0, target);
3529c332cc30Sdrh       return target;
3530598f1340Sdrh     }
353113573c71Sdrh #endif
3532fec19aadSdrh     case TK_STRING: {
353333e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3534076e85f5Sdrh       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
3535c332cc30Sdrh       return target;
3536cce7d176Sdrh     }
3537f0863fe5Sdrh     case TK_NULL: {
35389de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3539c332cc30Sdrh       return target;
3540f0863fe5Sdrh     }
35415338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
3542c572ef7fSdanielk1977     case TK_BLOB: {
35436c8c6cecSdrh       int n;
35446c8c6cecSdrh       const char *z;
3545ca48c90fSdrh       char *zBlob;
354633e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
354733e619fcSdrh       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
354833e619fcSdrh       assert( pExpr->u.zToken[1]=='\'' );
354933e619fcSdrh       z = &pExpr->u.zToken[2];
3550b7916a78Sdrh       n = sqlite3Strlen30(z) - 1;
3551b7916a78Sdrh       assert( z[n]=='\'' );
3552ca48c90fSdrh       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3553ca48c90fSdrh       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
3554c332cc30Sdrh       return target;
3555c572ef7fSdanielk1977     }
35565338a5f7Sdanielk1977 #endif
355750457896Sdrh     case TK_VARIABLE: {
355833e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
355933e619fcSdrh       assert( pExpr->u.zToken!=0 );
356033e619fcSdrh       assert( pExpr->u.zToken[0]!=0 );
3561eaf52d88Sdrh       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
356233e619fcSdrh       if( pExpr->u.zToken[1]!=0 ){
35639bf755ccSdrh         const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
35649bf755ccSdrh         assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
3565ce1bbe51Sdrh         pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
35669bf755ccSdrh         sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
35679bf755ccSdrh       }
3568c332cc30Sdrh       return target;
356950457896Sdrh     }
35704e0cff60Sdrh     case TK_REGISTER: {
3571c332cc30Sdrh       return pExpr->iTable;
35724e0cff60Sdrh     }
3573487e262fSdrh #ifndef SQLITE_OMIT_CAST
3574487e262fSdrh     case TK_CAST: {
3575487e262fSdrh       /* Expressions of the form:   CAST(pLeft AS token) */
35762dcef11bSdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
35771735fa88Sdrh       if( inReg!=target ){
35781735fa88Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
35791735fa88Sdrh         inReg = target;
35801735fa88Sdrh       }
35814169e430Sdrh       sqlite3VdbeAddOp2(v, OP_Cast, target,
35824169e430Sdrh                         sqlite3AffinityType(pExpr->u.zToken, 0));
3583c332cc30Sdrh       return inReg;
3584487e262fSdrh     }
3585487e262fSdrh #endif /* SQLITE_OMIT_CAST */
358671c57db0Sdan     case TK_IS:
358771c57db0Sdan     case TK_ISNOT:
358871c57db0Sdan       op = (op==TK_IS) ? TK_EQ : TK_NE;
358971c57db0Sdan       p5 = SQLITE_NULLEQ;
359071c57db0Sdan       /* fall-through */
3591c9b84a1fSdrh     case TK_LT:
3592c9b84a1fSdrh     case TK_LE:
3593c9b84a1fSdrh     case TK_GT:
3594c9b84a1fSdrh     case TK_GE:
3595c9b84a1fSdrh     case TK_NE:
3596c9b84a1fSdrh     case TK_EQ: {
359771c57db0Sdan       Expr *pLeft = pExpr->pLeft;
3598625015e0Sdan       if( sqlite3ExprIsVector(pLeft) ){
359979752b6eSdrh         codeVectorCompare(pParse, pExpr, target, op, p5);
360071c57db0Sdan       }else{
360171c57db0Sdan         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3602b6da74ebSdrh         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
360371c57db0Sdan         codeCompare(pParse, pLeft, pExpr->pRight, op,
360471c57db0Sdan             r1, r2, inReg, SQLITE_STOREP2 | p5);
36057d176105Sdrh         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
36067d176105Sdrh         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
36077d176105Sdrh         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
36087d176105Sdrh         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
36097d176105Sdrh         assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
36107d176105Sdrh         assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3611c5499befSdrh         testcase( regFree1==0 );
3612c5499befSdrh         testcase( regFree2==0 );
3613c9b84a1fSdrh       }
36146a2fe093Sdrh       break;
36156a2fe093Sdrh     }
3616cce7d176Sdrh     case TK_AND:
3617cce7d176Sdrh     case TK_OR:
3618cce7d176Sdrh     case TK_PLUS:
3619cce7d176Sdrh     case TK_STAR:
3620cce7d176Sdrh     case TK_MINUS:
3621bf4133cbSdrh     case TK_REM:
3622bf4133cbSdrh     case TK_BITAND:
3623bf4133cbSdrh     case TK_BITOR:
362417c40294Sdrh     case TK_SLASH:
3625bf4133cbSdrh     case TK_LSHIFT:
3626855eb1cfSdrh     case TK_RSHIFT:
36270040077dSdrh     case TK_CONCAT: {
36287d176105Sdrh       assert( TK_AND==OP_And );            testcase( op==TK_AND );
36297d176105Sdrh       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
36307d176105Sdrh       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
36317d176105Sdrh       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
36327d176105Sdrh       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
36337d176105Sdrh       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
36347d176105Sdrh       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
36357d176105Sdrh       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
36367d176105Sdrh       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
36377d176105Sdrh       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
36387d176105Sdrh       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
36392dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
36402dcef11bSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
36415b6afba9Sdrh       sqlite3VdbeAddOp3(v, op, r2, r1, target);
3642c5499befSdrh       testcase( regFree1==0 );
3643c5499befSdrh       testcase( regFree2==0 );
36440040077dSdrh       break;
36450040077dSdrh     }
3646cce7d176Sdrh     case TK_UMINUS: {
3647fec19aadSdrh       Expr *pLeft = pExpr->pLeft;
3648fec19aadSdrh       assert( pLeft );
364913573c71Sdrh       if( pLeft->op==TK_INTEGER ){
365013573c71Sdrh         codeInteger(pParse, pLeft, 1, target);
3651c332cc30Sdrh         return target;
365213573c71Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
365313573c71Sdrh       }else if( pLeft->op==TK_FLOAT ){
365433e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
365533e619fcSdrh         codeReal(v, pLeft->u.zToken, 1, target);
3656c332cc30Sdrh         return target;
365713573c71Sdrh #endif
36583c84ddffSdrh       }else{
365910d1edf0Sdrh         tempX.op = TK_INTEGER;
366010d1edf0Sdrh         tempX.flags = EP_IntValue|EP_TokenOnly;
366110d1edf0Sdrh         tempX.u.iValue = 0;
366210d1edf0Sdrh         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
3663e55cbd72Sdrh         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
36642dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
3665c5499befSdrh         testcase( regFree2==0 );
36663c84ddffSdrh       }
36676e142f54Sdrh       break;
36686e142f54Sdrh     }
3669bf4133cbSdrh     case TK_BITNOT:
36706e142f54Sdrh     case TK_NOT: {
36717d176105Sdrh       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
36727d176105Sdrh       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
3673e99fa2afSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3674e99fa2afSdrh       testcase( regFree1==0 );
3675e99fa2afSdrh       sqlite3VdbeAddOp2(v, op, r1, inReg);
3676cce7d176Sdrh       break;
3677cce7d176Sdrh     }
36788abed7b9Sdrh     case TK_TRUTH: {
367996acafbeSdrh       int isTrue;    /* IS TRUE or IS NOT TRUE */
368096acafbeSdrh       int bNormal;   /* IS TRUE or IS FALSE */
3681007c843bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3682007c843bSdrh       testcase( regFree1==0 );
368396acafbeSdrh       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
368496acafbeSdrh       bNormal = pExpr->op2==TK_IS;
368596acafbeSdrh       testcase( isTrue && bNormal);
368696acafbeSdrh       testcase( !isTrue && bNormal);
368796acafbeSdrh       sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
3688007c843bSdrh       break;
3689007c843bSdrh     }
3690cce7d176Sdrh     case TK_ISNULL:
3691cce7d176Sdrh     case TK_NOTNULL: {
36926a288a33Sdrh       int addr;
36937d176105Sdrh       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
36947d176105Sdrh       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
36959de221dfSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
36962dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3697c5499befSdrh       testcase( regFree1==0 );
36982dcef11bSdrh       addr = sqlite3VdbeAddOp1(v, op, r1);
36997d176105Sdrh       VdbeCoverageIf(v, op==TK_ISNULL);
37007d176105Sdrh       VdbeCoverageIf(v, op==TK_NOTNULL);
3701a976979bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
37026a288a33Sdrh       sqlite3VdbeJumpHere(v, addr);
3703a37cdde0Sdanielk1977       break;
3704f2bc013cSdrh     }
37052282792aSdrh     case TK_AGG_FUNCTION: {
370613449892Sdrh       AggInfo *pInfo = pExpr->pAggInfo;
37077e56e711Sdrh       if( pInfo==0 ){
370833e619fcSdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
370933e619fcSdrh         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
37107e56e711Sdrh       }else{
3711c332cc30Sdrh         return pInfo->aFunc[pExpr->iAgg].iMem;
37127e56e711Sdrh       }
37132282792aSdrh       break;
37142282792aSdrh     }
3715cce7d176Sdrh     case TK_FUNCTION: {
371612ffee8cSdrh       ExprList *pFarg;       /* List of function arguments */
371712ffee8cSdrh       int nFarg;             /* Number of function arguments */
371812ffee8cSdrh       FuncDef *pDef;         /* The function definition object */
371912ffee8cSdrh       const char *zId;       /* The function name */
3720693e6719Sdrh       u32 constMask = 0;     /* Mask of function arguments that are constant */
372112ffee8cSdrh       int i;                 /* Loop counter */
3722c332cc30Sdrh       sqlite3 *db = pParse->db;  /* The database connection */
372312ffee8cSdrh       u8 enc = ENC(db);      /* The text encoding used by this database */
372412ffee8cSdrh       CollSeq *pColl = 0;    /* A collating sequence */
372517435752Sdrh 
372667a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
3727eda079cdSdrh       if( ExprHasProperty(pExpr, EP_WinFunc) ){
3728eda079cdSdrh         return pExpr->y.pWin->regResult;
372986fb6e17Sdan       }
373067a9b8edSdan #endif
373186fb6e17Sdan 
37321e9b53f9Sdrh       if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
373349c5ab24Sdrh         /* SQL functions can be expensive. So try to move constant functions
3734ad879ffdSdrh         ** out of the inner loop, even if that means an extra OP_Copy. */
3735ad879ffdSdrh         return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
37361e9b53f9Sdrh       }
37376ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3738c5cd1249Sdrh       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
373912ffee8cSdrh         pFarg = 0;
374012ffee8cSdrh       }else{
374112ffee8cSdrh         pFarg = pExpr->x.pList;
374212ffee8cSdrh       }
374312ffee8cSdrh       nFarg = pFarg ? pFarg->nExpr : 0;
374433e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
374533e619fcSdrh       zId = pExpr->u.zToken;
374680738d9cSdrh       pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
3747cc15313cSdrh #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3748cc15313cSdrh       if( pDef==0 && pParse->explain ){
3749cc15313cSdrh         pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3750cc15313cSdrh       }
3751cc15313cSdrh #endif
3752b6e9f7a4Sdan       if( pDef==0 || pDef->xFinalize!=0 ){
375380738d9cSdrh         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
3754feb306f5Sdrh         break;
3755feb306f5Sdrh       }
3756ae6bb957Sdrh 
3757ae6bb957Sdrh       /* Attempt a direct implementation of the built-in COALESCE() and
375860ec914cSpeter.d.reid       ** IFNULL() functions.  This avoids unnecessary evaluation of
3759ae6bb957Sdrh       ** arguments past the first non-NULL argument.
3760ae6bb957Sdrh       */
3761d36e1041Sdrh       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
3762ec4ccdbcSdrh         int endCoalesce = sqlite3VdbeMakeLabel(pParse);
3763ae6bb957Sdrh         assert( nFarg>=2 );
3764ae6bb957Sdrh         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3765ae6bb957Sdrh         for(i=1; i<nFarg; i++){
3766ae6bb957Sdrh           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
3767688852abSdrh           VdbeCoverage(v);
3768ae6bb957Sdrh           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
3769ae6bb957Sdrh         }
3770ae6bb957Sdrh         sqlite3VdbeResolveLabel(v, endCoalesce);
3771ae6bb957Sdrh         break;
3772ae6bb957Sdrh       }
3773ae6bb957Sdrh 
3774cca9f3d2Sdrh       /* The UNLIKELY() function is a no-op.  The result is the value
3775cca9f3d2Sdrh       ** of the first argument.
3776cca9f3d2Sdrh       */
3777cca9f3d2Sdrh       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3778cca9f3d2Sdrh         assert( nFarg>=1 );
3779c332cc30Sdrh         return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
3780cca9f3d2Sdrh       }
3781ae6bb957Sdrh 
378254240751Sdrh #ifdef SQLITE_DEBUG
3783a1a523a5Sdrh       /* The AFFINITY() function evaluates to a string that describes
3784a1a523a5Sdrh       ** the type affinity of the argument.  This is used for testing of
3785a1a523a5Sdrh       ** the SQLite type logic.
3786a1a523a5Sdrh       */
3787a1a523a5Sdrh       if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
3788a1a523a5Sdrh         const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
3789a1a523a5Sdrh         char aff;
3790a1a523a5Sdrh         assert( nFarg==1 );
3791a1a523a5Sdrh         aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
3792a1a523a5Sdrh         sqlite3VdbeLoadString(v, target,
3793a1a523a5Sdrh                               aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
3794a1a523a5Sdrh         return target;
3795a1a523a5Sdrh       }
379654240751Sdrh #endif
3797a1a523a5Sdrh 
3798d1a01edaSdrh       for(i=0; i<nFarg; i++){
3799d1a01edaSdrh         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
3800693e6719Sdrh           testcase( i==31 );
3801693e6719Sdrh           constMask |= MASKBIT32(i);
3802d1a01edaSdrh         }
3803d1a01edaSdrh         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3804d1a01edaSdrh           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3805d1a01edaSdrh         }
3806d1a01edaSdrh       }
380712ffee8cSdrh       if( pFarg ){
3808d1a01edaSdrh         if( constMask ){
3809d1a01edaSdrh           r1 = pParse->nMem+1;
3810d1a01edaSdrh           pParse->nMem += nFarg;
3811d1a01edaSdrh         }else{
381212ffee8cSdrh           r1 = sqlite3GetTempRange(pParse, nFarg);
3813d1a01edaSdrh         }
3814a748fdccSdrh 
3815a748fdccSdrh         /* For length() and typeof() functions with a column argument,
3816a748fdccSdrh         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3817a748fdccSdrh         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3818a748fdccSdrh         ** loading.
3819a748fdccSdrh         */
3820d36e1041Sdrh         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
38214e245a4cSdrh           u8 exprOp;
3822a748fdccSdrh           assert( nFarg==1 );
3823a748fdccSdrh           assert( pFarg->a[0].pExpr!=0 );
38244e245a4cSdrh           exprOp = pFarg->a[0].pExpr->op;
38254e245a4cSdrh           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
3826a748fdccSdrh             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3827a748fdccSdrh             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
3828b1fba286Sdrh             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3829b1fba286Sdrh             pFarg->a[0].pExpr->op2 =
3830b1fba286Sdrh                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
3831a748fdccSdrh           }
3832a748fdccSdrh         }
3833a748fdccSdrh 
38345579d59fSdrh         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
3835d1a01edaSdrh                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
3836892d3179Sdrh       }else{
383712ffee8cSdrh         r1 = 0;
3838892d3179Sdrh       }
3839b7f6f68fSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
3840a43fa227Sdrh       /* Possibly overload the function if the first argument is
3841a43fa227Sdrh       ** a virtual table column.
3842a43fa227Sdrh       **
3843a43fa227Sdrh       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3844a43fa227Sdrh       ** second argument, not the first, as the argument to test to
3845a43fa227Sdrh       ** see if it is a column in a virtual table.  This is done because
3846a43fa227Sdrh       ** the left operand of infix functions (the operand we want to
3847a43fa227Sdrh       ** control overloading) ends up as the second argument to the
3848a43fa227Sdrh       ** function.  The expression "A glob B" is equivalent to
3849a43fa227Sdrh       ** "glob(B,A).  We want to use the A in "A glob B" to test
3850a43fa227Sdrh       ** for function overloading.  But we use the B term in "glob(B,A)".
3851a43fa227Sdrh       */
385259155065Sdrh       if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
385312ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
385412ffee8cSdrh       }else if( nFarg>0 ){
385512ffee8cSdrh         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
3856b7f6f68fSdrh       }
3857b7f6f68fSdrh #endif
3858d36e1041Sdrh       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
38598b213899Sdrh         if( !pColl ) pColl = db->pDfltColl;
386066a5167bSdrh         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
3861682f68b0Sdanielk1977       }
3862092457b1Sdrh #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
3863092457b1Sdrh       if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
38642fc865c1Sdrh         Expr *pArg = pFarg->a[0].pExpr;
38652fc865c1Sdrh         if( pArg->op==TK_COLUMN ){
3866092457b1Sdrh           sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
38672fc865c1Sdrh         }else{
38682fc865c1Sdrh           sqlite3VdbeAddOp2(v, OP_Null, 0, target);
38692fc865c1Sdrh         }
3870092457b1Sdrh       }else
3871092457b1Sdrh #endif
3872092457b1Sdrh       {
38733e34eabcSdrh         sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
38743e34eabcSdrh                           constMask, r1, target, (char*)pDef, P4_FUNCDEF);
387512ffee8cSdrh         sqlite3VdbeChangeP5(v, (u8)nFarg);
38762fc865c1Sdrh       }
3877d1a01edaSdrh       if( nFarg && constMask==0 ){
387812ffee8cSdrh         sqlite3ReleaseTempRange(pParse, r1, nFarg);
38792dcef11bSdrh       }
3880c332cc30Sdrh       return target;
38816ec2733bSdrh     }
3882fe2093d7Sdrh #ifndef SQLITE_OMIT_SUBQUERY
3883fe2093d7Sdrh     case TK_EXISTS:
388419a775c2Sdrh     case TK_SELECT: {
38858da209b1Sdan       int nCol;
3886c5499befSdrh       testcase( op==TK_EXISTS );
3887c5499befSdrh       testcase( op==TK_SELECT );
38888da209b1Sdan       if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
38898da209b1Sdan         sqlite3SubselectError(pParse, nCol, 1);
38908da209b1Sdan       }else{
389185bcdce2Sdrh         return sqlite3CodeSubselect(pParse, pExpr);
38928da209b1Sdan       }
389319a775c2Sdrh       break;
389419a775c2Sdrh     }
3895fc7f27b9Sdrh     case TK_SELECT_COLUMN: {
3896966e2911Sdrh       int n;
3897fc7f27b9Sdrh       if( pExpr->pLeft->iTable==0 ){
389885bcdce2Sdrh         pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
3899fc7f27b9Sdrh       }
3900966e2911Sdrh       assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
3901966e2911Sdrh       if( pExpr->iTable
3902966e2911Sdrh        && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
3903966e2911Sdrh       ){
3904966e2911Sdrh         sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
3905966e2911Sdrh                                 pExpr->iTable, n);
3906966e2911Sdrh       }
3907c332cc30Sdrh       return pExpr->pLeft->iTable + pExpr->iColumn;
3908fc7f27b9Sdrh     }
3909fef5208cSdrh     case TK_IN: {
3910ec4ccdbcSdrh       int destIfFalse = sqlite3VdbeMakeLabel(pParse);
3911ec4ccdbcSdrh       int destIfNull = sqlite3VdbeMakeLabel(pParse);
3912e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3913e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
391466ba23ceSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3915e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
3916e3365e6cSdrh       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3917e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfNull);
3918c332cc30Sdrh       return target;
3919fef5208cSdrh     }
3920e3365e6cSdrh #endif /* SQLITE_OMIT_SUBQUERY */
3921e3365e6cSdrh 
3922e3365e6cSdrh 
39232dcef11bSdrh     /*
39242dcef11bSdrh     **    x BETWEEN y AND z
39252dcef11bSdrh     **
39262dcef11bSdrh     ** This is equivalent to
39272dcef11bSdrh     **
39282dcef11bSdrh     **    x>=y AND x<=z
39292dcef11bSdrh     **
39302dcef11bSdrh     ** X is stored in pExpr->pLeft.
39312dcef11bSdrh     ** Y is stored in pExpr->pList->a[0].pExpr.
39322dcef11bSdrh     ** Z is stored in pExpr->pList->a[1].pExpr.
39332dcef11bSdrh     */
3934fef5208cSdrh     case TK_BETWEEN: {
393571c57db0Sdan       exprCodeBetween(pParse, pExpr, target, 0, 0);
3936c332cc30Sdrh       return target;
3937fef5208cSdrh     }
393894fa9c41Sdrh     case TK_SPAN:
3939ae80ddeaSdrh     case TK_COLLATE:
39404f07e5fbSdrh     case TK_UPLUS: {
39411efa8023Sdrh       pExpr = pExpr->pLeft;
394259ee43a7Sdrh       goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
3943a2e00042Sdrh     }
39442dcef11bSdrh 
3945165921a7Sdan     case TK_TRIGGER: {
394665a7cd16Sdan       /* If the opcode is TK_TRIGGER, then the expression is a reference
394765a7cd16Sdan       ** to a column in the new.* or old.* pseudo-tables available to
394865a7cd16Sdan       ** trigger programs. In this case Expr.iTable is set to 1 for the
394965a7cd16Sdan       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
395065a7cd16Sdan       ** is set to the column of the pseudo-table to read, or to -1 to
395165a7cd16Sdan       ** read the rowid field.
395265a7cd16Sdan       **
395365a7cd16Sdan       ** The expression is implemented using an OP_Param opcode. The p1
395465a7cd16Sdan       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
395565a7cd16Sdan       ** to reference another column of the old.* pseudo-table, where
395665a7cd16Sdan       ** i is the index of the column. For a new.rowid reference, p1 is
395765a7cd16Sdan       ** set to (n+1), where n is the number of columns in each pseudo-table.
395865a7cd16Sdan       ** For a reference to any other column in the new.* pseudo-table, p1
395965a7cd16Sdan       ** is set to (n+2+i), where n and i are as defined previously. For
396065a7cd16Sdan       ** example, if the table on which triggers are being fired is
396165a7cd16Sdan       ** declared as:
396265a7cd16Sdan       **
396365a7cd16Sdan       **   CREATE TABLE t1(a, b);
396465a7cd16Sdan       **
396565a7cd16Sdan       ** Then p1 is interpreted as follows:
396665a7cd16Sdan       **
396765a7cd16Sdan       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
396865a7cd16Sdan       **   p1==1   ->    old.a         p1==4   ->    new.a
396965a7cd16Sdan       **   p1==2   ->    old.b         p1==5   ->    new.b
397065a7cd16Sdan       */
3971eda079cdSdrh       Table *pTab = pExpr->y.pTab;
397265a7cd16Sdan       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
397365a7cd16Sdan 
397465a7cd16Sdan       assert( pExpr->iTable==0 || pExpr->iTable==1 );
397565a7cd16Sdan       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
397665a7cd16Sdan       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
397765a7cd16Sdan       assert( p1>=0 && p1<(pTab->nCol*2+2) );
397865a7cd16Sdan 
397965a7cd16Sdan       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
3980896494e8Sdrh       VdbeComment((v, "r[%d]=%s.%s", target,
3981165921a7Sdan         (pExpr->iTable ? "new" : "old"),
3982eda079cdSdrh         (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[pExpr->iColumn].zName)
3983165921a7Sdan       ));
398465a7cd16Sdan 
398544dbca83Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
398665a7cd16Sdan       /* If the column has REAL affinity, it may currently be stored as an
3987113762a2Sdrh       ** integer. Use OP_RealAffinity to make sure it is really real.
3988113762a2Sdrh       **
3989113762a2Sdrh       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3990113762a2Sdrh       ** floating point when extracting it from the record.  */
39912832ad42Sdan       if( pExpr->iColumn>=0
39922832ad42Sdan        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
39932832ad42Sdan       ){
39942832ad42Sdan         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
39952832ad42Sdan       }
399644dbca83Sdrh #endif
3997165921a7Sdan       break;
3998165921a7Sdan     }
3999165921a7Sdan 
400071c57db0Sdan     case TK_VECTOR: {
4001e835bc12Sdrh       sqlite3ErrorMsg(pParse, "row value misused");
400271c57db0Sdan       break;
400371c57db0Sdan     }
400471c57db0Sdan 
400531d6fd55Sdrh     case TK_IF_NULL_ROW: {
400631d6fd55Sdrh       int addrINR;
400731d6fd55Sdrh       addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
400831d6fd55Sdrh       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
400931d6fd55Sdrh       sqlite3VdbeJumpHere(v, addrINR);
401031d6fd55Sdrh       sqlite3VdbeChangeP3(v, addrINR, inReg);
401131d6fd55Sdrh       break;
401231d6fd55Sdrh     }
401331d6fd55Sdrh 
40142dcef11bSdrh     /*
40152dcef11bSdrh     ** Form A:
40162dcef11bSdrh     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
40172dcef11bSdrh     **
40182dcef11bSdrh     ** Form B:
40192dcef11bSdrh     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
40202dcef11bSdrh     **
40212dcef11bSdrh     ** Form A is can be transformed into the equivalent form B as follows:
40222dcef11bSdrh     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
40232dcef11bSdrh     **        WHEN x=eN THEN rN ELSE y END
40242dcef11bSdrh     **
40252dcef11bSdrh     ** X (if it exists) is in pExpr->pLeft.
4026c5cd1249Sdrh     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
4027c5cd1249Sdrh     ** odd.  The Y is also optional.  If the number of elements in x.pList
4028c5cd1249Sdrh     ** is even, then Y is omitted and the "otherwise" result is NULL.
40292dcef11bSdrh     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
40302dcef11bSdrh     **
40312dcef11bSdrh     ** The result of the expression is the Ri for the first matching Ei,
40322dcef11bSdrh     ** or if there is no matching Ei, the ELSE term Y, or if there is
40332dcef11bSdrh     ** no ELSE term, NULL.
40342dcef11bSdrh     */
403533cd4909Sdrh     default: assert( op==TK_CASE ); {
40362dcef11bSdrh       int endLabel;                     /* GOTO label for end of CASE stmt */
40372dcef11bSdrh       int nextCase;                     /* GOTO label for next WHEN clause */
40382dcef11bSdrh       int nExpr;                        /* 2x number of WHEN terms */
40392dcef11bSdrh       int i;                            /* Loop counter */
40402dcef11bSdrh       ExprList *pEList;                 /* List of WHEN terms */
40412dcef11bSdrh       struct ExprList_item *aListelem;  /* Array of WHEN terms */
40422dcef11bSdrh       Expr opCompare;                   /* The X==Ei expression */
40432dcef11bSdrh       Expr *pX;                         /* The X expression */
40441bd10f8aSdrh       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
404517a7f8ddSdrh 
40466ab3a2ecSdanielk1977       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
40476ab3a2ecSdanielk1977       assert(pExpr->x.pList->nExpr > 0);
40486ab3a2ecSdanielk1977       pEList = pExpr->x.pList;
4049be5c89acSdrh       aListelem = pEList->a;
4050be5c89acSdrh       nExpr = pEList->nExpr;
4051ec4ccdbcSdrh       endLabel = sqlite3VdbeMakeLabel(pParse);
40522dcef11bSdrh       if( (pX = pExpr->pLeft)!=0 ){
4053a8e05761Sdrh         exprNodeCopy(&tempX, pX);
405433cd4909Sdrh         testcase( pX->op==TK_COLUMN );
405512abf408Sdrh         exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
4056c5499befSdrh         testcase( regFree1==0 );
4057abb9d5f1Sdrh         memset(&opCompare, 0, sizeof(opCompare));
40582dcef11bSdrh         opCompare.op = TK_EQ;
405910d1edf0Sdrh         opCompare.pLeft = &tempX;
40602dcef11bSdrh         pTest = &opCompare;
40618b1db07fSdrh         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
40628b1db07fSdrh         ** The value in regFree1 might get SCopy-ed into the file result.
40638b1db07fSdrh         ** So make sure that the regFree1 register is not reused for other
40648b1db07fSdrh         ** purposes and possibly overwritten.  */
40658b1db07fSdrh         regFree1 = 0;
4066cce7d176Sdrh       }
4067c5cd1249Sdrh       for(i=0; i<nExpr-1; i=i+2){
40682dcef11bSdrh         if( pX ){
40691bd10f8aSdrh           assert( pTest!=0 );
40702dcef11bSdrh           opCompare.pRight = aListelem[i].pExpr;
4071f5905aa7Sdrh         }else{
40722dcef11bSdrh           pTest = aListelem[i].pExpr;
407317a7f8ddSdrh         }
4074ec4ccdbcSdrh         nextCase = sqlite3VdbeMakeLabel(pParse);
407533cd4909Sdrh         testcase( pTest->op==TK_COLUMN );
40762dcef11bSdrh         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
4077c5499befSdrh         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
40789de221dfSdrh         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
4079076e85f5Sdrh         sqlite3VdbeGoto(v, endLabel);
40802dcef11bSdrh         sqlite3VdbeResolveLabel(v, nextCase);
4081f570f011Sdrh       }
4082c5cd1249Sdrh       if( (nExpr&1)!=0 ){
4083c5cd1249Sdrh         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
408417a7f8ddSdrh       }else{
40859de221dfSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
408617a7f8ddSdrh       }
40872dcef11bSdrh       sqlite3VdbeResolveLabel(v, endLabel);
40886f34903eSdanielk1977       break;
40896f34903eSdanielk1977     }
40905338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
40916f34903eSdanielk1977     case TK_RAISE: {
4092165921a7Sdan       assert( pExpr->affinity==OE_Rollback
4093165921a7Sdan            || pExpr->affinity==OE_Abort
4094165921a7Sdan            || pExpr->affinity==OE_Fail
4095165921a7Sdan            || pExpr->affinity==OE_Ignore
4096165921a7Sdan       );
4097e0af83acSdan       if( !pParse->pTriggerTab ){
4098e0af83acSdan         sqlite3ErrorMsg(pParse,
4099e0af83acSdan                        "RAISE() may only be used within a trigger-program");
4100e0af83acSdan         return 0;
4101e0af83acSdan       }
4102e0af83acSdan       if( pExpr->affinity==OE_Abort ){
4103e0af83acSdan         sqlite3MayAbort(pParse);
4104e0af83acSdan       }
410533e619fcSdrh       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4106e0af83acSdan       if( pExpr->affinity==OE_Ignore ){
4107e0af83acSdan         sqlite3VdbeAddOp4(
4108e0af83acSdan             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
4109688852abSdrh         VdbeCoverage(v);
4110e0af83acSdan       }else{
4111433dccfbSdrh         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
4112f9c8ce3cSdrh                               pExpr->affinity, pExpr->u.zToken, 0, 0);
4113e0af83acSdan       }
4114e0af83acSdan 
4115ffe07b2dSdrh       break;
411617a7f8ddSdrh     }
41175338a5f7Sdanielk1977 #endif
4118ffe07b2dSdrh   }
41192dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
41202dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
41212dcef11bSdrh   return inReg;
41225b6afba9Sdrh }
41232dcef11bSdrh 
41242dcef11bSdrh /*
4125d1a01edaSdrh ** Factor out the code of the given expression to initialization time.
41261e9b53f9Sdrh **
4127ad879ffdSdrh ** If regDest>=0 then the result is always stored in that register and the
4128ad879ffdSdrh ** result is not reusable.  If regDest<0 then this routine is free to
4129ad879ffdSdrh ** store the value whereever it wants.  The register where the expression
4130ad879ffdSdrh ** is stored is returned.  When regDest<0, two identical expressions will
4131ad879ffdSdrh ** code to the same register.
4132d1a01edaSdrh */
41331e9b53f9Sdrh int sqlite3ExprCodeAtInit(
4134d673cddaSdrh   Parse *pParse,    /* Parsing context */
4135d673cddaSdrh   Expr *pExpr,      /* The expression to code when the VDBE initializes */
4136ad879ffdSdrh   int regDest       /* Store the value in this register */
4137d673cddaSdrh ){
4138d1a01edaSdrh   ExprList *p;
4139d9f158e7Sdrh   assert( ConstFactorOk(pParse) );
4140d1a01edaSdrh   p = pParse->pConstExpr;
4141ad879ffdSdrh   if( regDest<0 && p ){
41421e9b53f9Sdrh     struct ExprList_item *pItem;
41431e9b53f9Sdrh     int i;
41441e9b53f9Sdrh     for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
41455aa550cfSdan       if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
41461e9b53f9Sdrh         return pItem->u.iConstExprReg;
41471e9b53f9Sdrh       }
41481e9b53f9Sdrh     }
41491e9b53f9Sdrh   }
4150d1a01edaSdrh   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4151d1a01edaSdrh   p = sqlite3ExprListAppend(pParse, p, pExpr);
4152d673cddaSdrh   if( p ){
4153d673cddaSdrh      struct ExprList_item *pItem = &p->a[p->nExpr-1];
4154ad879ffdSdrh      pItem->reusable = regDest<0;
4155ad879ffdSdrh      if( regDest<0 ) regDest = ++pParse->nMem;
4156d673cddaSdrh      pItem->u.iConstExprReg = regDest;
4157d673cddaSdrh   }
4158d1a01edaSdrh   pParse->pConstExpr = p;
41591e9b53f9Sdrh   return regDest;
4160d1a01edaSdrh }
4161d1a01edaSdrh 
4162d1a01edaSdrh /*
41632dcef11bSdrh ** Generate code to evaluate an expression and store the results
41642dcef11bSdrh ** into a register.  Return the register number where the results
41652dcef11bSdrh ** are stored.
41662dcef11bSdrh **
41672dcef11bSdrh ** If the register is a temporary register that can be deallocated,
4168678ccce8Sdrh ** then write its number into *pReg.  If the result register is not
41692dcef11bSdrh ** a temporary, then set *pReg to zero.
4170f30a969bSdrh **
4171f30a969bSdrh ** If pExpr is a constant, then this routine might generate this
4172f30a969bSdrh ** code to fill the register in the initialization section of the
4173f30a969bSdrh ** VDBE program, in order to factor it out of the evaluation loop.
41742dcef11bSdrh */
41752dcef11bSdrh int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
4176f30a969bSdrh   int r2;
4177f30a969bSdrh   pExpr = sqlite3ExprSkipCollate(pExpr);
4178d9f158e7Sdrh   if( ConstFactorOk(pParse)
4179f30a969bSdrh    && pExpr->op!=TK_REGISTER
4180f30a969bSdrh    && sqlite3ExprIsConstantNotJoin(pExpr)
4181f30a969bSdrh   ){
4182f30a969bSdrh     *pReg  = 0;
4183ad879ffdSdrh     r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
4184f30a969bSdrh   }else{
41852dcef11bSdrh     int r1 = sqlite3GetTempReg(pParse);
4186f30a969bSdrh     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
41872dcef11bSdrh     if( r2==r1 ){
41882dcef11bSdrh       *pReg = r1;
41892dcef11bSdrh     }else{
41902dcef11bSdrh       sqlite3ReleaseTempReg(pParse, r1);
41912dcef11bSdrh       *pReg = 0;
41922dcef11bSdrh     }
4193f30a969bSdrh   }
41942dcef11bSdrh   return r2;
41952dcef11bSdrh }
41962dcef11bSdrh 
41972dcef11bSdrh /*
41982dcef11bSdrh ** Generate code that will evaluate expression pExpr and store the
41992dcef11bSdrh ** results in register target.  The results are guaranteed to appear
42002dcef11bSdrh ** in register target.
42012dcef11bSdrh */
420205a86c5cSdrh void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
42039cbf3425Sdrh   int inReg;
42049cbf3425Sdrh 
42059cbf3425Sdrh   assert( target>0 && target<=pParse->nMem );
4206ebc16717Sdrh   if( pExpr && pExpr->op==TK_REGISTER ){
4207ebc16717Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
4208ebc16717Sdrh   }else{
42099cbf3425Sdrh     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
42101c75c9d7Sdrh     assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
42110e359b30Sdrh     if( inReg!=target && pParse->pVdbe ){
42129cbf3425Sdrh       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
421317a7f8ddSdrh     }
4214ebc16717Sdrh   }
4215cce7d176Sdrh }
4216cce7d176Sdrh 
4217cce7d176Sdrh /*
42181c75c9d7Sdrh ** Make a transient copy of expression pExpr and then code it using
42191c75c9d7Sdrh ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
42201c75c9d7Sdrh ** except that the input expression is guaranteed to be unchanged.
42211c75c9d7Sdrh */
42221c75c9d7Sdrh void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
42231c75c9d7Sdrh   sqlite3 *db = pParse->db;
42241c75c9d7Sdrh   pExpr = sqlite3ExprDup(db, pExpr, 0);
42251c75c9d7Sdrh   if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
42261c75c9d7Sdrh   sqlite3ExprDelete(db, pExpr);
42271c75c9d7Sdrh }
42281c75c9d7Sdrh 
42291c75c9d7Sdrh /*
423005a86c5cSdrh ** Generate code that will evaluate expression pExpr and store the
423105a86c5cSdrh ** results in register target.  The results are guaranteed to appear
423205a86c5cSdrh ** in register target.  If the expression is constant, then this routine
423305a86c5cSdrh ** might choose to code the expression at initialization time.
423405a86c5cSdrh */
423505a86c5cSdrh void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4236b8b06690Sdrh   if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
4237ad879ffdSdrh     sqlite3ExprCodeAtInit(pParse, pExpr, target);
423805a86c5cSdrh   }else{
423905a86c5cSdrh     sqlite3ExprCode(pParse, pExpr, target);
424005a86c5cSdrh   }
4241cce7d176Sdrh }
4242cce7d176Sdrh 
4243cce7d176Sdrh /*
424460ec914cSpeter.d.reid ** Generate code that evaluates the given expression and puts the result
4245de4fcfddSdrh ** in register target.
424625303780Sdrh **
42472dcef11bSdrh ** Also make a copy of the expression results into another "cache" register
42482dcef11bSdrh ** and modify the expression so that the next time it is evaluated,
42492dcef11bSdrh ** the result is a copy of the cache register.
42502dcef11bSdrh **
42512dcef11bSdrh ** This routine is used for expressions that are used multiple
42522dcef11bSdrh ** times.  They are evaluated once and the results of the expression
42532dcef11bSdrh ** are reused.
425425303780Sdrh */
425505a86c5cSdrh void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
425625303780Sdrh   Vdbe *v = pParse->pVdbe;
425725303780Sdrh   int iMem;
425805a86c5cSdrh 
425905a86c5cSdrh   assert( target>0 );
426005a86c5cSdrh   assert( pExpr->op!=TK_REGISTER );
426105a86c5cSdrh   sqlite3ExprCode(pParse, pExpr, target);
42622dcef11bSdrh   iMem = ++pParse->nMem;
426305a86c5cSdrh   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4264a4c3c87eSdrh   exprToRegister(pExpr, iMem);
426525303780Sdrh }
42667e02e5e6Sdrh 
4267678ccce8Sdrh /*
4268268380caSdrh ** Generate code that pushes the value of every element of the given
42699cbf3425Sdrh ** expression list into a sequence of registers beginning at target.
4270268380caSdrh **
42713df6c3b1Sdrh ** Return the number of elements evaluated.  The number returned will
42723df6c3b1Sdrh ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
42733df6c3b1Sdrh ** is defined.
4274d1a01edaSdrh **
4275d1a01edaSdrh ** The SQLITE_ECEL_DUP flag prevents the arguments from being
4276d1a01edaSdrh ** filled using OP_SCopy.  OP_Copy must be used instead.
4277d1a01edaSdrh **
4278d1a01edaSdrh ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4279d1a01edaSdrh ** factored out into initialization code.
4280b0df9634Sdrh **
4281b0df9634Sdrh ** The SQLITE_ECEL_REF flag means that expressions in the list with
4282b0df9634Sdrh ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4283b0df9634Sdrh ** in registers at srcReg, and so the value can be copied from there.
42843df6c3b1Sdrh ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
42853df6c3b1Sdrh ** are simply omitted rather than being copied from srcReg.
4286268380caSdrh */
42874adee20fSdanielk1977 int sqlite3ExprCodeExprList(
4288268380caSdrh   Parse *pParse,     /* Parsing context */
4289389a1adbSdrh   ExprList *pList,   /* The expression list to be coded */
4290191b54cbSdrh   int target,        /* Where to write results */
42915579d59fSdrh   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
4292d1a01edaSdrh   u8 flags           /* SQLITE_ECEL_* flags */
4293268380caSdrh ){
4294268380caSdrh   struct ExprList_item *pItem;
42955579d59fSdrh   int i, j, n;
4296d1a01edaSdrh   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
42975579d59fSdrh   Vdbe *v = pParse->pVdbe;
42989d8b3072Sdrh   assert( pList!=0 );
42999cbf3425Sdrh   assert( target>0 );
4300d81a142bSdrh   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
4301268380caSdrh   n = pList->nExpr;
4302d9f158e7Sdrh   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
4303191b54cbSdrh   for(pItem=pList->a, i=0; i<n; i++, pItem++){
43047445ffe2Sdrh     Expr *pExpr = pItem->pExpr;
430524e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES
430624e25d32Sdan     if( pItem->bSorterRef ){
430724e25d32Sdan       i--;
430824e25d32Sdan       n--;
430924e25d32Sdan     }else
431024e25d32Sdan #endif
4311257c13faSdan     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
4312257c13faSdan       if( flags & SQLITE_ECEL_OMITREF ){
4313257c13faSdan         i--;
4314257c13faSdan         n--;
4315257c13faSdan       }else{
43165579d59fSdrh         sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4317257c13faSdan       }
4318b8b06690Sdrh     }else if( (flags & SQLITE_ECEL_FACTOR)!=0
4319b8b06690Sdrh            && sqlite3ExprIsConstantNotJoin(pExpr)
4320b8b06690Sdrh     ){
4321ad879ffdSdrh       sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
4322d1a01edaSdrh     }else{
43237445ffe2Sdrh       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4324746fd9ccSdrh       if( inReg!=target+i ){
43254eded604Sdrh         VdbeOp *pOp;
43264eded604Sdrh         if( copyOp==OP_Copy
43274eded604Sdrh          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
43284eded604Sdrh          && pOp->p1+pOp->p3+1==inReg
43294eded604Sdrh          && pOp->p2+pOp->p3+1==target+i
43304eded604Sdrh         ){
43314eded604Sdrh           pOp->p3++;
43324eded604Sdrh         }else{
43334eded604Sdrh           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
43344eded604Sdrh         }
4335d1a01edaSdrh       }
4336d176611bSdrh     }
4337268380caSdrh   }
4338f9b596ebSdrh   return n;
4339268380caSdrh }
4340268380caSdrh 
4341268380caSdrh /*
434236c563a2Sdrh ** Generate code for a BETWEEN operator.
434336c563a2Sdrh **
434436c563a2Sdrh **    x BETWEEN y AND z
434536c563a2Sdrh **
434636c563a2Sdrh ** The above is equivalent to
434736c563a2Sdrh **
434836c563a2Sdrh **    x>=y AND x<=z
434936c563a2Sdrh **
435036c563a2Sdrh ** Code it as such, taking care to do the common subexpression
435160ec914cSpeter.d.reid ** elimination of x.
435284b19a3dSdrh **
435384b19a3dSdrh ** The xJumpIf parameter determines details:
435484b19a3dSdrh **
435584b19a3dSdrh **    NULL:                   Store the boolean result in reg[dest]
435684b19a3dSdrh **    sqlite3ExprIfTrue:      Jump to dest if true
435784b19a3dSdrh **    sqlite3ExprIfFalse:     Jump to dest if false
435884b19a3dSdrh **
435984b19a3dSdrh ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
436036c563a2Sdrh */
436136c563a2Sdrh static void exprCodeBetween(
436236c563a2Sdrh   Parse *pParse,    /* Parsing and code generating context */
436336c563a2Sdrh   Expr *pExpr,      /* The BETWEEN expression */
436484b19a3dSdrh   int dest,         /* Jump destination or storage location */
436584b19a3dSdrh   void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
436636c563a2Sdrh   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
436736c563a2Sdrh ){
436836c563a2Sdrh  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
436936c563a2Sdrh   Expr compLeft;    /* The  x>=y  term */
437036c563a2Sdrh   Expr compRight;   /* The  x<=z  term */
4371db45bd5eSdrh   Expr exprX;       /* The  x  subexpression */
4372db45bd5eSdrh   int regFree1 = 0; /* Temporary use register */
437384b19a3dSdrh 
437471c57db0Sdan   memset(&compLeft, 0, sizeof(Expr));
437571c57db0Sdan   memset(&compRight, 0, sizeof(Expr));
437671c57db0Sdan   memset(&exprAnd, 0, sizeof(Expr));
4377db45bd5eSdrh 
4378db45bd5eSdrh   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4379a8e05761Sdrh   exprNodeCopy(&exprX, pExpr->pLeft);
438036c563a2Sdrh   exprAnd.op = TK_AND;
438136c563a2Sdrh   exprAnd.pLeft = &compLeft;
438236c563a2Sdrh   exprAnd.pRight = &compRight;
438336c563a2Sdrh   compLeft.op = TK_GE;
4384db45bd5eSdrh   compLeft.pLeft = &exprX;
438536c563a2Sdrh   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
438636c563a2Sdrh   compRight.op = TK_LE;
4387db45bd5eSdrh   compRight.pLeft = &exprX;
438836c563a2Sdrh   compRight.pRight = pExpr->x.pList->a[1].pExpr;
438912abf408Sdrh   exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
439084b19a3dSdrh   if( xJump ){
439184b19a3dSdrh     xJump(pParse, &exprAnd, dest, jumpIfNull);
439236c563a2Sdrh   }else{
439336fd41e5Sdrh     /* Mark the expression is being from the ON or USING clause of a join
439436fd41e5Sdrh     ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
439536fd41e5Sdrh     ** it into the Parse.pConstExpr list.  We should use a new bit for this,
439636fd41e5Sdrh     ** for clarity, but we are out of bits in the Expr.flags field so we
439736fd41e5Sdrh     ** have to reuse the EP_FromJoin bit.  Bummer. */
4398db45bd5eSdrh     exprX.flags |= EP_FromJoin;
439971c57db0Sdan     sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
440036c563a2Sdrh   }
4401db45bd5eSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
440236c563a2Sdrh 
440336c563a2Sdrh   /* Ensure adequate test coverage */
4404db45bd5eSdrh   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
4405db45bd5eSdrh   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
4406db45bd5eSdrh   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
4407db45bd5eSdrh   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
4408db45bd5eSdrh   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4409db45bd5eSdrh   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4410db45bd5eSdrh   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4411db45bd5eSdrh   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
441284b19a3dSdrh   testcase( xJump==0 );
441336c563a2Sdrh }
441436c563a2Sdrh 
441536c563a2Sdrh /*
4416cce7d176Sdrh ** Generate code for a boolean expression such that a jump is made
4417cce7d176Sdrh ** to the label "dest" if the expression is true but execution
4418cce7d176Sdrh ** continues straight thru if the expression is false.
4419f5905aa7Sdrh **
4420f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false), then
442135573356Sdrh ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
4422f2bc013cSdrh **
4423f2bc013cSdrh ** This code depends on the fact that certain token values (ex: TK_EQ)
4424f2bc013cSdrh ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4425f2bc013cSdrh ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
4426f2bc013cSdrh ** the make process cause these values to align.  Assert()s in the code
4427f2bc013cSdrh ** below verify that the numbers are aligned correctly.
4428cce7d176Sdrh */
44294adee20fSdanielk1977 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4430cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
4431cce7d176Sdrh   int op = 0;
44322dcef11bSdrh   int regFree1 = 0;
44332dcef11bSdrh   int regFree2 = 0;
44342dcef11bSdrh   int r1, r2;
44352dcef11bSdrh 
443635573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
443748864df9Smistachkin   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
443833cd4909Sdrh   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
4439f2bc013cSdrh   op = pExpr->op;
44407b35a77bSdan   switch( op ){
444117180fcaSdrh     case TK_AND:
444217180fcaSdrh     case TK_OR: {
444317180fcaSdrh       Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
444417180fcaSdrh       if( pAlt!=pExpr ){
444517180fcaSdrh         sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
444617180fcaSdrh       }else if( op==TK_AND ){
4447ec4ccdbcSdrh         int d2 = sqlite3VdbeMakeLabel(pParse);
4448c5499befSdrh         testcase( jumpIfNull==0 );
444917180fcaSdrh         sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
445017180fcaSdrh                            jumpIfNull^SQLITE_JUMPIFNULL);
44514adee20fSdanielk1977         sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
44524adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, d2);
445317180fcaSdrh       }else{
4454c5499befSdrh         testcase( jumpIfNull==0 );
44554adee20fSdanielk1977         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
44564adee20fSdanielk1977         sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
445717180fcaSdrh       }
4458cce7d176Sdrh       break;
4459cce7d176Sdrh     }
4460cce7d176Sdrh     case TK_NOT: {
4461c5499befSdrh       testcase( jumpIfNull==0 );
44624adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
4463cce7d176Sdrh       break;
4464cce7d176Sdrh     }
44658abed7b9Sdrh     case TK_TRUTH: {
446696acafbeSdrh       int isNot;      /* IS NOT TRUE or IS NOT FALSE */
446796acafbeSdrh       int isTrue;     /* IS TRUE or IS NOT TRUE */
4468007c843bSdrh       testcase( jumpIfNull==0 );
44698abed7b9Sdrh       isNot = pExpr->op2==TK_ISNOT;
447096acafbeSdrh       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
447143c4ac8bSdrh       testcase( isTrue && isNot );
447296acafbeSdrh       testcase( !isTrue && isNot );
447343c4ac8bSdrh       if( isTrue ^ isNot ){
44748abed7b9Sdrh         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
44758abed7b9Sdrh                           isNot ? SQLITE_JUMPIFNULL : 0);
44768abed7b9Sdrh       }else{
44778abed7b9Sdrh         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
44788abed7b9Sdrh                            isNot ? SQLITE_JUMPIFNULL : 0);
44798abed7b9Sdrh       }
4480007c843bSdrh       break;
4481007c843bSdrh     }
4482de845c2fSdrh     case TK_IS:
4483de845c2fSdrh     case TK_ISNOT:
4484de845c2fSdrh       testcase( op==TK_IS );
4485de845c2fSdrh       testcase( op==TK_ISNOT );
4486de845c2fSdrh       op = (op==TK_IS) ? TK_EQ : TK_NE;
4487de845c2fSdrh       jumpIfNull = SQLITE_NULLEQ;
4488de845c2fSdrh       /* Fall thru */
4489cce7d176Sdrh     case TK_LT:
4490cce7d176Sdrh     case TK_LE:
4491cce7d176Sdrh     case TK_GT:
4492cce7d176Sdrh     case TK_GE:
4493cce7d176Sdrh     case TK_NE:
44940ac65892Sdrh     case TK_EQ: {
4495625015e0Sdan       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
4496c5499befSdrh       testcase( jumpIfNull==0 );
4497b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4498b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
449935573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
45002dcef11bSdrh                   r1, r2, dest, jumpIfNull);
45017d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
45027d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
45037d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
45047d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4505de845c2fSdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4506de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4507de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4508de845c2fSdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4509de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4510de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
45116a2fe093Sdrh       testcase( regFree1==0 );
45126a2fe093Sdrh       testcase( regFree2==0 );
45136a2fe093Sdrh       break;
45146a2fe093Sdrh     }
4515cce7d176Sdrh     case TK_ISNULL:
4516cce7d176Sdrh     case TK_NOTNULL: {
45177d176105Sdrh       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
45187d176105Sdrh       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
45192dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
45202dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
45217d176105Sdrh       VdbeCoverageIf(v, op==TK_ISNULL);
45227d176105Sdrh       VdbeCoverageIf(v, op==TK_NOTNULL);
4523c5499befSdrh       testcase( regFree1==0 );
4524cce7d176Sdrh       break;
4525cce7d176Sdrh     }
4526fef5208cSdrh     case TK_BETWEEN: {
45275c03f30aSdrh       testcase( jumpIfNull==0 );
452871c57db0Sdan       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
4529fef5208cSdrh       break;
4530fef5208cSdrh     }
4531bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
4532e3365e6cSdrh     case TK_IN: {
4533ec4ccdbcSdrh       int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4534e3365e6cSdrh       int destIfNull = jumpIfNull ? dest : destIfFalse;
4535e3365e6cSdrh       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4536076e85f5Sdrh       sqlite3VdbeGoto(v, dest);
4537e3365e6cSdrh       sqlite3VdbeResolveLabel(v, destIfFalse);
4538e3365e6cSdrh       break;
4539e3365e6cSdrh     }
4540bb201344Sshaneh #endif
4541cce7d176Sdrh     default: {
45427b35a77bSdan     default_expr:
4543ad31727fSdrh       if( ExprAlwaysTrue(pExpr) ){
4544076e85f5Sdrh         sqlite3VdbeGoto(v, dest);
4545ad31727fSdrh       }else if( ExprAlwaysFalse(pExpr) ){
4546991a1985Sdrh         /* No-op */
4547991a1985Sdrh       }else{
45482dcef11bSdrh         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
45492dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
4550688852abSdrh         VdbeCoverage(v);
4551c5499befSdrh         testcase( regFree1==0 );
4552c5499befSdrh         testcase( jumpIfNull==0 );
4553991a1985Sdrh       }
4554cce7d176Sdrh       break;
4555cce7d176Sdrh     }
4556cce7d176Sdrh   }
45572dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
45582dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
4559cce7d176Sdrh }
4560cce7d176Sdrh 
4561cce7d176Sdrh /*
456266b89c8fSdrh ** Generate code for a boolean expression such that a jump is made
4563cce7d176Sdrh ** to the label "dest" if the expression is false but execution
4564cce7d176Sdrh ** continues straight thru if the expression is true.
4565f5905aa7Sdrh **
4566f5905aa7Sdrh ** If the expression evaluates to NULL (neither true nor false) then
456735573356Sdrh ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
456835573356Sdrh ** is 0.
4569cce7d176Sdrh */
45704adee20fSdanielk1977 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4571cce7d176Sdrh   Vdbe *v = pParse->pVdbe;
4572cce7d176Sdrh   int op = 0;
45732dcef11bSdrh   int regFree1 = 0;
45742dcef11bSdrh   int regFree2 = 0;
45752dcef11bSdrh   int r1, r2;
45762dcef11bSdrh 
457735573356Sdrh   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
457848864df9Smistachkin   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
457933cd4909Sdrh   if( pExpr==0 )    return;
4580f2bc013cSdrh 
4581f2bc013cSdrh   /* The value of pExpr->op and op are related as follows:
4582f2bc013cSdrh   **
4583f2bc013cSdrh   **       pExpr->op            op
4584f2bc013cSdrh   **       ---------          ----------
4585f2bc013cSdrh   **       TK_ISNULL          OP_NotNull
4586f2bc013cSdrh   **       TK_NOTNULL         OP_IsNull
4587f2bc013cSdrh   **       TK_NE              OP_Eq
4588f2bc013cSdrh   **       TK_EQ              OP_Ne
4589f2bc013cSdrh   **       TK_GT              OP_Le
4590f2bc013cSdrh   **       TK_LE              OP_Gt
4591f2bc013cSdrh   **       TK_GE              OP_Lt
4592f2bc013cSdrh   **       TK_LT              OP_Ge
4593f2bc013cSdrh   **
4594f2bc013cSdrh   ** For other values of pExpr->op, op is undefined and unused.
4595f2bc013cSdrh   ** The value of TK_ and OP_ constants are arranged such that we
4596f2bc013cSdrh   ** can compute the mapping above using the following expression.
4597f2bc013cSdrh   ** Assert()s verify that the computation is correct.
4598f2bc013cSdrh   */
4599f2bc013cSdrh   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4600f2bc013cSdrh 
4601f2bc013cSdrh   /* Verify correct alignment of TK_ and OP_ constants
4602f2bc013cSdrh   */
4603f2bc013cSdrh   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4604f2bc013cSdrh   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4605f2bc013cSdrh   assert( pExpr->op!=TK_NE || op==OP_Eq );
4606f2bc013cSdrh   assert( pExpr->op!=TK_EQ || op==OP_Ne );
4607f2bc013cSdrh   assert( pExpr->op!=TK_LT || op==OP_Ge );
4608f2bc013cSdrh   assert( pExpr->op!=TK_LE || op==OP_Gt );
4609f2bc013cSdrh   assert( pExpr->op!=TK_GT || op==OP_Le );
4610f2bc013cSdrh   assert( pExpr->op!=TK_GE || op==OP_Lt );
4611f2bc013cSdrh 
4612ba00e30aSdan   switch( pExpr->op ){
461317180fcaSdrh     case TK_AND:
461417180fcaSdrh     case TK_OR: {
461517180fcaSdrh       Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
461617180fcaSdrh       if( pAlt!=pExpr ){
461717180fcaSdrh         sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
461817180fcaSdrh       }else if( pExpr->op==TK_AND ){
4619c5499befSdrh         testcase( jumpIfNull==0 );
46204adee20fSdanielk1977         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
46214adee20fSdanielk1977         sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
462217180fcaSdrh       }else{
4623ec4ccdbcSdrh         int d2 = sqlite3VdbeMakeLabel(pParse);
4624c5499befSdrh         testcase( jumpIfNull==0 );
462517180fcaSdrh         sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
462617180fcaSdrh                           jumpIfNull^SQLITE_JUMPIFNULL);
46274adee20fSdanielk1977         sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
46284adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, d2);
462917180fcaSdrh       }
4630cce7d176Sdrh       break;
4631cce7d176Sdrh     }
4632cce7d176Sdrh     case TK_NOT: {
46335c03f30aSdrh       testcase( jumpIfNull==0 );
46344adee20fSdanielk1977       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
4635cce7d176Sdrh       break;
4636cce7d176Sdrh     }
46378abed7b9Sdrh     case TK_TRUTH: {
463896acafbeSdrh       int isNot;   /* IS NOT TRUE or IS NOT FALSE */
463996acafbeSdrh       int isTrue;  /* IS TRUE or IS NOT TRUE */
46408abed7b9Sdrh       testcase( jumpIfNull==0 );
46418abed7b9Sdrh       isNot = pExpr->op2==TK_ISNOT;
464296acafbeSdrh       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
464343c4ac8bSdrh       testcase( isTrue && isNot );
464496acafbeSdrh       testcase( !isTrue && isNot );
464543c4ac8bSdrh       if( isTrue ^ isNot ){
46468abed7b9Sdrh         /* IS TRUE and IS NOT FALSE */
46478abed7b9Sdrh         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
46488abed7b9Sdrh                            isNot ? 0 : SQLITE_JUMPIFNULL);
46498abed7b9Sdrh 
46508abed7b9Sdrh       }else{
46518abed7b9Sdrh         /* IS FALSE and IS NOT TRUE */
46528abed7b9Sdrh         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
46538abed7b9Sdrh                           isNot ? 0 : SQLITE_JUMPIFNULL);
46548abed7b9Sdrh       }
4655007c843bSdrh       break;
4656007c843bSdrh     }
4657de845c2fSdrh     case TK_IS:
4658de845c2fSdrh     case TK_ISNOT:
4659de845c2fSdrh       testcase( pExpr->op==TK_IS );
4660de845c2fSdrh       testcase( pExpr->op==TK_ISNOT );
4661de845c2fSdrh       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4662de845c2fSdrh       jumpIfNull = SQLITE_NULLEQ;
4663de845c2fSdrh       /* Fall thru */
4664cce7d176Sdrh     case TK_LT:
4665cce7d176Sdrh     case TK_LE:
4666cce7d176Sdrh     case TK_GT:
4667cce7d176Sdrh     case TK_GE:
4668cce7d176Sdrh     case TK_NE:
4669cce7d176Sdrh     case TK_EQ: {
4670625015e0Sdan       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
4671c5499befSdrh       testcase( jumpIfNull==0 );
4672b6da74ebSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4673b6da74ebSdrh       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
467435573356Sdrh       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
46752dcef11bSdrh                   r1, r2, dest, jumpIfNull);
46767d176105Sdrh       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
46777d176105Sdrh       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
46787d176105Sdrh       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
46797d176105Sdrh       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4680de845c2fSdrh       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4681de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4682de845c2fSdrh       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4683de845c2fSdrh       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4684de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4685de845c2fSdrh       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
46866a2fe093Sdrh       testcase( regFree1==0 );
46876a2fe093Sdrh       testcase( regFree2==0 );
46886a2fe093Sdrh       break;
46896a2fe093Sdrh     }
4690cce7d176Sdrh     case TK_ISNULL:
4691cce7d176Sdrh     case TK_NOTNULL: {
46922dcef11bSdrh       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
46932dcef11bSdrh       sqlite3VdbeAddOp2(v, op, r1, dest);
46947d176105Sdrh       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
46957d176105Sdrh       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
4696c5499befSdrh       testcase( regFree1==0 );
4697cce7d176Sdrh       break;
4698cce7d176Sdrh     }
4699fef5208cSdrh     case TK_BETWEEN: {
47005c03f30aSdrh       testcase( jumpIfNull==0 );
470171c57db0Sdan       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
4702fef5208cSdrh       break;
4703fef5208cSdrh     }
4704bb201344Sshaneh #ifndef SQLITE_OMIT_SUBQUERY
4705e3365e6cSdrh     case TK_IN: {
4706e3365e6cSdrh       if( jumpIfNull ){
4707e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4708e3365e6cSdrh       }else{
4709ec4ccdbcSdrh         int destIfNull = sqlite3VdbeMakeLabel(pParse);
4710e3365e6cSdrh         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4711e3365e6cSdrh         sqlite3VdbeResolveLabel(v, destIfNull);
4712e3365e6cSdrh       }
4713e3365e6cSdrh       break;
4714e3365e6cSdrh     }
4715bb201344Sshaneh #endif
4716cce7d176Sdrh     default: {
4717ba00e30aSdan     default_expr:
4718ad31727fSdrh       if( ExprAlwaysFalse(pExpr) ){
4719076e85f5Sdrh         sqlite3VdbeGoto(v, dest);
4720ad31727fSdrh       }else if( ExprAlwaysTrue(pExpr) ){
4721991a1985Sdrh         /* no-op */
4722991a1985Sdrh       }else{
47232dcef11bSdrh         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
47242dcef11bSdrh         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
4725688852abSdrh         VdbeCoverage(v);
4726c5499befSdrh         testcase( regFree1==0 );
4727c5499befSdrh         testcase( jumpIfNull==0 );
4728991a1985Sdrh       }
4729cce7d176Sdrh       break;
4730cce7d176Sdrh     }
4731cce7d176Sdrh   }
47322dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree1);
47332dcef11bSdrh   sqlite3ReleaseTempReg(pParse, regFree2);
4734cce7d176Sdrh }
47352282792aSdrh 
47362282792aSdrh /*
473772bc8208Sdrh ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
473872bc8208Sdrh ** code generation, and that copy is deleted after code generation. This
473972bc8208Sdrh ** ensures that the original pExpr is unchanged.
474072bc8208Sdrh */
474172bc8208Sdrh void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
474272bc8208Sdrh   sqlite3 *db = pParse->db;
474372bc8208Sdrh   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
474472bc8208Sdrh   if( db->mallocFailed==0 ){
474572bc8208Sdrh     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
474672bc8208Sdrh   }
474772bc8208Sdrh   sqlite3ExprDelete(db, pCopy);
474872bc8208Sdrh }
474972bc8208Sdrh 
47505aa550cfSdan /*
47515aa550cfSdan ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
47525aa550cfSdan ** type of expression.
47535aa550cfSdan **
47545aa550cfSdan ** If pExpr is a simple SQL value - an integer, real, string, blob
47555aa550cfSdan ** or NULL value - then the VDBE currently being prepared is configured
47565aa550cfSdan ** to re-prepare each time a new value is bound to variable pVar.
47575aa550cfSdan **
47585aa550cfSdan ** Additionally, if pExpr is a simple SQL value and the value is the
47595aa550cfSdan ** same as that currently bound to variable pVar, non-zero is returned.
47605aa550cfSdan ** Otherwise, if the values are not the same or if pExpr is not a simple
47615aa550cfSdan ** SQL value, zero is returned.
47625aa550cfSdan */
47635aa550cfSdan static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
47645aa550cfSdan   int res = 0;
4765c0804226Sdrh   int iVar;
4766c0804226Sdrh   sqlite3_value *pL, *pR = 0;
47675aa550cfSdan 
47685aa550cfSdan   sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
4769c0804226Sdrh   if( pR ){
4770c0804226Sdrh     iVar = pVar->iColumn;
4771c0804226Sdrh     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
4772c0804226Sdrh     pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
47735aa307e2Sdrh     if( pL ){
47745aa307e2Sdrh       if( sqlite3_value_type(pL)==SQLITE_TEXT ){
47755aa307e2Sdrh         sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
47765aa307e2Sdrh       }
47775aa307e2Sdrh       res =  0==sqlite3MemCompare(pL, pR, 0);
47785aa550cfSdan     }
47795aa550cfSdan     sqlite3ValueFree(pR);
47805aa550cfSdan     sqlite3ValueFree(pL);
47815aa550cfSdan   }
47825aa550cfSdan 
47835aa550cfSdan   return res;
47845aa550cfSdan }
478572bc8208Sdrh 
478672bc8208Sdrh /*
47871d9da70aSdrh ** Do a deep comparison of two expression trees.  Return 0 if the two
47881d9da70aSdrh ** expressions are completely identical.  Return 1 if they differ only
47891d9da70aSdrh ** by a COLLATE operator at the top level.  Return 2 if there are differences
47901d9da70aSdrh ** other than the top-level COLLATE operator.
4791d40aab0eSdrh **
4792619a1305Sdrh ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4793619a1305Sdrh ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4794619a1305Sdrh **
479566518ca7Sdrh ** The pA side might be using TK_REGISTER.  If that is the case and pB is
479666518ca7Sdrh ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
479766518ca7Sdrh **
47981d9da70aSdrh ** Sometimes this routine will return 2 even if the two expressions
4799d40aab0eSdrh ** really are equivalent.  If we cannot prove that the expressions are
48001d9da70aSdrh ** identical, we return 2 just to be safe.  So if this routine
48011d9da70aSdrh ** returns 2, then you do not really know for certain if the two
48021d9da70aSdrh ** expressions are the same.  But if you get a 0 or 1 return, then you
4803d40aab0eSdrh ** can be sure the expressions are the same.  In the places where
48041d9da70aSdrh ** this routine is used, it does not hurt to get an extra 2 - that
4805d40aab0eSdrh ** just might result in some slightly slower code.  But returning
48061d9da70aSdrh ** an incorrect 0 or 1 could lead to a malfunction.
48075aa550cfSdan **
4808c0804226Sdrh ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
4809c0804226Sdrh ** pParse->pReprepare can be matched against literals in pB.  The
4810c0804226Sdrh ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
4811c0804226Sdrh ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
4812c0804226Sdrh ** Argument pParse should normally be NULL. If it is not NULL and pA or
4813c0804226Sdrh ** pB causes a return value of 2.
48142282792aSdrh */
48155aa550cfSdan int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
481610d1edf0Sdrh   u32 combinedFlags;
48174b202ae2Sdanielk1977   if( pA==0 || pB==0 ){
48181d9da70aSdrh     return pB==pA ? 0 : 2;
48192282792aSdrh   }
48205aa550cfSdan   if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
48215aa550cfSdan     return 0;
48225aa550cfSdan   }
482310d1edf0Sdrh   combinedFlags = pA->flags | pB->flags;
482410d1edf0Sdrh   if( combinedFlags & EP_IntValue ){
482510d1edf0Sdrh     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
482610d1edf0Sdrh       return 0;
482710d1edf0Sdrh     }
48281d9da70aSdrh     return 2;
48296ab3a2ecSdanielk1977   }
483016dd3985Sdan   if( pA->op!=pB->op || pA->op==TK_RAISE ){
48315aa550cfSdan     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
4832ae80ddeaSdrh       return 1;
4833ae80ddeaSdrh     }
48345aa550cfSdan     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
4835ae80ddeaSdrh       return 1;
4836ae80ddeaSdrh     }
4837ae80ddeaSdrh     return 2;
4838ae80ddeaSdrh   }
48392edc5fd7Sdrh   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
4840390b88a4Sdrh     if( pA->op==TK_FUNCTION ){
4841390b88a4Sdrh       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4842eda079cdSdrh #ifndef SQLITE_OMIT_WINDOWFUNC
4843eda079cdSdrh       /* Justification for the assert():
4844eda079cdSdrh       ** window functions have p->op==TK_FUNCTION but aggregate functions
4845eda079cdSdrh       ** have p->op==TK_AGG_FUNCTION.  So any comparison between an aggregate
4846eda079cdSdrh       ** function and a window function should have failed before reaching
4847eda079cdSdrh       ** this point.  And, it is not possible to have a window function and
4848eda079cdSdrh       ** a scalar function with the same name and number of arguments.  So
4849eda079cdSdrh       ** if we reach this point, either A and B both window functions or
4850eda079cdSdrh       ** neither are a window functions. */
4851eda079cdSdrh       assert( ExprHasProperty(pA,EP_WinFunc)==ExprHasProperty(pB,EP_WinFunc) );
4852eda079cdSdrh       if( ExprHasProperty(pA,EP_WinFunc) ){
4853eda079cdSdrh         if( sqlite3WindowCompare(pParse,pA->y.pWin,pB->y.pWin)!=0 ) return 2;
4854eda079cdSdrh       }
4855eda079cdSdrh #endif
4856f20bbc5fSdrh     }else if( pA->op==TK_NULL ){
4857f20bbc5fSdrh       return 0;
4858d5af5420Sdrh     }else if( pA->op==TK_COLLATE ){
4859e79f6299Sdrh       if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4860f20bbc5fSdrh     }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
4861d5af5420Sdrh       return 2;
486210d1edf0Sdrh     }
486310d1edf0Sdrh   }
486410d1edf0Sdrh   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
486589b6de03Sdrh   if( (combinedFlags & EP_TokenOnly)==0 ){
486610d1edf0Sdrh     if( combinedFlags & EP_xIsSelect ) return 2;
4867efad2e23Sdrh     if( (combinedFlags & EP_FixedCol)==0
4868efad2e23Sdrh      && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
48695aa550cfSdan     if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
4870619a1305Sdrh     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
487103c5c213Sdrh     if( pA->op!=TK_STRING
487203c5c213Sdrh      && pA->op!=TK_TRUEFALSE
487303c5c213Sdrh      && (combinedFlags & EP_Reduced)==0
487403c5c213Sdrh     ){
4875619a1305Sdrh       if( pA->iColumn!=pB->iColumn ) return 2;
48768ac02a94Sdan       if( pA->op2!=pB->op2 ) return 2;
487766518ca7Sdrh       if( pA->iTable!=pB->iTable
487885f8aa79Sdrh        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
48791d9da70aSdrh     }
48801d9da70aSdrh   }
48812646da7eSdrh   return 0;
48822646da7eSdrh }
48832282792aSdrh 
48848c6f666bSdrh /*
48858c6f666bSdrh ** Compare two ExprList objects.  Return 0 if they are identical and
48868c6f666bSdrh ** non-zero if they differ in any way.
48878c6f666bSdrh **
4888619a1305Sdrh ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4889619a1305Sdrh ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4890619a1305Sdrh **
48918c6f666bSdrh ** This routine might return non-zero for equivalent ExprLists.  The
48928c6f666bSdrh ** only consequence will be disabled optimizations.  But this routine
48938c6f666bSdrh ** must never return 0 if the two ExprList objects are different, or
48948c6f666bSdrh ** a malfunction will result.
48958c6f666bSdrh **
48968c6f666bSdrh ** Two NULL pointers are considered to be the same.  But a NULL pointer
48978c6f666bSdrh ** always differs from a non-NULL pointer.
48988c6f666bSdrh */
4899619a1305Sdrh int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
49008c6f666bSdrh   int i;
49018c6f666bSdrh   if( pA==0 && pB==0 ) return 0;
49028c6f666bSdrh   if( pA==0 || pB==0 ) return 1;
49038c6f666bSdrh   if( pA->nExpr!=pB->nExpr ) return 1;
49048c6f666bSdrh   for(i=0; i<pA->nExpr; i++){
49058c6f666bSdrh     Expr *pExprA = pA->a[i].pExpr;
49068c6f666bSdrh     Expr *pExprB = pB->a[i].pExpr;
49078c6f666bSdrh     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
49085aa550cfSdan     if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
49098c6f666bSdrh   }
49108c6f666bSdrh   return 0;
49118c6f666bSdrh }
491213449892Sdrh 
49132282792aSdrh /*
4914f9463dfbSdrh ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
4915f9463dfbSdrh ** are ignored.
4916f9463dfbSdrh */
4917f9463dfbSdrh int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
49185aa550cfSdan   return sqlite3ExprCompare(0,
4919f9463dfbSdrh              sqlite3ExprSkipCollate(pA),
4920f9463dfbSdrh              sqlite3ExprSkipCollate(pB),
4921f9463dfbSdrh              iTab);
4922f9463dfbSdrh }
4923f9463dfbSdrh 
4924f9463dfbSdrh /*
4925c51cf864Sdrh ** Return non-zero if Expr p can only be true if pNN is not NULL.
4926c51cf864Sdrh */
4927c51cf864Sdrh static int exprImpliesNotNull(
4928c51cf864Sdrh   Parse *pParse,      /* Parsing context */
4929c51cf864Sdrh   Expr *p,            /* The expression to be checked */
4930c51cf864Sdrh   Expr *pNN,          /* The expression that is NOT NULL */
4931c51cf864Sdrh   int iTab,           /* Table being evaluated */
4932c51cf864Sdrh   int seenNot         /* True if p is an operand of NOT */
4933c51cf864Sdrh ){
4934c51cf864Sdrh   assert( p );
4935c51cf864Sdrh   assert( pNN );
4936c51cf864Sdrh   if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ) return 1;
4937c51cf864Sdrh   switch( p->op ){
4938c51cf864Sdrh     case TK_IN: {
4939c51cf864Sdrh       if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
4940c51cf864Sdrh       assert( ExprHasProperty(p,EP_xIsSelect)
4941c51cf864Sdrh            || (p->x.pList!=0 && p->x.pList->nExpr>0) );
4942c51cf864Sdrh       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
4943c51cf864Sdrh     }
4944c51cf864Sdrh     case TK_BETWEEN: {
4945c51cf864Sdrh       ExprList *pList = p->x.pList;
4946c51cf864Sdrh       assert( pList!=0 );
4947c51cf864Sdrh       assert( pList->nExpr==2 );
4948c51cf864Sdrh       if( seenNot ) return 0;
4949c51cf864Sdrh       if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, seenNot)
4950c51cf864Sdrh        || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, seenNot)
4951c51cf864Sdrh       ){
4952c51cf864Sdrh         return 1;
4953c51cf864Sdrh       }
4954c51cf864Sdrh       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
4955c51cf864Sdrh     }
4956c51cf864Sdrh     case TK_EQ:
4957c51cf864Sdrh     case TK_NE:
4958c51cf864Sdrh     case TK_LT:
4959c51cf864Sdrh     case TK_LE:
4960c51cf864Sdrh     case TK_GT:
4961c51cf864Sdrh     case TK_GE:
4962c51cf864Sdrh     case TK_PLUS:
4963c51cf864Sdrh     case TK_MINUS:
4964c51cf864Sdrh     case TK_STAR:
4965c51cf864Sdrh     case TK_REM:
4966c51cf864Sdrh     case TK_BITAND:
4967c51cf864Sdrh     case TK_BITOR:
4968c51cf864Sdrh     case TK_SLASH:
4969c51cf864Sdrh     case TK_LSHIFT:
4970c51cf864Sdrh     case TK_RSHIFT:
4971c51cf864Sdrh     case TK_CONCAT: {
4972c51cf864Sdrh       if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
4973c51cf864Sdrh       /* Fall thru into the next case */
4974c51cf864Sdrh     }
4975c51cf864Sdrh     case TK_SPAN:
4976c51cf864Sdrh     case TK_COLLATE:
4977c51cf864Sdrh     case TK_BITNOT:
4978c51cf864Sdrh     case TK_UPLUS:
4979c51cf864Sdrh     case TK_UMINUS: {
4980c51cf864Sdrh       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
4981c51cf864Sdrh     }
4982c51cf864Sdrh     case TK_TRUTH: {
4983c51cf864Sdrh       if( seenNot ) return 0;
4984c51cf864Sdrh       if( p->op2!=TK_IS ) return 0;
4985c51cf864Sdrh       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
4986c51cf864Sdrh     }
4987c51cf864Sdrh     case TK_NOT: {
4988c51cf864Sdrh       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
4989c51cf864Sdrh     }
4990c51cf864Sdrh   }
4991c51cf864Sdrh   return 0;
4992c51cf864Sdrh }
4993c51cf864Sdrh 
4994c51cf864Sdrh /*
49954bd5f73fSdrh ** Return true if we can prove the pE2 will always be true if pE1 is
49964bd5f73fSdrh ** true.  Return false if we cannot complete the proof or if pE2 might
49974bd5f73fSdrh ** be false.  Examples:
49984bd5f73fSdrh **
4999619a1305Sdrh **     pE1: x==5       pE2: x==5             Result: true
50004bd5f73fSdrh **     pE1: x>0        pE2: x==5             Result: false
5001619a1305Sdrh **     pE1: x=21       pE2: x=21 OR y=43     Result: true
50024bd5f73fSdrh **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
5003619a1305Sdrh **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
5004619a1305Sdrh **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
5005619a1305Sdrh **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
50064bd5f73fSdrh **
50074bd5f73fSdrh ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
50084bd5f73fSdrh ** Expr.iTable<0 then assume a table number given by iTab.
50094bd5f73fSdrh **
5010c0804226Sdrh ** If pParse is not NULL, then the values of bound variables in pE1 are
5011c0804226Sdrh ** compared against literal values in pE2 and pParse->pVdbe->expmask is
5012c0804226Sdrh ** modified to record which bound variables are referenced.  If pParse
5013c0804226Sdrh ** is NULL, then false will be returned if pE1 contains any bound variables.
5014c0804226Sdrh **
50154bd5f73fSdrh ** When in doubt, return false.  Returning true might give a performance
50164bd5f73fSdrh ** improvement.  Returning false might cause a performance reduction, but
50174bd5f73fSdrh ** it will always give the correct answer and is hence always safe.
50184bd5f73fSdrh */
50195aa550cfSdan int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
50205aa550cfSdan   if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
5021619a1305Sdrh     return 1;
5022619a1305Sdrh   }
5023619a1305Sdrh   if( pE2->op==TK_OR
50245aa550cfSdan    && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
50255aa550cfSdan              || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
5026619a1305Sdrh   ){
5027619a1305Sdrh     return 1;
5028619a1305Sdrh   }
5029664d6d13Sdrh   if( pE2->op==TK_NOTNULL
5030c51cf864Sdrh    && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
5031664d6d13Sdrh   ){
5032c51cf864Sdrh     return 1;
5033619a1305Sdrh   }
5034619a1305Sdrh   return 0;
50354bd5f73fSdrh }
50364bd5f73fSdrh 
50374bd5f73fSdrh /*
50382589787cSdrh ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
50392589787cSdrh ** If the expression node requires that the table at pWalker->iCur
5040f8937f90Sdrh ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
5041f8937f90Sdrh **
5042f8937f90Sdrh ** This routine controls an optimization.  False positives (setting
5043f8937f90Sdrh ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
5044f8937f90Sdrh ** (never setting pWalker->eCode) is a harmless missed optimization.
50452589787cSdrh */
50462589787cSdrh static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
5047f8937f90Sdrh   testcase( pExpr->op==TK_AGG_COLUMN );
5048821b610bSdrh   testcase( pExpr->op==TK_AGG_FUNCTION );
50492589787cSdrh   if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
50502589787cSdrh   switch( pExpr->op ){
50510493222fSdan     case TK_ISNOT:
5052a1054dccSdan     case TK_NOT:
50532589787cSdrh     case TK_ISNULL:
5054d5793672Sdrh     case TK_NOTNULL:
50552589787cSdrh     case TK_IS:
50562589787cSdrh     case TK_OR:
50572c492061Sdrh     case TK_CASE:
5058e3eff266Sdrh     case TK_IN:
50592589787cSdrh     case TK_FUNCTION:
50600493222fSdan       testcase( pExpr->op==TK_ISNOT );
50610493222fSdan       testcase( pExpr->op==TK_NOT );
5062821b610bSdrh       testcase( pExpr->op==TK_ISNULL );
5063d5793672Sdrh       testcase( pExpr->op==TK_NOTNULL );
5064821b610bSdrh       testcase( pExpr->op==TK_IS );
5065821b610bSdrh       testcase( pExpr->op==TK_OR );
5066821b610bSdrh       testcase( pExpr->op==TK_CASE );
5067821b610bSdrh       testcase( pExpr->op==TK_IN );
5068821b610bSdrh       testcase( pExpr->op==TK_FUNCTION );
50692589787cSdrh       return WRC_Prune;
50702589787cSdrh     case TK_COLUMN:
50712589787cSdrh       if( pWalker->u.iCur==pExpr->iTable ){
50722589787cSdrh         pWalker->eCode = 1;
50732589787cSdrh         return WRC_Abort;
50742589787cSdrh       }
50752589787cSdrh       return WRC_Prune;
50769881155dSdrh 
50779881155dSdrh     /* Virtual tables are allowed to use constraints like x=NULL.  So
50789881155dSdrh     ** a term of the form x=y does not prove that y is not null if x
50799881155dSdrh     ** is the column of a virtual table */
50809881155dSdrh     case TK_EQ:
50819881155dSdrh     case TK_NE:
50829881155dSdrh     case TK_LT:
50839881155dSdrh     case TK_LE:
50849881155dSdrh     case TK_GT:
50859881155dSdrh     case TK_GE:
50869881155dSdrh       testcase( pExpr->op==TK_EQ );
50879881155dSdrh       testcase( pExpr->op==TK_NE );
50889881155dSdrh       testcase( pExpr->op==TK_LT );
50899881155dSdrh       testcase( pExpr->op==TK_LE );
50909881155dSdrh       testcase( pExpr->op==TK_GT );
50919881155dSdrh       testcase( pExpr->op==TK_GE );
5092eda079cdSdrh       if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
5093eda079cdSdrh        || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
50949881155dSdrh       ){
50959881155dSdrh        return WRC_Prune;
50969881155dSdrh       }
50972589787cSdrh     default:
50982589787cSdrh       return WRC_Continue;
50992589787cSdrh   }
51002589787cSdrh }
51012589787cSdrh 
51022589787cSdrh /*
51032589787cSdrh ** Return true (non-zero) if expression p can only be true if at least
51042589787cSdrh ** one column of table iTab is non-null.  In other words, return true
51052589787cSdrh ** if expression p will always be NULL or false if every column of iTab
51062589787cSdrh ** is NULL.
51072589787cSdrh **
5108821b610bSdrh ** False negatives are acceptable.  In other words, it is ok to return
5109821b610bSdrh ** zero even if expression p will never be true of every column of iTab
5110821b610bSdrh ** is NULL.  A false negative is merely a missed optimization opportunity.
5111821b610bSdrh **
5112821b610bSdrh ** False positives are not allowed, however.  A false positive may result
5113821b610bSdrh ** in an incorrect answer.
5114821b610bSdrh **
51152589787cSdrh ** Terms of p that are marked with EP_FromJoin (and hence that come from
51162589787cSdrh ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
51172589787cSdrh **
51182589787cSdrh ** This routine is used to check if a LEFT JOIN can be converted into
51192589787cSdrh ** an ordinary JOIN.  The p argument is the WHERE clause.  If the WHERE
51202589787cSdrh ** clause requires that some column of the right table of the LEFT JOIN
51212589787cSdrh ** be non-NULL, then the LEFT JOIN can be safely converted into an
51222589787cSdrh ** ordinary join.
51232589787cSdrh */
51242589787cSdrh int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
51252589787cSdrh   Walker w;
5126d6db6598Sdrh   p = sqlite3ExprSkipCollate(p);
5127d6db6598Sdrh   while( p ){
5128d6db6598Sdrh     if( p->op==TK_NOTNULL ){
5129d6db6598Sdrh       p = p->pLeft;
5130d6db6598Sdrh     }else if( p->op==TK_AND ){
5131d6db6598Sdrh       if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
5132d6db6598Sdrh       p = p->pRight;
5133d6db6598Sdrh     }else{
5134d6db6598Sdrh       break;
5135d6db6598Sdrh     }
5136d6db6598Sdrh   }
51372589787cSdrh   w.xExprCallback = impliesNotNullRow;
51382589787cSdrh   w.xSelectCallback = 0;
51392589787cSdrh   w.xSelectCallback2 = 0;
51402589787cSdrh   w.eCode = 0;
51412589787cSdrh   w.u.iCur = iTab;
51422589787cSdrh   sqlite3WalkExpr(&w, p);
51432589787cSdrh   return w.eCode;
51442589787cSdrh }
51452589787cSdrh 
51462589787cSdrh /*
5147030796dfSdrh ** An instance of the following structure is used by the tree walker
51482409f8a1Sdrh ** to determine if an expression can be evaluated by reference to the
51492409f8a1Sdrh ** index only, without having to do a search for the corresponding
51502409f8a1Sdrh ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
51512409f8a1Sdrh ** is the cursor for the table.
51522409f8a1Sdrh */
51532409f8a1Sdrh struct IdxCover {
51542409f8a1Sdrh   Index *pIdx;     /* The index to be tested for coverage */
51552409f8a1Sdrh   int iCur;        /* Cursor number for the table corresponding to the index */
51562409f8a1Sdrh };
51572409f8a1Sdrh 
51582409f8a1Sdrh /*
51592409f8a1Sdrh ** Check to see if there are references to columns in table
51602409f8a1Sdrh ** pWalker->u.pIdxCover->iCur can be satisfied using the index
51612409f8a1Sdrh ** pWalker->u.pIdxCover->pIdx.
51622409f8a1Sdrh */
51632409f8a1Sdrh static int exprIdxCover(Walker *pWalker, Expr *pExpr){
51642409f8a1Sdrh   if( pExpr->op==TK_COLUMN
51652409f8a1Sdrh    && pExpr->iTable==pWalker->u.pIdxCover->iCur
51662409f8a1Sdrh    && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
51672409f8a1Sdrh   ){
51682409f8a1Sdrh     pWalker->eCode = 1;
51692409f8a1Sdrh     return WRC_Abort;
51702409f8a1Sdrh   }
51712409f8a1Sdrh   return WRC_Continue;
51722409f8a1Sdrh }
51732409f8a1Sdrh 
51742409f8a1Sdrh /*
5175e604ec0bSdrh ** Determine if an index pIdx on table with cursor iCur contains will
5176e604ec0bSdrh ** the expression pExpr.  Return true if the index does cover the
5177e604ec0bSdrh ** expression and false if the pExpr expression references table columns
5178e604ec0bSdrh ** that are not found in the index pIdx.
51792409f8a1Sdrh **
51802409f8a1Sdrh ** An index covering an expression means that the expression can be
51812409f8a1Sdrh ** evaluated using only the index and without having to lookup the
51822409f8a1Sdrh ** corresponding table entry.
51832409f8a1Sdrh */
51842409f8a1Sdrh int sqlite3ExprCoveredByIndex(
51852409f8a1Sdrh   Expr *pExpr,        /* The index to be tested */
51862409f8a1Sdrh   int iCur,           /* The cursor number for the corresponding table */
51872409f8a1Sdrh   Index *pIdx         /* The index that might be used for coverage */
51882409f8a1Sdrh ){
51892409f8a1Sdrh   Walker w;
51902409f8a1Sdrh   struct IdxCover xcov;
51912409f8a1Sdrh   memset(&w, 0, sizeof(w));
51922409f8a1Sdrh   xcov.iCur = iCur;
51932409f8a1Sdrh   xcov.pIdx = pIdx;
51942409f8a1Sdrh   w.xExprCallback = exprIdxCover;
51952409f8a1Sdrh   w.u.pIdxCover = &xcov;
51962409f8a1Sdrh   sqlite3WalkExpr(&w, pExpr);
51972409f8a1Sdrh   return !w.eCode;
51982409f8a1Sdrh }
51992409f8a1Sdrh 
52002409f8a1Sdrh 
52012409f8a1Sdrh /*
52022409f8a1Sdrh ** An instance of the following structure is used by the tree walker
5203030796dfSdrh ** to count references to table columns in the arguments of an
5204ed551b95Sdrh ** aggregate function, in order to implement the
5205ed551b95Sdrh ** sqlite3FunctionThisSrc() routine.
5206374fdce4Sdrh */
5207030796dfSdrh struct SrcCount {
5208030796dfSdrh   SrcList *pSrc;   /* One particular FROM clause in a nested query */
5209030796dfSdrh   int nThis;       /* Number of references to columns in pSrcList */
5210030796dfSdrh   int nOther;      /* Number of references to columns in other FROM clauses */
5211030796dfSdrh };
5212030796dfSdrh 
5213030796dfSdrh /*
5214030796dfSdrh ** Count the number of references to columns.
5215030796dfSdrh */
5216030796dfSdrh static int exprSrcCount(Walker *pWalker, Expr *pExpr){
5217fb0a6081Sdrh   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
5218fb0a6081Sdrh   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
5219fb0a6081Sdrh   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
5220fb0a6081Sdrh   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
5221fb0a6081Sdrh   ** NEVER() will need to be removed. */
5222fb0a6081Sdrh   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
5223374fdce4Sdrh     int i;
5224030796dfSdrh     struct SrcCount *p = pWalker->u.pSrcCount;
5225030796dfSdrh     SrcList *pSrc = p->pSrc;
5226655814d2Sdrh     int nSrc = pSrc ? pSrc->nSrc : 0;
5227655814d2Sdrh     for(i=0; i<nSrc; i++){
5228030796dfSdrh       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
5229374fdce4Sdrh     }
5230655814d2Sdrh     if( i<nSrc ){
5231030796dfSdrh       p->nThis++;
5232374fdce4Sdrh     }else{
5233030796dfSdrh       p->nOther++;
5234374fdce4Sdrh     }
5235374fdce4Sdrh   }
5236030796dfSdrh   return WRC_Continue;
5237030796dfSdrh }
5238374fdce4Sdrh 
5239374fdce4Sdrh /*
5240030796dfSdrh ** Determine if any of the arguments to the pExpr Function reference
5241030796dfSdrh ** pSrcList.  Return true if they do.  Also return true if the function
5242030796dfSdrh ** has no arguments or has only constant arguments.  Return false if pExpr
5243030796dfSdrh ** references columns but not columns of tables found in pSrcList.
5244374fdce4Sdrh */
5245030796dfSdrh int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
5246374fdce4Sdrh   Walker w;
5247030796dfSdrh   struct SrcCount cnt;
5248374fdce4Sdrh   assert( pExpr->op==TK_AGG_FUNCTION );
5249030796dfSdrh   w.xExprCallback = exprSrcCount;
5250979dd1beSdrh   w.xSelectCallback = 0;
5251030796dfSdrh   w.u.pSrcCount = &cnt;
5252030796dfSdrh   cnt.pSrc = pSrcList;
5253030796dfSdrh   cnt.nThis = 0;
5254030796dfSdrh   cnt.nOther = 0;
5255030796dfSdrh   sqlite3WalkExprList(&w, pExpr->x.pList);
5256030796dfSdrh   return cnt.nThis>0 || cnt.nOther==0;
5257374fdce4Sdrh }
5258374fdce4Sdrh 
5259374fdce4Sdrh /*
526013449892Sdrh ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
526113449892Sdrh ** the new element.  Return a negative number if malloc fails.
52622282792aSdrh */
526317435752Sdrh static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
526413449892Sdrh   int i;
5265cf643729Sdrh   pInfo->aCol = sqlite3ArrayAllocate(
526617435752Sdrh        db,
5267cf643729Sdrh        pInfo->aCol,
5268cf643729Sdrh        sizeof(pInfo->aCol[0]),
5269cf643729Sdrh        &pInfo->nColumn,
5270cf643729Sdrh        &i
5271cf643729Sdrh   );
527213449892Sdrh   return i;
52732282792aSdrh }
527413449892Sdrh 
527513449892Sdrh /*
527613449892Sdrh ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
527713449892Sdrh ** the new element.  Return a negative number if malloc fails.
527813449892Sdrh */
527917435752Sdrh static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
528013449892Sdrh   int i;
5281cf643729Sdrh   pInfo->aFunc = sqlite3ArrayAllocate(
528217435752Sdrh        db,
5283cf643729Sdrh        pInfo->aFunc,
5284cf643729Sdrh        sizeof(pInfo->aFunc[0]),
5285cf643729Sdrh        &pInfo->nFunc,
5286cf643729Sdrh        &i
5287cf643729Sdrh   );
528813449892Sdrh   return i;
52892282792aSdrh }
52902282792aSdrh 
52912282792aSdrh /*
52927d10d5a6Sdrh ** This is the xExprCallback for a tree walker.  It is used to
52937d10d5a6Sdrh ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
5294626a879aSdrh ** for additional information.
52952282792aSdrh */
52967d10d5a6Sdrh static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
52972282792aSdrh   int i;
52987d10d5a6Sdrh   NameContext *pNC = pWalker->u.pNC;
5299a58fdfb1Sdanielk1977   Parse *pParse = pNC->pParse;
5300a58fdfb1Sdanielk1977   SrcList *pSrcList = pNC->pSrcList;
530125c3b8caSdrh   AggInfo *pAggInfo = pNC->uNC.pAggInfo;
530213449892Sdrh 
530325c3b8caSdrh   assert( pNC->ncFlags & NC_UAggInfo );
53042282792aSdrh   switch( pExpr->op ){
530589c69d00Sdrh     case TK_AGG_COLUMN:
5306967e8b73Sdrh     case TK_COLUMN: {
53078b213899Sdrh       testcase( pExpr->op==TK_AGG_COLUMN );
53088b213899Sdrh       testcase( pExpr->op==TK_COLUMN );
530913449892Sdrh       /* Check to see if the column is in one of the tables in the FROM
531013449892Sdrh       ** clause of the aggregate query */
531120bc393cSdrh       if( ALWAYS(pSrcList!=0) ){
531213449892Sdrh         struct SrcList_item *pItem = pSrcList->a;
531313449892Sdrh         for(i=0; i<pSrcList->nSrc; i++, pItem++){
531413449892Sdrh           struct AggInfo_col *pCol;
5315c5cd1249Sdrh           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
531613449892Sdrh           if( pExpr->iTable==pItem->iCursor ){
531713449892Sdrh             /* If we reach this point, it means that pExpr refers to a table
531813449892Sdrh             ** that is in the FROM clause of the aggregate query.
531913449892Sdrh             **
532013449892Sdrh             ** Make an entry for the column in pAggInfo->aCol[] if there
532113449892Sdrh             ** is not an entry there already.
532213449892Sdrh             */
53237f906d63Sdrh             int k;
532413449892Sdrh             pCol = pAggInfo->aCol;
53257f906d63Sdrh             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
532613449892Sdrh               if( pCol->iTable==pExpr->iTable &&
532713449892Sdrh                   pCol->iColumn==pExpr->iColumn ){
53282282792aSdrh                 break;
53292282792aSdrh               }
53302282792aSdrh             }
53311e536953Sdanielk1977             if( (k>=pAggInfo->nColumn)
53321e536953Sdanielk1977              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
53331e536953Sdanielk1977             ){
53347f906d63Sdrh               pCol = &pAggInfo->aCol[k];
5335eda079cdSdrh               pCol->pTab = pExpr->y.pTab;
533613449892Sdrh               pCol->iTable = pExpr->iTable;
533713449892Sdrh               pCol->iColumn = pExpr->iColumn;
53380a07c107Sdrh               pCol->iMem = ++pParse->nMem;
533913449892Sdrh               pCol->iSorterColumn = -1;
53405774b806Sdrh               pCol->pExpr = pExpr;
534113449892Sdrh               if( pAggInfo->pGroupBy ){
534213449892Sdrh                 int j, n;
534313449892Sdrh                 ExprList *pGB = pAggInfo->pGroupBy;
534413449892Sdrh                 struct ExprList_item *pTerm = pGB->a;
534513449892Sdrh                 n = pGB->nExpr;
534613449892Sdrh                 for(j=0; j<n; j++, pTerm++){
534713449892Sdrh                   Expr *pE = pTerm->pExpr;
534813449892Sdrh                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
534913449892Sdrh                       pE->iColumn==pExpr->iColumn ){
535013449892Sdrh                     pCol->iSorterColumn = j;
535113449892Sdrh                     break;
53522282792aSdrh                   }
535313449892Sdrh                 }
535413449892Sdrh               }
535513449892Sdrh               if( pCol->iSorterColumn<0 ){
535613449892Sdrh                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
535713449892Sdrh               }
535813449892Sdrh             }
535913449892Sdrh             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
536013449892Sdrh             ** because it was there before or because we just created it).
536113449892Sdrh             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
536213449892Sdrh             ** pAggInfo->aCol[] entry.
536313449892Sdrh             */
5364ebb6a65dSdrh             ExprSetVVAProperty(pExpr, EP_NoReduce);
536513449892Sdrh             pExpr->pAggInfo = pAggInfo;
536613449892Sdrh             pExpr->op = TK_AGG_COLUMN;
5367cf697396Sshane             pExpr->iAgg = (i16)k;
536813449892Sdrh             break;
536913449892Sdrh           } /* endif pExpr->iTable==pItem->iCursor */
537013449892Sdrh         } /* end loop over pSrcList */
5371a58fdfb1Sdanielk1977       }
53727d10d5a6Sdrh       return WRC_Prune;
53732282792aSdrh     }
53742282792aSdrh     case TK_AGG_FUNCTION: {
53753a8c4be7Sdrh       if( (pNC->ncFlags & NC_InAggFunc)==0
5376ed551b95Sdrh        && pWalker->walkerDepth==pExpr->op2
53773a8c4be7Sdrh       ){
537813449892Sdrh         /* Check to see if pExpr is a duplicate of another aggregate
537913449892Sdrh         ** function that is already in the pAggInfo structure
538013449892Sdrh         */
538113449892Sdrh         struct AggInfo_func *pItem = pAggInfo->aFunc;
538213449892Sdrh         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
53835aa550cfSdan           if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
53842282792aSdrh             break;
53852282792aSdrh           }
53862282792aSdrh         }
538713449892Sdrh         if( i>=pAggInfo->nFunc ){
538813449892Sdrh           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
538913449892Sdrh           */
539014db2665Sdanielk1977           u8 enc = ENC(pParse->db);
53911e536953Sdanielk1977           i = addAggInfoFunc(pParse->db, pAggInfo);
539213449892Sdrh           if( i>=0 ){
53936ab3a2ecSdanielk1977             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
539413449892Sdrh             pItem = &pAggInfo->aFunc[i];
539513449892Sdrh             pItem->pExpr = pExpr;
53960a07c107Sdrh             pItem->iMem = ++pParse->nMem;
539733e619fcSdrh             assert( !ExprHasProperty(pExpr, EP_IntValue) );
539813449892Sdrh             pItem->pFunc = sqlite3FindFunction(pParse->db,
539980738d9cSdrh                    pExpr->u.zToken,
54006ab3a2ecSdanielk1977                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
5401fd357974Sdrh             if( pExpr->flags & EP_Distinct ){
5402fd357974Sdrh               pItem->iDistinct = pParse->nTab++;
5403fd357974Sdrh             }else{
5404fd357974Sdrh               pItem->iDistinct = -1;
5405fd357974Sdrh             }
54062282792aSdrh           }
540713449892Sdrh         }
540813449892Sdrh         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
540913449892Sdrh         */
5410c5cd1249Sdrh         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
5411ebb6a65dSdrh         ExprSetVVAProperty(pExpr, EP_NoReduce);
5412cf697396Sshane         pExpr->iAgg = (i16)i;
541313449892Sdrh         pExpr->pAggInfo = pAggInfo;
54143a8c4be7Sdrh         return WRC_Prune;
54156e83a57fSdrh       }else{
54166e83a57fSdrh         return WRC_Continue;
54176e83a57fSdrh       }
54182282792aSdrh     }
5419a58fdfb1Sdanielk1977   }
54207d10d5a6Sdrh   return WRC_Continue;
54217d10d5a6Sdrh }
54227d10d5a6Sdrh static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
5423d5a336efSdrh   UNUSED_PARAMETER(pSelect);
5424979dd1beSdrh   pWalker->walkerDepth++;
54257d10d5a6Sdrh   return WRC_Continue;
5426a58fdfb1Sdanielk1977 }
5427979dd1beSdrh static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
5428979dd1beSdrh   UNUSED_PARAMETER(pSelect);
5429979dd1beSdrh   pWalker->walkerDepth--;
5430979dd1beSdrh }
5431626a879aSdrh 
5432626a879aSdrh /*
5433e8abb4caSdrh ** Analyze the pExpr expression looking for aggregate functions and
5434e8abb4caSdrh ** for variables that need to be added to AggInfo object that pNC->pAggInfo
5435e8abb4caSdrh ** points to.  Additional entries are made on the AggInfo object as
5436e8abb4caSdrh ** necessary.
5437626a879aSdrh **
5438626a879aSdrh ** This routine should only be called after the expression has been
54397d10d5a6Sdrh ** analyzed by sqlite3ResolveExprNames().
5440626a879aSdrh */
5441d2b3e23bSdrh void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
54427d10d5a6Sdrh   Walker w;
54437d10d5a6Sdrh   w.xExprCallback = analyzeAggregate;
54447d10d5a6Sdrh   w.xSelectCallback = analyzeAggregatesInSelect;
5445979dd1beSdrh   w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
5446979dd1beSdrh   w.walkerDepth = 0;
54477d10d5a6Sdrh   w.u.pNC = pNC;
5448d9995031Sdan   w.pParse = 0;
544920bc393cSdrh   assert( pNC->pSrcList!=0 );
54507d10d5a6Sdrh   sqlite3WalkExpr(&w, pExpr);
54512282792aSdrh }
54525d9a4af9Sdrh 
54535d9a4af9Sdrh /*
54545d9a4af9Sdrh ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
54555d9a4af9Sdrh ** expression list.  Return the number of errors.
54565d9a4af9Sdrh **
54575d9a4af9Sdrh ** If an error is found, the analysis is cut short.
54585d9a4af9Sdrh */
5459d2b3e23bSdrh void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
54605d9a4af9Sdrh   struct ExprList_item *pItem;
54615d9a4af9Sdrh   int i;
54625d9a4af9Sdrh   if( pList ){
5463d2b3e23bSdrh     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
5464d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
54655d9a4af9Sdrh     }
54665d9a4af9Sdrh   }
54675d9a4af9Sdrh }
5468892d3179Sdrh 
5469892d3179Sdrh /*
5470ceea3321Sdrh ** Allocate a single new register for use to hold some intermediate result.
5471892d3179Sdrh */
5472892d3179Sdrh int sqlite3GetTempReg(Parse *pParse){
5473e55cbd72Sdrh   if( pParse->nTempReg==0 ){
5474892d3179Sdrh     return ++pParse->nMem;
5475892d3179Sdrh   }
54762f425f6bSdanielk1977   return pParse->aTempReg[--pParse->nTempReg];
5477892d3179Sdrh }
5478ceea3321Sdrh 
5479ceea3321Sdrh /*
5480ceea3321Sdrh ** Deallocate a register, making available for reuse for some other
5481ceea3321Sdrh ** purpose.
5482ceea3321Sdrh */
5483892d3179Sdrh void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
54842dcef11bSdrh   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
5485892d3179Sdrh     pParse->aTempReg[pParse->nTempReg++] = iReg;
5486892d3179Sdrh   }
5487892d3179Sdrh }
5488892d3179Sdrh 
5489892d3179Sdrh /*
5490ed24da4bSdrh ** Allocate or deallocate a block of nReg consecutive registers.
5491892d3179Sdrh */
5492892d3179Sdrh int sqlite3GetTempRange(Parse *pParse, int nReg){
5493e55cbd72Sdrh   int i, n;
5494ed24da4bSdrh   if( nReg==1 ) return sqlite3GetTempReg(pParse);
5495892d3179Sdrh   i = pParse->iRangeReg;
5496e55cbd72Sdrh   n = pParse->nRangeReg;
5497f49f3523Sdrh   if( nReg<=n ){
5498892d3179Sdrh     pParse->iRangeReg += nReg;
5499892d3179Sdrh     pParse->nRangeReg -= nReg;
5500892d3179Sdrh   }else{
5501892d3179Sdrh     i = pParse->nMem+1;
5502892d3179Sdrh     pParse->nMem += nReg;
5503892d3179Sdrh   }
5504892d3179Sdrh   return i;
5505892d3179Sdrh }
5506892d3179Sdrh void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
5507ed24da4bSdrh   if( nReg==1 ){
5508ed24da4bSdrh     sqlite3ReleaseTempReg(pParse, iReg);
5509ed24da4bSdrh     return;
5510ed24da4bSdrh   }
5511892d3179Sdrh   if( nReg>pParse->nRangeReg ){
5512892d3179Sdrh     pParse->nRangeReg = nReg;
5513892d3179Sdrh     pParse->iRangeReg = iReg;
5514892d3179Sdrh   }
5515892d3179Sdrh }
5516cdc69557Sdrh 
5517cdc69557Sdrh /*
5518cdc69557Sdrh ** Mark all temporary registers as being unavailable for reuse.
5519cdc69557Sdrh */
5520cdc69557Sdrh void sqlite3ClearTempRegCache(Parse *pParse){
5521cdc69557Sdrh   pParse->nTempReg = 0;
5522cdc69557Sdrh   pParse->nRangeReg = 0;
5523cdc69557Sdrh }
5524bb9b5f26Sdrh 
5525bb9b5f26Sdrh /*
5526bb9b5f26Sdrh ** Validate that no temporary register falls within the range of
5527bb9b5f26Sdrh ** iFirst..iLast, inclusive.  This routine is only call from within assert()
5528bb9b5f26Sdrh ** statements.
5529bb9b5f26Sdrh */
5530bb9b5f26Sdrh #ifdef SQLITE_DEBUG
5531bb9b5f26Sdrh int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
5532bb9b5f26Sdrh   int i;
5533bb9b5f26Sdrh   if( pParse->nRangeReg>0
55343963e584Sdrh    && pParse->iRangeReg+pParse->nRangeReg > iFirst
55353963e584Sdrh    && pParse->iRangeReg <= iLast
5536bb9b5f26Sdrh   ){
5537bb9b5f26Sdrh      return 0;
5538bb9b5f26Sdrh   }
5539bb9b5f26Sdrh   for(i=0; i<pParse->nTempReg; i++){
5540bb9b5f26Sdrh     if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
5541bb9b5f26Sdrh       return 0;
5542bb9b5f26Sdrh     }
5543bb9b5f26Sdrh   }
5544bb9b5f26Sdrh   return 1;
5545bb9b5f26Sdrh }
5546bb9b5f26Sdrh #endif /* SQLITE_DEBUG */
5547