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