1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
14 */
15 #include "sqliteInt.h"
16 
17 /* Forward declarations */
18 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
19 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
20 
21 /*
22 ** Return the affinity character for a single column of a table.
23 */
sqlite3TableColumnAffinity(Table * pTab,int iCol)24 char sqlite3TableColumnAffinity(Table *pTab, int iCol){
25   assert( iCol<pTab->nCol );
26   return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
27 }
28 
29 /*
30 ** Return the 'affinity' of the expression pExpr if any.
31 **
32 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33 ** or a sub-select with a column as the return value, then the
34 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35 ** indicating no affinity for the expression.
36 **
37 ** i.e. the WHERE clause expressions in the following statements all
38 ** have an affinity:
39 **
40 ** CREATE TABLE t1(a);
41 ** SELECT * FROM t1 WHERE a;
42 ** SELECT a AS b FROM t1 WHERE b;
43 ** SELECT * FROM t1 WHERE (select a from t1);
44 */
sqlite3ExprAffinity(Expr * pExpr)45 char sqlite3ExprAffinity(Expr *pExpr){
46   int op;
47   while( ExprHasProperty(pExpr, EP_Skip) ){
48     assert( pExpr->op==TK_COLLATE );
49     pExpr = pExpr->pLeft;
50     assert( pExpr!=0 );
51   }
52   op = pExpr->op;
53   if( op==TK_SELECT ){
54     assert( pExpr->flags&EP_xIsSelect );
55     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
56   }
57   if( op==TK_REGISTER ) op = pExpr->op2;
58 #ifndef SQLITE_OMIT_CAST
59   if( op==TK_CAST ){
60     assert( !ExprHasProperty(pExpr, EP_IntValue) );
61     return sqlite3AffinityType(pExpr->u.zToken, 0);
62   }
63 #endif
64   if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
65     return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
66   }
67   if( op==TK_SELECT_COLUMN ){
68     assert( pExpr->pLeft->flags&EP_xIsSelect );
69     return sqlite3ExprAffinity(
70         pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
71     );
72   }
73   if( op==TK_VECTOR ){
74     return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
75   }
76   return pExpr->affExpr;
77 }
78 
79 /*
80 ** Set the collating sequence for expression pExpr to be the collating
81 ** sequence named by pToken.   Return a pointer to a new Expr node that
82 ** implements the COLLATE operator.
83 **
84 ** If a memory allocation error occurs, that fact is recorded in pParse->db
85 ** and the pExpr parameter is returned unchanged.
86 */
sqlite3ExprAddCollateToken(Parse * pParse,Expr * pExpr,const Token * pCollName,int dequote)87 Expr *sqlite3ExprAddCollateToken(
88   Parse *pParse,           /* Parsing context */
89   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
90   const Token *pCollName,  /* Name of collating sequence */
91   int dequote              /* True to dequote pCollName */
92 ){
93   if( pCollName->n>0 ){
94     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
95     if( pNew ){
96       pNew->pLeft = pExpr;
97       pNew->flags |= EP_Collate|EP_Skip;
98       pExpr = pNew;
99     }
100   }
101   return pExpr;
102 }
sqlite3ExprAddCollateString(Parse * pParse,Expr * pExpr,const char * zC)103 Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
104   Token s;
105   assert( zC!=0 );
106   sqlite3TokenInit(&s, (char*)zC);
107   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
108 }
109 
110 /*
111 ** Skip over any TK_COLLATE operators.
112 */
sqlite3ExprSkipCollate(Expr * pExpr)113 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
114   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
115     assert( pExpr->op==TK_COLLATE );
116     pExpr = pExpr->pLeft;
117   }
118   return pExpr;
119 }
120 
121 /*
122 ** Skip over any TK_COLLATE operators and/or any unlikely()
123 ** or likelihood() or likely() functions at the root of an
124 ** expression.
125 */
sqlite3ExprSkipCollateAndLikely(Expr * pExpr)126 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
127   while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
128     if( ExprHasProperty(pExpr, EP_Unlikely) ){
129       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
130       assert( pExpr->x.pList->nExpr>0 );
131       assert( pExpr->op==TK_FUNCTION );
132       pExpr = pExpr->x.pList->a[0].pExpr;
133     }else{
134       assert( pExpr->op==TK_COLLATE );
135       pExpr = pExpr->pLeft;
136     }
137   }
138   return pExpr;
139 }
140 
141 /*
142 ** Return the collation sequence for the expression pExpr. If
143 ** there is no defined collating sequence, return NULL.
144 **
145 ** See also: sqlite3ExprNNCollSeq()
146 **
147 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
148 ** default collation if pExpr has no defined collation.
149 **
150 ** The collating sequence might be determined by a COLLATE operator
151 ** or by the presence of a column with a defined collating sequence.
152 ** COLLATE operators take first precedence.  Left operands take
153 ** precedence over right operands.
154 */
sqlite3ExprCollSeq(Parse * pParse,Expr * pExpr)155 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
156   sqlite3 *db = pParse->db;
157   CollSeq *pColl = 0;
158   Expr *p = pExpr;
159   while( p ){
160     int op = p->op;
161     if( op==TK_REGISTER ) op = p->op2;
162     if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
163      && p->y.pTab!=0
164     ){
165       /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
166       ** a TK_COLUMN but was previously evaluated and cached in a register */
167       int j = p->iColumn;
168       if( j>=0 ){
169         const char *zColl = p->y.pTab->aCol[j].zColl;
170         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
171       }
172       break;
173     }
174     if( op==TK_CAST || op==TK_UPLUS ){
175       p = p->pLeft;
176       continue;
177     }
178     if( op==TK_VECTOR ){
179       p = p->x.pList->a[0].pExpr;
180       continue;
181     }
182     if( op==TK_COLLATE ){
183       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
184       break;
185     }
186     if( p->flags & EP_Collate ){
187       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
188         p = p->pLeft;
189       }else{
190         Expr *pNext  = p->pRight;
191         /* The Expr.x union is never used at the same time as Expr.pRight */
192         assert( p->x.pList==0 || p->pRight==0 );
193         if( p->x.pList!=0
194          && !db->mallocFailed
195          && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
196         ){
197           int i;
198           for(i=0; i<p->x.pList->nExpr; i++){
199             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
200               pNext = p->x.pList->a[i].pExpr;
201               break;
202             }
203           }
204         }
205         p = pNext;
206       }
207     }else{
208       break;
209     }
210   }
211   if( sqlite3CheckCollSeq(pParse, pColl) ){
212     pColl = 0;
213   }
214   return pColl;
215 }
216 
217 /*
218 ** Return the collation sequence for the expression pExpr. If
219 ** there is no defined collating sequence, return a pointer to the
220 ** defautl collation sequence.
221 **
222 ** See also: sqlite3ExprCollSeq()
223 **
224 ** The sqlite3ExprCollSeq() routine works the same except that it
225 ** returns NULL if there is no defined collation.
226 */
sqlite3ExprNNCollSeq(Parse * pParse,Expr * pExpr)227 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
228   CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
229   if( p==0 ) p = pParse->db->pDfltColl;
230   assert( p!=0 );
231   return p;
232 }
233 
234 /*
235 ** Return TRUE if the two expressions have equivalent collating sequences.
236 */
sqlite3ExprCollSeqMatch(Parse * pParse,Expr * pE1,Expr * pE2)237 int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
238   CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
239   CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
240   return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
241 }
242 
243 /*
244 ** pExpr is an operand of a comparison operator.  aff2 is the
245 ** type affinity of the other operand.  This routine returns the
246 ** type affinity that should be used for the comparison operator.
247 */
sqlite3CompareAffinity(Expr * pExpr,char aff2)248 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
249   char aff1 = sqlite3ExprAffinity(pExpr);
250   if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
251     /* Both sides of the comparison are columns. If one has numeric
252     ** affinity, use that. Otherwise use no affinity.
253     */
254     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
255       return SQLITE_AFF_NUMERIC;
256     }else{
257       return SQLITE_AFF_BLOB;
258     }
259   }else{
260     /* One side is a column, the other is not. Use the columns affinity. */
261     assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
262     return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
263   }
264 }
265 
266 /*
267 ** pExpr is a comparison operator.  Return the type affinity that should
268 ** be applied to both operands prior to doing the comparison.
269 */
comparisonAffinity(Expr * pExpr)270 static char comparisonAffinity(Expr *pExpr){
271   char aff;
272   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
273           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
274           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
275   assert( pExpr->pLeft );
276   aff = sqlite3ExprAffinity(pExpr->pLeft);
277   if( pExpr->pRight ){
278     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
279   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
280     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
281   }else if( aff==0 ){
282     aff = SQLITE_AFF_BLOB;
283   }
284   return aff;
285 }
286 
287 /*
288 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
289 ** idx_affinity is the affinity of an indexed column. Return true
290 ** if the index with affinity idx_affinity may be used to implement
291 ** the comparison in pExpr.
292 */
sqlite3IndexAffinityOk(Expr * pExpr,char idx_affinity)293 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
294   char aff = comparisonAffinity(pExpr);
295   if( aff<SQLITE_AFF_TEXT ){
296     return 1;
297   }
298   if( aff==SQLITE_AFF_TEXT ){
299     return idx_affinity==SQLITE_AFF_TEXT;
300   }
301   return sqlite3IsNumericAffinity(idx_affinity);
302 }
303 
304 /*
305 ** Return the P5 value that should be used for a binary comparison
306 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
307 */
binaryCompareP5(Expr * pExpr1,Expr * pExpr2,int jumpIfNull)308 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
309   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
310   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
311   return aff;
312 }
313 
314 /*
315 ** Return a pointer to the collation sequence that should be used by
316 ** a binary comparison operator comparing pLeft and pRight.
317 **
318 ** If the left hand expression has a collating sequence type, then it is
319 ** used. Otherwise the collation sequence for the right hand expression
320 ** is used, or the default (BINARY) if neither expression has a collating
321 ** type.
322 **
323 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
324 ** it is not considered.
325 */
sqlite3BinaryCompareCollSeq(Parse * pParse,Expr * pLeft,Expr * pRight)326 CollSeq *sqlite3BinaryCompareCollSeq(
327   Parse *pParse,
328   Expr *pLeft,
329   Expr *pRight
330 ){
331   CollSeq *pColl;
332   assert( pLeft );
333   if( pLeft->flags & EP_Collate ){
334     pColl = sqlite3ExprCollSeq(pParse, pLeft);
335   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
336     pColl = sqlite3ExprCollSeq(pParse, pRight);
337   }else{
338     pColl = sqlite3ExprCollSeq(pParse, pLeft);
339     if( !pColl ){
340       pColl = sqlite3ExprCollSeq(pParse, pRight);
341     }
342   }
343   return pColl;
344 }
345 
346 /* Expresssion p is a comparison operator.  Return a collation sequence
347 ** appropriate for the comparison operator.
348 **
349 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
350 ** However, if the OP_Commuted flag is set, then the order of the operands
351 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
352 ** correct collating sequence is found.
353 */
sqlite3ExprCompareCollSeq(Parse * pParse,Expr * p)354 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, Expr *p){
355   if( ExprHasProperty(p, EP_Commuted) ){
356     return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
357   }else{
358     return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
359   }
360 }
361 
362 /*
363 ** Generate code for a comparison operator.
364 */
codeCompare(Parse * pParse,Expr * pLeft,Expr * pRight,int opcode,int in1,int in2,int dest,int jumpIfNull,int isCommuted)365 static int codeCompare(
366   Parse *pParse,    /* The parsing (and code generating) context */
367   Expr *pLeft,      /* The left operand */
368   Expr *pRight,     /* The right operand */
369   int opcode,       /* The comparison opcode */
370   int in1, int in2, /* Register holding operands */
371   int dest,         /* Jump here if true.  */
372   int jumpIfNull,   /* If true, jump if either operand is NULL */
373   int isCommuted    /* The comparison has been commuted */
374 ){
375   int p5;
376   int addr;
377   CollSeq *p4;
378 
379   if( pParse->nErr ) return 0;
380   if( isCommuted ){
381     p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
382   }else{
383     p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
384   }
385   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
386   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
387                            (void*)p4, P4_COLLSEQ);
388   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
389   return addr;
390 }
391 
392 /*
393 ** Return true if expression pExpr is a vector, or false otherwise.
394 **
395 ** A vector is defined as any expression that results in two or more
396 ** columns of result.  Every TK_VECTOR node is an vector because the
397 ** parser will not generate a TK_VECTOR with fewer than two entries.
398 ** But a TK_SELECT might be either a vector or a scalar. It is only
399 ** considered a vector if it has two or more result columns.
400 */
sqlite3ExprIsVector(Expr * pExpr)401 int sqlite3ExprIsVector(Expr *pExpr){
402   return sqlite3ExprVectorSize(pExpr)>1;
403 }
404 
405 /*
406 ** If the expression passed as the only argument is of type TK_VECTOR
407 ** return the number of expressions in the vector. Or, if the expression
408 ** is a sub-select, return the number of columns in the sub-select. For
409 ** any other type of expression, return 1.
410 */
sqlite3ExprVectorSize(Expr * pExpr)411 int sqlite3ExprVectorSize(Expr *pExpr){
412   u8 op = pExpr->op;
413   if( op==TK_REGISTER ) op = pExpr->op2;
414   if( op==TK_VECTOR ){
415     return pExpr->x.pList->nExpr;
416   }else if( op==TK_SELECT ){
417     return pExpr->x.pSelect->pEList->nExpr;
418   }else{
419     return 1;
420   }
421 }
422 
423 /*
424 ** Return a pointer to a subexpression of pVector that is the i-th
425 ** column of the vector (numbered starting with 0).  The caller must
426 ** ensure that i is within range.
427 **
428 ** If pVector is really a scalar (and "scalar" here includes subqueries
429 ** that return a single column!) then return pVector unmodified.
430 **
431 ** pVector retains ownership of the returned subexpression.
432 **
433 ** If the vector is a (SELECT ...) then the expression returned is
434 ** just the expression for the i-th term of the result set, and may
435 ** not be ready for evaluation because the table cursor has not yet
436 ** been positioned.
437 */
sqlite3VectorFieldSubexpr(Expr * pVector,int i)438 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
439   assert( i<sqlite3ExprVectorSize(pVector) );
440   if( sqlite3ExprIsVector(pVector) ){
441     assert( pVector->op2==0 || pVector->op==TK_REGISTER );
442     if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
443       return pVector->x.pSelect->pEList->a[i].pExpr;
444     }else{
445       return pVector->x.pList->a[i].pExpr;
446     }
447   }
448   return pVector;
449 }
450 
451 /*
452 ** Compute and return a new Expr object which when passed to
453 ** sqlite3ExprCode() will generate all necessary code to compute
454 ** the iField-th column of the vector expression pVector.
455 **
456 ** It is ok for pVector to be a scalar (as long as iField==0).
457 ** In that case, this routine works like sqlite3ExprDup().
458 **
459 ** The caller owns the returned Expr object and is responsible for
460 ** ensuring that the returned value eventually gets freed.
461 **
462 ** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
463 ** then the returned object will reference pVector and so pVector must remain
464 ** valid for the life of the returned object.  If pVector is a TK_VECTOR
465 ** or a scalar expression, then it can be deleted as soon as this routine
466 ** returns.
467 **
468 ** A trick to cause a TK_SELECT pVector to be deleted together with
469 ** the returned Expr object is to attach the pVector to the pRight field
470 ** of the returned TK_SELECT_COLUMN Expr object.
471 */
sqlite3ExprForVectorField(Parse * pParse,Expr * pVector,int iField)472 Expr *sqlite3ExprForVectorField(
473   Parse *pParse,       /* Parsing context */
474   Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
475   int iField           /* Which column of the vector to return */
476 ){
477   Expr *pRet;
478   if( pVector->op==TK_SELECT ){
479     assert( pVector->flags & EP_xIsSelect );
480     /* The TK_SELECT_COLUMN Expr node:
481     **
482     ** pLeft:           pVector containing TK_SELECT.  Not deleted.
483     ** pRight:          not used.  But recursively deleted.
484     ** iColumn:         Index of a column in pVector
485     ** iTable:          0 or the number of columns on the LHS of an assignment
486     ** pLeft->iTable:   First in an array of register holding result, or 0
487     **                  if the result is not yet computed.
488     **
489     ** sqlite3ExprDelete() specifically skips the recursive delete of
490     ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
491     ** can be attached to pRight to cause this node to take ownership of
492     ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
493     ** with the same pLeft pointer to the pVector, but only one of them
494     ** will own the pVector.
495     */
496     pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
497     if( pRet ){
498       pRet->iColumn = iField;
499       pRet->pLeft = pVector;
500     }
501     assert( pRet==0 || pRet->iTable==0 );
502   }else{
503     if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
504     pRet = sqlite3ExprDup(pParse->db, pVector, 0);
505     sqlite3RenameTokenRemap(pParse, pRet, pVector);
506   }
507   return pRet;
508 }
509 
510 /*
511 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
512 ** it. Return the register in which the result is stored (or, if the
513 ** sub-select returns more than one column, the first in an array
514 ** of registers in which the result is stored).
515 **
516 ** If pExpr is not a TK_SELECT expression, return 0.
517 */
exprCodeSubselect(Parse * pParse,Expr * pExpr)518 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
519   int reg = 0;
520 #ifndef SQLITE_OMIT_SUBQUERY
521   if( pExpr->op==TK_SELECT ){
522     reg = sqlite3CodeSubselect(pParse, pExpr);
523   }
524 #endif
525   return reg;
526 }
527 
528 /*
529 ** Argument pVector points to a vector expression - either a TK_VECTOR
530 ** or TK_SELECT that returns more than one column. This function returns
531 ** the register number of a register that contains the value of
532 ** element iField of the vector.
533 **
534 ** If pVector is a TK_SELECT expression, then code for it must have
535 ** already been generated using the exprCodeSubselect() routine. In this
536 ** case parameter regSelect should be the first in an array of registers
537 ** containing the results of the sub-select.
538 **
539 ** If pVector is of type TK_VECTOR, then code for the requested field
540 ** is generated. In this case (*pRegFree) may be set to the number of
541 ** a temporary register to be freed by the caller before returning.
542 **
543 ** Before returning, output parameter (*ppExpr) is set to point to the
544 ** Expr object corresponding to element iElem of the vector.
545 */
exprVectorRegister(Parse * pParse,Expr * pVector,int iField,int regSelect,Expr ** ppExpr,int * pRegFree)546 static int exprVectorRegister(
547   Parse *pParse,                  /* Parse context */
548   Expr *pVector,                  /* Vector to extract element from */
549   int iField,                     /* Field to extract from pVector */
550   int regSelect,                  /* First in array of registers */
551   Expr **ppExpr,                  /* OUT: Expression element */
552   int *pRegFree                   /* OUT: Temp register to free */
553 ){
554   u8 op = pVector->op;
555   assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
556   if( op==TK_REGISTER ){
557     *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
558     return pVector->iTable+iField;
559   }
560   if( op==TK_SELECT ){
561     *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
562      return regSelect+iField;
563   }
564   *ppExpr = pVector->x.pList->a[iField].pExpr;
565   return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
566 }
567 
568 /*
569 ** Expression pExpr is a comparison between two vector values. Compute
570 ** the result of the comparison (1, 0, or NULL) and write that
571 ** result into register dest.
572 **
573 ** The caller must satisfy the following preconditions:
574 **
575 **    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
576 **    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
577 **    otherwise:                op==pExpr->op and p5==0
578 */
codeVectorCompare(Parse * pParse,Expr * pExpr,int dest,u8 op,u8 p5)579 static void codeVectorCompare(
580   Parse *pParse,        /* Code generator context */
581   Expr *pExpr,          /* The comparison operation */
582   int dest,             /* Write results into this register */
583   u8 op,                /* Comparison operator */
584   u8 p5                 /* SQLITE_NULLEQ or zero */
585 ){
586   Vdbe *v = pParse->pVdbe;
587   Expr *pLeft = pExpr->pLeft;
588   Expr *pRight = pExpr->pRight;
589   int nLeft = sqlite3ExprVectorSize(pLeft);
590   int i;
591   int regLeft = 0;
592   int regRight = 0;
593   u8 opx = op;
594   int addrDone = sqlite3VdbeMakeLabel(pParse);
595   int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
596 
597   if( pParse->nErr ) return;
598   if( nLeft!=sqlite3ExprVectorSize(pRight) ){
599     sqlite3ErrorMsg(pParse, "row value misused");
600     return;
601   }
602   assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
603        || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
604        || pExpr->op==TK_LT || pExpr->op==TK_GT
605        || pExpr->op==TK_LE || pExpr->op==TK_GE
606   );
607   assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
608             || (pExpr->op==TK_ISNOT && op==TK_NE) );
609   assert( p5==0 || pExpr->op!=op );
610   assert( p5==SQLITE_NULLEQ || pExpr->op==op );
611 
612   p5 |= SQLITE_STOREP2;
613   if( opx==TK_LE ) opx = TK_LT;
614   if( opx==TK_GE ) opx = TK_GT;
615 
616   regLeft = exprCodeSubselect(pParse, pLeft);
617   regRight = exprCodeSubselect(pParse, pRight);
618 
619   for(i=0; 1 /*Loop exits by "break"*/; i++){
620     int regFree1 = 0, regFree2 = 0;
621     Expr *pL, *pR;
622     int r1, r2;
623     assert( i>=0 && i<nLeft );
624     r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
625     r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
626     codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
627     testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
628     testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
629     testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
630     testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
631     testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
632     testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
633     sqlite3ReleaseTempReg(pParse, regFree1);
634     sqlite3ReleaseTempReg(pParse, regFree2);
635     if( i==nLeft-1 ){
636       break;
637     }
638     if( opx==TK_EQ ){
639       sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
640       p5 |= SQLITE_KEEPNULL;
641     }else if( opx==TK_NE ){
642       sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
643       p5 |= SQLITE_KEEPNULL;
644     }else{
645       assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
646       sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
647       VdbeCoverageIf(v, op==TK_LT);
648       VdbeCoverageIf(v, op==TK_GT);
649       VdbeCoverageIf(v, op==TK_LE);
650       VdbeCoverageIf(v, op==TK_GE);
651       if( i==nLeft-2 ) opx = op;
652     }
653   }
654   sqlite3VdbeResolveLabel(v, addrDone);
655 }
656 
657 #if SQLITE_MAX_EXPR_DEPTH>0
658 /*
659 ** Check that argument nHeight is less than or equal to the maximum
660 ** expression depth allowed. If it is not, leave an error message in
661 ** pParse.
662 */
sqlite3ExprCheckHeight(Parse * pParse,int nHeight)663 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
664   int rc = SQLITE_OK;
665   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
666   if( nHeight>mxHeight ){
667     sqlite3ErrorMsg(pParse,
668        "Expression tree is too large (maximum depth %d)", mxHeight
669     );
670     rc = SQLITE_ERROR;
671   }
672   return rc;
673 }
674 
675 /* The following three functions, heightOfExpr(), heightOfExprList()
676 ** and heightOfSelect(), are used to determine the maximum height
677 ** of any expression tree referenced by the structure passed as the
678 ** first argument.
679 **
680 ** If this maximum height is greater than the current value pointed
681 ** to by pnHeight, the second parameter, then set *pnHeight to that
682 ** value.
683 */
heightOfExpr(Expr * p,int * pnHeight)684 static void heightOfExpr(Expr *p, int *pnHeight){
685   if( p ){
686     if( p->nHeight>*pnHeight ){
687       *pnHeight = p->nHeight;
688     }
689   }
690 }
heightOfExprList(ExprList * p,int * pnHeight)691 static void heightOfExprList(ExprList *p, int *pnHeight){
692   if( p ){
693     int i;
694     for(i=0; i<p->nExpr; i++){
695       heightOfExpr(p->a[i].pExpr, pnHeight);
696     }
697   }
698 }
heightOfSelect(Select * pSelect,int * pnHeight)699 static void heightOfSelect(Select *pSelect, int *pnHeight){
700   Select *p;
701   for(p=pSelect; p; p=p->pPrior){
702     heightOfExpr(p->pWhere, pnHeight);
703     heightOfExpr(p->pHaving, pnHeight);
704     heightOfExpr(p->pLimit, pnHeight);
705     heightOfExprList(p->pEList, pnHeight);
706     heightOfExprList(p->pGroupBy, pnHeight);
707     heightOfExprList(p->pOrderBy, pnHeight);
708   }
709 }
710 
711 /*
712 ** Set the Expr.nHeight variable in the structure passed as an
713 ** argument. An expression with no children, Expr.pList or
714 ** Expr.pSelect member has a height of 1. Any other expression
715 ** has a height equal to the maximum height of any other
716 ** referenced Expr plus one.
717 **
718 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
719 ** if appropriate.
720 */
exprSetHeight(Expr * p)721 static void exprSetHeight(Expr *p){
722   int nHeight = 0;
723   heightOfExpr(p->pLeft, &nHeight);
724   heightOfExpr(p->pRight, &nHeight);
725   if( ExprHasProperty(p, EP_xIsSelect) ){
726     heightOfSelect(p->x.pSelect, &nHeight);
727   }else if( p->x.pList ){
728     heightOfExprList(p->x.pList, &nHeight);
729     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
730   }
731   p->nHeight = nHeight + 1;
732 }
733 
734 /*
735 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
736 ** the height is greater than the maximum allowed expression depth,
737 ** leave an error in pParse.
738 **
739 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
740 ** Expr.flags.
741 */
sqlite3ExprSetHeightAndFlags(Parse * pParse,Expr * p)742 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
743   if( pParse->nErr ) return;
744   exprSetHeight(p);
745   sqlite3ExprCheckHeight(pParse, p->nHeight);
746 }
747 
748 /*
749 ** Return the maximum height of any expression tree referenced
750 ** by the select statement passed as an argument.
751 */
sqlite3SelectExprHeight(Select * p)752 int sqlite3SelectExprHeight(Select *p){
753   int nHeight = 0;
754   heightOfSelect(p, &nHeight);
755   return nHeight;
756 }
757 #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
758 /*
759 ** Propagate all EP_Propagate flags from the Expr.x.pList into
760 ** Expr.flags.
761 */
sqlite3ExprSetHeightAndFlags(Parse * pParse,Expr * p)762 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
763   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
764     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
765   }
766 }
767 #define exprSetHeight(y)
768 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
769 
770 /*
771 ** This routine is the core allocator for Expr nodes.
772 **
773 ** Construct a new expression node and return a pointer to it.  Memory
774 ** for this node and for the pToken argument is a single allocation
775 ** obtained from sqlite3DbMalloc().  The calling function
776 ** is responsible for making sure the node eventually gets freed.
777 **
778 ** If dequote is true, then the token (if it exists) is dequoted.
779 ** If dequote is false, no dequoting is performed.  The deQuote
780 ** parameter is ignored if pToken is NULL or if the token does not
781 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
782 ** then the EP_DblQuoted flag is set on the expression node.
783 **
784 ** Special case:  If op==TK_INTEGER and pToken points to a string that
785 ** can be translated into a 32-bit integer, then the token is not
786 ** stored in u.zToken.  Instead, the integer values is written
787 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
788 ** is allocated to hold the integer text and the dequote flag is ignored.
789 */
sqlite3ExprAlloc(sqlite3 * db,int op,const Token * pToken,int dequote)790 Expr *sqlite3ExprAlloc(
791   sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
792   int op,                 /* Expression opcode */
793   const Token *pToken,    /* Token argument.  Might be NULL */
794   int dequote             /* True to dequote */
795 ){
796   Expr *pNew;
797   int nExtra = 0;
798   int iValue = 0;
799 
800   assert( db!=0 );
801   if( pToken ){
802     if( op!=TK_INTEGER || pToken->z==0
803           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
804       nExtra = pToken->n+1;
805       assert( iValue>=0 );
806     }
807   }
808   pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
809   if( pNew ){
810     memset(pNew, 0, sizeof(Expr));
811     pNew->op = (u8)op;
812     pNew->iAgg = -1;
813     if( pToken ){
814       if( nExtra==0 ){
815         pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
816         pNew->u.iValue = iValue;
817       }else{
818         pNew->u.zToken = (char*)&pNew[1];
819         assert( pToken->z!=0 || pToken->n==0 );
820         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
821         pNew->u.zToken[pToken->n] = 0;
822         if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
823           sqlite3DequoteExpr(pNew);
824         }
825       }
826     }
827 #if SQLITE_MAX_EXPR_DEPTH>0
828     pNew->nHeight = 1;
829 #endif
830   }
831   return pNew;
832 }
833 
834 /*
835 ** Allocate a new expression node from a zero-terminated token that has
836 ** already been dequoted.
837 */
sqlite3Expr(sqlite3 * db,int op,const char * zToken)838 Expr *sqlite3Expr(
839   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
840   int op,                 /* Expression opcode */
841   const char *zToken      /* Token argument.  Might be NULL */
842 ){
843   Token x;
844   x.z = zToken;
845   x.n = sqlite3Strlen30(zToken);
846   return sqlite3ExprAlloc(db, op, &x, 0);
847 }
848 
849 /*
850 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
851 **
852 ** If pRoot==NULL that means that a memory allocation error has occurred.
853 ** In that case, delete the subtrees pLeft and pRight.
854 */
sqlite3ExprAttachSubtrees(sqlite3 * db,Expr * pRoot,Expr * pLeft,Expr * pRight)855 void sqlite3ExprAttachSubtrees(
856   sqlite3 *db,
857   Expr *pRoot,
858   Expr *pLeft,
859   Expr *pRight
860 ){
861   if( pRoot==0 ){
862     assert( db->mallocFailed );
863     sqlite3ExprDelete(db, pLeft);
864     sqlite3ExprDelete(db, pRight);
865   }else{
866     if( pRight ){
867       pRoot->pRight = pRight;
868       pRoot->flags |= EP_Propagate & pRight->flags;
869     }
870     if( pLeft ){
871       pRoot->pLeft = pLeft;
872       pRoot->flags |= EP_Propagate & pLeft->flags;
873     }
874     exprSetHeight(pRoot);
875   }
876 }
877 
878 /*
879 ** Allocate an Expr node which joins as many as two subtrees.
880 **
881 ** One or both of the subtrees can be NULL.  Return a pointer to the new
882 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
883 ** free the subtrees and return NULL.
884 */
sqlite3PExpr(Parse * pParse,int op,Expr * pLeft,Expr * pRight)885 Expr *sqlite3PExpr(
886   Parse *pParse,          /* Parsing context */
887   int op,                 /* Expression opcode */
888   Expr *pLeft,            /* Left operand */
889   Expr *pRight            /* Right operand */
890 ){
891   Expr *p;
892   p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
893   if( p ){
894     memset(p, 0, sizeof(Expr));
895     p->op = op & 0xff;
896     p->iAgg = -1;
897     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
898     sqlite3ExprCheckHeight(pParse, p->nHeight);
899   }else{
900     sqlite3ExprDelete(pParse->db, pLeft);
901     sqlite3ExprDelete(pParse->db, pRight);
902   }
903   return p;
904 }
905 
906 /*
907 ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
908 ** do a memory allocation failure) then delete the pSelect object.
909 */
sqlite3PExprAddSelect(Parse * pParse,Expr * pExpr,Select * pSelect)910 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
911   if( pExpr ){
912     pExpr->x.pSelect = pSelect;
913     ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
914     sqlite3ExprSetHeightAndFlags(pParse, pExpr);
915   }else{
916     assert( pParse->db->mallocFailed );
917     sqlite3SelectDelete(pParse->db, pSelect);
918   }
919 }
920 
921 
922 /*
923 ** Join two expressions using an AND operator.  If either expression is
924 ** NULL, then just return the other expression.
925 **
926 ** If one side or the other of the AND is known to be false, then instead
927 ** of returning an AND expression, just return a constant expression with
928 ** a value of false.
929 */
sqlite3ExprAnd(Parse * pParse,Expr * pLeft,Expr * pRight)930 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
931   sqlite3 *db = pParse->db;
932   if( pLeft==0  ){
933     return pRight;
934   }else if( pRight==0 ){
935     return pLeft;
936   }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight))
937          && !IN_RENAME_OBJECT
938   ){
939     sqlite3ExprDelete(db, pLeft);
940     sqlite3ExprDelete(db, pRight);
941     return sqlite3Expr(db, TK_INTEGER, "0");
942   }else{
943     return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
944   }
945 }
946 
947 /*
948 ** Construct a new expression node for a function with multiple
949 ** arguments.
950 */
sqlite3ExprFunction(Parse * pParse,ExprList * pList,Token * pToken,int eDistinct)951 Expr *sqlite3ExprFunction(
952   Parse *pParse,        /* Parsing context */
953   ExprList *pList,      /* Argument list */
954   Token *pToken,        /* Name of the function */
955   int eDistinct         /* SF_Distinct or SF_ALL or 0 */
956 ){
957   Expr *pNew;
958   sqlite3 *db = pParse->db;
959   assert( pToken );
960   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
961   if( pNew==0 ){
962     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
963     return 0;
964   }
965   if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
966     sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
967   }
968   pNew->x.pList = pList;
969   ExprSetProperty(pNew, EP_HasFunc);
970   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
971   sqlite3ExprSetHeightAndFlags(pParse, pNew);
972   if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
973   return pNew;
974 }
975 
976 /*
977 ** Check to see if a function is usable according to current access
978 ** rules:
979 **
980 **    SQLITE_FUNC_DIRECT    -     Only usable from top-level SQL
981 **
982 **    SQLITE_FUNC_UNSAFE    -     Usable if TRUSTED_SCHEMA or from
983 **                                top-level SQL
984 **
985 ** If the function is not usable, create an error.
986 */
sqlite3ExprFunctionUsable(Parse * pParse,Expr * pExpr,FuncDef * pDef)987 void sqlite3ExprFunctionUsable(
988   Parse *pParse,         /* Parsing and code generating context */
989   Expr *pExpr,           /* The function invocation */
990   FuncDef *pDef          /* The function being invoked */
991 ){
992   assert( !IN_RENAME_OBJECT );
993   assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
994   if( ExprHasProperty(pExpr, EP_FromDDL) ){
995     if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
996      || (pParse->db->flags & SQLITE_TrustedSchema)==0
997     ){
998       /* Functions prohibited in triggers and views if:
999       **     (1) tagged with SQLITE_DIRECTONLY
1000       **     (2) not tagged with SQLITE_INNOCUOUS (which means it
1001       **         is tagged with SQLITE_FUNC_UNSAFE) and
1002       **         SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1003       **         that the schema is possibly tainted).
1004       */
1005       sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName);
1006     }
1007   }
1008 }
1009 
1010 /*
1011 ** Assign a variable number to an expression that encodes a wildcard
1012 ** in the original SQL statement.
1013 **
1014 ** Wildcards consisting of a single "?" are assigned the next sequential
1015 ** variable number.
1016 **
1017 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
1018 ** sure "nnn" is not too big to avoid a denial of service attack when
1019 ** the SQL statement comes from an external source.
1020 **
1021 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1022 ** as the previous instance of the same wildcard.  Or if this is the first
1023 ** instance of the wildcard, the next sequential variable number is
1024 ** assigned.
1025 */
sqlite3ExprAssignVarNumber(Parse * pParse,Expr * pExpr,u32 n)1026 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
1027   sqlite3 *db = pParse->db;
1028   const char *z;
1029   ynVar x;
1030 
1031   if( pExpr==0 ) return;
1032   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
1033   z = pExpr->u.zToken;
1034   assert( z!=0 );
1035   assert( z[0]!=0 );
1036   assert( n==(u32)sqlite3Strlen30(z) );
1037   if( z[1]==0 ){
1038     /* Wildcard of the form "?".  Assign the next variable number */
1039     assert( z[0]=='?' );
1040     x = (ynVar)(++pParse->nVar);
1041   }else{
1042     int doAdd = 0;
1043     if( z[0]=='?' ){
1044       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
1045       ** use it as the variable number */
1046       i64 i;
1047       int bOk;
1048       if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1049         i = z[1]-'0';  /* The common case of ?N for a single digit N */
1050         bOk = 1;
1051       }else{
1052         bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1053       }
1054       testcase( i==0 );
1055       testcase( i==1 );
1056       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1057       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1058       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1059         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1060             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1061         return;
1062       }
1063       x = (ynVar)i;
1064       if( x>pParse->nVar ){
1065         pParse->nVar = (int)x;
1066         doAdd = 1;
1067       }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1068         doAdd = 1;
1069       }
1070     }else{
1071       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
1072       ** number as the prior appearance of the same name, or if the name
1073       ** has never appeared before, reuse the same variable number
1074       */
1075       x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1076       if( x==0 ){
1077         x = (ynVar)(++pParse->nVar);
1078         doAdd = 1;
1079       }
1080     }
1081     if( doAdd ){
1082       pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1083     }
1084   }
1085   pExpr->iColumn = x;
1086   if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1087     sqlite3ErrorMsg(pParse, "too many SQL variables");
1088   }
1089 }
1090 
1091 /*
1092 ** Recursively delete an expression tree.
1093 */
sqlite3ExprDeleteNN(sqlite3 * db,Expr * p)1094 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1095   assert( p!=0 );
1096   /* Sanity check: Assert that the IntValue is non-negative if it exists */
1097   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
1098 
1099   assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
1100   assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
1101           || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
1102 #ifdef SQLITE_DEBUG
1103   if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1104     assert( p->pLeft==0 );
1105     assert( p->pRight==0 );
1106     assert( p->x.pSelect==0 );
1107   }
1108 #endif
1109   if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1110     /* The Expr.x union is never used at the same time as Expr.pRight */
1111     assert( p->x.pList==0 || p->pRight==0 );
1112     if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1113     if( p->pRight ){
1114       assert( !ExprHasProperty(p, EP_WinFunc) );
1115       sqlite3ExprDeleteNN(db, p->pRight);
1116     }else if( ExprHasProperty(p, EP_xIsSelect) ){
1117       assert( !ExprHasProperty(p, EP_WinFunc) );
1118       sqlite3SelectDelete(db, p->x.pSelect);
1119     }else{
1120       sqlite3ExprListDelete(db, p->x.pList);
1121 #ifndef SQLITE_OMIT_WINDOWFUNC
1122       if( ExprHasProperty(p, EP_WinFunc) ){
1123         sqlite3WindowDelete(db, p->y.pWin);
1124       }
1125 #endif
1126     }
1127   }
1128   if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
1129   if( !ExprHasProperty(p, EP_Static) ){
1130     sqlite3DbFreeNN(db, p);
1131   }
1132 }
sqlite3ExprDelete(sqlite3 * db,Expr * p)1133 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1134   if( p ) sqlite3ExprDeleteNN(db, p);
1135 }
1136 
1137 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1138 ** expression.
1139 */
sqlite3ExprUnmapAndDelete(Parse * pParse,Expr * p)1140 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
1141   if( p ){
1142     if( IN_RENAME_OBJECT ){
1143       sqlite3RenameExprUnmap(pParse, p);
1144     }
1145     sqlite3ExprDeleteNN(pParse->db, p);
1146   }
1147 }
1148 
1149 /*
1150 ** Return the number of bytes allocated for the expression structure
1151 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1152 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1153 */
exprStructSize(Expr * p)1154 static int exprStructSize(Expr *p){
1155   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1156   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1157   return EXPR_FULLSIZE;
1158 }
1159 
1160 /*
1161 ** The dupedExpr*Size() routines each return the number of bytes required
1162 ** to store a copy of an expression or expression tree.  They differ in
1163 ** how much of the tree is measured.
1164 **
1165 **     dupedExprStructSize()     Size of only the Expr structure
1166 **     dupedExprNodeSize()       Size of Expr + space for token
1167 **     dupedExprSize()           Expr + token + subtree components
1168 **
1169 ***************************************************************************
1170 **
1171 ** The dupedExprStructSize() function returns two values OR-ed together:
1172 ** (1) the space required for a copy of the Expr structure only and
1173 ** (2) the EP_xxx flags that indicate what the structure size should be.
1174 ** The return values is always one of:
1175 **
1176 **      EXPR_FULLSIZE
1177 **      EXPR_REDUCEDSIZE   | EP_Reduced
1178 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
1179 **
1180 ** The size of the structure can be found by masking the return value
1181 ** of this routine with 0xfff.  The flags can be found by masking the
1182 ** return value with EP_Reduced|EP_TokenOnly.
1183 **
1184 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1185 ** (unreduced) Expr objects as they or originally constructed by the parser.
1186 ** During expression analysis, extra information is computed and moved into
1187 ** later parts of the Expr object and that extra information might get chopped
1188 ** off if the expression is reduced.  Note also that it does not work to
1189 ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
1190 ** to reduce a pristine expression tree from the parser.  The implementation
1191 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1192 ** to enforce this constraint.
1193 */
dupedExprStructSize(Expr * p,int flags)1194 static int dupedExprStructSize(Expr *p, int flags){
1195   int nSize;
1196   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1197   assert( EXPR_FULLSIZE<=0xfff );
1198   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1199   if( 0==flags || p->op==TK_SELECT_COLUMN
1200 #ifndef SQLITE_OMIT_WINDOWFUNC
1201    || ExprHasProperty(p, EP_WinFunc)
1202 #endif
1203   ){
1204     nSize = EXPR_FULLSIZE;
1205   }else{
1206     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1207     assert( !ExprHasProperty(p, EP_FromJoin) );
1208     assert( !ExprHasProperty(p, EP_MemToken) );
1209     assert( !ExprHasProperty(p, EP_NoReduce) );
1210     if( p->pLeft || p->x.pList ){
1211       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1212     }else{
1213       assert( p->pRight==0 );
1214       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1215     }
1216   }
1217   return nSize;
1218 }
1219 
1220 /*
1221 ** This function returns the space in bytes required to store the copy
1222 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1223 ** string is defined.)
1224 */
dupedExprNodeSize(Expr * p,int flags)1225 static int dupedExprNodeSize(Expr *p, int flags){
1226   int nByte = dupedExprStructSize(p, flags) & 0xfff;
1227   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1228     nByte += sqlite3Strlen30NN(p->u.zToken)+1;
1229   }
1230   return ROUND8(nByte);
1231 }
1232 
1233 /*
1234 ** Return the number of bytes required to create a duplicate of the
1235 ** expression passed as the first argument. The second argument is a
1236 ** mask containing EXPRDUP_XXX flags.
1237 **
1238 ** The value returned includes space to create a copy of the Expr struct
1239 ** itself and the buffer referred to by Expr.u.zToken, if any.
1240 **
1241 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
1242 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1243 ** and Expr.pRight variables (but not for any structures pointed to or
1244 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
1245 */
dupedExprSize(Expr * p,int flags)1246 static int dupedExprSize(Expr *p, int flags){
1247   int nByte = 0;
1248   if( p ){
1249     nByte = dupedExprNodeSize(p, flags);
1250     if( flags&EXPRDUP_REDUCE ){
1251       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
1252     }
1253   }
1254   return nByte;
1255 }
1256 
1257 /*
1258 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1259 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
1260 ** to store the copy of expression p, the copies of p->u.zToken
1261 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
1262 ** if any. Before returning, *pzBuffer is set to the first byte past the
1263 ** portion of the buffer copied into by this function.
1264 */
exprDup(sqlite3 * db,Expr * p,int dupFlags,u8 ** pzBuffer)1265 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1266   Expr *pNew;           /* Value to return */
1267   u8 *zAlloc;           /* Memory space from which to build Expr object */
1268   u32 staticFlag;       /* EP_Static if space not obtained from malloc */
1269 
1270   assert( db!=0 );
1271   assert( p );
1272   assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1273   assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
1274 
1275   /* Figure out where to write the new Expr structure. */
1276   if( pzBuffer ){
1277     zAlloc = *pzBuffer;
1278     staticFlag = EP_Static;
1279   }else{
1280     zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1281     staticFlag = 0;
1282   }
1283   pNew = (Expr *)zAlloc;
1284 
1285   if( pNew ){
1286     /* Set nNewSize to the size allocated for the structure pointed to
1287     ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1288     ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1289     ** by the copy of the p->u.zToken string (if any).
1290     */
1291     const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1292     const int nNewSize = nStructSize & 0xfff;
1293     int nToken;
1294     if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1295       nToken = sqlite3Strlen30(p->u.zToken) + 1;
1296     }else{
1297       nToken = 0;
1298     }
1299     if( dupFlags ){
1300       assert( ExprHasProperty(p, EP_Reduced)==0 );
1301       memcpy(zAlloc, p, nNewSize);
1302     }else{
1303       u32 nSize = (u32)exprStructSize(p);
1304       memcpy(zAlloc, p, nSize);
1305       if( nSize<EXPR_FULLSIZE ){
1306         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1307       }
1308     }
1309 
1310     /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1311     pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1312     pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1313     pNew->flags |= staticFlag;
1314 
1315     /* Copy the p->u.zToken string, if any. */
1316     if( nToken ){
1317       char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1318       memcpy(zToken, p->u.zToken, nToken);
1319     }
1320 
1321     if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
1322       /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1323       if( ExprHasProperty(p, EP_xIsSelect) ){
1324         pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1325       }else{
1326         pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1327       }
1328     }
1329 
1330     /* Fill in pNew->pLeft and pNew->pRight. */
1331     if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
1332       zAlloc += dupedExprNodeSize(p, dupFlags);
1333       if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
1334         pNew->pLeft = p->pLeft ?
1335                       exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1336         pNew->pRight = p->pRight ?
1337                        exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
1338       }
1339 #ifndef SQLITE_OMIT_WINDOWFUNC
1340       if( ExprHasProperty(p, EP_WinFunc) ){
1341         pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1342         assert( ExprHasProperty(pNew, EP_WinFunc) );
1343       }
1344 #endif /* SQLITE_OMIT_WINDOWFUNC */
1345       if( pzBuffer ){
1346         *pzBuffer = zAlloc;
1347       }
1348     }else{
1349       if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1350         if( pNew->op==TK_SELECT_COLUMN ){
1351           pNew->pLeft = p->pLeft;
1352           assert( p->iColumn==0 || p->pRight==0 );
1353           assert( p->pRight==0  || p->pRight==p->pLeft );
1354         }else{
1355           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1356         }
1357         pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1358       }
1359     }
1360   }
1361   return pNew;
1362 }
1363 
1364 /*
1365 ** Create and return a deep copy of the object passed as the second
1366 ** argument. If an OOM condition is encountered, NULL is returned
1367 ** and the db->mallocFailed flag set.
1368 */
1369 #ifndef SQLITE_OMIT_CTE
withDup(sqlite3 * db,With * p)1370 static With *withDup(sqlite3 *db, With *p){
1371   With *pRet = 0;
1372   if( p ){
1373     sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1374     pRet = sqlite3DbMallocZero(db, nByte);
1375     if( pRet ){
1376       int i;
1377       pRet->nCte = p->nCte;
1378       for(i=0; i<p->nCte; i++){
1379         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1380         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1381         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1382       }
1383     }
1384   }
1385   return pRet;
1386 }
1387 #else
1388 # define withDup(x,y) 0
1389 #endif
1390 
1391 #ifndef SQLITE_OMIT_WINDOWFUNC
1392 /*
1393 ** The gatherSelectWindows() procedure and its helper routine
1394 ** gatherSelectWindowsCallback() are used to scan all the expressions
1395 ** an a newly duplicated SELECT statement and gather all of the Window
1396 ** objects found there, assembling them onto the linked list at Select->pWin.
1397 */
gatherSelectWindowsCallback(Walker * pWalker,Expr * pExpr)1398 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1399   if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
1400     Select *pSelect = pWalker->u.pSelect;
1401     Window *pWin = pExpr->y.pWin;
1402     assert( pWin );
1403     assert( IsWindowFunc(pExpr) );
1404     assert( pWin->ppThis==0 );
1405     sqlite3WindowLink(pSelect, pWin);
1406   }
1407   return WRC_Continue;
1408 }
gatherSelectWindowsSelectCallback(Walker * pWalker,Select * p)1409 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1410   return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1411 }
gatherSelectWindows(Select * p)1412 static void gatherSelectWindows(Select *p){
1413   Walker w;
1414   w.xExprCallback = gatherSelectWindowsCallback;
1415   w.xSelectCallback = gatherSelectWindowsSelectCallback;
1416   w.xSelectCallback2 = 0;
1417   w.pParse = 0;
1418   w.u.pSelect = p;
1419   sqlite3WalkSelect(&w, p);
1420 }
1421 #endif
1422 
1423 
1424 /*
1425 ** The following group of routines make deep copies of expressions,
1426 ** expression lists, ID lists, and select statements.  The copies can
1427 ** be deleted (by being passed to their respective ...Delete() routines)
1428 ** without effecting the originals.
1429 **
1430 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1431 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1432 ** by subsequent calls to sqlite*ListAppend() routines.
1433 **
1434 ** Any tables that the SrcList might point to are not duplicated.
1435 **
1436 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1437 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1438 ** truncated version of the usual Expr structure that will be stored as
1439 ** part of the in-memory representation of the database schema.
1440 */
sqlite3ExprDup(sqlite3 * db,Expr * p,int flags)1441 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
1442   assert( flags==0 || flags==EXPRDUP_REDUCE );
1443   return p ? exprDup(db, p, flags, 0) : 0;
1444 }
sqlite3ExprListDup(sqlite3 * db,ExprList * p,int flags)1445 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
1446   ExprList *pNew;
1447   struct ExprList_item *pItem, *pOldItem;
1448   int i;
1449   Expr *pPriorSelectCol = 0;
1450   assert( db!=0 );
1451   if( p==0 ) return 0;
1452   pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1453   if( pNew==0 ) return 0;
1454   pNew->nExpr = p->nExpr;
1455   pItem = pNew->a;
1456   pOldItem = p->a;
1457   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1458     Expr *pOldExpr = pOldItem->pExpr;
1459     Expr *pNewExpr;
1460     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1461     if( pOldExpr
1462      && pOldExpr->op==TK_SELECT_COLUMN
1463      && (pNewExpr = pItem->pExpr)!=0
1464     ){
1465       assert( pNewExpr->iColumn==0 || i>0 );
1466       if( pNewExpr->iColumn==0 ){
1467         assert( pOldExpr->pLeft==pOldExpr->pRight );
1468         pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
1469       }else{
1470         assert( i>0 );
1471         assert( pItem[-1].pExpr!=0 );
1472         assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
1473         assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
1474         pNewExpr->pLeft = pPriorSelectCol;
1475       }
1476     }
1477     pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
1478     pItem->sortFlags = pOldItem->sortFlags;
1479     pItem->eEName = pOldItem->eEName;
1480     pItem->done = 0;
1481     pItem->bNulls = pOldItem->bNulls;
1482     pItem->bSorterRef = pOldItem->bSorterRef;
1483     pItem->u = pOldItem->u;
1484   }
1485   return pNew;
1486 }
1487 
1488 /*
1489 ** If cursors, triggers, views and subqueries are all omitted from
1490 ** the build, then none of the following routines, except for
1491 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1492 ** called with a NULL argument.
1493 */
1494 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1495  || !defined(SQLITE_OMIT_SUBQUERY)
sqlite3SrcListDup(sqlite3 * db,SrcList * p,int flags)1496 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1497   SrcList *pNew;
1498   int i;
1499   int nByte;
1500   assert( db!=0 );
1501   if( p==0 ) return 0;
1502   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1503   pNew = sqlite3DbMallocRawNN(db, nByte );
1504   if( pNew==0 ) return 0;
1505   pNew->nSrc = pNew->nAlloc = p->nSrc;
1506   for(i=0; i<p->nSrc; i++){
1507     struct SrcList_item *pNewItem = &pNew->a[i];
1508     struct SrcList_item *pOldItem = &p->a[i];
1509     Table *pTab;
1510     pNewItem->pSchema = pOldItem->pSchema;
1511     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1512     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1513     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1514     pNewItem->fg = pOldItem->fg;
1515     pNewItem->iCursor = pOldItem->iCursor;
1516     pNewItem->addrFillSub = pOldItem->addrFillSub;
1517     pNewItem->regReturn = pOldItem->regReturn;
1518     if( pNewItem->fg.isIndexedBy ){
1519       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1520     }
1521     pNewItem->pIBIndex = pOldItem->pIBIndex;
1522     if( pNewItem->fg.isTabFunc ){
1523       pNewItem->u1.pFuncArg =
1524           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1525     }
1526     pTab = pNewItem->pTab = pOldItem->pTab;
1527     if( pTab ){
1528       pTab->nTabRef++;
1529     }
1530     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1531     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
1532     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
1533     pNewItem->colUsed = pOldItem->colUsed;
1534   }
1535   return pNew;
1536 }
sqlite3IdListDup(sqlite3 * db,IdList * p)1537 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1538   IdList *pNew;
1539   int i;
1540   assert( db!=0 );
1541   if( p==0 ) return 0;
1542   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1543   if( pNew==0 ) return 0;
1544   pNew->nId = p->nId;
1545   pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
1546   if( pNew->a==0 ){
1547     sqlite3DbFreeNN(db, pNew);
1548     return 0;
1549   }
1550   /* Note that because the size of the allocation for p->a[] is not
1551   ** necessarily a power of two, sqlite3IdListAppend() may not be called
1552   ** on the duplicate created by this function. */
1553   for(i=0; i<p->nId; i++){
1554     struct IdList_item *pNewItem = &pNew->a[i];
1555     struct IdList_item *pOldItem = &p->a[i];
1556     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1557     pNewItem->idx = pOldItem->idx;
1558   }
1559   return pNew;
1560 }
sqlite3SelectDup(sqlite3 * db,Select * pDup,int flags)1561 Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
1562   Select *pRet = 0;
1563   Select *pNext = 0;
1564   Select **pp = &pRet;
1565   Select *p;
1566 
1567   assert( db!=0 );
1568   for(p=pDup; p; p=p->pPrior){
1569     Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1570     if( pNew==0 ) break;
1571     pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1572     pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1573     pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1574     pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1575     pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1576     pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1577     pNew->op = p->op;
1578     pNew->pNext = pNext;
1579     pNew->pPrior = 0;
1580     pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1581     pNew->iLimit = 0;
1582     pNew->iOffset = 0;
1583     pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1584     pNew->addrOpenEphm[0] = -1;
1585     pNew->addrOpenEphm[1] = -1;
1586     pNew->nSelectRow = p->nSelectRow;
1587     pNew->pWith = withDup(db, p->pWith);
1588 #ifndef SQLITE_OMIT_WINDOWFUNC
1589     pNew->pWin = 0;
1590     pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1591     if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
1592 #endif
1593     pNew->selId = p->selId;
1594     *pp = pNew;
1595     pp = &pNew->pPrior;
1596     pNext = pNew;
1597   }
1598 
1599   return pRet;
1600 }
1601 #else
sqlite3SelectDup(sqlite3 * db,Select * p,int flags)1602 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
1603   assert( p==0 );
1604   return 0;
1605 }
1606 #endif
1607 
1608 
1609 /*
1610 ** Add a new element to the end of an expression list.  If pList is
1611 ** initially NULL, then create a new expression list.
1612 **
1613 ** The pList argument must be either NULL or a pointer to an ExprList
1614 ** obtained from a prior call to sqlite3ExprListAppend().  This routine
1615 ** may not be used with an ExprList obtained from sqlite3ExprListDup().
1616 ** Reason:  This routine assumes that the number of slots in pList->a[]
1617 ** is a power of two.  That is true for sqlite3ExprListAppend() returns
1618 ** but is not necessarily true from the return value of sqlite3ExprListDup().
1619 **
1620 ** If a memory allocation error occurs, the entire list is freed and
1621 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
1622 ** that the new entry was successfully appended.
1623 */
sqlite3ExprListAppend(Parse * pParse,ExprList * pList,Expr * pExpr)1624 ExprList *sqlite3ExprListAppend(
1625   Parse *pParse,          /* Parsing context */
1626   ExprList *pList,        /* List to which to append. Might be NULL */
1627   Expr *pExpr             /* Expression to be appended. Might be NULL */
1628 ){
1629   struct ExprList_item *pItem;
1630   sqlite3 *db = pParse->db;
1631   assert( db!=0 );
1632   if( pList==0 ){
1633     pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
1634     if( pList==0 ){
1635       goto no_mem;
1636     }
1637     pList->nExpr = 0;
1638   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
1639     ExprList *pNew;
1640     pNew = sqlite3DbRealloc(db, pList,
1641          sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
1642     if( pNew==0 ){
1643       goto no_mem;
1644     }
1645     pList = pNew;
1646   }
1647   pItem = &pList->a[pList->nExpr++];
1648   assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) );
1649   assert( offsetof(struct ExprList_item,pExpr)==0 );
1650   memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName));
1651   pItem->pExpr = pExpr;
1652   return pList;
1653 
1654 no_mem:
1655   /* Avoid leaking memory if malloc has failed. */
1656   sqlite3ExprDelete(db, pExpr);
1657   sqlite3ExprListDelete(db, pList);
1658   return 0;
1659 }
1660 
1661 /*
1662 ** pColumns and pExpr form a vector assignment which is part of the SET
1663 ** clause of an UPDATE statement.  Like this:
1664 **
1665 **        (a,b,c) = (expr1,expr2,expr3)
1666 ** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
1667 **
1668 ** For each term of the vector assignment, append new entries to the
1669 ** expression list pList.  In the case of a subquery on the RHS, append
1670 ** TK_SELECT_COLUMN expressions.
1671 */
sqlite3ExprListAppendVector(Parse * pParse,ExprList * pList,IdList * pColumns,Expr * pExpr)1672 ExprList *sqlite3ExprListAppendVector(
1673   Parse *pParse,         /* Parsing context */
1674   ExprList *pList,       /* List to which to append. Might be NULL */
1675   IdList *pColumns,      /* List of names of LHS of the assignment */
1676   Expr *pExpr            /* Vector expression to be appended. Might be NULL */
1677 ){
1678   sqlite3 *db = pParse->db;
1679   int n;
1680   int i;
1681   int iFirst = pList ? pList->nExpr : 0;
1682   /* pColumns can only be NULL due to an OOM but an OOM will cause an
1683   ** exit prior to this routine being invoked */
1684   if( NEVER(pColumns==0) ) goto vector_append_error;
1685   if( pExpr==0 ) goto vector_append_error;
1686 
1687   /* If the RHS is a vector, then we can immediately check to see that
1688   ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
1689   ** wildcards ("*") in the result set of the SELECT must be expanded before
1690   ** we can do the size check, so defer the size check until code generation.
1691   */
1692   if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
1693     sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1694                     pColumns->nId, n);
1695     goto vector_append_error;
1696   }
1697 
1698   for(i=0; i<pColumns->nId; i++){
1699     Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1700     assert( pSubExpr!=0 || db->mallocFailed );
1701     assert( pSubExpr==0 || pSubExpr->iTable==0 );
1702     if( pSubExpr==0 ) continue;
1703     pSubExpr->iTable = pColumns->nId;
1704     pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1705     if( pList ){
1706       assert( pList->nExpr==iFirst+i+1 );
1707       pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
1708       pColumns->a[i].zName = 0;
1709     }
1710   }
1711 
1712   if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
1713     Expr *pFirst = pList->a[iFirst].pExpr;
1714     assert( pFirst!=0 );
1715     assert( pFirst->op==TK_SELECT_COLUMN );
1716 
1717     /* Store the SELECT statement in pRight so it will be deleted when
1718     ** sqlite3ExprListDelete() is called */
1719     pFirst->pRight = pExpr;
1720     pExpr = 0;
1721 
1722     /* Remember the size of the LHS in iTable so that we can check that
1723     ** the RHS and LHS sizes match during code generation. */
1724     pFirst->iTable = pColumns->nId;
1725   }
1726 
1727 vector_append_error:
1728   sqlite3ExprUnmapAndDelete(pParse, pExpr);
1729   sqlite3IdListDelete(db, pColumns);
1730   return pList;
1731 }
1732 
1733 /*
1734 ** Set the sort order for the last element on the given ExprList.
1735 */
sqlite3ExprListSetSortOrder(ExprList * p,int iSortOrder,int eNulls)1736 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
1737   struct ExprList_item *pItem;
1738   if( p==0 ) return;
1739   assert( p->nExpr>0 );
1740 
1741   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
1742   assert( iSortOrder==SQLITE_SO_UNDEFINED
1743        || iSortOrder==SQLITE_SO_ASC
1744        || iSortOrder==SQLITE_SO_DESC
1745   );
1746   assert( eNulls==SQLITE_SO_UNDEFINED
1747        || eNulls==SQLITE_SO_ASC
1748        || eNulls==SQLITE_SO_DESC
1749   );
1750 
1751   pItem = &p->a[p->nExpr-1];
1752   assert( pItem->bNulls==0 );
1753   if( iSortOrder==SQLITE_SO_UNDEFINED ){
1754     iSortOrder = SQLITE_SO_ASC;
1755   }
1756   pItem->sortFlags = (u8)iSortOrder;
1757 
1758   if( eNulls!=SQLITE_SO_UNDEFINED ){
1759     pItem->bNulls = 1;
1760     if( iSortOrder!=eNulls ){
1761       pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
1762     }
1763   }
1764 }
1765 
1766 /*
1767 ** Set the ExprList.a[].zEName element of the most recently added item
1768 ** on the expression list.
1769 **
1770 ** pList might be NULL following an OOM error.  But pName should never be
1771 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1772 ** is set.
1773 */
sqlite3ExprListSetName(Parse * pParse,ExprList * pList,Token * pName,int dequote)1774 void sqlite3ExprListSetName(
1775   Parse *pParse,          /* Parsing context */
1776   ExprList *pList,        /* List to which to add the span. */
1777   Token *pName,           /* Name to be added */
1778   int dequote             /* True to cause the name to be dequoted */
1779 ){
1780   assert( pList!=0 || pParse->db->mallocFailed!=0 );
1781   if( pList ){
1782     struct ExprList_item *pItem;
1783     assert( pList->nExpr>0 );
1784     pItem = &pList->a[pList->nExpr-1];
1785     assert( pItem->zEName==0 );
1786     assert( pItem->eEName==ENAME_NAME );
1787     pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1788     if( dequote ) sqlite3Dequote(pItem->zEName);
1789     if( IN_RENAME_OBJECT ){
1790       sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName);
1791     }
1792   }
1793 }
1794 
1795 /*
1796 ** Set the ExprList.a[].zSpan element of the most recently added item
1797 ** on the expression list.
1798 **
1799 ** pList might be NULL following an OOM error.  But pSpan should never be
1800 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
1801 ** is set.
1802 */
sqlite3ExprListSetSpan(Parse * pParse,ExprList * pList,const char * zStart,const char * zEnd)1803 void sqlite3ExprListSetSpan(
1804   Parse *pParse,          /* Parsing context */
1805   ExprList *pList,        /* List to which to add the span. */
1806   const char *zStart,     /* Start of the span */
1807   const char *zEnd        /* End of the span */
1808 ){
1809   sqlite3 *db = pParse->db;
1810   assert( pList!=0 || db->mallocFailed!=0 );
1811   if( pList ){
1812     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1813     assert( pList->nExpr>0 );
1814     if( pItem->zEName==0 ){
1815       pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
1816       pItem->eEName = ENAME_SPAN;
1817     }
1818   }
1819 }
1820 
1821 /*
1822 ** If the expression list pEList contains more than iLimit elements,
1823 ** leave an error message in pParse.
1824 */
sqlite3ExprListCheckLength(Parse * pParse,ExprList * pEList,const char * zObject)1825 void sqlite3ExprListCheckLength(
1826   Parse *pParse,
1827   ExprList *pEList,
1828   const char *zObject
1829 ){
1830   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1831   testcase( pEList && pEList->nExpr==mx );
1832   testcase( pEList && pEList->nExpr==mx+1 );
1833   if( pEList && pEList->nExpr>mx ){
1834     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1835   }
1836 }
1837 
1838 /*
1839 ** Delete an entire expression list.
1840 */
exprListDeleteNN(sqlite3 * db,ExprList * pList)1841 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
1842   int i = pList->nExpr;
1843   struct ExprList_item *pItem =  pList->a;
1844   assert( pList->nExpr>0 );
1845   do{
1846     sqlite3ExprDelete(db, pItem->pExpr);
1847     sqlite3DbFree(db, pItem->zEName);
1848     pItem++;
1849   }while( --i>0 );
1850   sqlite3DbFreeNN(db, pList);
1851 }
sqlite3ExprListDelete(sqlite3 * db,ExprList * pList)1852 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1853   if( pList ) exprListDeleteNN(db, pList);
1854 }
1855 
1856 /*
1857 ** Return the bitwise-OR of all Expr.flags fields in the given
1858 ** ExprList.
1859 */
sqlite3ExprListFlags(const ExprList * pList)1860 u32 sqlite3ExprListFlags(const ExprList *pList){
1861   int i;
1862   u32 m = 0;
1863   assert( pList!=0 );
1864   for(i=0; i<pList->nExpr; i++){
1865      Expr *pExpr = pList->a[i].pExpr;
1866      assert( pExpr!=0 );
1867      m |= pExpr->flags;
1868   }
1869   return m;
1870 }
1871 
1872 /*
1873 ** This is a SELECT-node callback for the expression walker that
1874 ** always "fails".  By "fail" in this case, we mean set
1875 ** pWalker->eCode to zero and abort.
1876 **
1877 ** This callback is used by multiple expression walkers.
1878 */
sqlite3SelectWalkFail(Walker * pWalker,Select * NotUsed)1879 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
1880   UNUSED_PARAMETER(NotUsed);
1881   pWalker->eCode = 0;
1882   return WRC_Abort;
1883 }
1884 
1885 /*
1886 ** Check the input string to see if it is "true" or "false" (in any case).
1887 **
1888 **       If the string is....           Return
1889 **         "true"                         EP_IsTrue
1890 **         "false"                        EP_IsFalse
1891 **         anything else                  0
1892 */
sqlite3IsTrueOrFalse(const char * zIn)1893 u32 sqlite3IsTrueOrFalse(const char *zIn){
1894   if( sqlite3StrICmp(zIn, "true")==0  ) return EP_IsTrue;
1895   if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
1896   return 0;
1897 }
1898 
1899 
1900 /*
1901 ** If the input expression is an ID with the name "true" or "false"
1902 ** then convert it into an TK_TRUEFALSE term.  Return non-zero if
1903 ** the conversion happened, and zero if the expression is unaltered.
1904 */
sqlite3ExprIdToTrueFalse(Expr * pExpr)1905 int sqlite3ExprIdToTrueFalse(Expr *pExpr){
1906   u32 v;
1907   assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
1908   if( !ExprHasProperty(pExpr, EP_Quoted)
1909    && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
1910   ){
1911     pExpr->op = TK_TRUEFALSE;
1912     ExprSetProperty(pExpr, v);
1913     return 1;
1914   }
1915   return 0;
1916 }
1917 
1918 /*
1919 ** The argument must be a TK_TRUEFALSE Expr node.  Return 1 if it is TRUE
1920 ** and 0 if it is FALSE.
1921 */
sqlite3ExprTruthValue(const Expr * pExpr)1922 int sqlite3ExprTruthValue(const Expr *pExpr){
1923   pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
1924   assert( pExpr->op==TK_TRUEFALSE );
1925   assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
1926        || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
1927   return pExpr->u.zToken[4]==0;
1928 }
1929 
1930 /*
1931 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
1932 ** terms that are always true or false.  Return the simplified expression.
1933 ** Or return the original expression if no simplification is possible.
1934 **
1935 ** Examples:
1936 **
1937 **     (x<10) AND true                =>   (x<10)
1938 **     (x<10) AND false               =>   false
1939 **     (x<10) AND (y=22 OR false)     =>   (x<10) AND (y=22)
1940 **     (x<10) AND (y=22 OR true)      =>   (x<10)
1941 **     (y=22) OR true                 =>   true
1942 */
sqlite3ExprSimplifiedAndOr(Expr * pExpr)1943 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
1944   assert( pExpr!=0 );
1945   if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
1946     Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
1947     Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
1948     if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
1949       pExpr = pExpr->op==TK_AND ? pRight : pLeft;
1950     }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
1951       pExpr = pExpr->op==TK_AND ? pLeft : pRight;
1952     }
1953   }
1954   return pExpr;
1955 }
1956 
1957 
1958 /*
1959 ** These routines are Walker callbacks used to check expressions to
1960 ** see if they are "constant" for some definition of constant.  The
1961 ** Walker.eCode value determines the type of "constant" we are looking
1962 ** for.
1963 **
1964 ** These callback routines are used to implement the following:
1965 **
1966 **     sqlite3ExprIsConstant()                  pWalker->eCode==1
1967 **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
1968 **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
1969 **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
1970 **
1971 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1972 ** is found to not be a constant.
1973 **
1974 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
1975 ** expressions in a CREATE TABLE statement.  The Walker.eCode value is 5
1976 ** when parsing an existing schema out of the sqlite_master table and 4
1977 ** when processing a new CREATE TABLE statement.  A bound parameter raises
1978 ** an error for new statements, but is silently converted
1979 ** to NULL for existing schemas.  This allows sqlite_master tables that
1980 ** contain a bound parameter because they were generated by older versions
1981 ** of SQLite to be parsed by newer versions of SQLite without raising a
1982 ** malformed schema error.
1983 */
exprNodeIsConstant(Walker * pWalker,Expr * pExpr)1984 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1985 
1986   /* If pWalker->eCode is 2 then any term of the expression that comes from
1987   ** the ON or USING clauses of a left join disqualifies the expression
1988   ** from being considered constant. */
1989   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1990     pWalker->eCode = 0;
1991     return WRC_Abort;
1992   }
1993 
1994   switch( pExpr->op ){
1995     /* Consider functions to be constant if all their arguments are constant
1996     ** and either pWalker->eCode==4 or 5 or the function has the
1997     ** SQLITE_FUNC_CONST flag. */
1998     case TK_FUNCTION:
1999       if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
2000        && !ExprHasProperty(pExpr, EP_WinFunc)
2001       ){
2002         if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
2003         return WRC_Continue;
2004       }else{
2005         pWalker->eCode = 0;
2006         return WRC_Abort;
2007       }
2008     case TK_ID:
2009       /* Convert "true" or "false" in a DEFAULT clause into the
2010       ** appropriate TK_TRUEFALSE operator */
2011       if( sqlite3ExprIdToTrueFalse(pExpr) ){
2012         return WRC_Prune;
2013       }
2014       /* Fall thru */
2015     case TK_COLUMN:
2016     case TK_AGG_FUNCTION:
2017     case TK_AGG_COLUMN:
2018       testcase( pExpr->op==TK_ID );
2019       testcase( pExpr->op==TK_COLUMN );
2020       testcase( pExpr->op==TK_AGG_FUNCTION );
2021       testcase( pExpr->op==TK_AGG_COLUMN );
2022       if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
2023         return WRC_Continue;
2024       }
2025       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
2026         return WRC_Continue;
2027       }
2028       /* Fall through */
2029     case TK_IF_NULL_ROW:
2030     case TK_REGISTER:
2031       testcase( pExpr->op==TK_REGISTER );
2032       testcase( pExpr->op==TK_IF_NULL_ROW );
2033       pWalker->eCode = 0;
2034       return WRC_Abort;
2035     case TK_VARIABLE:
2036       if( pWalker->eCode==5 ){
2037         /* Silently convert bound parameters that appear inside of CREATE
2038         ** statements into a NULL when parsing the CREATE statement text out
2039         ** of the sqlite_master table */
2040         pExpr->op = TK_NULL;
2041       }else if( pWalker->eCode==4 ){
2042         /* A bound parameter in a CREATE statement that originates from
2043         ** sqlite3_prepare() causes an error */
2044         pWalker->eCode = 0;
2045         return WRC_Abort;
2046       }
2047       /* Fall through */
2048     default:
2049       testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
2050       testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
2051       return WRC_Continue;
2052   }
2053 }
exprIsConst(Expr * p,int initFlag,int iCur)2054 static int exprIsConst(Expr *p, int initFlag, int iCur){
2055   Walker w;
2056   w.eCode = initFlag;
2057   w.xExprCallback = exprNodeIsConstant;
2058   w.xSelectCallback = sqlite3SelectWalkFail;
2059 #ifdef SQLITE_DEBUG
2060   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2061 #endif
2062   w.u.iCur = iCur;
2063   sqlite3WalkExpr(&w, p);
2064   return w.eCode;
2065 }
2066 
2067 /*
2068 ** Walk an expression tree.  Return non-zero if the expression is constant
2069 ** and 0 if it involves variables or function calls.
2070 **
2071 ** For the purposes of this function, a double-quoted string (ex: "abc")
2072 ** is considered a variable but a single-quoted string (ex: 'abc') is
2073 ** a constant.
2074 */
sqlite3ExprIsConstant(Expr * p)2075 int sqlite3ExprIsConstant(Expr *p){
2076   return exprIsConst(p, 1, 0);
2077 }
2078 
2079 /*
2080 ** Walk an expression tree.  Return non-zero if
2081 **
2082 **   (1) the expression is constant, and
2083 **   (2) the expression does originate in the ON or USING clause
2084 **       of a LEFT JOIN, and
2085 **   (3) the expression does not contain any EP_FixedCol TK_COLUMN
2086 **       operands created by the constant propagation optimization.
2087 **
2088 ** When this routine returns true, it indicates that the expression
2089 ** can be added to the pParse->pConstExpr list and evaluated once when
2090 ** the prepared statement starts up.  See sqlite3ExprCodeAtInit().
2091 */
sqlite3ExprIsConstantNotJoin(Expr * p)2092 int sqlite3ExprIsConstantNotJoin(Expr *p){
2093   return exprIsConst(p, 2, 0);
2094 }
2095 
2096 /*
2097 ** Walk an expression tree.  Return non-zero if the expression is constant
2098 ** for any single row of the table with cursor iCur.  In other words, the
2099 ** expression must not refer to any non-deterministic function nor any
2100 ** table other than iCur.
2101 */
sqlite3ExprIsTableConstant(Expr * p,int iCur)2102 int sqlite3ExprIsTableConstant(Expr *p, int iCur){
2103   return exprIsConst(p, 3, iCur);
2104 }
2105 
2106 
2107 /*
2108 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2109 */
exprNodeIsConstantOrGroupBy(Walker * pWalker,Expr * pExpr)2110 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2111   ExprList *pGroupBy = pWalker->u.pGroupBy;
2112   int i;
2113 
2114   /* Check if pExpr is identical to any GROUP BY term. If so, consider
2115   ** it constant.  */
2116   for(i=0; i<pGroupBy->nExpr; i++){
2117     Expr *p = pGroupBy->a[i].pExpr;
2118     if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
2119       CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2120       if( sqlite3IsBinary(pColl) ){
2121         return WRC_Prune;
2122       }
2123     }
2124   }
2125 
2126   /* Check if pExpr is a sub-select. If so, consider it variable. */
2127   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2128     pWalker->eCode = 0;
2129     return WRC_Abort;
2130   }
2131 
2132   return exprNodeIsConstant(pWalker, pExpr);
2133 }
2134 
2135 /*
2136 ** Walk the expression tree passed as the first argument. Return non-zero
2137 ** if the expression consists entirely of constants or copies of terms
2138 ** in pGroupBy that sort with the BINARY collation sequence.
2139 **
2140 ** This routine is used to determine if a term of the HAVING clause can
2141 ** be promoted into the WHERE clause.  In order for such a promotion to work,
2142 ** the value of the HAVING clause term must be the same for all members of
2143 ** a "group".  The requirement that the GROUP BY term must be BINARY
2144 ** assumes that no other collating sequence will have a finer-grained
2145 ** grouping than binary.  In other words (A=B COLLATE binary) implies
2146 ** A=B in every other collating sequence.  The requirement that the
2147 ** GROUP BY be BINARY is stricter than necessary.  It would also work
2148 ** to promote HAVING clauses that use the same alternative collating
2149 ** sequence as the GROUP BY term, but that is much harder to check,
2150 ** alternative collating sequences are uncommon, and this is only an
2151 ** optimization, so we take the easy way out and simply require the
2152 ** GROUP BY to use the BINARY collating sequence.
2153 */
sqlite3ExprIsConstantOrGroupBy(Parse * pParse,Expr * p,ExprList * pGroupBy)2154 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2155   Walker w;
2156   w.eCode = 1;
2157   w.xExprCallback = exprNodeIsConstantOrGroupBy;
2158   w.xSelectCallback = 0;
2159   w.u.pGroupBy = pGroupBy;
2160   w.pParse = pParse;
2161   sqlite3WalkExpr(&w, p);
2162   return w.eCode;
2163 }
2164 
2165 /*
2166 ** Walk an expression tree for the DEFAULT field of a column definition
2167 ** in a CREATE TABLE statement.  Return non-zero if the expression is
2168 ** acceptable for use as a DEFAULT.  That is to say, return non-zero if
2169 ** the expression is constant or a function call with constant arguments.
2170 ** Return and 0 if there are any variables.
2171 **
2172 ** isInit is true when parsing from sqlite_master.  isInit is false when
2173 ** processing a new CREATE TABLE statement.  When isInit is true, parameters
2174 ** (such as ? or $abc) in the expression are converted into NULL.  When
2175 ** isInit is false, parameters raise an error.  Parameters should not be
2176 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2177 ** allowed it, so we need to support it when reading sqlite_master for
2178 ** backwards compatibility.
2179 **
2180 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2181 **
2182 ** For the purposes of this function, a double-quoted string (ex: "abc")
2183 ** is considered a variable but a single-quoted string (ex: 'abc') is
2184 ** a constant.
2185 */
sqlite3ExprIsConstantOrFunction(Expr * p,u8 isInit)2186 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2187   assert( isInit==0 || isInit==1 );
2188   return exprIsConst(p, 4+isInit, 0);
2189 }
2190 
2191 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2192 /*
2193 ** Walk an expression tree.  Return 1 if the expression contains a
2194 ** subquery of some kind.  Return 0 if there are no subqueries.
2195 */
sqlite3ExprContainsSubquery(Expr * p)2196 int sqlite3ExprContainsSubquery(Expr *p){
2197   Walker w;
2198   w.eCode = 1;
2199   w.xExprCallback = sqlite3ExprWalkNoop;
2200   w.xSelectCallback = sqlite3SelectWalkFail;
2201 #ifdef SQLITE_DEBUG
2202   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2203 #endif
2204   sqlite3WalkExpr(&w, p);
2205   return w.eCode==0;
2206 }
2207 #endif
2208 
2209 /*
2210 ** If the expression p codes a constant integer that is small enough
2211 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2212 ** in *pValue.  If the expression is not an integer or if it is too big
2213 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2214 */
sqlite3ExprIsInteger(Expr * p,int * pValue)2215 int sqlite3ExprIsInteger(Expr *p, int *pValue){
2216   int rc = 0;
2217   if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */
2218 
2219   /* If an expression is an integer literal that fits in a signed 32-bit
2220   ** integer, then the EP_IntValue flag will have already been set */
2221   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2222            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2223 
2224   if( p->flags & EP_IntValue ){
2225     *pValue = p->u.iValue;
2226     return 1;
2227   }
2228   switch( p->op ){
2229     case TK_UPLUS: {
2230       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
2231       break;
2232     }
2233     case TK_UMINUS: {
2234       int v;
2235       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
2236         assert( v!=(-2147483647-1) );
2237         *pValue = -v;
2238         rc = 1;
2239       }
2240       break;
2241     }
2242     default: break;
2243   }
2244   return rc;
2245 }
2246 
2247 /*
2248 ** Return FALSE if there is no chance that the expression can be NULL.
2249 **
2250 ** If the expression might be NULL or if the expression is too complex
2251 ** to tell return TRUE.
2252 **
2253 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2254 ** when we know that a value cannot be NULL.  Hence, a false positive
2255 ** (returning TRUE when in fact the expression can never be NULL) might
2256 ** be a small performance hit but is otherwise harmless.  On the other
2257 ** hand, a false negative (returning FALSE when the result could be NULL)
2258 ** will likely result in an incorrect answer.  So when in doubt, return
2259 ** TRUE.
2260 */
sqlite3ExprCanBeNull(const Expr * p)2261 int sqlite3ExprCanBeNull(const Expr *p){
2262   u8 op;
2263   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2264     p = p->pLeft;
2265   }
2266   op = p->op;
2267   if( op==TK_REGISTER ) op = p->op2;
2268   switch( op ){
2269     case TK_INTEGER:
2270     case TK_STRING:
2271     case TK_FLOAT:
2272     case TK_BLOB:
2273       return 0;
2274     case TK_COLUMN:
2275       return ExprHasProperty(p, EP_CanBeNull) ||
2276              p->y.pTab==0 ||  /* Reference to column of index on expression */
2277              (p->iColumn>=0
2278               && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */
2279               && p->y.pTab->aCol[p->iColumn].notNull==0);
2280     default:
2281       return 1;
2282   }
2283 }
2284 
2285 /*
2286 ** Return TRUE if the given expression is a constant which would be
2287 ** unchanged by OP_Affinity with the affinity given in the second
2288 ** argument.
2289 **
2290 ** This routine is used to determine if the OP_Affinity operation
2291 ** can be omitted.  When in doubt return FALSE.  A false negative
2292 ** is harmless.  A false positive, however, can result in the wrong
2293 ** answer.
2294 */
sqlite3ExprNeedsNoAffinityChange(const Expr * p,char aff)2295 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2296   u8 op;
2297   int unaryMinus = 0;
2298   if( aff==SQLITE_AFF_BLOB ) return 1;
2299   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2300     if( p->op==TK_UMINUS ) unaryMinus = 1;
2301     p = p->pLeft;
2302   }
2303   op = p->op;
2304   if( op==TK_REGISTER ) op = p->op2;
2305   switch( op ){
2306     case TK_INTEGER: {
2307       return aff>=SQLITE_AFF_NUMERIC;
2308     }
2309     case TK_FLOAT: {
2310       return aff>=SQLITE_AFF_NUMERIC;
2311     }
2312     case TK_STRING: {
2313       return !unaryMinus && aff==SQLITE_AFF_TEXT;
2314     }
2315     case TK_BLOB: {
2316       return !unaryMinus;
2317     }
2318     case TK_COLUMN: {
2319       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
2320       return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
2321     }
2322     default: {
2323       return 0;
2324     }
2325   }
2326 }
2327 
2328 /*
2329 ** Return TRUE if the given string is a row-id column name.
2330 */
sqlite3IsRowid(const char * z)2331 int sqlite3IsRowid(const char *z){
2332   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2333   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2334   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2335   return 0;
2336 }
2337 
2338 /*
2339 ** pX is the RHS of an IN operator.  If pX is a SELECT statement
2340 ** that can be simplified to a direct table access, then return
2341 ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
2342 ** or if the SELECT statement needs to be manifested into a transient
2343 ** table, then return NULL.
2344 */
2345 #ifndef SQLITE_OMIT_SUBQUERY
isCandidateForInOpt(Expr * pX)2346 static Select *isCandidateForInOpt(Expr *pX){
2347   Select *p;
2348   SrcList *pSrc;
2349   ExprList *pEList;
2350   Table *pTab;
2351   int i;
2352   if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
2353   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
2354   p = pX->x.pSelect;
2355   if( p->pPrior ) return 0;              /* Not a compound SELECT */
2356   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2357     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2358     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2359     return 0; /* No DISTINCT keyword and no aggregate functions */
2360   }
2361   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
2362   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
2363   if( p->pWhere ) return 0;              /* Has no WHERE clause */
2364   pSrc = p->pSrc;
2365   assert( pSrc!=0 );
2366   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
2367   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
2368   pTab = pSrc->a[0].pTab;
2369   assert( pTab!=0 );
2370   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
2371   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
2372   pEList = p->pEList;
2373   assert( pEList!=0 );
2374   /* All SELECT results must be columns. */
2375   for(i=0; i<pEList->nExpr; i++){
2376     Expr *pRes = pEList->a[i].pExpr;
2377     if( pRes->op!=TK_COLUMN ) return 0;
2378     assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
2379   }
2380   return p;
2381 }
2382 #endif /* SQLITE_OMIT_SUBQUERY */
2383 
2384 #ifndef SQLITE_OMIT_SUBQUERY
2385 /*
2386 ** Generate code that checks the left-most column of index table iCur to see if
2387 ** it contains any NULL entries.  Cause the register at regHasNull to be set
2388 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
2389 ** to be set to NULL if iCur contains one or more NULL values.
2390 */
sqlite3SetHasNullFlag(Vdbe * v,int iCur,int regHasNull)2391 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2392   int addr1;
2393   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2394   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2395   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2396   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
2397   VdbeComment((v, "first_entry_in(%d)", iCur));
2398   sqlite3VdbeJumpHere(v, addr1);
2399 }
2400 #endif
2401 
2402 
2403 #ifndef SQLITE_OMIT_SUBQUERY
2404 /*
2405 ** The argument is an IN operator with a list (not a subquery) on the
2406 ** right-hand side.  Return TRUE if that list is constant.
2407 */
sqlite3InRhsIsConstant(Expr * pIn)2408 static int sqlite3InRhsIsConstant(Expr *pIn){
2409   Expr *pLHS;
2410   int res;
2411   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2412   pLHS = pIn->pLeft;
2413   pIn->pLeft = 0;
2414   res = sqlite3ExprIsConstant(pIn);
2415   pIn->pLeft = pLHS;
2416   return res;
2417 }
2418 #endif
2419 
2420 /*
2421 ** This function is used by the implementation of the IN (...) operator.
2422 ** The pX parameter is the expression on the RHS of the IN operator, which
2423 ** might be either a list of expressions or a subquery.
2424 **
2425 ** The job of this routine is to find or create a b-tree object that can
2426 ** be used either to test for membership in the RHS set or to iterate through
2427 ** all members of the RHS set, skipping duplicates.
2428 **
2429 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2430 ** and pX->iTable is set to the index of that cursor.
2431 **
2432 ** The returned value of this function indicates the b-tree type, as follows:
2433 **
2434 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
2435 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
2436 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2437 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
2438 **                         populated epheremal table.
2439 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
2440 **                         implemented as a sequence of comparisons.
2441 **
2442 ** An existing b-tree might be used if the RHS expression pX is a simple
2443 ** subquery such as:
2444 **
2445 **     SELECT <column1>, <column2>... FROM <table>
2446 **
2447 ** If the RHS of the IN operator is a list or a more complex subquery, then
2448 ** an ephemeral table might need to be generated from the RHS and then
2449 ** pX->iTable made to point to the ephemeral table instead of an
2450 ** existing table.
2451 **
2452 ** The inFlags parameter must contain, at a minimum, one of the bits
2453 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both.  If inFlags contains
2454 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2455 ** membership test.  When the IN_INDEX_LOOP bit is set, the IN index will
2456 ** be used to loop over all values of the RHS of the IN operator.
2457 **
2458 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2459 ** through the set members) then the b-tree must not contain duplicates.
2460 ** An epheremal table will be created unless the selected columns are guaranteed
2461 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2462 ** a UNIQUE constraint or index.
2463 **
2464 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2465 ** for fast set membership tests) then an epheremal table must
2466 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2467 ** index can be found with the specified <columns> as its left-most.
2468 **
2469 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2470 ** if the RHS of the IN operator is a list (not a subquery) then this
2471 ** routine might decide that creating an ephemeral b-tree for membership
2472 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
2473 ** calling routine should implement the IN operator using a sequence
2474 ** of Eq or Ne comparison operations.
2475 **
2476 ** When the b-tree is being used for membership tests, the calling function
2477 ** might need to know whether or not the RHS side of the IN operator
2478 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
2479 ** if there is any chance that the (...) might contain a NULL value at
2480 ** runtime, then a register is allocated and the register number written
2481 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2482 ** NULL value, then *prRhsHasNull is left unchanged.
2483 **
2484 ** If a register is allocated and its location stored in *prRhsHasNull, then
2485 ** the value in that register will be NULL if the b-tree contains one or more
2486 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2487 ** NULL values.
2488 **
2489 ** If the aiMap parameter is not NULL, it must point to an array containing
2490 ** one element for each column returned by the SELECT statement on the RHS
2491 ** of the IN(...) operator. The i'th entry of the array is populated with the
2492 ** offset of the index column that matches the i'th column returned by the
2493 ** SELECT. For example, if the expression and selected index are:
2494 **
2495 **   (?,?,?) IN (SELECT a, b, c FROM t1)
2496 **   CREATE INDEX i1 ON t1(b, c, a);
2497 **
2498 ** then aiMap[] is populated with {2, 0, 1}.
2499 */
2500 #ifndef SQLITE_OMIT_SUBQUERY
sqlite3FindInIndex(Parse * pParse,Expr * pX,u32 inFlags,int * prRhsHasNull,int * aiMap,int * piTab)2501 int sqlite3FindInIndex(
2502   Parse *pParse,             /* Parsing context */
2503   Expr *pX,                  /* The IN expression */
2504   u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2505   int *prRhsHasNull,         /* Register holding NULL status.  See notes */
2506   int *aiMap,                /* Mapping from Index fields to RHS fields */
2507   int *piTab                 /* OUT: index to use */
2508 ){
2509   Select *p;                            /* SELECT to the right of IN operator */
2510   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
2511   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
2512   int mustBeUnique;                     /* True if RHS must be unique */
2513   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
2514 
2515   assert( pX->op==TK_IN );
2516   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
2517 
2518   /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2519   ** whether or not the SELECT result contains NULL values, check whether
2520   ** or not NULL is actually possible (it may not be, for example, due
2521   ** to NOT NULL constraints in the schema). If no NULL values are possible,
2522   ** set prRhsHasNull to 0 before continuing.  */
2523   if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2524     int i;
2525     ExprList *pEList = pX->x.pSelect->pEList;
2526     for(i=0; i<pEList->nExpr; i++){
2527       if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2528     }
2529     if( i==pEList->nExpr ){
2530       prRhsHasNull = 0;
2531     }
2532   }
2533 
2534   /* Check to see if an existing table or index can be used to
2535   ** satisfy the query.  This is preferable to generating a new
2536   ** ephemeral table.  */
2537   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
2538     sqlite3 *db = pParse->db;              /* Database connection */
2539     Table *pTab;                           /* Table <table>. */
2540     i16 iDb;                               /* Database idx for pTab */
2541     ExprList *pEList = p->pEList;
2542     int nExpr = pEList->nExpr;
2543 
2544     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
2545     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2546     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
2547     pTab = p->pSrc->a[0].pTab;
2548 
2549     /* Code an OP_Transaction and OP_TableLock for <table>. */
2550     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2551     sqlite3CodeVerifySchema(pParse, iDb);
2552     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
2553 
2554     assert(v);  /* sqlite3GetVdbe() has always been previously called */
2555     if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
2556       /* The "x IN (SELECT rowid FROM table)" case */
2557       int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
2558       VdbeCoverage(v);
2559 
2560       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2561       eType = IN_INDEX_ROWID;
2562       ExplainQueryPlan((pParse, 0,
2563             "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
2564       sqlite3VdbeJumpHere(v, iAddr);
2565     }else{
2566       Index *pIdx;                         /* Iterator variable */
2567       int affinity_ok = 1;
2568       int i;
2569 
2570       /* Check that the affinity that will be used to perform each
2571       ** comparison is the same as the affinity of each column in table
2572       ** on the RHS of the IN operator.  If it not, it is not possible to
2573       ** use any index of the RHS table.  */
2574       for(i=0; i<nExpr && affinity_ok; i++){
2575         Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2576         int iCol = pEList->a[i].pExpr->iColumn;
2577         char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
2578         char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2579         testcase( cmpaff==SQLITE_AFF_BLOB );
2580         testcase( cmpaff==SQLITE_AFF_TEXT );
2581         switch( cmpaff ){
2582           case SQLITE_AFF_BLOB:
2583             break;
2584           case SQLITE_AFF_TEXT:
2585             /* sqlite3CompareAffinity() only returns TEXT if one side or the
2586             ** other has no affinity and the other side is TEXT.  Hence,
2587             ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2588             ** and for the term on the LHS of the IN to have no affinity. */
2589             assert( idxaff==SQLITE_AFF_TEXT );
2590             break;
2591           default:
2592             affinity_ok = sqlite3IsNumericAffinity(idxaff);
2593         }
2594       }
2595 
2596       if( affinity_ok ){
2597         /* Search for an existing index that will work for this IN operator */
2598         for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2599           Bitmask colUsed;      /* Columns of the index used */
2600           Bitmask mCol;         /* Mask for the current column */
2601           if( pIdx->nColumn<nExpr ) continue;
2602           if( pIdx->pPartIdxWhere!=0 ) continue;
2603           /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2604           ** BITMASK(nExpr) without overflowing */
2605           testcase( pIdx->nColumn==BMS-2 );
2606           testcase( pIdx->nColumn==BMS-1 );
2607           if( pIdx->nColumn>=BMS-1 ) continue;
2608           if( mustBeUnique ){
2609             if( pIdx->nKeyCol>nExpr
2610              ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2611             ){
2612               continue;  /* This index is not unique over the IN RHS columns */
2613             }
2614           }
2615 
2616           colUsed = 0;   /* Columns of index used so far */
2617           for(i=0; i<nExpr; i++){
2618             Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2619             Expr *pRhs = pEList->a[i].pExpr;
2620             CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2621             int j;
2622 
2623             assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
2624             for(j=0; j<nExpr; j++){
2625               if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2626               assert( pIdx->azColl[j] );
2627               if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2628                 continue;
2629               }
2630               break;
2631             }
2632             if( j==nExpr ) break;
2633             mCol = MASKBIT(j);
2634             if( mCol & colUsed ) break; /* Each column used only once */
2635             colUsed |= mCol;
2636             if( aiMap ) aiMap[i] = j;
2637           }
2638 
2639           assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2640           if( colUsed==(MASKBIT(nExpr)-1) ){
2641             /* If we reach this point, that means the index pIdx is usable */
2642             int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2643             ExplainQueryPlan((pParse, 0,
2644                               "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
2645             sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2646             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2647             VdbeComment((v, "%s", pIdx->zName));
2648             assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2649             eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
2650 
2651             if( prRhsHasNull ){
2652 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
2653               i64 mask = (1<<nExpr)-1;
2654               sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
2655                   iTab, 0, 0, (u8*)&mask, P4_INT64);
2656 #endif
2657               *prRhsHasNull = ++pParse->nMem;
2658               if( nExpr==1 ){
2659                 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2660               }
2661             }
2662             sqlite3VdbeJumpHere(v, iAddr);
2663           }
2664         } /* End loop over indexes */
2665       } /* End if( affinity_ok ) */
2666     } /* End if not an rowid index */
2667   } /* End attempt to optimize using an index */
2668 
2669   /* If no preexisting index is available for the IN clause
2670   ** and IN_INDEX_NOOP is an allowed reply
2671   ** and the RHS of the IN operator is a list, not a subquery
2672   ** and the RHS is not constant or has two or fewer terms,
2673   ** then it is not worth creating an ephemeral table to evaluate
2674   ** the IN operator so return IN_INDEX_NOOP.
2675   */
2676   if( eType==0
2677    && (inFlags & IN_INDEX_NOOP_OK)
2678    && !ExprHasProperty(pX, EP_xIsSelect)
2679    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2680   ){
2681     eType = IN_INDEX_NOOP;
2682   }
2683 
2684   if( eType==0 ){
2685     /* Could not find an existing table or index to use as the RHS b-tree.
2686     ** We will have to generate an ephemeral table to do the job.
2687     */
2688     u32 savedNQueryLoop = pParse->nQueryLoop;
2689     int rMayHaveNull = 0;
2690     eType = IN_INDEX_EPH;
2691     if( inFlags & IN_INDEX_LOOP ){
2692       pParse->nQueryLoop = 0;
2693     }else if( prRhsHasNull ){
2694       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
2695     }
2696     assert( pX->op==TK_IN );
2697     sqlite3CodeRhsOfIN(pParse, pX, iTab);
2698     if( rMayHaveNull ){
2699       sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
2700     }
2701     pParse->nQueryLoop = savedNQueryLoop;
2702   }
2703 
2704   if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2705     int i, n;
2706     n = sqlite3ExprVectorSize(pX->pLeft);
2707     for(i=0; i<n; i++) aiMap[i] = i;
2708   }
2709   *piTab = iTab;
2710   return eType;
2711 }
2712 #endif
2713 
2714 #ifndef SQLITE_OMIT_SUBQUERY
2715 /*
2716 ** Argument pExpr is an (?, ?...) IN(...) expression. This
2717 ** function allocates and returns a nul-terminated string containing
2718 ** the affinities to be used for each column of the comparison.
2719 **
2720 ** It is the responsibility of the caller to ensure that the returned
2721 ** string is eventually freed using sqlite3DbFree().
2722 */
exprINAffinity(Parse * pParse,Expr * pExpr)2723 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2724   Expr *pLeft = pExpr->pLeft;
2725   int nVal = sqlite3ExprVectorSize(pLeft);
2726   Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
2727   char *zRet;
2728 
2729   assert( pExpr->op==TK_IN );
2730   zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
2731   if( zRet ){
2732     int i;
2733     for(i=0; i<nVal; i++){
2734       Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
2735       char a = sqlite3ExprAffinity(pA);
2736       if( pSelect ){
2737         zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2738       }else{
2739         zRet[i] = a;
2740       }
2741     }
2742     zRet[nVal] = '\0';
2743   }
2744   return zRet;
2745 }
2746 #endif
2747 
2748 #ifndef SQLITE_OMIT_SUBQUERY
2749 /*
2750 ** Load the Parse object passed as the first argument with an error
2751 ** message of the form:
2752 **
2753 **   "sub-select returns N columns - expected M"
2754 */
sqlite3SubselectError(Parse * pParse,int nActual,int nExpect)2755 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2756   if( pParse->nErr==0 ){
2757     const char *zFmt = "sub-select returns %d columns - expected %d";
2758     sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2759   }
2760 }
2761 #endif
2762 
2763 /*
2764 ** Expression pExpr is a vector that has been used in a context where
2765 ** it is not permitted. If pExpr is a sub-select vector, this routine
2766 ** loads the Parse object with a message of the form:
2767 **
2768 **   "sub-select returns N columns - expected 1"
2769 **
2770 ** Or, if it is a regular scalar vector:
2771 **
2772 **   "row value misused"
2773 */
sqlite3VectorErrorMsg(Parse * pParse,Expr * pExpr)2774 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
2775 #ifndef SQLITE_OMIT_SUBQUERY
2776   if( pExpr->flags & EP_xIsSelect ){
2777     sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
2778   }else
2779 #endif
2780   {
2781     sqlite3ErrorMsg(pParse, "row value misused");
2782   }
2783 }
2784 
2785 #ifndef SQLITE_OMIT_SUBQUERY
2786 /*
2787 ** Generate code that will construct an ephemeral table containing all terms
2788 ** in the RHS of an IN operator.  The IN operator can be in either of two
2789 ** forms:
2790 **
2791 **     x IN (4,5,11)              -- IN operator with list on right-hand side
2792 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
2793 **
2794 ** The pExpr parameter is the IN operator.  The cursor number for the
2795 ** constructed ephermeral table is returned.  The first time the ephemeral
2796 ** table is computed, the cursor number is also stored in pExpr->iTable,
2797 ** however the cursor number returned might not be the same, as it might
2798 ** have been duplicated using OP_OpenDup.
2799 **
2800 ** If the LHS expression ("x" in the examples) is a column value, or
2801 ** the SELECT statement returns a column value, then the affinity of that
2802 ** column is used to build the index keys. If both 'x' and the
2803 ** SELECT... statement are columns, then numeric affinity is used
2804 ** if either column has NUMERIC or INTEGER affinity. If neither
2805 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2806 ** is used.
2807 */
sqlite3CodeRhsOfIN(Parse * pParse,Expr * pExpr,int iTab)2808 void sqlite3CodeRhsOfIN(
2809   Parse *pParse,          /* Parsing context */
2810   Expr *pExpr,            /* The IN operator */
2811   int iTab                /* Use this cursor number */
2812 ){
2813   int addrOnce = 0;           /* Address of the OP_Once instruction at top */
2814   int addr;                   /* Address of OP_OpenEphemeral instruction */
2815   Expr *pLeft;                /* the LHS of the IN operator */
2816   KeyInfo *pKeyInfo = 0;      /* Key information */
2817   int nVal;                   /* Size of vector pLeft */
2818   Vdbe *v;                    /* The prepared statement under construction */
2819 
2820   v = pParse->pVdbe;
2821   assert( v!=0 );
2822 
2823   /* The evaluation of the IN must be repeated every time it
2824   ** is encountered if any of the following is true:
2825   **
2826   **    *  The right-hand side is a correlated subquery
2827   **    *  The right-hand side is an expression list containing variables
2828   **    *  We are inside a trigger
2829   **
2830   ** If all of the above are false, then we can compute the RHS just once
2831   ** and reuse it many names.
2832   */
2833   if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
2834     /* Reuse of the RHS is allowed */
2835     /* If this routine has already been coded, but the previous code
2836     ** might not have been invoked yet, so invoke it now as a subroutine.
2837     */
2838     if( ExprHasProperty(pExpr, EP_Subrtn) ){
2839       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2840       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2841         ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
2842               pExpr->x.pSelect->selId));
2843       }
2844       sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
2845                         pExpr->y.sub.iAddr);
2846       sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
2847       sqlite3VdbeJumpHere(v, addrOnce);
2848       return;
2849     }
2850 
2851     /* Begin coding the subroutine */
2852     ExprSetProperty(pExpr, EP_Subrtn);
2853     assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
2854     pExpr->y.sub.regReturn = ++pParse->nMem;
2855     pExpr->y.sub.iAddr =
2856       sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
2857     VdbeComment((v, "return address"));
2858 
2859     addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2860   }
2861 
2862   /* Check to see if this is a vector IN operator */
2863   pLeft = pExpr->pLeft;
2864   nVal = sqlite3ExprVectorSize(pLeft);
2865 
2866   /* Construct the ephemeral table that will contain the content of
2867   ** RHS of the IN operator.
2868   */
2869   pExpr->iTable = iTab;
2870   addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
2871 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
2872   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2873     VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
2874   }else{
2875     VdbeComment((v, "RHS of IN operator"));
2876   }
2877 #endif
2878   pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
2879 
2880   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2881     /* Case 1:     expr IN (SELECT ...)
2882     **
2883     ** Generate code to write the results of the select into the temporary
2884     ** table allocated and opened above.
2885     */
2886     Select *pSelect = pExpr->x.pSelect;
2887     ExprList *pEList = pSelect->pEList;
2888 
2889     ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
2890         addrOnce?"":"CORRELATED ", pSelect->selId
2891     ));
2892     /* If the LHS and RHS of the IN operator do not match, that
2893     ** error will have been caught long before we reach this point. */
2894     if( ALWAYS(pEList->nExpr==nVal) ){
2895       SelectDest dest;
2896       int i;
2897       sqlite3SelectDestInit(&dest, SRT_Set, iTab);
2898       dest.zAffSdst = exprINAffinity(pParse, pExpr);
2899       pSelect->iLimit = 0;
2900       testcase( pSelect->selFlags & SF_Distinct );
2901       testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2902       if( sqlite3Select(pParse, pSelect, &dest) ){
2903         sqlite3DbFree(pParse->db, dest.zAffSdst);
2904         sqlite3KeyInfoUnref(pKeyInfo);
2905         return;
2906       }
2907       sqlite3DbFree(pParse->db, dest.zAffSdst);
2908       assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2909       assert( pEList!=0 );
2910       assert( pEList->nExpr>0 );
2911       assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2912       for(i=0; i<nVal; i++){
2913         Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
2914         pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2915             pParse, p, pEList->a[i].pExpr
2916         );
2917       }
2918     }
2919   }else if( ALWAYS(pExpr->x.pList!=0) ){
2920     /* Case 2:     expr IN (exprlist)
2921     **
2922     ** For each expression, build an index key from the evaluation and
2923     ** store it in the temporary table. If <expr> is a column, then use
2924     ** that columns affinity when building index keys. If <expr> is not
2925     ** a column, use numeric affinity.
2926     */
2927     char affinity;            /* Affinity of the LHS of the IN */
2928     int i;
2929     ExprList *pList = pExpr->x.pList;
2930     struct ExprList_item *pItem;
2931     int r1, r2;
2932     affinity = sqlite3ExprAffinity(pLeft);
2933     if( affinity<=SQLITE_AFF_NONE ){
2934       affinity = SQLITE_AFF_BLOB;
2935     }
2936     if( pKeyInfo ){
2937       assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2938       pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2939     }
2940 
2941     /* Loop through each expression in <exprlist>. */
2942     r1 = sqlite3GetTempReg(pParse);
2943     r2 = sqlite3GetTempReg(pParse);
2944     for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2945       Expr *pE2 = pItem->pExpr;
2946 
2947       /* If the expression is not constant then we will need to
2948       ** disable the test that was generated above that makes sure
2949       ** this code only executes once.  Because for a non-constant
2950       ** expression we need to rerun this code each time.
2951       */
2952       if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
2953         sqlite3VdbeChangeToNoop(v, addrOnce);
2954         ExprClearProperty(pExpr, EP_Subrtn);
2955         addrOnce = 0;
2956       }
2957 
2958       /* Evaluate the expression and insert it into the temp table */
2959       sqlite3ExprCode(pParse, pE2, r1);
2960       sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
2961       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
2962     }
2963     sqlite3ReleaseTempReg(pParse, r1);
2964     sqlite3ReleaseTempReg(pParse, r2);
2965   }
2966   if( pKeyInfo ){
2967     sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
2968   }
2969   if( addrOnce ){
2970     sqlite3VdbeJumpHere(v, addrOnce);
2971     /* Subroutine return */
2972     sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
2973     sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
2974     sqlite3ClearTempRegCache(pParse);
2975   }
2976 }
2977 #endif /* SQLITE_OMIT_SUBQUERY */
2978 
2979 /*
2980 ** Generate code for scalar subqueries used as a subquery expression
2981 ** or EXISTS operator:
2982 **
2983 **     (SELECT a FROM b)          -- subquery
2984 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
2985 **
2986 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
2987 **
2988 ** Return the register that holds the result.  For a multi-column SELECT,
2989 ** the result is stored in a contiguous array of registers and the
2990 ** return value is the register of the left-most result column.
2991 ** Return 0 if an error occurs.
2992 */
2993 #ifndef SQLITE_OMIT_SUBQUERY
sqlite3CodeSubselect(Parse * pParse,Expr * pExpr)2994 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
2995   int addrOnce = 0;           /* Address of OP_Once at top of subroutine */
2996   int rReg = 0;               /* Register storing resulting */
2997   Select *pSel;               /* SELECT statement to encode */
2998   SelectDest dest;            /* How to deal with SELECT result */
2999   int nReg;                   /* Registers to allocate */
3000   Expr *pLimit;               /* New limit expression */
3001 
3002   Vdbe *v = pParse->pVdbe;
3003   assert( v!=0 );
3004   testcase( pExpr->op==TK_EXISTS );
3005   testcase( pExpr->op==TK_SELECT );
3006   assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
3007   assert( ExprHasProperty(pExpr, EP_xIsSelect) );
3008   pSel = pExpr->x.pSelect;
3009 
3010   /* The evaluation of the EXISTS/SELECT must be repeated every time it
3011   ** is encountered if any of the following is true:
3012   **
3013   **    *  The right-hand side is a correlated subquery
3014   **    *  The right-hand side is an expression list containing variables
3015   **    *  We are inside a trigger
3016   **
3017   ** If all of the above are false, then we can run this code just once
3018   ** save the results, and reuse the same result on subsequent invocations.
3019   */
3020   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
3021     /* If this routine has already been coded, then invoke it as a
3022     ** subroutine. */
3023     if( ExprHasProperty(pExpr, EP_Subrtn) ){
3024       ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
3025       sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3026                         pExpr->y.sub.iAddr);
3027       return pExpr->iTable;
3028     }
3029 
3030     /* Begin coding the subroutine */
3031     ExprSetProperty(pExpr, EP_Subrtn);
3032     pExpr->y.sub.regReturn = ++pParse->nMem;
3033     pExpr->y.sub.iAddr =
3034       sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
3035     VdbeComment((v, "return address"));
3036 
3037     addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3038   }
3039 
3040   /* For a SELECT, generate code to put the values for all columns of
3041   ** the first row into an array of registers and return the index of
3042   ** the first register.
3043   **
3044   ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3045   ** into a register and return that register number.
3046   **
3047   ** In both cases, the query is augmented with "LIMIT 1".  Any
3048   ** preexisting limit is discarded in place of the new LIMIT 1.
3049   */
3050   ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
3051         addrOnce?"":"CORRELATED ", pSel->selId));
3052   nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
3053   sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
3054   pParse->nMem += nReg;
3055   if( pExpr->op==TK_SELECT ){
3056     dest.eDest = SRT_Mem;
3057     dest.iSdst = dest.iSDParm;
3058     dest.nSdst = nReg;
3059     sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
3060     VdbeComment((v, "Init subquery result"));
3061   }else{
3062     dest.eDest = SRT_Exists;
3063     sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
3064     VdbeComment((v, "Init EXISTS result"));
3065   }
3066   if( pSel->pLimit ){
3067     /* The subquery already has a limit.  If the pre-existing limit is X
3068     ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3069     sqlite3 *db = pParse->db;
3070     pLimit = sqlite3Expr(db, TK_INTEGER, "0");
3071     if( pLimit ){
3072       pLimit->affExpr = SQLITE_AFF_NUMERIC;
3073       pLimit = sqlite3PExpr(pParse, TK_NE,
3074                             sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
3075     }
3076     sqlite3ExprDelete(db, pSel->pLimit->pLeft);
3077     pSel->pLimit->pLeft = pLimit;
3078   }else{
3079     /* If there is no pre-existing limit add a limit of 1 */
3080     pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
3081     pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
3082   }
3083   pSel->iLimit = 0;
3084   if( sqlite3Select(pParse, pSel, &dest) ){
3085     return 0;
3086   }
3087   pExpr->iTable = rReg = dest.iSDParm;
3088   ExprSetVVAProperty(pExpr, EP_NoReduce);
3089   if( addrOnce ){
3090     sqlite3VdbeJumpHere(v, addrOnce);
3091 
3092     /* Subroutine return */
3093     sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
3094     sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
3095     sqlite3ClearTempRegCache(pParse);
3096   }
3097 
3098   return rReg;
3099 }
3100 #endif /* SQLITE_OMIT_SUBQUERY */
3101 
3102 #ifndef SQLITE_OMIT_SUBQUERY
3103 /*
3104 ** Expr pIn is an IN(...) expression. This function checks that the
3105 ** sub-select on the RHS of the IN() operator has the same number of
3106 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3107 ** a sub-query, that the LHS is a vector of size 1.
3108 */
sqlite3ExprCheckIN(Parse * pParse,Expr * pIn)3109 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
3110   int nVector = sqlite3ExprVectorSize(pIn->pLeft);
3111   if( (pIn->flags & EP_xIsSelect) ){
3112     if( nVector!=pIn->x.pSelect->pEList->nExpr ){
3113       sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
3114       return 1;
3115     }
3116   }else if( nVector!=1 ){
3117     sqlite3VectorErrorMsg(pParse, pIn->pLeft);
3118     return 1;
3119   }
3120   return 0;
3121 }
3122 #endif
3123 
3124 #ifndef SQLITE_OMIT_SUBQUERY
3125 /*
3126 ** Generate code for an IN expression.
3127 **
3128 **      x IN (SELECT ...)
3129 **      x IN (value, value, ...)
3130 **
3131 ** The left-hand side (LHS) is a scalar or vector expression.  The
3132 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3133 ** subquery.  If the RHS is a subquery, the number of result columns must
3134 ** match the number of columns in the vector on the LHS.  If the RHS is
3135 ** a list of values, the LHS must be a scalar.
3136 **
3137 ** The IN operator is true if the LHS value is contained within the RHS.
3138 ** The result is false if the LHS is definitely not in the RHS.  The
3139 ** result is NULL if the presence of the LHS in the RHS cannot be
3140 ** determined due to NULLs.
3141 **
3142 ** This routine generates code that jumps to destIfFalse if the LHS is not
3143 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
3144 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
3145 ** within the RHS then fall through.
3146 **
3147 ** See the separate in-operator.md documentation file in the canonical
3148 ** SQLite source tree for additional information.
3149 */
sqlite3ExprCodeIN(Parse * pParse,Expr * pExpr,int destIfFalse,int destIfNull)3150 static void sqlite3ExprCodeIN(
3151   Parse *pParse,        /* Parsing and code generating context */
3152   Expr *pExpr,          /* The IN expression */
3153   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
3154   int destIfNull        /* Jump here if the results are unknown due to NULLs */
3155 ){
3156   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
3157   int eType;            /* Type of the RHS */
3158   int rLhs;             /* Register(s) holding the LHS values */
3159   int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
3160   Vdbe *v;              /* Statement under construction */
3161   int *aiMap = 0;       /* Map from vector field to index column */
3162   char *zAff = 0;       /* Affinity string for comparisons */
3163   int nVector;          /* Size of vectors for this IN operator */
3164   int iDummy;           /* Dummy parameter to exprCodeVector() */
3165   Expr *pLeft;          /* The LHS of the IN operator */
3166   int i;                /* loop counter */
3167   int destStep2;        /* Where to jump when NULLs seen in step 2 */
3168   int destStep6 = 0;    /* Start of code for Step 6 */
3169   int addrTruthOp;      /* Address of opcode that determines the IN is true */
3170   int destNotNull;      /* Jump here if a comparison is not true in step 6 */
3171   int addrTop;          /* Top of the step-6 loop */
3172   int iTab = 0;         /* Index to use */
3173 
3174   pLeft = pExpr->pLeft;
3175   if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3176   zAff = exprINAffinity(pParse, pExpr);
3177   nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3178   aiMap = (int*)sqlite3DbMallocZero(
3179       pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3180   );
3181   if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3182 
3183   /* Attempt to compute the RHS. After this step, if anything other than
3184   ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3185   ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3186   ** the RHS has not yet been coded.  */
3187   v = pParse->pVdbe;
3188   assert( v!=0 );       /* OOM detected prior to this routine */
3189   VdbeNoopComment((v, "begin IN expr"));
3190   eType = sqlite3FindInIndex(pParse, pExpr,
3191                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
3192                              destIfFalse==destIfNull ? 0 : &rRhsHasNull,
3193                              aiMap, &iTab);
3194 
3195   assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3196        || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3197   );
3198 #ifdef SQLITE_DEBUG
3199   /* Confirm that aiMap[] contains nVector integer values between 0 and
3200   ** nVector-1. */
3201   for(i=0; i<nVector; i++){
3202     int j, cnt;
3203     for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3204     assert( cnt==1 );
3205   }
3206 #endif
3207 
3208   /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3209   ** vector, then it is stored in an array of nVector registers starting
3210   ** at r1.
3211   **
3212   ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3213   ** so that the fields are in the same order as an existing index.   The
3214   ** aiMap[] array contains a mapping from the original LHS field order to
3215   ** the field order that matches the RHS index.
3216   */
3217   rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3218   for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3219   if( i==nVector ){
3220     /* LHS fields are not reordered */
3221     rLhs = rLhsOrig;
3222   }else{
3223     /* Need to reorder the LHS fields according to aiMap */
3224     rLhs = sqlite3GetTempRange(pParse, nVector);
3225     for(i=0; i<nVector; i++){
3226       sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3227     }
3228   }
3229 
3230   /* If sqlite3FindInIndex() did not find or create an index that is
3231   ** suitable for evaluating the IN operator, then evaluate using a
3232   ** sequence of comparisons.
3233   **
3234   ** This is step (1) in the in-operator.md optimized algorithm.
3235   */
3236   if( eType==IN_INDEX_NOOP ){
3237     ExprList *pList = pExpr->x.pList;
3238     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3239     int labelOk = sqlite3VdbeMakeLabel(pParse);
3240     int r2, regToFree;
3241     int regCkNull = 0;
3242     int ii;
3243     int bLhsReal;  /* True if the LHS of the IN has REAL affinity */
3244     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3245     if( destIfNull!=destIfFalse ){
3246       regCkNull = sqlite3GetTempReg(pParse);
3247       sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
3248     }
3249     bLhsReal = sqlite3ExprAffinity(pExpr->pLeft)==SQLITE_AFF_REAL;
3250     for(ii=0; ii<pList->nExpr; ii++){
3251       if( bLhsReal ){
3252         r2 = regToFree = sqlite3GetTempReg(pParse);
3253         sqlite3ExprCode(pParse, pList->a[ii].pExpr, r2);
3254         sqlite3VdbeAddOp4(v, OP_Affinity, r2, 1, 0, "E", P4_STATIC);
3255       }else{
3256         r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
3257       }
3258       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
3259         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3260       }
3261       sqlite3ReleaseTempReg(pParse, regToFree);
3262       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
3263         int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
3264         sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
3265                           (void*)pColl, P4_COLLSEQ);
3266         VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
3267         VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
3268         VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
3269         VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
3270         sqlite3VdbeChangeP5(v, zAff[0]);
3271       }else{
3272         int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
3273         assert( destIfNull==destIfFalse );
3274         sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
3275                           (void*)pColl, P4_COLLSEQ);
3276         VdbeCoverageIf(v, op==OP_Ne);
3277         VdbeCoverageIf(v, op==OP_IsNull);
3278         sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
3279       }
3280     }
3281     if( regCkNull ){
3282       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
3283       sqlite3VdbeGoto(v, destIfFalse);
3284     }
3285     sqlite3VdbeResolveLabel(v, labelOk);
3286     sqlite3ReleaseTempReg(pParse, regCkNull);
3287     goto sqlite3ExprCodeIN_finished;
3288   }
3289 
3290   /* Step 2: Check to see if the LHS contains any NULL columns.  If the
3291   ** LHS does contain NULLs then the result must be either FALSE or NULL.
3292   ** We will then skip the binary search of the RHS.
3293   */
3294   if( destIfNull==destIfFalse ){
3295     destStep2 = destIfFalse;
3296   }else{
3297     destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
3298   }
3299   if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;
3300   for(i=0; i<nVector; i++){
3301     Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3302     if( sqlite3ExprCanBeNull(p) ){
3303       sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
3304       VdbeCoverage(v);
3305     }
3306   }
3307 
3308   /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
3309   ** of the RHS using the LHS as a probe.  If found, the result is
3310   ** true.
3311   */
3312   if( eType==IN_INDEX_ROWID ){
3313     /* In this case, the RHS is the ROWID of table b-tree and so we also
3314     ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
3315     ** into a single opcode. */
3316     sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
3317     VdbeCoverage(v);
3318     addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
3319   }else{
3320     sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3321     if( destIfFalse==destIfNull ){
3322       /* Combine Step 3 and Step 5 into a single opcode */
3323       sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
3324                            rLhs, nVector); VdbeCoverage(v);
3325       goto sqlite3ExprCodeIN_finished;
3326     }
3327     /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3328     addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
3329                                       rLhs, nVector); VdbeCoverage(v);
3330   }
3331 
3332   /* Step 4.  If the RHS is known to be non-NULL and we did not find
3333   ** an match on the search above, then the result must be FALSE.
3334   */
3335   if( rRhsHasNull && nVector==1 ){
3336     sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3337     VdbeCoverage(v);
3338   }
3339 
3340   /* Step 5.  If we do not care about the difference between NULL and
3341   ** FALSE, then just return false.
3342   */
3343   if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3344 
3345   /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
3346   ** If any comparison is NULL, then the result is NULL.  If all
3347   ** comparisons are FALSE then the final result is FALSE.
3348   **
3349   ** For a scalar LHS, it is sufficient to check just the first row
3350   ** of the RHS.
3351   */
3352   if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
3353   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
3354   VdbeCoverage(v);
3355   if( nVector>1 ){
3356     destNotNull = sqlite3VdbeMakeLabel(pParse);
3357   }else{
3358     /* For nVector==1, combine steps 6 and 7 by immediately returning
3359     ** FALSE if the first comparison is not NULL */
3360     destNotNull = destIfFalse;
3361   }
3362   for(i=0; i<nVector; i++){
3363     Expr *p;
3364     CollSeq *pColl;
3365     int r3 = sqlite3GetTempReg(pParse);
3366     p = sqlite3VectorFieldSubexpr(pLeft, i);
3367     pColl = sqlite3ExprCollSeq(pParse, p);
3368     sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
3369     sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
3370                       (void*)pColl, P4_COLLSEQ);
3371     VdbeCoverage(v);
3372     sqlite3ReleaseTempReg(pParse, r3);
3373   }
3374   sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3375   if( nVector>1 ){
3376     sqlite3VdbeResolveLabel(v, destNotNull);
3377     sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
3378     VdbeCoverage(v);
3379 
3380     /* Step 7:  If we reach this point, we know that the result must
3381     ** be false. */
3382     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3383   }
3384 
3385   /* Jumps here in order to return true. */
3386   sqlite3VdbeJumpHere(v, addrTruthOp);
3387 
3388 sqlite3ExprCodeIN_finished:
3389   if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
3390   VdbeComment((v, "end IN expr"));
3391 sqlite3ExprCodeIN_oom_error:
3392   sqlite3DbFree(pParse->db, aiMap);
3393   sqlite3DbFree(pParse->db, zAff);
3394 }
3395 #endif /* SQLITE_OMIT_SUBQUERY */
3396 
3397 #ifndef SQLITE_OMIT_FLOATING_POINT
3398 /*
3399 ** Generate an instruction that will put the floating point
3400 ** value described by z[0..n-1] into register iMem.
3401 **
3402 ** The z[] string will probably not be zero-terminated.  But the
3403 ** z[n] character is guaranteed to be something that does not look
3404 ** like the continuation of the number.
3405 */
codeReal(Vdbe * v,const char * z,int negateFlag,int iMem)3406 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
3407   if( ALWAYS(z!=0) ){
3408     double value;
3409     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
3410     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3411     if( negateFlag ) value = -value;
3412     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
3413   }
3414 }
3415 #endif
3416 
3417 
3418 /*
3419 ** Generate an instruction that will put the integer describe by
3420 ** text z[0..n-1] into register iMem.
3421 **
3422 ** Expr.u.zToken is always UTF8 and zero-terminated.
3423 */
codeInteger(Parse * pParse,Expr * pExpr,int negFlag,int iMem)3424 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3425   Vdbe *v = pParse->pVdbe;
3426   if( pExpr->flags & EP_IntValue ){
3427     int i = pExpr->u.iValue;
3428     assert( i>=0 );
3429     if( negFlag ) i = -i;
3430     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3431   }else{
3432     int c;
3433     i64 value;
3434     const char *z = pExpr->u.zToken;
3435     assert( z!=0 );
3436     c = sqlite3DecOrHexToI64(z, &value);
3437     if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
3438 #ifdef SQLITE_OMIT_FLOATING_POINT
3439       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
3440 #else
3441 #ifndef SQLITE_OMIT_HEX_INTEGER
3442       if( sqlite3_strnicmp(z,"0x",2)==0 ){
3443         sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
3444       }else
3445 #endif
3446       {
3447         codeReal(v, z, negFlag, iMem);
3448       }
3449 #endif
3450     }else{
3451       if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
3452       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3453     }
3454   }
3455 }
3456 
3457 
3458 /* Generate code that will load into register regOut a value that is
3459 ** appropriate for the iIdxCol-th column of index pIdx.
3460 */
sqlite3ExprCodeLoadIndexColumn(Parse * pParse,Index * pIdx,int iTabCur,int iIdxCol,int regOut)3461 void sqlite3ExprCodeLoadIndexColumn(
3462   Parse *pParse,  /* The parsing context */
3463   Index *pIdx,    /* The index whose column is to be loaded */
3464   int iTabCur,    /* Cursor pointing to a table row */
3465   int iIdxCol,    /* The column of the index to be loaded */
3466   int regOut      /* Store the index column value in this register */
3467 ){
3468   i16 iTabCol = pIdx->aiColumn[iIdxCol];
3469   if( iTabCol==XN_EXPR ){
3470     assert( pIdx->aColExpr );
3471     assert( pIdx->aColExpr->nExpr>iIdxCol );
3472     pParse->iSelfTab = iTabCur + 1;
3473     sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
3474     pParse->iSelfTab = 0;
3475   }else{
3476     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3477                                     iTabCol, regOut);
3478   }
3479 }
3480 
3481 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3482 /*
3483 ** Generate code that will compute the value of generated column pCol
3484 ** and store the result in register regOut
3485 */
sqlite3ExprCodeGeneratedColumn(Parse * pParse,Column * pCol,int regOut)3486 void sqlite3ExprCodeGeneratedColumn(
3487   Parse *pParse,
3488   Column *pCol,
3489   int regOut
3490 ){
3491   int iAddr;
3492   Vdbe *v = pParse->pVdbe;
3493   assert( v!=0 );
3494   assert( pParse->iSelfTab!=0 );
3495   if( pParse->iSelfTab>0 ){
3496     iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
3497   }else{
3498     iAddr = 0;
3499   }
3500   sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut);
3501   if( pCol->affinity>=SQLITE_AFF_TEXT ){
3502     sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
3503   }
3504   if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
3505 }
3506 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
3507 
3508 /*
3509 ** Generate code to extract the value of the iCol-th column of a table.
3510 */
sqlite3ExprCodeGetColumnOfTable(Vdbe * v,Table * pTab,int iTabCur,int iCol,int regOut)3511 void sqlite3ExprCodeGetColumnOfTable(
3512   Vdbe *v,        /* Parsing context */
3513   Table *pTab,    /* The table containing the value */
3514   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
3515   int iCol,       /* Index of the column to extract */
3516   int regOut      /* Extract the value into this register */
3517 ){
3518   Column *pCol;
3519   assert( v!=0 );
3520   if( pTab==0 ){
3521     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
3522     return;
3523   }
3524   if( iCol<0 || iCol==pTab->iPKey ){
3525     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3526   }else{
3527     int op;
3528     int x;
3529     if( IsVirtual(pTab) ){
3530       op = OP_VColumn;
3531       x = iCol;
3532 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3533     }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
3534       Parse *pParse = sqlite3VdbeParser(v);
3535       if( pCol->colFlags & COLFLAG_BUSY ){
3536         sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
3537       }else{
3538         int savedSelfTab = pParse->iSelfTab;
3539         pCol->colFlags |= COLFLAG_BUSY;
3540         pParse->iSelfTab = iTabCur+1;
3541         sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
3542         pParse->iSelfTab = savedSelfTab;
3543         pCol->colFlags &= ~COLFLAG_BUSY;
3544       }
3545       return;
3546 #endif
3547     }else if( !HasRowid(pTab) ){
3548       testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
3549       x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3550       op = OP_Column;
3551     }else{
3552       x = sqlite3TableColumnToStorage(pTab,iCol);
3553       testcase( x!=iCol );
3554       op = OP_Column;
3555     }
3556     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
3557     sqlite3ColumnDefault(v, pTab, iCol, regOut);
3558   }
3559 }
3560 
3561 /*
3562 ** Generate code that will extract the iColumn-th column from
3563 ** table pTab and store the column value in register iReg.
3564 **
3565 ** There must be an open cursor to pTab in iTable when this routine
3566 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
3567 */
sqlite3ExprCodeGetColumn(Parse * pParse,Table * pTab,int iColumn,int iTable,int iReg,u8 p5)3568 int sqlite3ExprCodeGetColumn(
3569   Parse *pParse,   /* Parsing and code generating context */
3570   Table *pTab,     /* Description of the table we are reading from */
3571   int iColumn,     /* Index of the table column */
3572   int iTable,      /* The cursor pointing to the table */
3573   int iReg,        /* Store results here */
3574   u8 p5            /* P5 value for OP_Column + FLAGS */
3575 ){
3576   assert( pParse->pVdbe!=0 );
3577   sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
3578   if( p5 ){
3579     VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
3580     if( pOp->opcode==OP_Column ) pOp->p5 = p5;
3581   }
3582   return iReg;
3583 }
3584 
3585 /*
3586 ** Generate code to move content from registers iFrom...iFrom+nReg-1
3587 ** over to iTo..iTo+nReg-1.
3588 */
sqlite3ExprCodeMove(Parse * pParse,int iFrom,int iTo,int nReg)3589 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
3590   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
3591 }
3592 
3593 /*
3594 ** Convert a scalar expression node to a TK_REGISTER referencing
3595 ** register iReg.  The caller must ensure that iReg already contains
3596 ** the correct value for the expression.
3597 */
exprToRegister(Expr * pExpr,int iReg)3598 static void exprToRegister(Expr *pExpr, int iReg){
3599   Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
3600   p->op2 = p->op;
3601   p->op = TK_REGISTER;
3602   p->iTable = iReg;
3603   ExprClearProperty(p, EP_Skip);
3604 }
3605 
3606 /*
3607 ** Evaluate an expression (either a vector or a scalar expression) and store
3608 ** the result in continguous temporary registers.  Return the index of
3609 ** the first register used to store the result.
3610 **
3611 ** If the returned result register is a temporary scalar, then also write
3612 ** that register number into *piFreeable.  If the returned result register
3613 ** is not a temporary or if the expression is a vector set *piFreeable
3614 ** to 0.
3615 */
exprCodeVector(Parse * pParse,Expr * p,int * piFreeable)3616 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3617   int iResult;
3618   int nResult = sqlite3ExprVectorSize(p);
3619   if( nResult==1 ){
3620     iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3621   }else{
3622     *piFreeable = 0;
3623     if( p->op==TK_SELECT ){
3624 #if SQLITE_OMIT_SUBQUERY
3625       iResult = 0;
3626 #else
3627       iResult = sqlite3CodeSubselect(pParse, p);
3628 #endif
3629     }else{
3630       int i;
3631       iResult = pParse->nMem+1;
3632       pParse->nMem += nResult;
3633       for(i=0; i<nResult; i++){
3634         sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
3635       }
3636     }
3637   }
3638   return iResult;
3639 }
3640 
3641 /*
3642 ** Generate code to implement special SQL functions that are implemented
3643 ** in-line rather than by using the usual callbacks.
3644 */
exprCodeInlineFunction(Parse * pParse,ExprList * pFarg,int iFuncId,int target)3645 static int exprCodeInlineFunction(
3646   Parse *pParse,        /* Parsing context */
3647   ExprList *pFarg,      /* List of function arguments */
3648   int iFuncId,          /* Function ID.  One of the INTFUNC_... values */
3649   int target            /* Store function result in this register */
3650 ){
3651   int nFarg;
3652   Vdbe *v = pParse->pVdbe;
3653   assert( v!=0 );
3654   assert( pFarg!=0 );
3655   nFarg = pFarg->nExpr;
3656   assert( nFarg>0 );  /* All in-line functions have at least one argument */
3657   switch( iFuncId ){
3658     case INLINEFUNC_coalesce: {
3659       /* Attempt a direct implementation of the built-in COALESCE() and
3660       ** IFNULL() functions.  This avoids unnecessary evaluation of
3661       ** arguments past the first non-NULL argument.
3662       */
3663       int endCoalesce = sqlite3VdbeMakeLabel(pParse);
3664       int i;
3665       assert( nFarg>=2 );
3666       sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3667       for(i=1; i<nFarg; i++){
3668         sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
3669         VdbeCoverage(v);
3670         sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
3671       }
3672       if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){
3673         sqlite3VdbeChangeP5(v, 1);  /* Tag trailing OP_Copy as not mergable */
3674       }
3675       sqlite3VdbeResolveLabel(v, endCoalesce);
3676       break;
3677     }
3678 
3679     default: {
3680       /* The UNLIKELY() function is a no-op.  The result is the value
3681       ** of the first argument.
3682       */
3683       assert( nFarg==1 || nFarg==2 );
3684       target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
3685       break;
3686     }
3687 
3688   /***********************************************************************
3689   ** Test-only SQL functions that are only usable if enabled
3690   ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
3691   */
3692     case INLINEFUNC_expr_compare: {
3693       /* Compare two expressions using sqlite3ExprCompare() */
3694       assert( nFarg==2 );
3695       sqlite3VdbeAddOp2(v, OP_Integer,
3696          sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
3697          target);
3698       break;
3699     }
3700 
3701     case INLINEFUNC_expr_implies_expr: {
3702       /* Compare two expressions using sqlite3ExprImpliesExpr() */
3703       assert( nFarg==2 );
3704       sqlite3VdbeAddOp2(v, OP_Integer,
3705          sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
3706          target);
3707       break;
3708     }
3709 
3710     case INLINEFUNC_implies_nonnull_row: {
3711       /* REsult of sqlite3ExprImpliesNonNullRow() */
3712       Expr *pA1;
3713       assert( nFarg==2 );
3714       pA1 = pFarg->a[1].pExpr;
3715       if( pA1->op==TK_COLUMN ){
3716         sqlite3VdbeAddOp2(v, OP_Integer,
3717            sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),
3718            target);
3719       }else{
3720         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3721       }
3722       break;
3723     }
3724 
3725 #ifdef SQLITE_DEBUG
3726     case INLINEFUNC_affinity: {
3727       /* The AFFINITY() function evaluates to a string that describes
3728       ** the type affinity of the argument.  This is used for testing of
3729       ** the SQLite type logic.
3730       */
3731       const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
3732       char aff;
3733       assert( nFarg==1 );
3734       aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
3735       sqlite3VdbeLoadString(v, target,
3736               (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
3737       break;
3738     }
3739 #endif
3740   }
3741   return target;
3742 }
3743 
3744 
3745 /*
3746 ** Generate code into the current Vdbe to evaluate the given
3747 ** expression.  Attempt to store the results in register "target".
3748 ** Return the register where results are stored.
3749 **
3750 ** With this routine, there is no guarantee that results will
3751 ** be stored in target.  The result might be stored in some other
3752 ** register if it is convenient to do so.  The calling function
3753 ** must check the return code and move the results to the desired
3754 ** register.
3755 */
sqlite3ExprCodeTarget(Parse * pParse,Expr * pExpr,int target)3756 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
3757   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
3758   int op;                   /* The opcode being coded */
3759   int inReg = target;       /* Results stored in register inReg */
3760   int regFree1 = 0;         /* If non-zero free this temporary register */
3761   int regFree2 = 0;         /* If non-zero free this temporary register */
3762   int r1, r2;               /* Various register numbers */
3763   Expr tempX;               /* Temporary expression node */
3764   int p5 = 0;
3765 
3766   assert( target>0 && target<=pParse->nMem );
3767   if( v==0 ){
3768     assert( pParse->db->mallocFailed );
3769     return 0;
3770   }
3771 
3772 expr_code_doover:
3773   if( pExpr==0 ){
3774     op = TK_NULL;
3775   }else{
3776     op = pExpr->op;
3777   }
3778   switch( op ){
3779     case TK_AGG_COLUMN: {
3780       AggInfo *pAggInfo = pExpr->pAggInfo;
3781       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3782       if( !pAggInfo->directMode ){
3783         assert( pCol->iMem>0 );
3784         return pCol->iMem;
3785       }else if( pAggInfo->useSortingIdx ){
3786         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
3787                               pCol->iSorterColumn, target);
3788         return target;
3789       }
3790       /* Otherwise, fall thru into the TK_COLUMN case */
3791     }
3792     case TK_COLUMN: {
3793       int iTab = pExpr->iTable;
3794       int iReg;
3795       if( ExprHasProperty(pExpr, EP_FixedCol) ){
3796         /* This COLUMN expression is really a constant due to WHERE clause
3797         ** constraints, and that constant is coded by the pExpr->pLeft
3798         ** expresssion.  However, make sure the constant has the correct
3799         ** datatype by applying the Affinity of the table column to the
3800         ** constant.
3801         */
3802         int aff;
3803         iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
3804         if( pExpr->y.pTab ){
3805           aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
3806         }else{
3807           aff = pExpr->affExpr;
3808         }
3809         if( aff>SQLITE_AFF_BLOB ){
3810           static const char zAff[] = "B\000C\000D\000E";
3811           assert( SQLITE_AFF_BLOB=='A' );
3812           assert( SQLITE_AFF_TEXT=='B' );
3813           if( iReg!=target ){
3814             sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
3815             iReg = target;
3816           }
3817           sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
3818                             &zAff[(aff-'B')*2], P4_STATIC);
3819         }
3820         return iReg;
3821       }
3822       if( iTab<0 ){
3823         if( pParse->iSelfTab<0 ){
3824           /* Other columns in the same row for CHECK constraints or
3825           ** generated columns or for inserting into partial index.
3826           ** The row is unpacked into registers beginning at
3827           ** 0-(pParse->iSelfTab).  The rowid (if any) is in a register
3828           ** immediately prior to the first column.
3829           */
3830           Column *pCol;
3831           Table *pTab = pExpr->y.pTab;
3832           int iSrc;
3833           int iCol = pExpr->iColumn;
3834           assert( pTab!=0 );
3835           assert( iCol>=XN_ROWID );
3836           assert( iCol<pTab->nCol );
3837           if( iCol<0 ){
3838             return -1-pParse->iSelfTab;
3839           }
3840           pCol = pTab->aCol + iCol;
3841           testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
3842           iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
3843 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3844           if( pCol->colFlags & COLFLAG_GENERATED ){
3845             if( pCol->colFlags & COLFLAG_BUSY ){
3846               sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
3847                               pCol->zName);
3848               return 0;
3849             }
3850             pCol->colFlags |= COLFLAG_BUSY;
3851             if( pCol->colFlags & COLFLAG_NOTAVAIL ){
3852               sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
3853             }
3854             pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
3855             return iSrc;
3856           }else
3857 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
3858           if( pCol->affinity==SQLITE_AFF_REAL ){
3859             sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
3860             sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3861             return target;
3862           }else{
3863             return iSrc;
3864           }
3865         }else{
3866           /* Coding an expression that is part of an index where column names
3867           ** in the index refer to the table to which the index belongs */
3868           iTab = pParse->iSelfTab - 1;
3869         }
3870       }
3871       iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
3872                                pExpr->iColumn, iTab, target,
3873                                pExpr->op2);
3874       if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){
3875         sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
3876       }
3877       return iReg;
3878     }
3879     case TK_INTEGER: {
3880       codeInteger(pParse, pExpr, 0, target);
3881       return target;
3882     }
3883     case TK_TRUEFALSE: {
3884       sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
3885       return target;
3886     }
3887 #ifndef SQLITE_OMIT_FLOATING_POINT
3888     case TK_FLOAT: {
3889       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3890       codeReal(v, pExpr->u.zToken, 0, target);
3891       return target;
3892     }
3893 #endif
3894     case TK_STRING: {
3895       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3896       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
3897       return target;
3898     }
3899     default: {
3900       /* Make NULL the default case so that if a bug causes an illegal
3901       ** Expr node to be passed into this function, it will be handled
3902       ** sanely and not crash.  But keep the assert() to bring the problem
3903       ** to the attention of the developers. */
3904       assert( op==TK_NULL );
3905       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3906       return target;
3907     }
3908 #ifndef SQLITE_OMIT_BLOB_LITERAL
3909     case TK_BLOB: {
3910       int n;
3911       const char *z;
3912       char *zBlob;
3913       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3914       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3915       assert( pExpr->u.zToken[1]=='\'' );
3916       z = &pExpr->u.zToken[2];
3917       n = sqlite3Strlen30(z) - 1;
3918       assert( z[n]=='\'' );
3919       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3920       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
3921       return target;
3922     }
3923 #endif
3924     case TK_VARIABLE: {
3925       assert( !ExprHasProperty(pExpr, EP_IntValue) );
3926       assert( pExpr->u.zToken!=0 );
3927       assert( pExpr->u.zToken[0]!=0 );
3928       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3929       if( pExpr->u.zToken[1]!=0 ){
3930         const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
3931         assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
3932         pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
3933         sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
3934       }
3935       return target;
3936     }
3937     case TK_REGISTER: {
3938       return pExpr->iTable;
3939     }
3940 #ifndef SQLITE_OMIT_CAST
3941     case TK_CAST: {
3942       /* Expressions of the form:   CAST(pLeft AS token) */
3943       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3944       if( inReg!=target ){
3945         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3946         inReg = target;
3947       }
3948       sqlite3VdbeAddOp2(v, OP_Cast, target,
3949                         sqlite3AffinityType(pExpr->u.zToken, 0));
3950       return inReg;
3951     }
3952 #endif /* SQLITE_OMIT_CAST */
3953     case TK_IS:
3954     case TK_ISNOT:
3955       op = (op==TK_IS) ? TK_EQ : TK_NE;
3956       p5 = SQLITE_NULLEQ;
3957       /* fall-through */
3958     case TK_LT:
3959     case TK_LE:
3960     case TK_GT:
3961     case TK_GE:
3962     case TK_NE:
3963     case TK_EQ: {
3964       Expr *pLeft = pExpr->pLeft;
3965       if( sqlite3ExprIsVector(pLeft) ){
3966         codeVectorCompare(pParse, pExpr, target, op, p5);
3967       }else{
3968         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3969         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3970         codeCompare(pParse, pLeft, pExpr->pRight, op,
3971             r1, r2, inReg, SQLITE_STOREP2 | p5,
3972             ExprHasProperty(pExpr,EP_Commuted));
3973         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3974         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3975         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3976         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3977         assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3978         assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3979         testcase( regFree1==0 );
3980         testcase( regFree2==0 );
3981       }
3982       break;
3983     }
3984     case TK_AND:
3985     case TK_OR:
3986     case TK_PLUS:
3987     case TK_STAR:
3988     case TK_MINUS:
3989     case TK_REM:
3990     case TK_BITAND:
3991     case TK_BITOR:
3992     case TK_SLASH:
3993     case TK_LSHIFT:
3994     case TK_RSHIFT:
3995     case TK_CONCAT: {
3996       assert( TK_AND==OP_And );            testcase( op==TK_AND );
3997       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
3998       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
3999       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
4000       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
4001       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
4002       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
4003       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
4004       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
4005       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
4006       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
4007       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4008       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4009       sqlite3VdbeAddOp3(v, op, r2, r1, target);
4010       testcase( regFree1==0 );
4011       testcase( regFree2==0 );
4012       break;
4013     }
4014     case TK_UMINUS: {
4015       Expr *pLeft = pExpr->pLeft;
4016       assert( pLeft );
4017       if( pLeft->op==TK_INTEGER ){
4018         codeInteger(pParse, pLeft, 1, target);
4019         return target;
4020 #ifndef SQLITE_OMIT_FLOATING_POINT
4021       }else if( pLeft->op==TK_FLOAT ){
4022         assert( !ExprHasProperty(pExpr, EP_IntValue) );
4023         codeReal(v, pLeft->u.zToken, 1, target);
4024         return target;
4025 #endif
4026       }else{
4027         tempX.op = TK_INTEGER;
4028         tempX.flags = EP_IntValue|EP_TokenOnly;
4029         tempX.u.iValue = 0;
4030         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
4031         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
4032         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
4033         testcase( regFree2==0 );
4034       }
4035       break;
4036     }
4037     case TK_BITNOT:
4038     case TK_NOT: {
4039       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
4040       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
4041       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4042       testcase( regFree1==0 );
4043       sqlite3VdbeAddOp2(v, op, r1, inReg);
4044       break;
4045     }
4046     case TK_TRUTH: {
4047       int isTrue;    /* IS TRUE or IS NOT TRUE */
4048       int bNormal;   /* IS TRUE or IS FALSE */
4049       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4050       testcase( regFree1==0 );
4051       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4052       bNormal = pExpr->op2==TK_IS;
4053       testcase( isTrue && bNormal);
4054       testcase( !isTrue && bNormal);
4055       sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
4056       break;
4057     }
4058     case TK_ISNULL:
4059     case TK_NOTNULL: {
4060       int addr;
4061       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
4062       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4063       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4064       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4065       testcase( regFree1==0 );
4066       addr = sqlite3VdbeAddOp1(v, op, r1);
4067       VdbeCoverageIf(v, op==TK_ISNULL);
4068       VdbeCoverageIf(v, op==TK_NOTNULL);
4069       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
4070       sqlite3VdbeJumpHere(v, addr);
4071       break;
4072     }
4073     case TK_AGG_FUNCTION: {
4074       AggInfo *pInfo = pExpr->pAggInfo;
4075       if( pInfo==0 ){
4076         assert( !ExprHasProperty(pExpr, EP_IntValue) );
4077         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
4078       }else{
4079         return pInfo->aFunc[pExpr->iAgg].iMem;
4080       }
4081       break;
4082     }
4083     case TK_FUNCTION: {
4084       ExprList *pFarg;       /* List of function arguments */
4085       int nFarg;             /* Number of function arguments */
4086       FuncDef *pDef;         /* The function definition object */
4087       const char *zId;       /* The function name */
4088       u32 constMask = 0;     /* Mask of function arguments that are constant */
4089       int i;                 /* Loop counter */
4090       sqlite3 *db = pParse->db;  /* The database connection */
4091       u8 enc = ENC(db);      /* The text encoding used by this database */
4092       CollSeq *pColl = 0;    /* A collating sequence */
4093 
4094 #ifndef SQLITE_OMIT_WINDOWFUNC
4095       if( ExprHasProperty(pExpr, EP_WinFunc) ){
4096         return pExpr->y.pWin->regResult;
4097       }
4098 #endif
4099 
4100       if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
4101         /* SQL functions can be expensive. So try to move constant functions
4102         ** out of the inner loop, even if that means an extra OP_Copy. */
4103         return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
4104       }
4105       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4106       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
4107         pFarg = 0;
4108       }else{
4109         pFarg = pExpr->x.pList;
4110       }
4111       nFarg = pFarg ? pFarg->nExpr : 0;
4112       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4113       zId = pExpr->u.zToken;
4114       pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
4115 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4116       if( pDef==0 && pParse->explain ){
4117         pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
4118       }
4119 #endif
4120       if( pDef==0 || pDef->xFinalize!=0 ){
4121         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
4122         break;
4123       }
4124       if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
4125         assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
4126         assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
4127         return exprCodeInlineFunction(pParse, pFarg,
4128              SQLITE_PTR_TO_INT(pDef->pUserData), target);
4129       }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
4130         sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
4131       }
4132 
4133       for(i=0; i<nFarg; i++){
4134         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
4135           testcase( i==31 );
4136           constMask |= MASKBIT32(i);
4137         }
4138         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
4139           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
4140         }
4141       }
4142       if( pFarg ){
4143         if( constMask ){
4144           r1 = pParse->nMem+1;
4145           pParse->nMem += nFarg;
4146         }else{
4147           r1 = sqlite3GetTempRange(pParse, nFarg);
4148         }
4149 
4150         /* For length() and typeof() functions with a column argument,
4151         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4152         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
4153         ** loading.
4154         */
4155         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
4156           u8 exprOp;
4157           assert( nFarg==1 );
4158           assert( pFarg->a[0].pExpr!=0 );
4159           exprOp = pFarg->a[0].pExpr->op;
4160           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
4161             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
4162             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
4163             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
4164             pFarg->a[0].pExpr->op2 =
4165                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
4166           }
4167         }
4168 
4169         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
4170                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
4171       }else{
4172         r1 = 0;
4173       }
4174 #ifndef SQLITE_OMIT_VIRTUALTABLE
4175       /* Possibly overload the function if the first argument is
4176       ** a virtual table column.
4177       **
4178       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4179       ** second argument, not the first, as the argument to test to
4180       ** see if it is a column in a virtual table.  This is done because
4181       ** the left operand of infix functions (the operand we want to
4182       ** control overloading) ends up as the second argument to the
4183       ** function.  The expression "A glob B" is equivalent to
4184       ** "glob(B,A).  We want to use the A in "A glob B" to test
4185       ** for function overloading.  But we use the B term in "glob(B,A)".
4186       */
4187       if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
4188         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
4189       }else if( nFarg>0 ){
4190         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
4191       }
4192 #endif
4193       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
4194         if( !pColl ) pColl = db->pDfltColl;
4195         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
4196       }
4197 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4198       if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
4199         Expr *pArg = pFarg->a[0].pExpr;
4200         if( pArg->op==TK_COLUMN ){
4201           sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
4202         }else{
4203           sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4204         }
4205       }else
4206 #endif
4207       {
4208         sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
4209                                    pDef, pExpr->op2);
4210       }
4211       if( nFarg ){
4212         if( constMask==0 ){
4213           sqlite3ReleaseTempRange(pParse, r1, nFarg);
4214         }else{
4215           sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
4216         }
4217       }
4218       return target;
4219     }
4220 #ifndef SQLITE_OMIT_SUBQUERY
4221     case TK_EXISTS:
4222     case TK_SELECT: {
4223       int nCol;
4224       testcase( op==TK_EXISTS );
4225       testcase( op==TK_SELECT );
4226       if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
4227         sqlite3SubselectError(pParse, nCol, 1);
4228       }else{
4229         return sqlite3CodeSubselect(pParse, pExpr);
4230       }
4231       break;
4232     }
4233     case TK_SELECT_COLUMN: {
4234       int n;
4235       if( pExpr->pLeft->iTable==0 ){
4236         pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
4237       }
4238       assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
4239       if( pExpr->iTable!=0
4240        && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
4241       ){
4242         sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
4243                                 pExpr->iTable, n);
4244       }
4245       return pExpr->pLeft->iTable + pExpr->iColumn;
4246     }
4247     case TK_IN: {
4248       int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4249       int destIfNull = sqlite3VdbeMakeLabel(pParse);
4250       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4251       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4252       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4253       sqlite3VdbeResolveLabel(v, destIfFalse);
4254       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
4255       sqlite3VdbeResolveLabel(v, destIfNull);
4256       return target;
4257     }
4258 #endif /* SQLITE_OMIT_SUBQUERY */
4259 
4260 
4261     /*
4262     **    x BETWEEN y AND z
4263     **
4264     ** This is equivalent to
4265     **
4266     **    x>=y AND x<=z
4267     **
4268     ** X is stored in pExpr->pLeft.
4269     ** Y is stored in pExpr->pList->a[0].pExpr.
4270     ** Z is stored in pExpr->pList->a[1].pExpr.
4271     */
4272     case TK_BETWEEN: {
4273       exprCodeBetween(pParse, pExpr, target, 0, 0);
4274       return target;
4275     }
4276     case TK_SPAN:
4277     case TK_COLLATE:
4278     case TK_UPLUS: {
4279       pExpr = pExpr->pLeft;
4280       goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4281     }
4282 
4283     case TK_TRIGGER: {
4284       /* If the opcode is TK_TRIGGER, then the expression is a reference
4285       ** to a column in the new.* or old.* pseudo-tables available to
4286       ** trigger programs. In this case Expr.iTable is set to 1 for the
4287       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4288       ** is set to the column of the pseudo-table to read, or to -1 to
4289       ** read the rowid field.
4290       **
4291       ** The expression is implemented using an OP_Param opcode. The p1
4292       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4293       ** to reference another column of the old.* pseudo-table, where
4294       ** i is the index of the column. For a new.rowid reference, p1 is
4295       ** set to (n+1), where n is the number of columns in each pseudo-table.
4296       ** For a reference to any other column in the new.* pseudo-table, p1
4297       ** is set to (n+2+i), where n and i are as defined previously. For
4298       ** example, if the table on which triggers are being fired is
4299       ** declared as:
4300       **
4301       **   CREATE TABLE t1(a, b);
4302       **
4303       ** Then p1 is interpreted as follows:
4304       **
4305       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
4306       **   p1==1   ->    old.a         p1==4   ->    new.a
4307       **   p1==2   ->    old.b         p1==5   ->    new.b
4308       */
4309       Table *pTab = pExpr->y.pTab;
4310       int iCol = pExpr->iColumn;
4311       int p1 = pExpr->iTable * (pTab->nCol+1) + 1
4312                      + sqlite3TableColumnToStorage(pTab, iCol);
4313 
4314       assert( pExpr->iTable==0 || pExpr->iTable==1 );
4315       assert( iCol>=-1 && iCol<pTab->nCol );
4316       assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
4317       assert( p1>=0 && p1<(pTab->nCol*2+2) );
4318 
4319       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
4320       VdbeComment((v, "r[%d]=%s.%s", target,
4321         (pExpr->iTable ? "new" : "old"),
4322         (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
4323       ));
4324 
4325 #ifndef SQLITE_OMIT_FLOATING_POINT
4326       /* If the column has REAL affinity, it may currently be stored as an
4327       ** integer. Use OP_RealAffinity to make sure it is really real.
4328       **
4329       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
4330       ** floating point when extracting it from the record.  */
4331       if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
4332         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4333       }
4334 #endif
4335       break;
4336     }
4337 
4338     case TK_VECTOR: {
4339       sqlite3ErrorMsg(pParse, "row value misused");
4340       break;
4341     }
4342 
4343     /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
4344     ** that derive from the right-hand table of a LEFT JOIN.  The
4345     ** Expr.iTable value is the table number for the right-hand table.
4346     ** The expression is only evaluated if that table is not currently
4347     ** on a LEFT JOIN NULL row.
4348     */
4349     case TK_IF_NULL_ROW: {
4350       int addrINR;
4351       u8 okConstFactor = pParse->okConstFactor;
4352       addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
4353       /* Temporarily disable factoring of constant expressions, since
4354       ** even though expressions may appear to be constant, they are not
4355       ** really constant because they originate from the right-hand side
4356       ** of a LEFT JOIN. */
4357       pParse->okConstFactor = 0;
4358       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
4359       pParse->okConstFactor = okConstFactor;
4360       sqlite3VdbeJumpHere(v, addrINR);
4361       sqlite3VdbeChangeP3(v, addrINR, inReg);
4362       break;
4363     }
4364 
4365     /*
4366     ** Form A:
4367     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4368     **
4369     ** Form B:
4370     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4371     **
4372     ** Form A is can be transformed into the equivalent form B as follows:
4373     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
4374     **        WHEN x=eN THEN rN ELSE y END
4375     **
4376     ** X (if it exists) is in pExpr->pLeft.
4377     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
4378     ** odd.  The Y is also optional.  If the number of elements in x.pList
4379     ** is even, then Y is omitted and the "otherwise" result is NULL.
4380     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
4381     **
4382     ** The result of the expression is the Ri for the first matching Ei,
4383     ** or if there is no matching Ei, the ELSE term Y, or if there is
4384     ** no ELSE term, NULL.
4385     */
4386     case TK_CASE: {
4387       int endLabel;                     /* GOTO label for end of CASE stmt */
4388       int nextCase;                     /* GOTO label for next WHEN clause */
4389       int nExpr;                        /* 2x number of WHEN terms */
4390       int i;                            /* Loop counter */
4391       ExprList *pEList;                 /* List of WHEN terms */
4392       struct ExprList_item *aListelem;  /* Array of WHEN terms */
4393       Expr opCompare;                   /* The X==Ei expression */
4394       Expr *pX;                         /* The X expression */
4395       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
4396       Expr *pDel = 0;
4397       sqlite3 *db = pParse->db;
4398 
4399       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
4400       assert(pExpr->x.pList->nExpr > 0);
4401       pEList = pExpr->x.pList;
4402       aListelem = pEList->a;
4403       nExpr = pEList->nExpr;
4404       endLabel = sqlite3VdbeMakeLabel(pParse);
4405       if( (pX = pExpr->pLeft)!=0 ){
4406         pDel = sqlite3ExprDup(db, pX, 0);
4407         if( db->mallocFailed ){
4408           sqlite3ExprDelete(db, pDel);
4409           break;
4410         }
4411         testcase( pX->op==TK_COLUMN );
4412         exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
4413         testcase( regFree1==0 );
4414         memset(&opCompare, 0, sizeof(opCompare));
4415         opCompare.op = TK_EQ;
4416         opCompare.pLeft = pDel;
4417         pTest = &opCompare;
4418         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4419         ** The value in regFree1 might get SCopy-ed into the file result.
4420         ** So make sure that the regFree1 register is not reused for other
4421         ** purposes and possibly overwritten.  */
4422         regFree1 = 0;
4423       }
4424       for(i=0; i<nExpr-1; i=i+2){
4425         if( pX ){
4426           assert( pTest!=0 );
4427           opCompare.pRight = aListelem[i].pExpr;
4428         }else{
4429           pTest = aListelem[i].pExpr;
4430         }
4431         nextCase = sqlite3VdbeMakeLabel(pParse);
4432         testcase( pTest->op==TK_COLUMN );
4433         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
4434         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
4435         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
4436         sqlite3VdbeGoto(v, endLabel);
4437         sqlite3VdbeResolveLabel(v, nextCase);
4438       }
4439       if( (nExpr&1)!=0 ){
4440         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
4441       }else{
4442         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4443       }
4444       sqlite3ExprDelete(db, pDel);
4445       sqlite3VdbeResolveLabel(v, endLabel);
4446       break;
4447     }
4448 #ifndef SQLITE_OMIT_TRIGGER
4449     case TK_RAISE: {
4450       assert( pExpr->affExpr==OE_Rollback
4451            || pExpr->affExpr==OE_Abort
4452            || pExpr->affExpr==OE_Fail
4453            || pExpr->affExpr==OE_Ignore
4454       );
4455       if( !pParse->pTriggerTab ){
4456         sqlite3ErrorMsg(pParse,
4457                        "RAISE() may only be used within a trigger-program");
4458         return 0;
4459       }
4460       if( pExpr->affExpr==OE_Abort ){
4461         sqlite3MayAbort(pParse);
4462       }
4463       assert( !ExprHasProperty(pExpr, EP_IntValue) );
4464       if( pExpr->affExpr==OE_Ignore ){
4465         sqlite3VdbeAddOp4(
4466             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
4467         VdbeCoverage(v);
4468       }else{
4469         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
4470                               pExpr->affExpr, pExpr->u.zToken, 0, 0);
4471       }
4472 
4473       break;
4474     }
4475 #endif
4476   }
4477   sqlite3ReleaseTempReg(pParse, regFree1);
4478   sqlite3ReleaseTempReg(pParse, regFree2);
4479   return inReg;
4480 }
4481 
4482 /*
4483 ** Factor out the code of the given expression to initialization time.
4484 **
4485 ** If regDest>=0 then the result is always stored in that register and the
4486 ** result is not reusable.  If regDest<0 then this routine is free to
4487 ** store the value whereever it wants.  The register where the expression
4488 ** is stored is returned.  When regDest<0, two identical expressions will
4489 ** code to the same register.
4490 */
sqlite3ExprCodeAtInit(Parse * pParse,Expr * pExpr,int regDest)4491 int sqlite3ExprCodeAtInit(
4492   Parse *pParse,    /* Parsing context */
4493   Expr *pExpr,      /* The expression to code when the VDBE initializes */
4494   int regDest       /* Store the value in this register */
4495 ){
4496   ExprList *p;
4497   assert( ConstFactorOk(pParse) );
4498   p = pParse->pConstExpr;
4499   if( regDest<0 && p ){
4500     struct ExprList_item *pItem;
4501     int i;
4502     for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
4503       if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
4504         return pItem->u.iConstExprReg;
4505       }
4506     }
4507   }
4508   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4509   p = sqlite3ExprListAppend(pParse, p, pExpr);
4510   if( p ){
4511      struct ExprList_item *pItem = &p->a[p->nExpr-1];
4512      pItem->reusable = regDest<0;
4513      if( regDest<0 ) regDest = ++pParse->nMem;
4514      pItem->u.iConstExprReg = regDest;
4515   }
4516   pParse->pConstExpr = p;
4517   return regDest;
4518 }
4519 
4520 /*
4521 ** Generate code to evaluate an expression and store the results
4522 ** into a register.  Return the register number where the results
4523 ** are stored.
4524 **
4525 ** If the register is a temporary register that can be deallocated,
4526 ** then write its number into *pReg.  If the result register is not
4527 ** a temporary, then set *pReg to zero.
4528 **
4529 ** If pExpr is a constant, then this routine might generate this
4530 ** code to fill the register in the initialization section of the
4531 ** VDBE program, in order to factor it out of the evaluation loop.
4532 */
sqlite3ExprCodeTemp(Parse * pParse,Expr * pExpr,int * pReg)4533 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
4534   int r2;
4535   pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
4536   if( ConstFactorOk(pParse)
4537    && pExpr->op!=TK_REGISTER
4538    && sqlite3ExprIsConstantNotJoin(pExpr)
4539   ){
4540     *pReg  = 0;
4541     r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
4542   }else{
4543     int r1 = sqlite3GetTempReg(pParse);
4544     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
4545     if( r2==r1 ){
4546       *pReg = r1;
4547     }else{
4548       sqlite3ReleaseTempReg(pParse, r1);
4549       *pReg = 0;
4550     }
4551   }
4552   return r2;
4553 }
4554 
4555 /*
4556 ** Generate code that will evaluate expression pExpr and store the
4557 ** results in register target.  The results are guaranteed to appear
4558 ** in register target.
4559 */
sqlite3ExprCode(Parse * pParse,Expr * pExpr,int target)4560 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
4561   int inReg;
4562 
4563   assert( target>0 && target<=pParse->nMem );
4564   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
4565   assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
4566   if( inReg!=target && pParse->pVdbe ){
4567     u8 op;
4568     if( ExprHasProperty(pExpr,EP_Subquery) ){
4569       op = OP_Copy;
4570     }else{
4571       op = OP_SCopy;
4572     }
4573     sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
4574   }
4575 }
4576 
4577 /*
4578 ** Make a transient copy of expression pExpr and then code it using
4579 ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
4580 ** except that the input expression is guaranteed to be unchanged.
4581 */
sqlite3ExprCodeCopy(Parse * pParse,Expr * pExpr,int target)4582 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
4583   sqlite3 *db = pParse->db;
4584   pExpr = sqlite3ExprDup(db, pExpr, 0);
4585   if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4586   sqlite3ExprDelete(db, pExpr);
4587 }
4588 
4589 /*
4590 ** Generate code that will evaluate expression pExpr and store the
4591 ** results in register target.  The results are guaranteed to appear
4592 ** in register target.  If the expression is constant, then this routine
4593 ** might choose to code the expression at initialization time.
4594 */
sqlite3ExprCodeFactorable(Parse * pParse,Expr * pExpr,int target)4595 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4596   if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
4597     sqlite3ExprCodeAtInit(pParse, pExpr, target);
4598   }else{
4599     sqlite3ExprCodeCopy(pParse, pExpr, target);
4600   }
4601 }
4602 
4603 /*
4604 ** Generate code that pushes the value of every element of the given
4605 ** expression list into a sequence of registers beginning at target.
4606 **
4607 ** Return the number of elements evaluated.  The number returned will
4608 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
4609 ** is defined.
4610 **
4611 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
4612 ** filled using OP_SCopy.  OP_Copy must be used instead.
4613 **
4614 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4615 ** factored out into initialization code.
4616 **
4617 ** The SQLITE_ECEL_REF flag means that expressions in the list with
4618 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4619 ** in registers at srcReg, and so the value can be copied from there.
4620 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
4621 ** are simply omitted rather than being copied from srcReg.
4622 */
sqlite3ExprCodeExprList(Parse * pParse,ExprList * pList,int target,int srcReg,u8 flags)4623 int sqlite3ExprCodeExprList(
4624   Parse *pParse,     /* Parsing context */
4625   ExprList *pList,   /* The expression list to be coded */
4626   int target,        /* Where to write results */
4627   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
4628   u8 flags           /* SQLITE_ECEL_* flags */
4629 ){
4630   struct ExprList_item *pItem;
4631   int i, j, n;
4632   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
4633   Vdbe *v = pParse->pVdbe;
4634   assert( pList!=0 );
4635   assert( target>0 );
4636   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
4637   n = pList->nExpr;
4638   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
4639   for(pItem=pList->a, i=0; i<n; i++, pItem++){
4640     Expr *pExpr = pItem->pExpr;
4641 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
4642     if( pItem->bSorterRef ){
4643       i--;
4644       n--;
4645     }else
4646 #endif
4647     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
4648       if( flags & SQLITE_ECEL_OMITREF ){
4649         i--;
4650         n--;
4651       }else{
4652         sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4653       }
4654     }else if( (flags & SQLITE_ECEL_FACTOR)!=0
4655            && sqlite3ExprIsConstantNotJoin(pExpr)
4656     ){
4657       sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
4658     }else{
4659       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4660       if( inReg!=target+i ){
4661         VdbeOp *pOp;
4662         if( copyOp==OP_Copy
4663          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4664          && pOp->p1+pOp->p3+1==inReg
4665          && pOp->p2+pOp->p3+1==target+i
4666          && pOp->p5==0  /* The do-not-merge flag must be clear */
4667         ){
4668           pOp->p3++;
4669         }else{
4670           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4671         }
4672       }
4673     }
4674   }
4675   return n;
4676 }
4677 
4678 /*
4679 ** Generate code for a BETWEEN operator.
4680 **
4681 **    x BETWEEN y AND z
4682 **
4683 ** The above is equivalent to
4684 **
4685 **    x>=y AND x<=z
4686 **
4687 ** Code it as such, taking care to do the common subexpression
4688 ** elimination of x.
4689 **
4690 ** The xJumpIf parameter determines details:
4691 **
4692 **    NULL:                   Store the boolean result in reg[dest]
4693 **    sqlite3ExprIfTrue:      Jump to dest if true
4694 **    sqlite3ExprIfFalse:     Jump to dest if false
4695 **
4696 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
4697 */
exprCodeBetween(Parse * pParse,Expr * pExpr,int dest,void (* xJump)(Parse *,Expr *,int,int),int jumpIfNull)4698 static void exprCodeBetween(
4699   Parse *pParse,    /* Parsing and code generating context */
4700   Expr *pExpr,      /* The BETWEEN expression */
4701   int dest,         /* Jump destination or storage location */
4702   void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
4703   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
4704 ){
4705   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
4706   Expr compLeft;    /* The  x>=y  term */
4707   Expr compRight;   /* The  x<=z  term */
4708   int regFree1 = 0; /* Temporary use register */
4709   Expr *pDel = 0;
4710   sqlite3 *db = pParse->db;
4711 
4712   memset(&compLeft, 0, sizeof(Expr));
4713   memset(&compRight, 0, sizeof(Expr));
4714   memset(&exprAnd, 0, sizeof(Expr));
4715 
4716   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4717   pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
4718   if( db->mallocFailed==0 ){
4719     exprAnd.op = TK_AND;
4720     exprAnd.pLeft = &compLeft;
4721     exprAnd.pRight = &compRight;
4722     compLeft.op = TK_GE;
4723     compLeft.pLeft = pDel;
4724     compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4725     compRight.op = TK_LE;
4726     compRight.pLeft = pDel;
4727     compRight.pRight = pExpr->x.pList->a[1].pExpr;
4728     exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
4729     if( xJump ){
4730       xJump(pParse, &exprAnd, dest, jumpIfNull);
4731     }else{
4732       /* Mark the expression is being from the ON or USING clause of a join
4733       ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
4734       ** it into the Parse.pConstExpr list.  We should use a new bit for this,
4735       ** for clarity, but we are out of bits in the Expr.flags field so we
4736       ** have to reuse the EP_FromJoin bit.  Bummer. */
4737       pDel->flags |= EP_FromJoin;
4738       sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
4739     }
4740     sqlite3ReleaseTempReg(pParse, regFree1);
4741   }
4742   sqlite3ExprDelete(db, pDel);
4743 
4744   /* Ensure adequate test coverage */
4745   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
4746   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
4747   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
4748   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
4749   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4750   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4751   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4752   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
4753   testcase( xJump==0 );
4754 }
4755 
4756 /*
4757 ** Generate code for a boolean expression such that a jump is made
4758 ** to the label "dest" if the expression is true but execution
4759 ** continues straight thru if the expression is false.
4760 **
4761 ** If the expression evaluates to NULL (neither true nor false), then
4762 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
4763 **
4764 ** This code depends on the fact that certain token values (ex: TK_EQ)
4765 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4766 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
4767 ** the make process cause these values to align.  Assert()s in the code
4768 ** below verify that the numbers are aligned correctly.
4769 */
sqlite3ExprIfTrue(Parse * pParse,Expr * pExpr,int dest,int jumpIfNull)4770 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4771   Vdbe *v = pParse->pVdbe;
4772   int op = 0;
4773   int regFree1 = 0;
4774   int regFree2 = 0;
4775   int r1, r2;
4776 
4777   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4778   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
4779   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
4780   op = pExpr->op;
4781   switch( op ){
4782     case TK_AND:
4783     case TK_OR: {
4784       Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
4785       if( pAlt!=pExpr ){
4786         sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
4787       }else if( op==TK_AND ){
4788         int d2 = sqlite3VdbeMakeLabel(pParse);
4789         testcase( jumpIfNull==0 );
4790         sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
4791                            jumpIfNull^SQLITE_JUMPIFNULL);
4792         sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4793         sqlite3VdbeResolveLabel(v, d2);
4794       }else{
4795         testcase( jumpIfNull==0 );
4796         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
4797         sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4798       }
4799       break;
4800     }
4801     case TK_NOT: {
4802       testcase( jumpIfNull==0 );
4803       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
4804       break;
4805     }
4806     case TK_TRUTH: {
4807       int isNot;      /* IS NOT TRUE or IS NOT FALSE */
4808       int isTrue;     /* IS TRUE or IS NOT TRUE */
4809       testcase( jumpIfNull==0 );
4810       isNot = pExpr->op2==TK_ISNOT;
4811       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4812       testcase( isTrue && isNot );
4813       testcase( !isTrue && isNot );
4814       if( isTrue ^ isNot ){
4815         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
4816                           isNot ? SQLITE_JUMPIFNULL : 0);
4817       }else{
4818         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
4819                            isNot ? SQLITE_JUMPIFNULL : 0);
4820       }
4821       break;
4822     }
4823     case TK_IS:
4824     case TK_ISNOT:
4825       testcase( op==TK_IS );
4826       testcase( op==TK_ISNOT );
4827       op = (op==TK_IS) ? TK_EQ : TK_NE;
4828       jumpIfNull = SQLITE_NULLEQ;
4829       /* Fall thru */
4830     case TK_LT:
4831     case TK_LE:
4832     case TK_GT:
4833     case TK_GE:
4834     case TK_NE:
4835     case TK_EQ: {
4836       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
4837       testcase( jumpIfNull==0 );
4838       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4839       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4840       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
4841                   r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
4842       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4843       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4844       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4845       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4846       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4847       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4848       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4849       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4850       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4851       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4852       testcase( regFree1==0 );
4853       testcase( regFree2==0 );
4854       break;
4855     }
4856     case TK_ISNULL:
4857     case TK_NOTNULL: {
4858       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
4859       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4860       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4861       sqlite3VdbeAddOp2(v, op, r1, dest);
4862       VdbeCoverageIf(v, op==TK_ISNULL);
4863       VdbeCoverageIf(v, op==TK_NOTNULL);
4864       testcase( regFree1==0 );
4865       break;
4866     }
4867     case TK_BETWEEN: {
4868       testcase( jumpIfNull==0 );
4869       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
4870       break;
4871     }
4872 #ifndef SQLITE_OMIT_SUBQUERY
4873     case TK_IN: {
4874       int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4875       int destIfNull = jumpIfNull ? dest : destIfFalse;
4876       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4877       sqlite3VdbeGoto(v, dest);
4878       sqlite3VdbeResolveLabel(v, destIfFalse);
4879       break;
4880     }
4881 #endif
4882     default: {
4883     default_expr:
4884       if( ExprAlwaysTrue(pExpr) ){
4885         sqlite3VdbeGoto(v, dest);
4886       }else if( ExprAlwaysFalse(pExpr) ){
4887         /* No-op */
4888       }else{
4889         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4890         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
4891         VdbeCoverage(v);
4892         testcase( regFree1==0 );
4893         testcase( jumpIfNull==0 );
4894       }
4895       break;
4896     }
4897   }
4898   sqlite3ReleaseTempReg(pParse, regFree1);
4899   sqlite3ReleaseTempReg(pParse, regFree2);
4900 }
4901 
4902 /*
4903 ** Generate code for a boolean expression such that a jump is made
4904 ** to the label "dest" if the expression is false but execution
4905 ** continues straight thru if the expression is true.
4906 **
4907 ** If the expression evaluates to NULL (neither true nor false) then
4908 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4909 ** is 0.
4910 */
sqlite3ExprIfFalse(Parse * pParse,Expr * pExpr,int dest,int jumpIfNull)4911 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4912   Vdbe *v = pParse->pVdbe;
4913   int op = 0;
4914   int regFree1 = 0;
4915   int regFree2 = 0;
4916   int r1, r2;
4917 
4918   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4919   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
4920   if( pExpr==0 )    return;
4921 
4922   /* The value of pExpr->op and op are related as follows:
4923   **
4924   **       pExpr->op            op
4925   **       ---------          ----------
4926   **       TK_ISNULL          OP_NotNull
4927   **       TK_NOTNULL         OP_IsNull
4928   **       TK_NE              OP_Eq
4929   **       TK_EQ              OP_Ne
4930   **       TK_GT              OP_Le
4931   **       TK_LE              OP_Gt
4932   **       TK_GE              OP_Lt
4933   **       TK_LT              OP_Ge
4934   **
4935   ** For other values of pExpr->op, op is undefined and unused.
4936   ** The value of TK_ and OP_ constants are arranged such that we
4937   ** can compute the mapping above using the following expression.
4938   ** Assert()s verify that the computation is correct.
4939   */
4940   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4941 
4942   /* Verify correct alignment of TK_ and OP_ constants
4943   */
4944   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4945   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4946   assert( pExpr->op!=TK_NE || op==OP_Eq );
4947   assert( pExpr->op!=TK_EQ || op==OP_Ne );
4948   assert( pExpr->op!=TK_LT || op==OP_Ge );
4949   assert( pExpr->op!=TK_LE || op==OP_Gt );
4950   assert( pExpr->op!=TK_GT || op==OP_Le );
4951   assert( pExpr->op!=TK_GE || op==OP_Lt );
4952 
4953   switch( pExpr->op ){
4954     case TK_AND:
4955     case TK_OR: {
4956       Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
4957       if( pAlt!=pExpr ){
4958         sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
4959       }else if( pExpr->op==TK_AND ){
4960         testcase( jumpIfNull==0 );
4961         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
4962         sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4963       }else{
4964         int d2 = sqlite3VdbeMakeLabel(pParse);
4965         testcase( jumpIfNull==0 );
4966         sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
4967                           jumpIfNull^SQLITE_JUMPIFNULL);
4968         sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4969         sqlite3VdbeResolveLabel(v, d2);
4970       }
4971       break;
4972     }
4973     case TK_NOT: {
4974       testcase( jumpIfNull==0 );
4975       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
4976       break;
4977     }
4978     case TK_TRUTH: {
4979       int isNot;   /* IS NOT TRUE or IS NOT FALSE */
4980       int isTrue;  /* IS TRUE or IS NOT TRUE */
4981       testcase( jumpIfNull==0 );
4982       isNot = pExpr->op2==TK_ISNOT;
4983       isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4984       testcase( isTrue && isNot );
4985       testcase( !isTrue && isNot );
4986       if( isTrue ^ isNot ){
4987         /* IS TRUE and IS NOT FALSE */
4988         sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
4989                            isNot ? 0 : SQLITE_JUMPIFNULL);
4990 
4991       }else{
4992         /* IS FALSE and IS NOT TRUE */
4993         sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
4994                           isNot ? 0 : SQLITE_JUMPIFNULL);
4995       }
4996       break;
4997     }
4998     case TK_IS:
4999     case TK_ISNOT:
5000       testcase( pExpr->op==TK_IS );
5001       testcase( pExpr->op==TK_ISNOT );
5002       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
5003       jumpIfNull = SQLITE_NULLEQ;
5004       /* Fall thru */
5005     case TK_LT:
5006     case TK_LE:
5007     case TK_GT:
5008     case TK_GE:
5009     case TK_NE:
5010     case TK_EQ: {
5011       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5012       testcase( jumpIfNull==0 );
5013       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5014       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5015       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5016                   r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
5017       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5018       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5019       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5020       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5021       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5022       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5023       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5024       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5025       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5026       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5027       testcase( regFree1==0 );
5028       testcase( regFree2==0 );
5029       break;
5030     }
5031     case TK_ISNULL:
5032     case TK_NOTNULL: {
5033       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5034       sqlite3VdbeAddOp2(v, op, r1, dest);
5035       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
5036       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
5037       testcase( regFree1==0 );
5038       break;
5039     }
5040     case TK_BETWEEN: {
5041       testcase( jumpIfNull==0 );
5042       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
5043       break;
5044     }
5045 #ifndef SQLITE_OMIT_SUBQUERY
5046     case TK_IN: {
5047       if( jumpIfNull ){
5048         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
5049       }else{
5050         int destIfNull = sqlite3VdbeMakeLabel(pParse);
5051         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
5052         sqlite3VdbeResolveLabel(v, destIfNull);
5053       }
5054       break;
5055     }
5056 #endif
5057     default: {
5058     default_expr:
5059       if( ExprAlwaysFalse(pExpr) ){
5060         sqlite3VdbeGoto(v, dest);
5061       }else if( ExprAlwaysTrue(pExpr) ){
5062         /* no-op */
5063       }else{
5064         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5065         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
5066         VdbeCoverage(v);
5067         testcase( regFree1==0 );
5068         testcase( jumpIfNull==0 );
5069       }
5070       break;
5071     }
5072   }
5073   sqlite3ReleaseTempReg(pParse, regFree1);
5074   sqlite3ReleaseTempReg(pParse, regFree2);
5075 }
5076 
5077 /*
5078 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5079 ** code generation, and that copy is deleted after code generation. This
5080 ** ensures that the original pExpr is unchanged.
5081 */
sqlite3ExprIfFalseDup(Parse * pParse,Expr * pExpr,int dest,int jumpIfNull)5082 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
5083   sqlite3 *db = pParse->db;
5084   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
5085   if( db->mallocFailed==0 ){
5086     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
5087   }
5088   sqlite3ExprDelete(db, pCopy);
5089 }
5090 
5091 /*
5092 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5093 ** type of expression.
5094 **
5095 ** If pExpr is a simple SQL value - an integer, real, string, blob
5096 ** or NULL value - then the VDBE currently being prepared is configured
5097 ** to re-prepare each time a new value is bound to variable pVar.
5098 **
5099 ** Additionally, if pExpr is a simple SQL value and the value is the
5100 ** same as that currently bound to variable pVar, non-zero is returned.
5101 ** Otherwise, if the values are not the same or if pExpr is not a simple
5102 ** SQL value, zero is returned.
5103 */
exprCompareVariable(Parse * pParse,Expr * pVar,Expr * pExpr)5104 static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
5105   int res = 0;
5106   int iVar;
5107   sqlite3_value *pL, *pR = 0;
5108 
5109   sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
5110   if( pR ){
5111     iVar = pVar->iColumn;
5112     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
5113     pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
5114     if( pL ){
5115       if( sqlite3_value_type(pL)==SQLITE_TEXT ){
5116         sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
5117       }
5118       res =  0==sqlite3MemCompare(pL, pR, 0);
5119     }
5120     sqlite3ValueFree(pR);
5121     sqlite3ValueFree(pL);
5122   }
5123 
5124   return res;
5125 }
5126 
5127 /*
5128 ** Do a deep comparison of two expression trees.  Return 0 if the two
5129 ** expressions are completely identical.  Return 1 if they differ only
5130 ** by a COLLATE operator at the top level.  Return 2 if there are differences
5131 ** other than the top-level COLLATE operator.
5132 **
5133 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5134 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5135 **
5136 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
5137 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5138 **
5139 ** Sometimes this routine will return 2 even if the two expressions
5140 ** really are equivalent.  If we cannot prove that the expressions are
5141 ** identical, we return 2 just to be safe.  So if this routine
5142 ** returns 2, then you do not really know for certain if the two
5143 ** expressions are the same.  But if you get a 0 or 1 return, then you
5144 ** can be sure the expressions are the same.  In the places where
5145 ** this routine is used, it does not hurt to get an extra 2 - that
5146 ** just might result in some slightly slower code.  But returning
5147 ** an incorrect 0 or 1 could lead to a malfunction.
5148 **
5149 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5150 ** pParse->pReprepare can be matched against literals in pB.  The
5151 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5152 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5153 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5154 ** pB causes a return value of 2.
5155 */
sqlite3ExprCompare(Parse * pParse,Expr * pA,Expr * pB,int iTab)5156 int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
5157   u32 combinedFlags;
5158   if( pA==0 || pB==0 ){
5159     return pB==pA ? 0 : 2;
5160   }
5161   if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
5162     return 0;
5163   }
5164   combinedFlags = pA->flags | pB->flags;
5165   if( combinedFlags & EP_IntValue ){
5166     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
5167       return 0;
5168     }
5169     return 2;
5170   }
5171   if( pA->op!=pB->op || pA->op==TK_RAISE ){
5172     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
5173       return 1;
5174     }
5175     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
5176       return 1;
5177     }
5178     return 2;
5179   }
5180   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
5181     if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
5182       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5183 #ifndef SQLITE_OMIT_WINDOWFUNC
5184       assert( pA->op==pB->op );
5185       if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
5186         return 2;
5187       }
5188       if( ExprHasProperty(pA,EP_WinFunc) ){
5189         if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
5190           return 2;
5191         }
5192       }
5193 #endif
5194     }else if( pA->op==TK_NULL ){
5195       return 0;
5196     }else if( pA->op==TK_COLLATE ){
5197       if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5198     }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
5199       return 2;
5200     }
5201   }
5202   if( (pA->flags & (EP_Distinct|EP_Commuted))
5203      != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
5204   if( (combinedFlags & EP_TokenOnly)==0 ){
5205     if( combinedFlags & EP_xIsSelect ) return 2;
5206     if( (combinedFlags & EP_FixedCol)==0
5207      && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
5208     if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
5209     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
5210     if( pA->op!=TK_STRING
5211      && pA->op!=TK_TRUEFALSE
5212      && (combinedFlags & EP_Reduced)==0
5213     ){
5214       if( pA->iColumn!=pB->iColumn ) return 2;
5215       if( pA->op2!=pB->op2 ){
5216         if( pA->op==TK_TRUTH ) return 2;
5217         if( pA->op==TK_FUNCTION && iTab<0 ){
5218           /* Ex: CREATE TABLE t1(a CHECK( a<julianday('now') ));
5219           **     INSERT INTO t1(a) VALUES(julianday('now')+10);
5220           ** Without this test, sqlite3ExprCodeAtInit() will run on the
5221           ** the julianday() of INSERT first, and remember that expression.
5222           ** Then sqlite3ExprCodeInit() will see the julianday() in the CHECK
5223           ** constraint as redundant, reusing the one from the INSERT, even
5224           ** though the julianday() in INSERT lacks the critical NC_IsCheck
5225           ** flag.  See ticket [830277d9db6c3ba1] (2019-10-30)
5226           */
5227           return 2;
5228         }
5229       }
5230       if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
5231         return 2;
5232       }
5233     }
5234   }
5235   return 0;
5236 }
5237 
5238 /*
5239 ** Compare two ExprList objects.  Return 0 if they are identical, 1
5240 ** if they are certainly different, or 2 if it is not possible to
5241 ** determine if they are identical or not.
5242 **
5243 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5244 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5245 **
5246 ** This routine might return non-zero for equivalent ExprLists.  The
5247 ** only consequence will be disabled optimizations.  But this routine
5248 ** must never return 0 if the two ExprList objects are different, or
5249 ** a malfunction will result.
5250 **
5251 ** Two NULL pointers are considered to be the same.  But a NULL pointer
5252 ** always differs from a non-NULL pointer.
5253 */
sqlite3ExprListCompare(ExprList * pA,ExprList * pB,int iTab)5254 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
5255   int i;
5256   if( pA==0 && pB==0 ) return 0;
5257   if( pA==0 || pB==0 ) return 1;
5258   if( pA->nExpr!=pB->nExpr ) return 1;
5259   for(i=0; i<pA->nExpr; i++){
5260     int res;
5261     Expr *pExprA = pA->a[i].pExpr;
5262     Expr *pExprB = pB->a[i].pExpr;
5263     if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
5264     if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
5265   }
5266   return 0;
5267 }
5268 
5269 /*
5270 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
5271 ** are ignored.
5272 */
sqlite3ExprCompareSkip(Expr * pA,Expr * pB,int iTab)5273 int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
5274   return sqlite3ExprCompare(0,
5275              sqlite3ExprSkipCollateAndLikely(pA),
5276              sqlite3ExprSkipCollateAndLikely(pB),
5277              iTab);
5278 }
5279 
5280 /*
5281 ** Return non-zero if Expr p can only be true if pNN is not NULL.
5282 **
5283 ** Or if seenNot is true, return non-zero if Expr p can only be
5284 ** non-NULL if pNN is not NULL
5285 */
exprImpliesNotNull(Parse * pParse,Expr * p,Expr * pNN,int iTab,int seenNot)5286 static int exprImpliesNotNull(
5287   Parse *pParse,      /* Parsing context */
5288   Expr *p,            /* The expression to be checked */
5289   Expr *pNN,          /* The expression that is NOT NULL */
5290   int iTab,           /* Table being evaluated */
5291   int seenNot         /* Return true only if p can be any non-NULL value */
5292 ){
5293   assert( p );
5294   assert( pNN );
5295   if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
5296     return pNN->op!=TK_NULL;
5297   }
5298   switch( p->op ){
5299     case TK_IN: {
5300       if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
5301       assert( ExprHasProperty(p,EP_xIsSelect)
5302            || (p->x.pList!=0 && p->x.pList->nExpr>0) );
5303       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5304     }
5305     case TK_BETWEEN: {
5306       ExprList *pList = p->x.pList;
5307       assert( pList!=0 );
5308       assert( pList->nExpr==2 );
5309       if( seenNot ) return 0;
5310       if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
5311        || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
5312       ){
5313         return 1;
5314       }
5315       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5316     }
5317     case TK_EQ:
5318     case TK_NE:
5319     case TK_LT:
5320     case TK_LE:
5321     case TK_GT:
5322     case TK_GE:
5323     case TK_PLUS:
5324     case TK_MINUS:
5325     case TK_BITOR:
5326     case TK_LSHIFT:
5327     case TK_RSHIFT:
5328     case TK_CONCAT:
5329       seenNot = 1;
5330       /* Fall thru */
5331     case TK_STAR:
5332     case TK_REM:
5333     case TK_BITAND:
5334     case TK_SLASH: {
5335       if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
5336       /* Fall thru into the next case */
5337     }
5338     case TK_SPAN:
5339     case TK_COLLATE:
5340     case TK_UPLUS:
5341     case TK_UMINUS: {
5342       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
5343     }
5344     case TK_TRUTH: {
5345       if( seenNot ) return 0;
5346       if( p->op2!=TK_IS ) return 0;
5347       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5348     }
5349     case TK_BITNOT:
5350     case TK_NOT: {
5351       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5352     }
5353   }
5354   return 0;
5355 }
5356 
5357 /*
5358 ** Return true if we can prove the pE2 will always be true if pE1 is
5359 ** true.  Return false if we cannot complete the proof or if pE2 might
5360 ** be false.  Examples:
5361 **
5362 **     pE1: x==5       pE2: x==5             Result: true
5363 **     pE1: x>0        pE2: x==5             Result: false
5364 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
5365 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
5366 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
5367 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
5368 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
5369 **
5370 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
5371 ** Expr.iTable<0 then assume a table number given by iTab.
5372 **
5373 ** If pParse is not NULL, then the values of bound variables in pE1 are
5374 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
5375 ** modified to record which bound variables are referenced.  If pParse
5376 ** is NULL, then false will be returned if pE1 contains any bound variables.
5377 **
5378 ** When in doubt, return false.  Returning true might give a performance
5379 ** improvement.  Returning false might cause a performance reduction, but
5380 ** it will always give the correct answer and is hence always safe.
5381 */
sqlite3ExprImpliesExpr(Parse * pParse,Expr * pE1,Expr * pE2,int iTab)5382 int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
5383   if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
5384     return 1;
5385   }
5386   if( pE2->op==TK_OR
5387    && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
5388              || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
5389   ){
5390     return 1;
5391   }
5392   if( pE2->op==TK_NOTNULL
5393    && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
5394   ){
5395     return 1;
5396   }
5397   return 0;
5398 }
5399 
5400 /*
5401 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
5402 ** If the expression node requires that the table at pWalker->iCur
5403 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
5404 **
5405 ** This routine controls an optimization.  False positives (setting
5406 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
5407 ** (never setting pWalker->eCode) is a harmless missed optimization.
5408 */
impliesNotNullRow(Walker * pWalker,Expr * pExpr)5409 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
5410   testcase( pExpr->op==TK_AGG_COLUMN );
5411   testcase( pExpr->op==TK_AGG_FUNCTION );
5412   if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
5413   switch( pExpr->op ){
5414     case TK_ISNOT:
5415     case TK_ISNULL:
5416     case TK_NOTNULL:
5417     case TK_IS:
5418     case TK_OR:
5419     case TK_VECTOR:
5420     case TK_CASE:
5421     case TK_IN:
5422     case TK_FUNCTION:
5423     case TK_TRUTH:
5424       testcase( pExpr->op==TK_ISNOT );
5425       testcase( pExpr->op==TK_ISNULL );
5426       testcase( pExpr->op==TK_NOTNULL );
5427       testcase( pExpr->op==TK_IS );
5428       testcase( pExpr->op==TK_OR );
5429       testcase( pExpr->op==TK_VECTOR );
5430       testcase( pExpr->op==TK_CASE );
5431       testcase( pExpr->op==TK_IN );
5432       testcase( pExpr->op==TK_FUNCTION );
5433       testcase( pExpr->op==TK_TRUTH );
5434       return WRC_Prune;
5435     case TK_COLUMN:
5436       if( pWalker->u.iCur==pExpr->iTable ){
5437         pWalker->eCode = 1;
5438         return WRC_Abort;
5439       }
5440       return WRC_Prune;
5441 
5442     case TK_AND:
5443       if( pWalker->eCode==0 ){
5444         sqlite3WalkExpr(pWalker, pExpr->pLeft);
5445         if( pWalker->eCode ){
5446           pWalker->eCode = 0;
5447           sqlite3WalkExpr(pWalker, pExpr->pRight);
5448         }
5449       }
5450       return WRC_Prune;
5451 
5452     case TK_BETWEEN:
5453       if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
5454         assert( pWalker->eCode );
5455         return WRC_Abort;
5456       }
5457       return WRC_Prune;
5458 
5459     /* Virtual tables are allowed to use constraints like x=NULL.  So
5460     ** a term of the form x=y does not prove that y is not null if x
5461     ** is the column of a virtual table */
5462     case TK_EQ:
5463     case TK_NE:
5464     case TK_LT:
5465     case TK_LE:
5466     case TK_GT:
5467     case TK_GE: {
5468       Expr *pLeft = pExpr->pLeft;
5469       Expr *pRight = pExpr->pRight;
5470       testcase( pExpr->op==TK_EQ );
5471       testcase( pExpr->op==TK_NE );
5472       testcase( pExpr->op==TK_LT );
5473       testcase( pExpr->op==TK_LE );
5474       testcase( pExpr->op==TK_GT );
5475       testcase( pExpr->op==TK_GE );
5476       /* The y.pTab=0 assignment in wherecode.c always happens after the
5477       ** impliesNotNullRow() test */
5478       if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0)
5479                                && IsVirtual(pLeft->y.pTab))
5480        || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0)
5481                                && IsVirtual(pRight->y.pTab))
5482       ){
5483         return WRC_Prune;
5484       }
5485     }
5486     default:
5487       return WRC_Continue;
5488   }
5489 }
5490 
5491 /*
5492 ** Return true (non-zero) if expression p can only be true if at least
5493 ** one column of table iTab is non-null.  In other words, return true
5494 ** if expression p will always be NULL or false if every column of iTab
5495 ** is NULL.
5496 **
5497 ** False negatives are acceptable.  In other words, it is ok to return
5498 ** zero even if expression p will never be true of every column of iTab
5499 ** is NULL.  A false negative is merely a missed optimization opportunity.
5500 **
5501 ** False positives are not allowed, however.  A false positive may result
5502 ** in an incorrect answer.
5503 **
5504 ** Terms of p that are marked with EP_FromJoin (and hence that come from
5505 ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
5506 **
5507 ** This routine is used to check if a LEFT JOIN can be converted into
5508 ** an ordinary JOIN.  The p argument is the WHERE clause.  If the WHERE
5509 ** clause requires that some column of the right table of the LEFT JOIN
5510 ** be non-NULL, then the LEFT JOIN can be safely converted into an
5511 ** ordinary join.
5512 */
sqlite3ExprImpliesNonNullRow(Expr * p,int iTab)5513 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
5514   Walker w;
5515   p = sqlite3ExprSkipCollateAndLikely(p);
5516   if( p==0 ) return 0;
5517   if( p->op==TK_NOTNULL ){
5518     p = p->pLeft;
5519   }else{
5520     while( p->op==TK_AND ){
5521       if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
5522       p = p->pRight;
5523     }
5524   }
5525   w.xExprCallback = impliesNotNullRow;
5526   w.xSelectCallback = 0;
5527   w.xSelectCallback2 = 0;
5528   w.eCode = 0;
5529   w.u.iCur = iTab;
5530   sqlite3WalkExpr(&w, p);
5531   return w.eCode;
5532 }
5533 
5534 /*
5535 ** An instance of the following structure is used by the tree walker
5536 ** to determine if an expression can be evaluated by reference to the
5537 ** index only, without having to do a search for the corresponding
5538 ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
5539 ** is the cursor for the table.
5540 */
5541 struct IdxCover {
5542   Index *pIdx;     /* The index to be tested for coverage */
5543   int iCur;        /* Cursor number for the table corresponding to the index */
5544 };
5545 
5546 /*
5547 ** Check to see if there are references to columns in table
5548 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
5549 ** pWalker->u.pIdxCover->pIdx.
5550 */
exprIdxCover(Walker * pWalker,Expr * pExpr)5551 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
5552   if( pExpr->op==TK_COLUMN
5553    && pExpr->iTable==pWalker->u.pIdxCover->iCur
5554    && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
5555   ){
5556     pWalker->eCode = 1;
5557     return WRC_Abort;
5558   }
5559   return WRC_Continue;
5560 }
5561 
5562 /*
5563 ** Determine if an index pIdx on table with cursor iCur contains will
5564 ** the expression pExpr.  Return true if the index does cover the
5565 ** expression and false if the pExpr expression references table columns
5566 ** that are not found in the index pIdx.
5567 **
5568 ** An index covering an expression means that the expression can be
5569 ** evaluated using only the index and without having to lookup the
5570 ** corresponding table entry.
5571 */
sqlite3ExprCoveredByIndex(Expr * pExpr,int iCur,Index * pIdx)5572 int sqlite3ExprCoveredByIndex(
5573   Expr *pExpr,        /* The index to be tested */
5574   int iCur,           /* The cursor number for the corresponding table */
5575   Index *pIdx         /* The index that might be used for coverage */
5576 ){
5577   Walker w;
5578   struct IdxCover xcov;
5579   memset(&w, 0, sizeof(w));
5580   xcov.iCur = iCur;
5581   xcov.pIdx = pIdx;
5582   w.xExprCallback = exprIdxCover;
5583   w.u.pIdxCover = &xcov;
5584   sqlite3WalkExpr(&w, pExpr);
5585   return !w.eCode;
5586 }
5587 
5588 
5589 /*
5590 ** An instance of the following structure is used by the tree walker
5591 ** to count references to table columns in the arguments of an
5592 ** aggregate function, in order to implement the
5593 ** sqlite3FunctionThisSrc() routine.
5594 */
5595 struct SrcCount {
5596   SrcList *pSrc;   /* One particular FROM clause in a nested query */
5597   int nThis;       /* Number of references to columns in pSrcList */
5598   int nOther;      /* Number of references to columns in other FROM clauses */
5599 };
5600 
5601 /*
5602 ** Count the number of references to columns.
5603 */
exprSrcCount(Walker * pWalker,Expr * pExpr)5604 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
5605   /* There was once a NEVER() on the second term on the grounds that
5606   ** sqlite3FunctionUsesThisSrc() was always called before
5607   ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet
5608   ** been converted into TK_AGG_COLUMN. But this is no longer true due
5609   ** to window functions - sqlite3WindowRewrite() may now indirectly call
5610   ** FunctionUsesThisSrc() when creating a new sub-select. */
5611   if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
5612     int i;
5613     struct SrcCount *p = pWalker->u.pSrcCount;
5614     SrcList *pSrc = p->pSrc;
5615     int nSrc = pSrc ? pSrc->nSrc : 0;
5616     for(i=0; i<nSrc; i++){
5617       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
5618     }
5619     if( i<nSrc ){
5620       p->nThis++;
5621     }else if( nSrc==0 || pExpr->iTable<pSrc->a[0].iCursor ){
5622       /* In a well-formed parse tree (no name resolution errors),
5623       ** TK_COLUMN nodes with smaller Expr.iTable values are in an
5624       ** outer context.  Those are the only ones to count as "other" */
5625       p->nOther++;
5626     }
5627   }
5628   return WRC_Continue;
5629 }
5630 
5631 /*
5632 ** Determine if any of the arguments to the pExpr Function reference
5633 ** pSrcList.  Return true if they do.  Also return true if the function
5634 ** has no arguments or has only constant arguments.  Return false if pExpr
5635 ** references columns but not columns of tables found in pSrcList.
5636 */
sqlite3FunctionUsesThisSrc(Expr * pExpr,SrcList * pSrcList)5637 int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
5638   Walker w;
5639   struct SrcCount cnt;
5640   assert( pExpr->op==TK_AGG_FUNCTION );
5641   memset(&w, 0, sizeof(w));
5642   w.xExprCallback = exprSrcCount;
5643   w.xSelectCallback = sqlite3SelectWalkNoop;
5644   w.u.pSrcCount = &cnt;
5645   cnt.pSrc = pSrcList;
5646   cnt.nThis = 0;
5647   cnt.nOther = 0;
5648   sqlite3WalkExprList(&w, pExpr->x.pList);
5649 #ifndef SQLITE_OMIT_WINDOWFUNC
5650   if( ExprHasProperty(pExpr, EP_WinFunc) ){
5651     sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
5652   }
5653 #endif
5654   return cnt.nThis>0 || cnt.nOther==0;
5655 }
5656 
5657 /*
5658 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
5659 ** the new element.  Return a negative number if malloc fails.
5660 */
addAggInfoColumn(sqlite3 * db,AggInfo * pInfo)5661 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
5662   int i;
5663   pInfo->aCol = sqlite3ArrayAllocate(
5664        db,
5665        pInfo->aCol,
5666        sizeof(pInfo->aCol[0]),
5667        &pInfo->nColumn,
5668        &i
5669   );
5670   return i;
5671 }
5672 
5673 /*
5674 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
5675 ** the new element.  Return a negative number if malloc fails.
5676 */
addAggInfoFunc(sqlite3 * db,AggInfo * pInfo)5677 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
5678   int i;
5679   pInfo->aFunc = sqlite3ArrayAllocate(
5680        db,
5681        pInfo->aFunc,
5682        sizeof(pInfo->aFunc[0]),
5683        &pInfo->nFunc,
5684        &i
5685   );
5686   return i;
5687 }
5688 
5689 /*
5690 ** This is the xExprCallback for a tree walker.  It is used to
5691 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
5692 ** for additional information.
5693 */
analyzeAggregate(Walker * pWalker,Expr * pExpr)5694 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
5695   int i;
5696   NameContext *pNC = pWalker->u.pNC;
5697   Parse *pParse = pNC->pParse;
5698   SrcList *pSrcList = pNC->pSrcList;
5699   AggInfo *pAggInfo = pNC->uNC.pAggInfo;
5700 
5701   assert( pNC->ncFlags & NC_UAggInfo );
5702   switch( pExpr->op ){
5703     case TK_AGG_COLUMN:
5704     case TK_COLUMN: {
5705       testcase( pExpr->op==TK_AGG_COLUMN );
5706       testcase( pExpr->op==TK_COLUMN );
5707       /* Check to see if the column is in one of the tables in the FROM
5708       ** clause of the aggregate query */
5709       if( ALWAYS(pSrcList!=0) ){
5710         struct SrcList_item *pItem = pSrcList->a;
5711         for(i=0; i<pSrcList->nSrc; i++, pItem++){
5712           struct AggInfo_col *pCol;
5713           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
5714           if( pExpr->iTable==pItem->iCursor ){
5715             /* If we reach this point, it means that pExpr refers to a table
5716             ** that is in the FROM clause of the aggregate query.
5717             **
5718             ** Make an entry for the column in pAggInfo->aCol[] if there
5719             ** is not an entry there already.
5720             */
5721             int k;
5722             pCol = pAggInfo->aCol;
5723             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
5724               if( pCol->iTable==pExpr->iTable &&
5725                   pCol->iColumn==pExpr->iColumn ){
5726                 break;
5727               }
5728             }
5729             if( (k>=pAggInfo->nColumn)
5730              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
5731             ){
5732               pCol = &pAggInfo->aCol[k];
5733               pCol->pTab = pExpr->y.pTab;
5734               pCol->iTable = pExpr->iTable;
5735               pCol->iColumn = pExpr->iColumn;
5736               pCol->iMem = ++pParse->nMem;
5737               pCol->iSorterColumn = -1;
5738               pCol->pExpr = pExpr;
5739               if( pAggInfo->pGroupBy ){
5740                 int j, n;
5741                 ExprList *pGB = pAggInfo->pGroupBy;
5742                 struct ExprList_item *pTerm = pGB->a;
5743                 n = pGB->nExpr;
5744                 for(j=0; j<n; j++, pTerm++){
5745                   Expr *pE = pTerm->pExpr;
5746                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
5747                       pE->iColumn==pExpr->iColumn ){
5748                     pCol->iSorterColumn = j;
5749                     break;
5750                   }
5751                 }
5752               }
5753               if( pCol->iSorterColumn<0 ){
5754                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
5755               }
5756             }
5757             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
5758             ** because it was there before or because we just created it).
5759             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
5760             ** pAggInfo->aCol[] entry.
5761             */
5762             ExprSetVVAProperty(pExpr, EP_NoReduce);
5763             pExpr->pAggInfo = pAggInfo;
5764             pExpr->op = TK_AGG_COLUMN;
5765             pExpr->iAgg = (i16)k;
5766             break;
5767           } /* endif pExpr->iTable==pItem->iCursor */
5768         } /* end loop over pSrcList */
5769       }
5770       return WRC_Prune;
5771     }
5772     case TK_AGG_FUNCTION: {
5773       if( (pNC->ncFlags & NC_InAggFunc)==0
5774        && pWalker->walkerDepth==pExpr->op2
5775       ){
5776         /* Check to see if pExpr is a duplicate of another aggregate
5777         ** function that is already in the pAggInfo structure
5778         */
5779         struct AggInfo_func *pItem = pAggInfo->aFunc;
5780         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
5781           if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
5782             break;
5783           }
5784         }
5785         if( i>=pAggInfo->nFunc ){
5786           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
5787           */
5788           u8 enc = ENC(pParse->db);
5789           i = addAggInfoFunc(pParse->db, pAggInfo);
5790           if( i>=0 ){
5791             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
5792             pItem = &pAggInfo->aFunc[i];
5793             pItem->pExpr = pExpr;
5794             pItem->iMem = ++pParse->nMem;
5795             assert( !ExprHasProperty(pExpr, EP_IntValue) );
5796             pItem->pFunc = sqlite3FindFunction(pParse->db,
5797                    pExpr->u.zToken,
5798                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
5799             if( pExpr->flags & EP_Distinct ){
5800               pItem->iDistinct = pParse->nTab++;
5801             }else{
5802               pItem->iDistinct = -1;
5803             }
5804           }
5805         }
5806         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
5807         */
5808         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
5809         ExprSetVVAProperty(pExpr, EP_NoReduce);
5810         pExpr->iAgg = (i16)i;
5811         pExpr->pAggInfo = pAggInfo;
5812         return WRC_Prune;
5813       }else{
5814         return WRC_Continue;
5815       }
5816     }
5817   }
5818   return WRC_Continue;
5819 }
analyzeAggregatesInSelect(Walker * pWalker,Select * pSelect)5820 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
5821   UNUSED_PARAMETER(pSelect);
5822   pWalker->walkerDepth++;
5823   return WRC_Continue;
5824 }
analyzeAggregatesInSelectEnd(Walker * pWalker,Select * pSelect)5825 static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
5826   UNUSED_PARAMETER(pSelect);
5827   pWalker->walkerDepth--;
5828 }
5829 
5830 /*
5831 ** Analyze the pExpr expression looking for aggregate functions and
5832 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
5833 ** points to.  Additional entries are made on the AggInfo object as
5834 ** necessary.
5835 **
5836 ** This routine should only be called after the expression has been
5837 ** analyzed by sqlite3ResolveExprNames().
5838 */
sqlite3ExprAnalyzeAggregates(NameContext * pNC,Expr * pExpr)5839 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
5840   Walker w;
5841   w.xExprCallback = analyzeAggregate;
5842   w.xSelectCallback = analyzeAggregatesInSelect;
5843   w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
5844   w.walkerDepth = 0;
5845   w.u.pNC = pNC;
5846   w.pParse = 0;
5847   assert( pNC->pSrcList!=0 );
5848   sqlite3WalkExpr(&w, pExpr);
5849 }
5850 
5851 /*
5852 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
5853 ** expression list.  Return the number of errors.
5854 **
5855 ** If an error is found, the analysis is cut short.
5856 */
sqlite3ExprAnalyzeAggList(NameContext * pNC,ExprList * pList)5857 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
5858   struct ExprList_item *pItem;
5859   int i;
5860   if( pList ){
5861     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
5862       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
5863     }
5864   }
5865 }
5866 
5867 /*
5868 ** Allocate a single new register for use to hold some intermediate result.
5869 */
sqlite3GetTempReg(Parse * pParse)5870 int sqlite3GetTempReg(Parse *pParse){
5871   if( pParse->nTempReg==0 ){
5872     return ++pParse->nMem;
5873   }
5874   return pParse->aTempReg[--pParse->nTempReg];
5875 }
5876 
5877 /*
5878 ** Deallocate a register, making available for reuse for some other
5879 ** purpose.
5880 */
sqlite3ReleaseTempReg(Parse * pParse,int iReg)5881 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
5882   if( iReg ){
5883     sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
5884     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
5885       pParse->aTempReg[pParse->nTempReg++] = iReg;
5886     }
5887   }
5888 }
5889 
5890 /*
5891 ** Allocate or deallocate a block of nReg consecutive registers.
5892 */
sqlite3GetTempRange(Parse * pParse,int nReg)5893 int sqlite3GetTempRange(Parse *pParse, int nReg){
5894   int i, n;
5895   if( nReg==1 ) return sqlite3GetTempReg(pParse);
5896   i = pParse->iRangeReg;
5897   n = pParse->nRangeReg;
5898   if( nReg<=n ){
5899     pParse->iRangeReg += nReg;
5900     pParse->nRangeReg -= nReg;
5901   }else{
5902     i = pParse->nMem+1;
5903     pParse->nMem += nReg;
5904   }
5905   return i;
5906 }
sqlite3ReleaseTempRange(Parse * pParse,int iReg,int nReg)5907 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
5908   if( nReg==1 ){
5909     sqlite3ReleaseTempReg(pParse, iReg);
5910     return;
5911   }
5912   sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
5913   if( nReg>pParse->nRangeReg ){
5914     pParse->nRangeReg = nReg;
5915     pParse->iRangeReg = iReg;
5916   }
5917 }
5918 
5919 /*
5920 ** Mark all temporary registers as being unavailable for reuse.
5921 **
5922 ** Always invoke this procedure after coding a subroutine or co-routine
5923 ** that might be invoked from other parts of the code, to ensure that
5924 ** the sub/co-routine does not use registers in common with the code that
5925 ** invokes the sub/co-routine.
5926 */
sqlite3ClearTempRegCache(Parse * pParse)5927 void sqlite3ClearTempRegCache(Parse *pParse){
5928   pParse->nTempReg = 0;
5929   pParse->nRangeReg = 0;
5930 }
5931 
5932 /*
5933 ** Validate that no temporary register falls within the range of
5934 ** iFirst..iLast, inclusive.  This routine is only call from within assert()
5935 ** statements.
5936 */
5937 #ifdef SQLITE_DEBUG
sqlite3NoTempsInRange(Parse * pParse,int iFirst,int iLast)5938 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
5939   int i;
5940   if( pParse->nRangeReg>0
5941    && pParse->iRangeReg+pParse->nRangeReg > iFirst
5942    && pParse->iRangeReg <= iLast
5943   ){
5944      return 0;
5945   }
5946   for(i=0; i<pParse->nTempReg; i++){
5947     if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
5948       return 0;
5949     }
5950   }
5951   return 1;
5952 }
5953 #endif /* SQLITE_DEBUG */
5954