Minor doc tweaks.
[sqlite.git] / src / expr.c
blobcc915987ddb30dd90da79950f161416400d0e8ad
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.
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
15 #include "sqliteInt.h"
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);
22 ** Return the affinity character for a single column of a table.
24 char sqlite3TableColumnAffinity(const Table *pTab, int iCol){
25 if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER;
26 return pTab->aCol[iCol].affinity;
30 ** Return the 'affinity' of the expression pExpr if any.
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.
37 ** i.e. the WHERE clause expressions in the following statements all
38 ** have an affinity:
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);
45 char sqlite3ExprAffinity(const Expr *pExpr){
46 int op;
47 op = pExpr->op;
48 while( 1 /* exit-by-break */ ){
49 if( op==TK_COLUMN || (op==TK_AGG_COLUMN && pExpr->y.pTab!=0) ){
50 assert( ExprUseYTab(pExpr) );
51 assert( pExpr->y.pTab!=0 );
52 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
54 if( op==TK_SELECT ){
55 assert( ExprUseXSelect(pExpr) );
56 assert( pExpr->x.pSelect!=0 );
57 assert( pExpr->x.pSelect->pEList!=0 );
58 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
59 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
61 #ifndef SQLITE_OMIT_CAST
62 if( op==TK_CAST ){
63 assert( !ExprHasProperty(pExpr, EP_IntValue) );
64 return sqlite3AffinityType(pExpr->u.zToken, 0);
66 #endif
67 if( op==TK_SELECT_COLUMN ){
68 assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) );
69 assert( pExpr->iColumn < pExpr->iTable );
70 assert( pExpr->iColumn >= 0 );
71 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
72 return sqlite3ExprAffinity(
73 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
76 if( op==TK_VECTOR ){
77 assert( ExprUseXList(pExpr) );
78 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
80 if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
81 assert( pExpr->op==TK_COLLATE
82 || pExpr->op==TK_IF_NULL_ROW
83 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
84 pExpr = pExpr->pLeft;
85 op = pExpr->op;
86 continue;
88 if( op!=TK_REGISTER ) break;
89 op = pExpr->op2;
90 if( NEVER( op==TK_REGISTER ) ) break;
92 return pExpr->affExpr;
96 ** Make a guess at all the possible datatypes of the result that could
97 ** be returned by an expression. Return a bitmask indicating the answer:
99 ** 0x01 Numeric
100 ** 0x02 Text
101 ** 0x04 Blob
103 ** If the expression must return NULL, then 0x00 is returned.
105 int sqlite3ExprDataType(const Expr *pExpr){
106 while( pExpr ){
107 switch( pExpr->op ){
108 case TK_COLLATE:
109 case TK_IF_NULL_ROW:
110 case TK_UPLUS: {
111 pExpr = pExpr->pLeft;
112 break;
114 case TK_NULL: {
115 pExpr = 0;
116 break;
118 case TK_STRING: {
119 return 0x02;
121 case TK_BLOB: {
122 return 0x04;
124 case TK_CONCAT: {
125 return 0x06;
127 case TK_VARIABLE:
128 case TK_AGG_FUNCTION:
129 case TK_FUNCTION: {
130 return 0x07;
132 case TK_COLUMN:
133 case TK_AGG_COLUMN:
134 case TK_SELECT:
135 case TK_CAST:
136 case TK_SELECT_COLUMN:
137 case TK_VECTOR: {
138 int aff = sqlite3ExprAffinity(pExpr);
139 if( aff>=SQLITE_AFF_NUMERIC ) return 0x05;
140 if( aff==SQLITE_AFF_TEXT ) return 0x06;
141 return 0x07;
143 case TK_CASE: {
144 int res = 0;
145 int ii;
146 ExprList *pList = pExpr->x.pList;
147 assert( ExprUseXList(pExpr) && pList!=0 );
148 assert( pList->nExpr > 0);
149 for(ii=1; ii<pList->nExpr; ii+=2){
150 res |= sqlite3ExprDataType(pList->a[ii].pExpr);
152 if( pList->nExpr % 2 ){
153 res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr);
155 return res;
157 default: {
158 return 0x01;
160 } /* End of switch(op) */
161 } /* End of while(pExpr) */
162 return 0x00;
166 ** Set the collating sequence for expression pExpr to be the collating
167 ** sequence named by pToken. Return a pointer to a new Expr node that
168 ** implements the COLLATE operator.
170 ** If a memory allocation error occurs, that fact is recorded in pParse->db
171 ** and the pExpr parameter is returned unchanged.
173 Expr *sqlite3ExprAddCollateToken(
174 const Parse *pParse, /* Parsing context */
175 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
176 const Token *pCollName, /* Name of collating sequence */
177 int dequote /* True to dequote pCollName */
179 if( pCollName->n>0 ){
180 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
181 if( pNew ){
182 pNew->pLeft = pExpr;
183 pNew->flags |= EP_Collate|EP_Skip;
184 pExpr = pNew;
187 return pExpr;
189 Expr *sqlite3ExprAddCollateString(
190 const Parse *pParse, /* Parsing context */
191 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
192 const char *zC /* The collating sequence name */
194 Token s;
195 assert( zC!=0 );
196 sqlite3TokenInit(&s, (char*)zC);
197 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
201 ** Skip over any TK_COLLATE operators.
203 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
204 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
205 assert( pExpr->op==TK_COLLATE );
206 pExpr = pExpr->pLeft;
208 return pExpr;
212 ** Skip over any TK_COLLATE operators and/or any unlikely()
213 ** or likelihood() or likely() functions at the root of an
214 ** expression.
216 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
217 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
218 if( ExprHasProperty(pExpr, EP_Unlikely) ){
219 assert( ExprUseXList(pExpr) );
220 assert( pExpr->x.pList->nExpr>0 );
221 assert( pExpr->op==TK_FUNCTION );
222 pExpr = pExpr->x.pList->a[0].pExpr;
223 }else if( pExpr->op==TK_COLLATE ){
224 pExpr = pExpr->pLeft;
225 }else{
226 break;
229 return pExpr;
233 ** Return the collation sequence for the expression pExpr. If
234 ** there is no defined collating sequence, return NULL.
236 ** See also: sqlite3ExprNNCollSeq()
238 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
239 ** default collation if pExpr has no defined collation.
241 ** The collating sequence might be determined by a COLLATE operator
242 ** or by the presence of a column with a defined collating sequence.
243 ** COLLATE operators take first precedence. Left operands take
244 ** precedence over right operands.
246 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
247 sqlite3 *db = pParse->db;
248 CollSeq *pColl = 0;
249 const Expr *p = pExpr;
250 while( p ){
251 int op = p->op;
252 if( op==TK_REGISTER ) op = p->op2;
253 if( (op==TK_AGG_COLUMN && p->y.pTab!=0)
254 || op==TK_COLUMN || op==TK_TRIGGER
256 int j;
257 assert( ExprUseYTab(p) );
258 assert( p->y.pTab!=0 );
259 if( (j = p->iColumn)>=0 ){
260 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
261 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
263 break;
265 if( op==TK_CAST || op==TK_UPLUS ){
266 p = p->pLeft;
267 continue;
269 if( op==TK_VECTOR ){
270 assert( ExprUseXList(p) );
271 p = p->x.pList->a[0].pExpr;
272 continue;
274 if( op==TK_COLLATE ){
275 assert( !ExprHasProperty(p, EP_IntValue) );
276 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
277 break;
279 if( p->flags & EP_Collate ){
280 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
281 p = p->pLeft;
282 }else{
283 Expr *pNext = p->pRight;
284 /* The Expr.x union is never used at the same time as Expr.pRight */
285 assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );
286 if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){
287 int i;
288 for(i=0; i<p->x.pList->nExpr; i++){
289 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
290 pNext = p->x.pList->a[i].pExpr;
291 break;
295 p = pNext;
297 }else{
298 break;
301 if( sqlite3CheckCollSeq(pParse, pColl) ){
302 pColl = 0;
304 return pColl;
308 ** Return the collation sequence for the expression pExpr. If
309 ** there is no defined collating sequence, return a pointer to the
310 ** default collation sequence.
312 ** See also: sqlite3ExprCollSeq()
314 ** The sqlite3ExprCollSeq() routine works the same except that it
315 ** returns NULL if there is no defined collation.
317 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
318 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
319 if( p==0 ) p = pParse->db->pDfltColl;
320 assert( p!=0 );
321 return p;
325 ** Return TRUE if the two expressions have equivalent collating sequences.
327 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
328 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
329 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
330 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
334 ** pExpr is an operand of a comparison operator. aff2 is the
335 ** type affinity of the other operand. This routine returns the
336 ** type affinity that should be used for the comparison operator.
338 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
339 char aff1 = sqlite3ExprAffinity(pExpr);
340 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
341 /* Both sides of the comparison are columns. If one has numeric
342 ** affinity, use that. Otherwise use no affinity.
344 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
345 return SQLITE_AFF_NUMERIC;
346 }else{
347 return SQLITE_AFF_BLOB;
349 }else{
350 /* One side is a column, the other is not. Use the columns affinity. */
351 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
352 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
357 ** pExpr is a comparison operator. Return the type affinity that should
358 ** be applied to both operands prior to doing the comparison.
360 static char comparisonAffinity(const Expr *pExpr){
361 char aff;
362 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
363 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
364 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
365 assert( pExpr->pLeft );
366 aff = sqlite3ExprAffinity(pExpr->pLeft);
367 if( pExpr->pRight ){
368 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
369 }else if( ExprUseXSelect(pExpr) ){
370 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
371 }else if( aff==0 ){
372 aff = SQLITE_AFF_BLOB;
374 return aff;
378 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
379 ** idx_affinity is the affinity of an indexed column. Return true
380 ** if the index with affinity idx_affinity may be used to implement
381 ** the comparison in pExpr.
383 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
384 char aff = comparisonAffinity(pExpr);
385 if( aff<SQLITE_AFF_TEXT ){
386 return 1;
388 if( aff==SQLITE_AFF_TEXT ){
389 return idx_affinity==SQLITE_AFF_TEXT;
391 return sqlite3IsNumericAffinity(idx_affinity);
395 ** Return the P5 value that should be used for a binary comparison
396 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
398 static u8 binaryCompareP5(
399 const Expr *pExpr1, /* Left operand */
400 const Expr *pExpr2, /* Right operand */
401 int jumpIfNull /* Extra flags added to P5 */
403 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
404 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
405 return aff;
409 ** Return a pointer to the collation sequence that should be used by
410 ** a binary comparison operator comparing pLeft and pRight.
412 ** If the left hand expression has a collating sequence type, then it is
413 ** used. Otherwise the collation sequence for the right hand expression
414 ** is used, or the default (BINARY) if neither expression has a collating
415 ** type.
417 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
418 ** it is not considered.
420 CollSeq *sqlite3BinaryCompareCollSeq(
421 Parse *pParse,
422 const Expr *pLeft,
423 const Expr *pRight
425 CollSeq *pColl;
426 assert( pLeft );
427 if( pLeft->flags & EP_Collate ){
428 pColl = sqlite3ExprCollSeq(pParse, pLeft);
429 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
430 pColl = sqlite3ExprCollSeq(pParse, pRight);
431 }else{
432 pColl = sqlite3ExprCollSeq(pParse, pLeft);
433 if( !pColl ){
434 pColl = sqlite3ExprCollSeq(pParse, pRight);
437 return pColl;
440 /* Expression p is a comparison operator. Return a collation sequence
441 ** appropriate for the comparison operator.
443 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
444 ** However, if the OP_Commuted flag is set, then the order of the operands
445 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
446 ** correct collating sequence is found.
448 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
449 if( ExprHasProperty(p, EP_Commuted) ){
450 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
451 }else{
452 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
457 ** Generate code for a comparison operator.
459 static int codeCompare(
460 Parse *pParse, /* The parsing (and code generating) context */
461 Expr *pLeft, /* The left operand */
462 Expr *pRight, /* The right operand */
463 int opcode, /* The comparison opcode */
464 int in1, int in2, /* Register holding operands */
465 int dest, /* Jump here if true. */
466 int jumpIfNull, /* If true, jump if either operand is NULL */
467 int isCommuted /* The comparison has been commuted */
469 int p5;
470 int addr;
471 CollSeq *p4;
473 if( pParse->nErr ) return 0;
474 if( isCommuted ){
475 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
476 }else{
477 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
479 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
480 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
481 (void*)p4, P4_COLLSEQ);
482 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
483 return addr;
487 ** Return true if expression pExpr is a vector, or false otherwise.
489 ** A vector is defined as any expression that results in two or more
490 ** columns of result. Every TK_VECTOR node is an vector because the
491 ** parser will not generate a TK_VECTOR with fewer than two entries.
492 ** But a TK_SELECT might be either a vector or a scalar. It is only
493 ** considered a vector if it has two or more result columns.
495 int sqlite3ExprIsVector(const Expr *pExpr){
496 return sqlite3ExprVectorSize(pExpr)>1;
500 ** If the expression passed as the only argument is of type TK_VECTOR
501 ** return the number of expressions in the vector. Or, if the expression
502 ** is a sub-select, return the number of columns in the sub-select. For
503 ** any other type of expression, return 1.
505 int sqlite3ExprVectorSize(const Expr *pExpr){
506 u8 op = pExpr->op;
507 if( op==TK_REGISTER ) op = pExpr->op2;
508 if( op==TK_VECTOR ){
509 assert( ExprUseXList(pExpr) );
510 return pExpr->x.pList->nExpr;
511 }else if( op==TK_SELECT ){
512 assert( ExprUseXSelect(pExpr) );
513 return pExpr->x.pSelect->pEList->nExpr;
514 }else{
515 return 1;
520 ** Return a pointer to a subexpression of pVector that is the i-th
521 ** column of the vector (numbered starting with 0). The caller must
522 ** ensure that i is within range.
524 ** If pVector is really a scalar (and "scalar" here includes subqueries
525 ** that return a single column!) then return pVector unmodified.
527 ** pVector retains ownership of the returned subexpression.
529 ** If the vector is a (SELECT ...) then the expression returned is
530 ** just the expression for the i-th term of the result set, and may
531 ** not be ready for evaluation because the table cursor has not yet
532 ** been positioned.
534 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
535 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
536 if( sqlite3ExprIsVector(pVector) ){
537 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
538 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
539 assert( ExprUseXSelect(pVector) );
540 return pVector->x.pSelect->pEList->a[i].pExpr;
541 }else{
542 assert( ExprUseXList(pVector) );
543 return pVector->x.pList->a[i].pExpr;
546 return pVector;
550 ** Compute and return a new Expr object which when passed to
551 ** sqlite3ExprCode() will generate all necessary code to compute
552 ** the iField-th column of the vector expression pVector.
554 ** It is ok for pVector to be a scalar (as long as iField==0).
555 ** In that case, this routine works like sqlite3ExprDup().
557 ** The caller owns the returned Expr object and is responsible for
558 ** ensuring that the returned value eventually gets freed.
560 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
561 ** then the returned object will reference pVector and so pVector must remain
562 ** valid for the life of the returned object. If pVector is a TK_VECTOR
563 ** or a scalar expression, then it can be deleted as soon as this routine
564 ** returns.
566 ** A trick to cause a TK_SELECT pVector to be deleted together with
567 ** the returned Expr object is to attach the pVector to the pRight field
568 ** of the returned TK_SELECT_COLUMN Expr object.
570 Expr *sqlite3ExprForVectorField(
571 Parse *pParse, /* Parsing context */
572 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
573 int iField, /* Which column of the vector to return */
574 int nField /* Total number of columns in the vector */
576 Expr *pRet;
577 if( pVector->op==TK_SELECT ){
578 assert( ExprUseXSelect(pVector) );
579 /* The TK_SELECT_COLUMN Expr node:
581 ** pLeft: pVector containing TK_SELECT. Not deleted.
582 ** pRight: not used. But recursively deleted.
583 ** iColumn: Index of a column in pVector
584 ** iTable: 0 or the number of columns on the LHS of an assignment
585 ** pLeft->iTable: First in an array of register holding result, or 0
586 ** if the result is not yet computed.
588 ** sqlite3ExprDelete() specifically skips the recursive delete of
589 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
590 ** can be attached to pRight to cause this node to take ownership of
591 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
592 ** with the same pLeft pointer to the pVector, but only one of them
593 ** will own the pVector.
595 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
596 if( pRet ){
597 ExprSetProperty(pRet, EP_FullSize);
598 pRet->iTable = nField;
599 pRet->iColumn = iField;
600 pRet->pLeft = pVector;
602 }else{
603 if( pVector->op==TK_VECTOR ){
604 Expr **ppVector;
605 assert( ExprUseXList(pVector) );
606 ppVector = &pVector->x.pList->a[iField].pExpr;
607 pVector = *ppVector;
608 if( IN_RENAME_OBJECT ){
609 /* This must be a vector UPDATE inside a trigger */
610 *ppVector = 0;
611 return pVector;
614 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
616 return pRet;
620 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
621 ** it. Return the register in which the result is stored (or, if the
622 ** sub-select returns more than one column, the first in an array
623 ** of registers in which the result is stored).
625 ** If pExpr is not a TK_SELECT expression, return 0.
627 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
628 int reg = 0;
629 #ifndef SQLITE_OMIT_SUBQUERY
630 if( pExpr->op==TK_SELECT ){
631 reg = sqlite3CodeSubselect(pParse, pExpr);
633 #endif
634 return reg;
638 ** Argument pVector points to a vector expression - either a TK_VECTOR
639 ** or TK_SELECT that returns more than one column. This function returns
640 ** the register number of a register that contains the value of
641 ** element iField of the vector.
643 ** If pVector is a TK_SELECT expression, then code for it must have
644 ** already been generated using the exprCodeSubselect() routine. In this
645 ** case parameter regSelect should be the first in an array of registers
646 ** containing the results of the sub-select.
648 ** If pVector is of type TK_VECTOR, then code for the requested field
649 ** is generated. In this case (*pRegFree) may be set to the number of
650 ** a temporary register to be freed by the caller before returning.
652 ** Before returning, output parameter (*ppExpr) is set to point to the
653 ** Expr object corresponding to element iElem of the vector.
655 static int exprVectorRegister(
656 Parse *pParse, /* Parse context */
657 Expr *pVector, /* Vector to extract element from */
658 int iField, /* Field to extract from pVector */
659 int regSelect, /* First in array of registers */
660 Expr **ppExpr, /* OUT: Expression element */
661 int *pRegFree /* OUT: Temp register to free */
663 u8 op = pVector->op;
664 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );
665 if( op==TK_REGISTER ){
666 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
667 return pVector->iTable+iField;
669 if( op==TK_SELECT ){
670 assert( ExprUseXSelect(pVector) );
671 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
672 return regSelect+iField;
674 if( op==TK_VECTOR ){
675 assert( ExprUseXList(pVector) );
676 *ppExpr = pVector->x.pList->a[iField].pExpr;
677 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
679 return 0;
683 ** Expression pExpr is a comparison between two vector values. Compute
684 ** the result of the comparison (1, 0, or NULL) and write that
685 ** result into register dest.
687 ** The caller must satisfy the following preconditions:
689 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
690 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
691 ** otherwise: op==pExpr->op and p5==0
693 static void codeVectorCompare(
694 Parse *pParse, /* Code generator context */
695 Expr *pExpr, /* The comparison operation */
696 int dest, /* Write results into this register */
697 u8 op, /* Comparison operator */
698 u8 p5 /* SQLITE_NULLEQ or zero */
700 Vdbe *v = pParse->pVdbe;
701 Expr *pLeft = pExpr->pLeft;
702 Expr *pRight = pExpr->pRight;
703 int nLeft = sqlite3ExprVectorSize(pLeft);
704 int i;
705 int regLeft = 0;
706 int regRight = 0;
707 u8 opx = op;
708 int addrCmp = 0;
709 int addrDone = sqlite3VdbeMakeLabel(pParse);
710 int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
712 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
713 if( pParse->nErr ) return;
714 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
715 sqlite3ErrorMsg(pParse, "row value misused");
716 return;
718 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
719 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
720 || pExpr->op==TK_LT || pExpr->op==TK_GT
721 || pExpr->op==TK_LE || pExpr->op==TK_GE
723 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
724 || (pExpr->op==TK_ISNOT && op==TK_NE) );
725 assert( p5==0 || pExpr->op!=op );
726 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
728 if( op==TK_LE ) opx = TK_LT;
729 if( op==TK_GE ) opx = TK_GT;
730 if( op==TK_NE ) opx = TK_EQ;
732 regLeft = exprCodeSubselect(pParse, pLeft);
733 regRight = exprCodeSubselect(pParse, pRight);
735 sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);
736 for(i=0; 1 /*Loop exits by "break"*/; i++){
737 int regFree1 = 0, regFree2 = 0;
738 Expr *pL = 0, *pR = 0;
739 int r1, r2;
740 assert( i>=0 && i<nLeft );
741 if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);
742 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
743 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
744 addrCmp = sqlite3VdbeCurrentAddr(v);
745 codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);
746 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
747 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
748 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
749 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
750 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
751 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
752 sqlite3ReleaseTempReg(pParse, regFree1);
753 sqlite3ReleaseTempReg(pParse, regFree2);
754 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
755 addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);
756 testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);
757 testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);
759 if( p5==SQLITE_NULLEQ ){
760 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);
761 }else{
762 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);
764 if( i==nLeft-1 ){
765 break;
767 if( opx==TK_EQ ){
768 sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);
769 }else{
770 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
771 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
772 if( i==nLeft-2 ) opx = op;
775 sqlite3VdbeJumpHere(v, addrCmp);
776 sqlite3VdbeResolveLabel(v, addrDone);
777 if( op==TK_NE ){
778 sqlite3VdbeAddOp2(v, OP_Not, dest, dest);
782 #if SQLITE_MAX_EXPR_DEPTH>0
784 ** Check that argument nHeight is less than or equal to the maximum
785 ** expression depth allowed. If it is not, leave an error message in
786 ** pParse.
788 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
789 int rc = SQLITE_OK;
790 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
791 if( nHeight>mxHeight ){
792 sqlite3ErrorMsg(pParse,
793 "Expression tree is too large (maximum depth %d)", mxHeight
795 rc = SQLITE_ERROR;
797 return rc;
800 /* The following three functions, heightOfExpr(), heightOfExprList()
801 ** and heightOfSelect(), are used to determine the maximum height
802 ** of any expression tree referenced by the structure passed as the
803 ** first argument.
805 ** If this maximum height is greater than the current value pointed
806 ** to by pnHeight, the second parameter, then set *pnHeight to that
807 ** value.
809 static void heightOfExpr(const Expr *p, int *pnHeight){
810 if( p ){
811 if( p->nHeight>*pnHeight ){
812 *pnHeight = p->nHeight;
816 static void heightOfExprList(const ExprList *p, int *pnHeight){
817 if( p ){
818 int i;
819 for(i=0; i<p->nExpr; i++){
820 heightOfExpr(p->a[i].pExpr, pnHeight);
824 static void heightOfSelect(const Select *pSelect, int *pnHeight){
825 const Select *p;
826 for(p=pSelect; p; p=p->pPrior){
827 heightOfExpr(p->pWhere, pnHeight);
828 heightOfExpr(p->pHaving, pnHeight);
829 heightOfExpr(p->pLimit, pnHeight);
830 heightOfExprList(p->pEList, pnHeight);
831 heightOfExprList(p->pGroupBy, pnHeight);
832 heightOfExprList(p->pOrderBy, pnHeight);
837 ** Set the Expr.nHeight variable in the structure passed as an
838 ** argument. An expression with no children, Expr.pList or
839 ** Expr.pSelect member has a height of 1. Any other expression
840 ** has a height equal to the maximum height of any other
841 ** referenced Expr plus one.
843 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
844 ** if appropriate.
846 static void exprSetHeight(Expr *p){
847 int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
848 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){
849 nHeight = p->pRight->nHeight;
851 if( ExprUseXSelect(p) ){
852 heightOfSelect(p->x.pSelect, &nHeight);
853 }else if( p->x.pList ){
854 heightOfExprList(p->x.pList, &nHeight);
855 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
857 p->nHeight = nHeight + 1;
861 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
862 ** the height is greater than the maximum allowed expression depth,
863 ** leave an error in pParse.
865 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
866 ** Expr.flags.
868 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
869 if( pParse->nErr ) return;
870 exprSetHeight(p);
871 sqlite3ExprCheckHeight(pParse, p->nHeight);
875 ** Return the maximum height of any expression tree referenced
876 ** by the select statement passed as an argument.
878 int sqlite3SelectExprHeight(const Select *p){
879 int nHeight = 0;
880 heightOfSelect(p, &nHeight);
881 return nHeight;
883 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
885 ** Propagate all EP_Propagate flags from the Expr.x.pList into
886 ** Expr.flags.
888 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
889 if( pParse->nErr ) return;
890 if( p && ExprUseXList(p) && p->x.pList ){
891 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
894 #define exprSetHeight(y)
895 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
898 ** Set the error offset for an Expr node, if possible.
900 void sqlite3ExprSetErrorOffset(Expr *pExpr, int iOfst){
901 if( pExpr==0 ) return;
902 if( NEVER(ExprUseWJoin(pExpr)) ) return;
903 pExpr->w.iOfst = iOfst;
907 ** This routine is the core allocator for Expr nodes.
909 ** Construct a new expression node and return a pointer to it. Memory
910 ** for this node and for the pToken argument is a single allocation
911 ** obtained from sqlite3DbMalloc(). The calling function
912 ** is responsible for making sure the node eventually gets freed.
914 ** If dequote is true, then the token (if it exists) is dequoted.
915 ** If dequote is false, no dequoting is performed. The deQuote
916 ** parameter is ignored if pToken is NULL or if the token does not
917 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
918 ** then the EP_DblQuoted flag is set on the expression node.
920 ** Special case (tag-20240227-a): If op==TK_INTEGER and pToken points to
921 ** a string that can be translated into a 32-bit integer, then the token is
922 ** not stored in u.zToken. Instead, the integer values is written
923 ** into u.iValue and the EP_IntValue flag is set. No extra storage
924 ** is allocated to hold the integer text and the dequote flag is ignored.
925 ** See also tag-20240227-b.
927 Expr *sqlite3ExprAlloc(
928 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
929 int op, /* Expression opcode */
930 const Token *pToken, /* Token argument. Might be NULL */
931 int dequote /* True to dequote */
933 Expr *pNew;
934 int nExtra = 0;
935 int iValue = 0;
937 assert( db!=0 );
938 if( pToken ){
939 if( op!=TK_INTEGER || pToken->z==0
940 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
941 nExtra = pToken->n+1; /* tag-20240227-a */
942 assert( iValue>=0 );
945 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
946 if( pNew ){
947 memset(pNew, 0, sizeof(Expr));
948 pNew->op = (u8)op;
949 pNew->iAgg = -1;
950 if( pToken ){
951 if( nExtra==0 ){
952 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
953 pNew->u.iValue = iValue;
954 }else{
955 pNew->u.zToken = (char*)&pNew[1];
956 assert( pToken->z!=0 || pToken->n==0 );
957 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
958 pNew->u.zToken[pToken->n] = 0;
959 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
960 sqlite3DequoteExpr(pNew);
964 #if SQLITE_MAX_EXPR_DEPTH>0
965 pNew->nHeight = 1;
966 #endif
968 return pNew;
972 ** Allocate a new expression node from a zero-terminated token that has
973 ** already been dequoted.
975 Expr *sqlite3Expr(
976 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
977 int op, /* Expression opcode */
978 const char *zToken /* Token argument. Might be NULL */
980 Token x;
981 x.z = zToken;
982 x.n = sqlite3Strlen30(zToken);
983 return sqlite3ExprAlloc(db, op, &x, 0);
987 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
989 ** If pRoot==NULL that means that a memory allocation error has occurred.
990 ** In that case, delete the subtrees pLeft and pRight.
992 void sqlite3ExprAttachSubtrees(
993 sqlite3 *db,
994 Expr *pRoot,
995 Expr *pLeft,
996 Expr *pRight
998 if( pRoot==0 ){
999 assert( db->mallocFailed );
1000 sqlite3ExprDelete(db, pLeft);
1001 sqlite3ExprDelete(db, pRight);
1002 }else{
1003 assert( ExprUseXList(pRoot) );
1004 assert( pRoot->x.pSelect==0 );
1005 if( pRight ){
1006 pRoot->pRight = pRight;
1007 pRoot->flags |= EP_Propagate & pRight->flags;
1008 #if SQLITE_MAX_EXPR_DEPTH>0
1009 pRoot->nHeight = pRight->nHeight+1;
1010 }else{
1011 pRoot->nHeight = 1;
1012 #endif
1014 if( pLeft ){
1015 pRoot->pLeft = pLeft;
1016 pRoot->flags |= EP_Propagate & pLeft->flags;
1017 #if SQLITE_MAX_EXPR_DEPTH>0
1018 if( pLeft->nHeight>=pRoot->nHeight ){
1019 pRoot->nHeight = pLeft->nHeight+1;
1021 #endif
1027 ** Allocate an Expr node which joins as many as two subtrees.
1029 ** One or both of the subtrees can be NULL. Return a pointer to the new
1030 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1031 ** free the subtrees and return NULL.
1033 Expr *sqlite3PExpr(
1034 Parse *pParse, /* Parsing context */
1035 int op, /* Expression opcode */
1036 Expr *pLeft, /* Left operand */
1037 Expr *pRight /* Right operand */
1039 Expr *p;
1040 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
1041 if( p ){
1042 memset(p, 0, sizeof(Expr));
1043 p->op = op & 0xff;
1044 p->iAgg = -1;
1045 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
1046 sqlite3ExprCheckHeight(pParse, p->nHeight);
1047 }else{
1048 sqlite3ExprDelete(pParse->db, pLeft);
1049 sqlite3ExprDelete(pParse->db, pRight);
1051 return p;
1055 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1056 ** do a memory allocation failure) then delete the pSelect object.
1058 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
1059 if( pExpr ){
1060 pExpr->x.pSelect = pSelect;
1061 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
1062 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
1063 }else{
1064 assert( pParse->db->mallocFailed );
1065 sqlite3SelectDelete(pParse->db, pSelect);
1070 ** Expression list pEList is a list of vector values. This function
1071 ** converts the contents of pEList to a VALUES(...) Select statement
1072 ** returning 1 row for each element of the list. For example, the
1073 ** expression list:
1075 ** ( (1,2), (3,4) (5,6) )
1077 ** is translated to the equivalent of:
1079 ** VALUES(1,2), (3,4), (5,6)
1081 ** Each of the vector values in pEList must contain exactly nElem terms.
1082 ** If a list element that is not a vector or does not contain nElem terms,
1083 ** an error message is left in pParse.
1085 ** This is used as part of processing IN(...) expressions with a list
1086 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1088 Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){
1089 int ii;
1090 Select *pRet = 0;
1091 assert( nElem>1 );
1092 for(ii=0; ii<pEList->nExpr; ii++){
1093 Select *pSel;
1094 Expr *pExpr = pEList->a[ii].pExpr;
1095 int nExprElem;
1096 if( pExpr->op==TK_VECTOR ){
1097 assert( ExprUseXList(pExpr) );
1098 nExprElem = pExpr->x.pList->nExpr;
1099 }else{
1100 nExprElem = 1;
1102 if( nExprElem!=nElem ){
1103 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
1104 nExprElem, nExprElem>1?"s":"", nElem
1106 break;
1108 assert( ExprUseXList(pExpr) );
1109 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
1110 pExpr->x.pList = 0;
1111 if( pSel ){
1112 if( pRet ){
1113 pSel->op = TK_ALL;
1114 pSel->pPrior = pRet;
1116 pRet = pSel;
1120 if( pRet && pRet->pPrior ){
1121 pRet->selFlags |= SF_MultiValue;
1123 sqlite3ExprListDelete(pParse->db, pEList);
1124 return pRet;
1128 ** Join two expressions using an AND operator. If either expression is
1129 ** NULL, then just return the other expression.
1131 ** If one side or the other of the AND is known to be false, and neither side
1132 ** is part of an ON clause, then instead of returning an AND expression,
1133 ** just return a constant expression with a value of false.
1135 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
1136 sqlite3 *db = pParse->db;
1137 if( pLeft==0 ){
1138 return pRight;
1139 }else if( pRight==0 ){
1140 return pLeft;
1141 }else{
1142 u32 f = pLeft->flags | pRight->flags;
1143 if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse
1144 && !IN_RENAME_OBJECT
1146 sqlite3ExprDeferredDelete(pParse, pLeft);
1147 sqlite3ExprDeferredDelete(pParse, pRight);
1148 return sqlite3Expr(db, TK_INTEGER, "0");
1149 }else{
1150 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
1156 ** Construct a new expression node for a function with multiple
1157 ** arguments.
1159 Expr *sqlite3ExprFunction(
1160 Parse *pParse, /* Parsing context */
1161 ExprList *pList, /* Argument list */
1162 const Token *pToken, /* Name of the function */
1163 int eDistinct /* SF_Distinct or SF_ALL or 0 */
1165 Expr *pNew;
1166 sqlite3 *db = pParse->db;
1167 assert( pToken );
1168 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
1169 if( pNew==0 ){
1170 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
1171 return 0;
1173 assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) );
1174 pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
1175 if( pList
1176 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
1177 && !pParse->nested
1179 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
1181 pNew->x.pList = pList;
1182 ExprSetProperty(pNew, EP_HasFunc);
1183 assert( ExprUseXList(pNew) );
1184 sqlite3ExprSetHeightAndFlags(pParse, pNew);
1185 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
1186 return pNew;
1190 ** Report an error when attempting to use an ORDER BY clause within
1191 ** the arguments of a non-aggregate function.
1193 void sqlite3ExprOrderByAggregateError(Parse *pParse, Expr *p){
1194 sqlite3ErrorMsg(pParse,
1195 "ORDER BY may not be used with non-aggregate %#T()", p
1200 ** Attach an ORDER BY clause to a function call.
1202 ** functionname( arguments ORDER BY sortlist )
1203 ** \_____________________/ \______/
1204 ** pExpr pOrderBy
1206 ** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER
1207 ** and added to the Expr.pLeft field of the parent TK_FUNCTION node.
1209 void sqlite3ExprAddFunctionOrderBy(
1210 Parse *pParse, /* Parsing context */
1211 Expr *pExpr, /* The function call to which ORDER BY is to be added */
1212 ExprList *pOrderBy /* The ORDER BY clause to add */
1214 Expr *pOB;
1215 sqlite3 *db = pParse->db;
1216 if( NEVER(pOrderBy==0) ){
1217 assert( db->mallocFailed );
1218 return;
1220 if( pExpr==0 ){
1221 assert( db->mallocFailed );
1222 sqlite3ExprListDelete(db, pOrderBy);
1223 return;
1225 assert( pExpr->op==TK_FUNCTION );
1226 assert( pExpr->pLeft==0 );
1227 assert( ExprUseXList(pExpr) );
1228 if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){
1229 /* Ignore ORDER BY on zero-argument aggregates */
1230 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pOrderBy);
1231 return;
1233 if( IsWindowFunc(pExpr) ){
1234 sqlite3ExprOrderByAggregateError(pParse, pExpr);
1235 sqlite3ExprListDelete(db, pOrderBy);
1236 return;
1239 pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0);
1240 if( pOB==0 ){
1241 sqlite3ExprListDelete(db, pOrderBy);
1242 return;
1244 pOB->x.pList = pOrderBy;
1245 assert( ExprUseXList(pOB) );
1246 pExpr->pLeft = pOB;
1247 ExprSetProperty(pOB, EP_FullSize);
1251 ** Check to see if a function is usable according to current access
1252 ** rules:
1254 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1256 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1257 ** top-level SQL
1259 ** If the function is not usable, create an error.
1261 void sqlite3ExprFunctionUsable(
1262 Parse *pParse, /* Parsing and code generating context */
1263 const Expr *pExpr, /* The function invocation */
1264 const FuncDef *pDef /* The function being invoked */
1266 assert( !IN_RENAME_OBJECT );
1267 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
1268 if( ExprHasProperty(pExpr, EP_FromDDL) ){
1269 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
1270 || (pParse->db->flags & SQLITE_TrustedSchema)==0
1272 /* Functions prohibited in triggers and views if:
1273 ** (1) tagged with SQLITE_DIRECTONLY
1274 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1275 ** is tagged with SQLITE_FUNC_UNSAFE) and
1276 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1277 ** that the schema is possibly tainted).
1279 sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr);
1285 ** Assign a variable number to an expression that encodes a wildcard
1286 ** in the original SQL statement.
1288 ** Wildcards consisting of a single "?" are assigned the next sequential
1289 ** variable number.
1291 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1292 ** sure "nnn" is not too big to avoid a denial of service attack when
1293 ** the SQL statement comes from an external source.
1295 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1296 ** as the previous instance of the same wildcard. Or if this is the first
1297 ** instance of the wildcard, the next sequential variable number is
1298 ** assigned.
1300 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
1301 sqlite3 *db = pParse->db;
1302 const char *z;
1303 ynVar x;
1305 if( pExpr==0 ) return;
1306 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
1307 z = pExpr->u.zToken;
1308 assert( z!=0 );
1309 assert( z[0]!=0 );
1310 assert( n==(u32)sqlite3Strlen30(z) );
1311 if( z[1]==0 ){
1312 /* Wildcard of the form "?". Assign the next variable number */
1313 assert( z[0]=='?' );
1314 x = (ynVar)(++pParse->nVar);
1315 }else{
1316 int doAdd = 0;
1317 if( z[0]=='?' ){
1318 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1319 ** use it as the variable number */
1320 i64 i;
1321 int bOk;
1322 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1323 i = z[1]-'0'; /* The common case of ?N for a single digit N */
1324 bOk = 1;
1325 }else{
1326 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1328 testcase( i==0 );
1329 testcase( i==1 );
1330 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1331 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1332 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1333 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1334 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1335 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1336 return;
1338 x = (ynVar)i;
1339 if( x>pParse->nVar ){
1340 pParse->nVar = (int)x;
1341 doAdd = 1;
1342 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1343 doAdd = 1;
1345 }else{
1346 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1347 ** number as the prior appearance of the same name, or if the name
1348 ** has never appeared before, reuse the same variable number
1350 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1351 if( x==0 ){
1352 x = (ynVar)(++pParse->nVar);
1353 doAdd = 1;
1356 if( doAdd ){
1357 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1360 pExpr->iColumn = x;
1361 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1362 sqlite3ErrorMsg(pParse, "too many SQL variables");
1363 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1368 ** Recursively delete an expression tree.
1370 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1371 assert( p!=0 );
1372 assert( db!=0 );
1373 exprDeleteRestart:
1374 assert( !ExprUseUValue(p) || p->u.iValue>=0 );
1375 assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
1376 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
1377 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
1378 #ifdef SQLITE_DEBUG
1379 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1380 assert( p->pLeft==0 );
1381 assert( p->pRight==0 );
1382 assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
1383 assert( !ExprUseXList(p) || p->x.pList==0 );
1385 #endif
1386 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1387 /* The Expr.x union is never used at the same time as Expr.pRight */
1388 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
1389 if( p->pRight ){
1390 assert( !ExprHasProperty(p, EP_WinFunc) );
1391 sqlite3ExprDeleteNN(db, p->pRight);
1392 }else if( ExprUseXSelect(p) ){
1393 assert( !ExprHasProperty(p, EP_WinFunc) );
1394 sqlite3SelectDelete(db, p->x.pSelect);
1395 }else{
1396 sqlite3ExprListDelete(db, p->x.pList);
1397 #ifndef SQLITE_OMIT_WINDOWFUNC
1398 if( ExprHasProperty(p, EP_WinFunc) ){
1399 sqlite3WindowDelete(db, p->y.pWin);
1401 #endif
1403 if( p->pLeft && p->op!=TK_SELECT_COLUMN ){
1404 Expr *pLeft = p->pLeft;
1405 if( !ExprHasProperty(p, EP_Static)
1406 && !ExprHasProperty(pLeft, EP_Static)
1408 /* Avoid unnecessary recursion on unary operators */
1409 sqlite3DbNNFreeNN(db, p);
1410 p = pLeft;
1411 goto exprDeleteRestart;
1412 }else{
1413 sqlite3ExprDeleteNN(db, pLeft);
1417 if( !ExprHasProperty(p, EP_Static) ){
1418 sqlite3DbNNFreeNN(db, p);
1421 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1422 if( p ) sqlite3ExprDeleteNN(db, p);
1424 void sqlite3ExprDeleteGeneric(sqlite3 *db, void *p){
1425 if( ALWAYS(p) ) sqlite3ExprDeleteNN(db, (Expr*)p);
1429 ** Clear both elements of an OnOrUsing object
1431 void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){
1432 if( p==0 ){
1433 /* Nothing to clear */
1434 }else if( p->pOn ){
1435 sqlite3ExprDeleteNN(db, p->pOn);
1436 }else if( p->pUsing ){
1437 sqlite3IdListDelete(db, p->pUsing);
1442 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1443 ** This is similar to sqlite3ExprDelete() except that the delete is
1444 ** deferred until the pParse is deleted.
1446 ** The pExpr might be deleted immediately on an OOM error.
1448 ** Return 0 if the delete was successfully deferred. Return non-zero
1449 ** if the delete happened immediately because of an OOM.
1451 int sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
1452 return 0==sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr);
1455 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1456 ** expression.
1458 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
1459 if( p ){
1460 if( IN_RENAME_OBJECT ){
1461 sqlite3RenameExprUnmap(pParse, p);
1463 sqlite3ExprDeleteNN(pParse->db, p);
1468 ** Return the number of bytes allocated for the expression structure
1469 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1470 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1472 static int exprStructSize(const Expr *p){
1473 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1474 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1475 return EXPR_FULLSIZE;
1479 ** The dupedExpr*Size() routines each return the number of bytes required
1480 ** to store a copy of an expression or expression tree. They differ in
1481 ** how much of the tree is measured.
1483 ** dupedExprStructSize() Size of only the Expr structure
1484 ** dupedExprNodeSize() Size of Expr + space for token
1485 ** dupedExprSize() Expr + token + subtree components
1487 ***************************************************************************
1489 ** The dupedExprStructSize() function returns two values OR-ed together:
1490 ** (1) the space required for a copy of the Expr structure only and
1491 ** (2) the EP_xxx flags that indicate what the structure size should be.
1492 ** The return values is always one of:
1494 ** EXPR_FULLSIZE
1495 ** EXPR_REDUCEDSIZE | EP_Reduced
1496 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1498 ** The size of the structure can be found by masking the return value
1499 ** of this routine with 0xfff. The flags can be found by masking the
1500 ** return value with EP_Reduced|EP_TokenOnly.
1502 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1503 ** (unreduced) Expr objects as they or originally constructed by the parser.
1504 ** During expression analysis, extra information is computed and moved into
1505 ** later parts of the Expr object and that extra information might get chopped
1506 ** off if the expression is reduced. Note also that it does not work to
1507 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1508 ** to reduce a pristine expression tree from the parser. The implementation
1509 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1510 ** to enforce this constraint.
1512 static int dupedExprStructSize(const Expr *p, int flags){
1513 int nSize;
1514 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1515 assert( EXPR_FULLSIZE<=0xfff );
1516 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1517 if( 0==flags || ExprHasProperty(p, EP_FullSize) ){
1518 nSize = EXPR_FULLSIZE;
1519 }else{
1520 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1521 assert( !ExprHasProperty(p, EP_OuterON) );
1522 assert( !ExprHasVVAProperty(p, EP_NoReduce) );
1523 if( p->pLeft || p->x.pList ){
1524 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1525 }else{
1526 assert( p->pRight==0 );
1527 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1530 return nSize;
1534 ** This function returns the space in bytes required to store the copy
1535 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1536 ** string is defined.)
1538 static int dupedExprNodeSize(const Expr *p, int flags){
1539 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1540 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1541 nByte += sqlite3Strlen30NN(p->u.zToken)+1;
1543 return ROUND8(nByte);
1547 ** Return the number of bytes required to create a duplicate of the
1548 ** expression passed as the first argument.
1550 ** The value returned includes space to create a copy of the Expr struct
1551 ** itself and the buffer referred to by Expr.u.zToken, if any.
1553 ** The return value includes space to duplicate all Expr nodes in the
1554 ** tree formed by Expr.pLeft and Expr.pRight, but not any other
1555 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
1557 static int dupedExprSize(const Expr *p){
1558 int nByte;
1559 assert( p!=0 );
1560 nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE);
1561 if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
1562 if( p->pRight ) nByte += dupedExprSize(p->pRight);
1563 assert( nByte==ROUND8(nByte) );
1564 return nByte;
1568 ** An EdupBuf is a memory allocation used to stored multiple Expr objects
1569 ** together with their Expr.zToken content. This is used to help implement
1570 ** compression while doing sqlite3ExprDup(). The top-level Expr does the
1571 ** allocation for itself and many of its decendents, then passes an instance
1572 ** of the structure down into exprDup() so that they decendents can have
1573 ** access to that memory.
1575 typedef struct EdupBuf EdupBuf;
1576 struct EdupBuf {
1577 u8 *zAlloc; /* Memory space available for storage */
1578 #ifdef SQLITE_DEBUG
1579 u8 *zEnd; /* First byte past the end of memory */
1580 #endif
1584 ** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
1585 ** is not NULL then it points to memory that can be used to store a copy
1586 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf
1587 ** is updated with the new buffer tail prior to returning.
1589 static Expr *exprDup(
1590 sqlite3 *db, /* Database connection (for memory allocation) */
1591 const Expr *p, /* Expr tree to be duplicated */
1592 int dupFlags, /* EXPRDUP_REDUCE for compression. 0 if not */
1593 EdupBuf *pEdupBuf /* Preallocated storage space, or NULL */
1595 Expr *pNew; /* Value to return */
1596 EdupBuf sEdupBuf; /* Memory space from which to build Expr object */
1597 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1598 int nToken = -1; /* Space needed for p->u.zToken. -1 means unknown */
1600 assert( db!=0 );
1601 assert( p );
1602 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1603 assert( pEdupBuf==0 || dupFlags==EXPRDUP_REDUCE );
1605 /* Figure out where to write the new Expr structure. */
1606 if( pEdupBuf ){
1607 sEdupBuf.zAlloc = pEdupBuf->zAlloc;
1608 #ifdef SQLITE_DEBUG
1609 sEdupBuf.zEnd = pEdupBuf->zEnd;
1610 #endif
1611 staticFlag = EP_Static;
1612 assert( sEdupBuf.zAlloc!=0 );
1613 assert( dupFlags==EXPRDUP_REDUCE );
1614 }else{
1615 int nAlloc;
1616 if( dupFlags ){
1617 nAlloc = dupedExprSize(p);
1618 }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1619 nToken = sqlite3Strlen30NN(p->u.zToken)+1;
1620 nAlloc = ROUND8(EXPR_FULLSIZE + nToken);
1621 }else{
1622 nToken = 0;
1623 nAlloc = ROUND8(EXPR_FULLSIZE);
1625 assert( nAlloc==ROUND8(nAlloc) );
1626 sEdupBuf.zAlloc = sqlite3DbMallocRawNN(db, nAlloc);
1627 #ifdef SQLITE_DEBUG
1628 sEdupBuf.zEnd = sEdupBuf.zAlloc ? sEdupBuf.zAlloc+nAlloc : 0;
1629 #endif
1631 staticFlag = 0;
1633 pNew = (Expr *)sEdupBuf.zAlloc;
1634 assert( EIGHT_BYTE_ALIGNMENT(pNew) );
1636 if( pNew ){
1637 /* Set nNewSize to the size allocated for the structure pointed to
1638 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1639 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1640 ** by the copy of the p->u.zToken string (if any).
1642 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1643 int nNewSize = nStructSize & 0xfff;
1644 if( nToken<0 ){
1645 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1646 nToken = sqlite3Strlen30(p->u.zToken) + 1;
1647 }else{
1648 nToken = 0;
1651 if( dupFlags ){
1652 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= nNewSize+nToken );
1653 assert( ExprHasProperty(p, EP_Reduced)==0 );
1654 memcpy(sEdupBuf.zAlloc, p, nNewSize);
1655 }else{
1656 u32 nSize = (u32)exprStructSize(p);
1657 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >=
1658 (int)EXPR_FULLSIZE+nToken );
1659 memcpy(sEdupBuf.zAlloc, p, nSize);
1660 if( nSize<EXPR_FULLSIZE ){
1661 memset(&sEdupBuf.zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1663 nNewSize = EXPR_FULLSIZE;
1666 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1667 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
1668 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1669 pNew->flags |= staticFlag;
1670 ExprClearVVAProperties(pNew);
1671 if( dupFlags ){
1672 ExprSetVVAProperty(pNew, EP_Immutable);
1675 /* Copy the p->u.zToken string, if any. */
1676 assert( nToken>=0 );
1677 if( nToken>0 ){
1678 char *zToken = pNew->u.zToken = (char*)&sEdupBuf.zAlloc[nNewSize];
1679 memcpy(zToken, p->u.zToken, nToken);
1680 nNewSize += nToken;
1682 sEdupBuf.zAlloc += ROUND8(nNewSize);
1684 if( ((p->flags|pNew->flags)&(EP_TokenOnly|EP_Leaf))==0 ){
1686 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1687 if( ExprUseXSelect(p) ){
1688 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1689 }else{
1690 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList,
1691 p->op!=TK_ORDER ? dupFlags : 0);
1694 #ifndef SQLITE_OMIT_WINDOWFUNC
1695 if( ExprHasProperty(p, EP_WinFunc) ){
1696 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1697 assert( ExprHasProperty(pNew, EP_WinFunc) );
1699 #endif /* SQLITE_OMIT_WINDOWFUNC */
1701 /* Fill in pNew->pLeft and pNew->pRight. */
1702 if( dupFlags ){
1703 if( p->op==TK_SELECT_COLUMN ){
1704 pNew->pLeft = p->pLeft;
1705 assert( p->pRight==0
1706 || p->pRight==p->pLeft
1707 || ExprHasProperty(p->pLeft, EP_Subquery) );
1708 }else{
1709 pNew->pLeft = p->pLeft ?
1710 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &sEdupBuf) : 0;
1712 pNew->pRight = p->pRight ?
1713 exprDup(db, p->pRight, EXPRDUP_REDUCE, &sEdupBuf) : 0;
1714 }else{
1715 if( p->op==TK_SELECT_COLUMN ){
1716 pNew->pLeft = p->pLeft;
1717 assert( p->pRight==0
1718 || p->pRight==p->pLeft
1719 || ExprHasProperty(p->pLeft, EP_Subquery) );
1720 }else{
1721 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1723 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1727 if( pEdupBuf ) memcpy(pEdupBuf, &sEdupBuf, sizeof(sEdupBuf));
1728 assert( sEdupBuf.zAlloc <= sEdupBuf.zEnd );
1729 return pNew;
1733 ** Create and return a deep copy of the object passed as the second
1734 ** argument. If an OOM condition is encountered, NULL is returned
1735 ** and the db->mallocFailed flag set.
1737 #ifndef SQLITE_OMIT_CTE
1738 With *sqlite3WithDup(sqlite3 *db, With *p){
1739 With *pRet = 0;
1740 if( p ){
1741 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1742 pRet = sqlite3DbMallocZero(db, nByte);
1743 if( pRet ){
1744 int i;
1745 pRet->nCte = p->nCte;
1746 for(i=0; i<p->nCte; i++){
1747 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1748 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1749 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1750 pRet->a[i].eM10d = p->a[i].eM10d;
1754 return pRet;
1756 #else
1757 # define sqlite3WithDup(x,y) 0
1758 #endif
1760 #ifndef SQLITE_OMIT_WINDOWFUNC
1762 ** The gatherSelectWindows() procedure and its helper routine
1763 ** gatherSelectWindowsCallback() are used to scan all the expressions
1764 ** an a newly duplicated SELECT statement and gather all of the Window
1765 ** objects found there, assembling them onto the linked list at Select->pWin.
1767 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1768 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
1769 Select *pSelect = pWalker->u.pSelect;
1770 Window *pWin = pExpr->y.pWin;
1771 assert( pWin );
1772 assert( IsWindowFunc(pExpr) );
1773 assert( pWin->ppThis==0 );
1774 sqlite3WindowLink(pSelect, pWin);
1776 return WRC_Continue;
1778 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1779 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1781 static void gatherSelectWindows(Select *p){
1782 Walker w;
1783 w.xExprCallback = gatherSelectWindowsCallback;
1784 w.xSelectCallback = gatherSelectWindowsSelectCallback;
1785 w.xSelectCallback2 = 0;
1786 w.pParse = 0;
1787 w.u.pSelect = p;
1788 sqlite3WalkSelect(&w, p);
1790 #endif
1794 ** The following group of routines make deep copies of expressions,
1795 ** expression lists, ID lists, and select statements. The copies can
1796 ** be deleted (by being passed to their respective ...Delete() routines)
1797 ** without effecting the originals.
1799 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1800 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1801 ** by subsequent calls to sqlite*ListAppend() routines.
1803 ** Any tables that the SrcList might point to are not duplicated.
1805 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1806 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1807 ** truncated version of the usual Expr structure that will be stored as
1808 ** part of the in-memory representation of the database schema.
1810 Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){
1811 assert( flags==0 || flags==EXPRDUP_REDUCE );
1812 return p ? exprDup(db, p, flags, 0) : 0;
1814 ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){
1815 ExprList *pNew;
1816 struct ExprList_item *pItem;
1817 const struct ExprList_item *pOldItem;
1818 int i;
1819 Expr *pPriorSelectColOld = 0;
1820 Expr *pPriorSelectColNew = 0;
1821 assert( db!=0 );
1822 if( p==0 ) return 0;
1823 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1824 if( pNew==0 ) return 0;
1825 pNew->nExpr = p->nExpr;
1826 pNew->nAlloc = p->nAlloc;
1827 pItem = pNew->a;
1828 pOldItem = p->a;
1829 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1830 Expr *pOldExpr = pOldItem->pExpr;
1831 Expr *pNewExpr;
1832 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1833 if( pOldExpr
1834 && pOldExpr->op==TK_SELECT_COLUMN
1835 && (pNewExpr = pItem->pExpr)!=0
1837 if( pNewExpr->pRight ){
1838 pPriorSelectColOld = pOldExpr->pRight;
1839 pPriorSelectColNew = pNewExpr->pRight;
1840 pNewExpr->pLeft = pNewExpr->pRight;
1841 }else{
1842 if( pOldExpr->pLeft!=pPriorSelectColOld ){
1843 pPriorSelectColOld = pOldExpr->pLeft;
1844 pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags);
1845 pNewExpr->pRight = pPriorSelectColNew;
1847 pNewExpr->pLeft = pPriorSelectColNew;
1850 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
1851 pItem->fg = pOldItem->fg;
1852 pItem->fg.done = 0;
1853 pItem->u = pOldItem->u;
1855 return pNew;
1859 ** If cursors, triggers, views and subqueries are all omitted from
1860 ** the build, then none of the following routines, except for
1861 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1862 ** called with a NULL argument.
1864 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1865 || !defined(SQLITE_OMIT_SUBQUERY)
1866 SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){
1867 SrcList *pNew;
1868 int i;
1869 int nByte;
1870 assert( db!=0 );
1871 if( p==0 ) return 0;
1872 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1873 pNew = sqlite3DbMallocRawNN(db, nByte );
1874 if( pNew==0 ) return 0;
1875 pNew->nSrc = pNew->nAlloc = p->nSrc;
1876 for(i=0; i<p->nSrc; i++){
1877 SrcItem *pNewItem = &pNew->a[i];
1878 const SrcItem *pOldItem = &p->a[i];
1879 Table *pTab;
1880 pNewItem->fg = pOldItem->fg;
1881 if( pOldItem->fg.isSubquery ){
1882 Subquery *pNewSubq = sqlite3DbMallocRaw(db, sizeof(Subquery));
1883 if( pNewSubq==0 ){
1884 assert( db->mallocFailed );
1885 pNewItem->fg.isSubquery = 0;
1886 }else{
1887 memcpy(pNewSubq, pOldItem->u4.pSubq, sizeof(*pNewSubq));
1888 pNewSubq->pSelect = sqlite3SelectDup(db, pNewSubq->pSelect, flags);
1889 if( pNewSubq->pSelect==0 ){
1890 sqlite3DbFree(db, pNewSubq);
1891 pNewSubq = 0;
1892 pNewItem->fg.isSubquery = 0;
1895 pNewItem->u4.pSubq = pNewSubq;
1896 }else if( pOldItem->fg.fixedSchema ){
1897 pNewItem->u4.pSchema = pOldItem->u4.pSchema;
1898 }else{
1899 pNewItem->u4.zDatabase = sqlite3DbStrDup(db, pOldItem->u4.zDatabase);
1901 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1902 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1903 pNewItem->iCursor = pOldItem->iCursor;
1904 if( pNewItem->fg.isIndexedBy ){
1905 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1906 }else if( pNewItem->fg.isTabFunc ){
1907 pNewItem->u1.pFuncArg =
1908 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1909 }else{
1910 pNewItem->u1.nRow = pOldItem->u1.nRow;
1912 pNewItem->u2 = pOldItem->u2;
1913 if( pNewItem->fg.isCte ){
1914 pNewItem->u2.pCteUse->nUse++;
1916 pTab = pNewItem->pSTab = pOldItem->pSTab;
1917 if( pTab ){
1918 pTab->nTabRef++;
1920 if( pOldItem->fg.isUsing ){
1921 assert( pNewItem->fg.isUsing );
1922 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing);
1923 }else{
1924 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags);
1926 pNewItem->colUsed = pOldItem->colUsed;
1928 return pNew;
1930 IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){
1931 IdList *pNew;
1932 int i;
1933 assert( db!=0 );
1934 if( p==0 ) return 0;
1935 assert( p->eU4!=EU4_EXPR );
1936 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) );
1937 if( pNew==0 ) return 0;
1938 pNew->nId = p->nId;
1939 pNew->eU4 = p->eU4;
1940 for(i=0; i<p->nId; i++){
1941 struct IdList_item *pNewItem = &pNew->a[i];
1942 const struct IdList_item *pOldItem = &p->a[i];
1943 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1944 pNewItem->u4 = pOldItem->u4;
1946 return pNew;
1948 Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){
1949 Select *pRet = 0;
1950 Select *pNext = 0;
1951 Select **pp = &pRet;
1952 const Select *p;
1954 assert( db!=0 );
1955 for(p=pDup; p; p=p->pPrior){
1956 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1957 if( pNew==0 ) break;
1958 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1959 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1960 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1961 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1962 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1963 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1964 pNew->op = p->op;
1965 pNew->pNext = pNext;
1966 pNew->pPrior = 0;
1967 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1968 pNew->iLimit = 0;
1969 pNew->iOffset = 0;
1970 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1971 pNew->addrOpenEphm[0] = -1;
1972 pNew->addrOpenEphm[1] = -1;
1973 pNew->nSelectRow = p->nSelectRow;
1974 pNew->pWith = sqlite3WithDup(db, p->pWith);
1975 #ifndef SQLITE_OMIT_WINDOWFUNC
1976 pNew->pWin = 0;
1977 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1978 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
1979 #endif
1980 pNew->selId = p->selId;
1981 if( db->mallocFailed ){
1982 /* Any prior OOM might have left the Select object incomplete.
1983 ** Delete the whole thing rather than allow an incomplete Select
1984 ** to be used by the code generator. */
1985 pNew->pNext = 0;
1986 sqlite3SelectDelete(db, pNew);
1987 break;
1989 *pp = pNew;
1990 pp = &pNew->pPrior;
1991 pNext = pNew;
1993 return pRet;
1995 #else
1996 Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){
1997 assert( p==0 );
1998 return 0;
2000 #endif
2004 ** Add a new element to the end of an expression list. If pList is
2005 ** initially NULL, then create a new expression list.
2007 ** The pList argument must be either NULL or a pointer to an ExprList
2008 ** obtained from a prior call to sqlite3ExprListAppend().
2010 ** If a memory allocation error occurs, the entire list is freed and
2011 ** NULL is returned. If non-NULL is returned, then it is guaranteed
2012 ** that the new entry was successfully appended.
2014 static const struct ExprList_item zeroItem = {0};
2015 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(
2016 sqlite3 *db, /* Database handle. Used for memory allocation */
2017 Expr *pExpr /* Expression to be appended. Might be NULL */
2019 struct ExprList_item *pItem;
2020 ExprList *pList;
2022 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
2023 if( pList==0 ){
2024 sqlite3ExprDelete(db, pExpr);
2025 return 0;
2027 pList->nAlloc = 4;
2028 pList->nExpr = 1;
2029 pItem = &pList->a[0];
2030 *pItem = zeroItem;
2031 pItem->pExpr = pExpr;
2032 return pList;
2034 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(
2035 sqlite3 *db, /* Database handle. Used for memory allocation */
2036 ExprList *pList, /* List to which to append. Might be NULL */
2037 Expr *pExpr /* Expression to be appended. Might be NULL */
2039 struct ExprList_item *pItem;
2040 ExprList *pNew;
2041 pList->nAlloc *= 2;
2042 pNew = sqlite3DbRealloc(db, pList,
2043 sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
2044 if( pNew==0 ){
2045 sqlite3ExprListDelete(db, pList);
2046 sqlite3ExprDelete(db, pExpr);
2047 return 0;
2048 }else{
2049 pList = pNew;
2051 pItem = &pList->a[pList->nExpr++];
2052 *pItem = zeroItem;
2053 pItem->pExpr = pExpr;
2054 return pList;
2056 ExprList *sqlite3ExprListAppend(
2057 Parse *pParse, /* Parsing context */
2058 ExprList *pList, /* List to which to append. Might be NULL */
2059 Expr *pExpr /* Expression to be appended. Might be NULL */
2061 struct ExprList_item *pItem;
2062 if( pList==0 ){
2063 return sqlite3ExprListAppendNew(pParse->db,pExpr);
2065 if( pList->nAlloc<pList->nExpr+1 ){
2066 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
2068 pItem = &pList->a[pList->nExpr++];
2069 *pItem = zeroItem;
2070 pItem->pExpr = pExpr;
2071 return pList;
2075 ** pColumns and pExpr form a vector assignment which is part of the SET
2076 ** clause of an UPDATE statement. Like this:
2078 ** (a,b,c) = (expr1,expr2,expr3)
2079 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
2081 ** For each term of the vector assignment, append new entries to the
2082 ** expression list pList. In the case of a subquery on the RHS, append
2083 ** TK_SELECT_COLUMN expressions.
2085 ExprList *sqlite3ExprListAppendVector(
2086 Parse *pParse, /* Parsing context */
2087 ExprList *pList, /* List to which to append. Might be NULL */
2088 IdList *pColumns, /* List of names of LHS of the assignment */
2089 Expr *pExpr /* Vector expression to be appended. Might be NULL */
2091 sqlite3 *db = pParse->db;
2092 int n;
2093 int i;
2094 int iFirst = pList ? pList->nExpr : 0;
2095 /* pColumns can only be NULL due to an OOM but an OOM will cause an
2096 ** exit prior to this routine being invoked */
2097 if( NEVER(pColumns==0) ) goto vector_append_error;
2098 if( pExpr==0 ) goto vector_append_error;
2100 /* If the RHS is a vector, then we can immediately check to see that
2101 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
2102 ** wildcards ("*") in the result set of the SELECT must be expanded before
2103 ** we can do the size check, so defer the size check until code generation.
2105 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
2106 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
2107 pColumns->nId, n);
2108 goto vector_append_error;
2111 for(i=0; i<pColumns->nId; i++){
2112 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
2113 assert( pSubExpr!=0 || db->mallocFailed );
2114 if( pSubExpr==0 ) continue;
2115 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
2116 if( pList ){
2117 assert( pList->nExpr==iFirst+i+1 );
2118 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
2119 pColumns->a[i].zName = 0;
2123 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
2124 Expr *pFirst = pList->a[iFirst].pExpr;
2125 assert( pFirst!=0 );
2126 assert( pFirst->op==TK_SELECT_COLUMN );
2128 /* Store the SELECT statement in pRight so it will be deleted when
2129 ** sqlite3ExprListDelete() is called */
2130 pFirst->pRight = pExpr;
2131 pExpr = 0;
2133 /* Remember the size of the LHS in iTable so that we can check that
2134 ** the RHS and LHS sizes match during code generation. */
2135 pFirst->iTable = pColumns->nId;
2138 vector_append_error:
2139 sqlite3ExprUnmapAndDelete(pParse, pExpr);
2140 sqlite3IdListDelete(db, pColumns);
2141 return pList;
2145 ** Set the sort order for the last element on the given ExprList.
2147 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
2148 struct ExprList_item *pItem;
2149 if( p==0 ) return;
2150 assert( p->nExpr>0 );
2152 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
2153 assert( iSortOrder==SQLITE_SO_UNDEFINED
2154 || iSortOrder==SQLITE_SO_ASC
2155 || iSortOrder==SQLITE_SO_DESC
2157 assert( eNulls==SQLITE_SO_UNDEFINED
2158 || eNulls==SQLITE_SO_ASC
2159 || eNulls==SQLITE_SO_DESC
2162 pItem = &p->a[p->nExpr-1];
2163 assert( pItem->fg.bNulls==0 );
2164 if( iSortOrder==SQLITE_SO_UNDEFINED ){
2165 iSortOrder = SQLITE_SO_ASC;
2167 pItem->fg.sortFlags = (u8)iSortOrder;
2169 if( eNulls!=SQLITE_SO_UNDEFINED ){
2170 pItem->fg.bNulls = 1;
2171 if( iSortOrder!=eNulls ){
2172 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL;
2178 ** Set the ExprList.a[].zEName element of the most recently added item
2179 ** on the expression list.
2181 ** pList might be NULL following an OOM error. But pName should never be
2182 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2183 ** is set.
2185 void sqlite3ExprListSetName(
2186 Parse *pParse, /* Parsing context */
2187 ExprList *pList, /* List to which to add the span. */
2188 const Token *pName, /* Name to be added */
2189 int dequote /* True to cause the name to be dequoted */
2191 assert( pList!=0 || pParse->db->mallocFailed!=0 );
2192 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
2193 if( pList ){
2194 struct ExprList_item *pItem;
2195 assert( pList->nExpr>0 );
2196 pItem = &pList->a[pList->nExpr-1];
2197 assert( pItem->zEName==0 );
2198 assert( pItem->fg.eEName==ENAME_NAME );
2199 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
2200 if( dequote ){
2201 /* If dequote==0, then pName->z does not point to part of a DDL
2202 ** statement handled by the parser. And so no token need be added
2203 ** to the token-map. */
2204 sqlite3Dequote(pItem->zEName);
2205 if( IN_RENAME_OBJECT ){
2206 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
2213 ** Set the ExprList.a[].zSpan element of the most recently added item
2214 ** on the expression list.
2216 ** pList might be NULL following an OOM error. But pSpan should never be
2217 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2218 ** is set.
2220 void sqlite3ExprListSetSpan(
2221 Parse *pParse, /* Parsing context */
2222 ExprList *pList, /* List to which to add the span. */
2223 const char *zStart, /* Start of the span */
2224 const char *zEnd /* End of the span */
2226 sqlite3 *db = pParse->db;
2227 assert( pList!=0 || db->mallocFailed!=0 );
2228 if( pList ){
2229 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
2230 assert( pList->nExpr>0 );
2231 if( pItem->zEName==0 ){
2232 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
2233 pItem->fg.eEName = ENAME_SPAN;
2239 ** If the expression list pEList contains more than iLimit elements,
2240 ** leave an error message in pParse.
2242 void sqlite3ExprListCheckLength(
2243 Parse *pParse,
2244 ExprList *pEList,
2245 const char *zObject
2247 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
2248 testcase( pEList && pEList->nExpr==mx );
2249 testcase( pEList && pEList->nExpr==mx+1 );
2250 if( pEList && pEList->nExpr>mx ){
2251 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
2256 ** Delete an entire expression list.
2258 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
2259 int i = pList->nExpr;
2260 struct ExprList_item *pItem = pList->a;
2261 assert( pList->nExpr>0 );
2262 assert( db!=0 );
2264 sqlite3ExprDelete(db, pItem->pExpr);
2265 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName);
2266 pItem++;
2267 }while( --i>0 );
2268 sqlite3DbNNFreeNN(db, pList);
2270 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
2271 if( pList ) exprListDeleteNN(db, pList);
2273 void sqlite3ExprListDeleteGeneric(sqlite3 *db, void *pList){
2274 if( ALWAYS(pList) ) exprListDeleteNN(db, (ExprList*)pList);
2278 ** Return the bitwise-OR of all Expr.flags fields in the given
2279 ** ExprList.
2281 u32 sqlite3ExprListFlags(const ExprList *pList){
2282 int i;
2283 u32 m = 0;
2284 assert( pList!=0 );
2285 for(i=0; i<pList->nExpr; i++){
2286 Expr *pExpr = pList->a[i].pExpr;
2287 assert( pExpr!=0 );
2288 m |= pExpr->flags;
2290 return m;
2294 ** This is a SELECT-node callback for the expression walker that
2295 ** always "fails". By "fail" in this case, we mean set
2296 ** pWalker->eCode to zero and abort.
2298 ** This callback is used by multiple expression walkers.
2300 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
2301 UNUSED_PARAMETER(NotUsed);
2302 pWalker->eCode = 0;
2303 return WRC_Abort;
2307 ** Check the input string to see if it is "true" or "false" (in any case).
2309 ** If the string is.... Return
2310 ** "true" EP_IsTrue
2311 ** "false" EP_IsFalse
2312 ** anything else 0
2314 u32 sqlite3IsTrueOrFalse(const char *zIn){
2315 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue;
2316 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
2317 return 0;
2322 ** If the input expression is an ID with the name "true" or "false"
2323 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2324 ** the conversion happened, and zero if the expression is unaltered.
2326 int sqlite3ExprIdToTrueFalse(Expr *pExpr){
2327 u32 v;
2328 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
2329 if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue)
2330 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
2332 pExpr->op = TK_TRUEFALSE;
2333 ExprSetProperty(pExpr, v);
2334 return 1;
2336 return 0;
2340 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2341 ** and 0 if it is FALSE.
2343 int sqlite3ExprTruthValue(const Expr *pExpr){
2344 pExpr = sqlite3ExprSkipCollateAndLikely((Expr*)pExpr);
2345 assert( pExpr->op==TK_TRUEFALSE );
2346 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2347 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
2348 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
2349 return pExpr->u.zToken[4]==0;
2353 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2354 ** terms that are always true or false. Return the simplified expression.
2355 ** Or return the original expression if no simplification is possible.
2357 ** Examples:
2359 ** (x<10) AND true => (x<10)
2360 ** (x<10) AND false => false
2361 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2362 ** (x<10) AND (y=22 OR true) => (x<10)
2363 ** (y=22) OR true => true
2365 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
2366 assert( pExpr!=0 );
2367 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
2368 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
2369 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
2370 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
2371 pExpr = pExpr->op==TK_AND ? pRight : pLeft;
2372 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
2373 pExpr = pExpr->op==TK_AND ? pLeft : pRight;
2376 return pExpr;
2380 ** pExpr is a TK_FUNCTION node. Try to determine whether or not the
2381 ** function is a constant function. A function is constant if all of
2382 ** the following are true:
2384 ** (1) It is a scalar function (not an aggregate or window function)
2385 ** (2) It has either the SQLITE_FUNC_CONSTANT or SQLITE_FUNC_SLOCHNG
2386 ** property.
2387 ** (3) All of its arguments are constants
2389 ** This routine sets pWalker->eCode to 0 if pExpr is not a constant.
2390 ** It makes no changes to pWalker->eCode if pExpr is constant. In
2391 ** every case, it returns WRC_Abort.
2393 ** Called as a service subroutine from exprNodeIsConstant().
2395 static SQLITE_NOINLINE int exprNodeIsConstantFunction(
2396 Walker *pWalker,
2397 Expr *pExpr
2399 int n; /* Number of arguments */
2400 ExprList *pList; /* List of arguments */
2401 FuncDef *pDef; /* The function */
2402 sqlite3 *db; /* The database */
2404 assert( pExpr->op==TK_FUNCTION );
2405 if( ExprHasProperty(pExpr, EP_TokenOnly)
2406 || (pList = pExpr->x.pList)==0
2408 n = 0;
2409 }else{
2410 n = pList->nExpr;
2411 sqlite3WalkExprList(pWalker, pList);
2412 if( pWalker->eCode==0 ) return WRC_Abort;
2414 db = pWalker->pParse->db;
2415 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
2416 if( pDef==0
2417 || pDef->xFinalize!=0
2418 || (pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
2419 || ExprHasProperty(pExpr, EP_WinFunc)
2421 pWalker->eCode = 0;
2422 return WRC_Abort;
2424 return WRC_Prune;
2429 ** These routines are Walker callbacks used to check expressions to
2430 ** see if they are "constant" for some definition of constant. The
2431 ** Walker.eCode value determines the type of "constant" we are looking
2432 ** for.
2434 ** These callback routines are used to implement the following:
2436 ** sqlite3ExprIsConstant() pWalker->eCode==1
2437 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2438 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2439 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2441 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2442 ** is found to not be a constant.
2444 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2445 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2446 ** when parsing an existing schema out of the sqlite_schema table and 4
2447 ** when processing a new CREATE TABLE statement. A bound parameter raises
2448 ** an error for new statements, but is silently converted
2449 ** to NULL for existing schemas. This allows sqlite_schema tables that
2450 ** contain a bound parameter because they were generated by older versions
2451 ** of SQLite to be parsed by newer versions of SQLite without raising a
2452 ** malformed schema error.
2454 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
2455 assert( pWalker->eCode>0 );
2457 /* If pWalker->eCode is 2 then any term of the expression that comes from
2458 ** the ON or USING clauses of an outer join disqualifies the expression
2459 ** from being considered constant. */
2460 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){
2461 pWalker->eCode = 0;
2462 return WRC_Abort;
2465 switch( pExpr->op ){
2466 /* Consider functions to be constant if all their arguments are constant
2467 ** and either pWalker->eCode==4 or 5 or the function has the
2468 ** SQLITE_FUNC_CONST flag. */
2469 case TK_FUNCTION:
2470 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
2471 && !ExprHasProperty(pExpr, EP_WinFunc)
2473 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
2474 return WRC_Continue;
2475 }else if( pWalker->pParse ){
2476 return exprNodeIsConstantFunction(pWalker, pExpr);
2477 }else{
2478 pWalker->eCode = 0;
2479 return WRC_Abort;
2481 case TK_ID:
2482 /* Convert "true" or "false" in a DEFAULT clause into the
2483 ** appropriate TK_TRUEFALSE operator */
2484 if( sqlite3ExprIdToTrueFalse(pExpr) ){
2485 return WRC_Prune;
2487 /* no break */ deliberate_fall_through
2488 case TK_COLUMN:
2489 case TK_AGG_FUNCTION:
2490 case TK_AGG_COLUMN:
2491 testcase( pExpr->op==TK_ID );
2492 testcase( pExpr->op==TK_COLUMN );
2493 testcase( pExpr->op==TK_AGG_FUNCTION );
2494 testcase( pExpr->op==TK_AGG_COLUMN );
2495 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
2496 return WRC_Continue;
2498 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
2499 return WRC_Continue;
2501 /* no break */ deliberate_fall_through
2502 case TK_IF_NULL_ROW:
2503 case TK_REGISTER:
2504 case TK_DOT:
2505 case TK_RAISE:
2506 testcase( pExpr->op==TK_REGISTER );
2507 testcase( pExpr->op==TK_IF_NULL_ROW );
2508 testcase( pExpr->op==TK_DOT );
2509 testcase( pExpr->op==TK_RAISE );
2510 pWalker->eCode = 0;
2511 return WRC_Abort;
2512 case TK_VARIABLE:
2513 if( pWalker->eCode==5 ){
2514 /* Silently convert bound parameters that appear inside of CREATE
2515 ** statements into a NULL when parsing the CREATE statement text out
2516 ** of the sqlite_schema table */
2517 pExpr->op = TK_NULL;
2518 }else if( pWalker->eCode==4 ){
2519 /* A bound parameter in a CREATE statement that originates from
2520 ** sqlite3_prepare() causes an error */
2521 pWalker->eCode = 0;
2522 return WRC_Abort;
2524 /* no break */ deliberate_fall_through
2525 default:
2526 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
2527 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
2528 return WRC_Continue;
2531 static int exprIsConst(Parse *pParse, Expr *p, int initFlag){
2532 Walker w;
2533 w.eCode = initFlag;
2534 w.pParse = pParse;
2535 w.xExprCallback = exprNodeIsConstant;
2536 w.xSelectCallback = sqlite3SelectWalkFail;
2537 #ifdef SQLITE_DEBUG
2538 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2539 #endif
2540 sqlite3WalkExpr(&w, p);
2541 return w.eCode;
2545 ** Walk an expression tree. Return non-zero if the expression is constant
2546 ** and 0 if it involves variables or function calls.
2548 ** For the purposes of this function, a double-quoted string (ex: "abc")
2549 ** is considered a variable but a single-quoted string (ex: 'abc') is
2550 ** a constant.
2552 ** The pParse parameter may be NULL. But if it is NULL, there is no way
2553 ** to determine if function calls are constant or not, and hence all
2554 ** function calls will be considered to be non-constant. If pParse is
2555 ** not NULL, then a function call might be constant, depending on the
2556 ** function and on its parameters.
2558 int sqlite3ExprIsConstant(Parse *pParse, Expr *p){
2559 return exprIsConst(pParse, p, 1);
2563 ** Walk an expression tree. Return non-zero if
2565 ** (1) the expression is constant, and
2566 ** (2) the expression does originate in the ON or USING clause
2567 ** of a LEFT JOIN, and
2568 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2569 ** operands created by the constant propagation optimization.
2571 ** When this routine returns true, it indicates that the expression
2572 ** can be added to the pParse->pConstExpr list and evaluated once when
2573 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2575 static int sqlite3ExprIsConstantNotJoin(Parse *pParse, Expr *p){
2576 return exprIsConst(pParse, p, 2);
2580 ** This routine examines sub-SELECT statements as an expression is being
2581 ** walked as part of sqlite3ExprIsTableConstant(). Sub-SELECTs are considered
2582 ** constant as long as they are uncorrelated - meaning that they do not
2583 ** contain any terms from outer contexts.
2585 static int exprSelectWalkTableConstant(Walker *pWalker, Select *pSelect){
2586 assert( pSelect!=0 );
2587 assert( pWalker->eCode==3 || pWalker->eCode==0 );
2588 if( (pSelect->selFlags & SF_Correlated)!=0 ){
2589 pWalker->eCode = 0;
2590 return WRC_Abort;
2592 return WRC_Prune;
2596 ** Walk an expression tree. Return non-zero if the expression is constant
2597 ** for any single row of the table with cursor iCur. In other words, the
2598 ** expression must not refer to any non-deterministic function nor any
2599 ** table other than iCur.
2601 ** Consider uncorrelated subqueries to be constants if the bAllowSubq
2602 ** parameter is true.
2604 static int sqlite3ExprIsTableConstant(Expr *p, int iCur, int bAllowSubq){
2605 Walker w;
2606 w.eCode = 3;
2607 w.pParse = 0;
2608 w.xExprCallback = exprNodeIsConstant;
2609 if( bAllowSubq ){
2610 w.xSelectCallback = exprSelectWalkTableConstant;
2611 }else{
2612 w.xSelectCallback = sqlite3SelectWalkFail;
2613 #ifdef SQLITE_DEBUG
2614 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2615 #endif
2617 w.u.iCur = iCur;
2618 sqlite3WalkExpr(&w, p);
2619 return w.eCode;
2623 ** Check pExpr to see if it is an constraint on the single data source
2624 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
2625 ** constrains pSrc but does not depend on any other tables or data
2626 ** sources anywhere else in the query. Return true (non-zero) if pExpr
2627 ** is a constraint on pSrc only.
2629 ** This is an optimization. False negatives will perhaps cause slower
2630 ** queries, but false positives will yield incorrect answers. So when in
2631 ** doubt, return 0.
2633 ** To be an single-source constraint, the following must be true:
2635 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2637 ** (2a) pExpr cannot use subqueries unless the bAllowSubq parameter is
2638 ** true and the subquery is non-correlated
2640 ** (2b) pExpr cannot use non-deterministic functions.
2642 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2643 ** (Is there some way to relax this constraint?)
2645 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2646 ** (4a) pExpr must come from an ON clause..
2647 ** (4b) and specifically the ON clause associated with the LEFT JOIN.
2649 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2650 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2651 ** clause, not an ON clause.
2653 ** (6) Either:
2655 ** (6a) pExpr does not originate in an ON or USING clause, or
2657 ** (6b) The ON or USING clause from which pExpr is derived is
2658 ** not to the left of a RIGHT JOIN (or FULL JOIN).
2660 ** Without this restriction, accepting pExpr as a single-table
2661 ** constraint might move the the ON/USING filter expression
2662 ** from the left side of a RIGHT JOIN over to the right side,
2663 ** which leads to incorrect answers. See also restriction (9)
2664 ** on push-down.
2666 int sqlite3ExprIsSingleTableConstraint(
2667 Expr *pExpr, /* The constraint */
2668 const SrcList *pSrcList, /* Complete FROM clause */
2669 int iSrc, /* Which element of pSrcList to use */
2670 int bAllowSubq /* Allow non-correlated subqueries */
2672 const SrcItem *pSrc = &pSrcList->a[iSrc];
2673 if( pSrc->fg.jointype & JT_LTORJ ){
2674 return 0; /* rule (3) */
2676 if( pSrc->fg.jointype & JT_LEFT ){
2677 if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (4a) */
2678 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */
2679 }else{
2680 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (5) */
2682 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) /* (6a) */
2683 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (6b) */
2685 int jj;
2686 for(jj=0; jj<iSrc; jj++){
2687 if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){
2688 if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){
2689 return 0; /* restriction (6) */
2691 break;
2695 /* Rules (1), (2a), and (2b) handled by the following: */
2696 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor, bAllowSubq);
2701 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2703 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2704 ExprList *pGroupBy = pWalker->u.pGroupBy;
2705 int i;
2707 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2708 ** it constant. */
2709 for(i=0; i<pGroupBy->nExpr; i++){
2710 Expr *p = pGroupBy->a[i].pExpr;
2711 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
2712 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2713 if( sqlite3IsBinary(pColl) ){
2714 return WRC_Prune;
2719 /* Check if pExpr is a sub-select. If so, consider it variable. */
2720 if( ExprUseXSelect(pExpr) ){
2721 pWalker->eCode = 0;
2722 return WRC_Abort;
2725 return exprNodeIsConstant(pWalker, pExpr);
2729 ** Walk the expression tree passed as the first argument. Return non-zero
2730 ** if the expression consists entirely of constants or copies of terms
2731 ** in pGroupBy that sort with the BINARY collation sequence.
2733 ** This routine is used to determine if a term of the HAVING clause can
2734 ** be promoted into the WHERE clause. In order for such a promotion to work,
2735 ** the value of the HAVING clause term must be the same for all members of
2736 ** a "group". The requirement that the GROUP BY term must be BINARY
2737 ** assumes that no other collating sequence will have a finer-grained
2738 ** grouping than binary. In other words (A=B COLLATE binary) implies
2739 ** A=B in every other collating sequence. The requirement that the
2740 ** GROUP BY be BINARY is stricter than necessary. It would also work
2741 ** to promote HAVING clauses that use the same alternative collating
2742 ** sequence as the GROUP BY term, but that is much harder to check,
2743 ** alternative collating sequences are uncommon, and this is only an
2744 ** optimization, so we take the easy way out and simply require the
2745 ** GROUP BY to use the BINARY collating sequence.
2747 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2748 Walker w;
2749 w.eCode = 1;
2750 w.xExprCallback = exprNodeIsConstantOrGroupBy;
2751 w.xSelectCallback = 0;
2752 w.u.pGroupBy = pGroupBy;
2753 w.pParse = pParse;
2754 sqlite3WalkExpr(&w, p);
2755 return w.eCode;
2759 ** Walk an expression tree for the DEFAULT field of a column definition
2760 ** in a CREATE TABLE statement. Return non-zero if the expression is
2761 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2762 ** the expression is constant or a function call with constant arguments.
2763 ** Return and 0 if there are any variables.
2765 ** isInit is true when parsing from sqlite_schema. isInit is false when
2766 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2767 ** (such as ? or $abc) in the expression are converted into NULL. When
2768 ** isInit is false, parameters raise an error. Parameters should not be
2769 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2770 ** allowed it, so we need to support it when reading sqlite_schema for
2771 ** backwards compatibility.
2773 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2775 ** For the purposes of this function, a double-quoted string (ex: "abc")
2776 ** is considered a variable but a single-quoted string (ex: 'abc') is
2777 ** a constant.
2779 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2780 assert( isInit==0 || isInit==1 );
2781 return exprIsConst(0, p, 4+isInit);
2784 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2786 ** Walk an expression tree. Return 1 if the expression contains a
2787 ** subquery of some kind. Return 0 if there are no subqueries.
2789 int sqlite3ExprContainsSubquery(Expr *p){
2790 Walker w;
2791 w.eCode = 1;
2792 w.xExprCallback = sqlite3ExprWalkNoop;
2793 w.xSelectCallback = sqlite3SelectWalkFail;
2794 #ifdef SQLITE_DEBUG
2795 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2796 #endif
2797 sqlite3WalkExpr(&w, p);
2798 return w.eCode==0;
2800 #endif
2803 ** If the expression p codes a constant integer that is small enough
2804 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2805 ** in *pValue. If the expression is not an integer or if it is too big
2806 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2808 ** If the pParse pointer is provided, then allow the expression p to be
2809 ** a parameter (TK_VARIABLE) that is bound to an integer.
2810 ** But if pParse is NULL, then p must be a pure integer literal.
2812 int sqlite3ExprIsInteger(const Expr *p, int *pValue, Parse *pParse){
2813 int rc = 0;
2814 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
2816 /* If an expression is an integer literal that fits in a signed 32-bit
2817 ** integer, then the EP_IntValue flag will have already been set */
2818 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2819 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2821 if( p->flags & EP_IntValue ){
2822 *pValue = p->u.iValue;
2823 return 1;
2825 switch( p->op ){
2826 case TK_UPLUS: {
2827 rc = sqlite3ExprIsInteger(p->pLeft, pValue, 0);
2828 break;
2830 case TK_UMINUS: {
2831 int v = 0;
2832 if( sqlite3ExprIsInteger(p->pLeft, &v, 0) ){
2833 assert( ((unsigned int)v)!=0x80000000 );
2834 *pValue = -v;
2835 rc = 1;
2837 break;
2839 case TK_VARIABLE: {
2840 sqlite3_value *pVal;
2841 if( pParse==0 ) break;
2842 if( NEVER(pParse->pVdbe==0) ) break;
2843 if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) break;
2844 sqlite3VdbeSetVarmask(pParse->pVdbe, p->iColumn);
2845 pVal = sqlite3VdbeGetBoundValue(pParse->pReprepare, p->iColumn,
2846 SQLITE_AFF_BLOB);
2847 if( pVal ){
2848 if( sqlite3_value_type(pVal)==SQLITE_INTEGER ){
2849 sqlite3_int64 vv = sqlite3_value_int64(pVal);
2850 if( vv == (vv & 0x7fffffff) ){ /* non-negative numbers only */
2851 *pValue = (int)vv;
2852 rc = 1;
2855 sqlite3ValueFree(pVal);
2857 break;
2859 default: break;
2861 return rc;
2865 ** Return FALSE if there is no chance that the expression can be NULL.
2867 ** If the expression might be NULL or if the expression is too complex
2868 ** to tell return TRUE.
2870 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2871 ** when we know that a value cannot be NULL. Hence, a false positive
2872 ** (returning TRUE when in fact the expression can never be NULL) might
2873 ** be a small performance hit but is otherwise harmless. On the other
2874 ** hand, a false negative (returning FALSE when the result could be NULL)
2875 ** will likely result in an incorrect answer. So when in doubt, return
2876 ** TRUE.
2878 int sqlite3ExprCanBeNull(const Expr *p){
2879 u8 op;
2880 assert( p!=0 );
2881 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2882 p = p->pLeft;
2883 assert( p!=0 );
2885 op = p->op;
2886 if( op==TK_REGISTER ) op = p->op2;
2887 switch( op ){
2888 case TK_INTEGER:
2889 case TK_STRING:
2890 case TK_FLOAT:
2891 case TK_BLOB:
2892 return 0;
2893 case TK_COLUMN:
2894 assert( ExprUseYTab(p) );
2895 return ExprHasProperty(p, EP_CanBeNull)
2896 || NEVER(p->y.pTab==0) /* Reference to column of index on expr */
2897 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
2898 || (p->iColumn==XN_ROWID && IsView(p->y.pTab))
2899 #endif
2900 || (p->iColumn>=0
2901 && p->y.pTab->aCol!=0 /* Possible due to prior error */
2902 && ALWAYS(p->iColumn<p->y.pTab->nCol)
2903 && p->y.pTab->aCol[p->iColumn].notNull==0);
2904 default:
2905 return 1;
2910 ** Return TRUE if the given expression is a constant which would be
2911 ** unchanged by OP_Affinity with the affinity given in the second
2912 ** argument.
2914 ** This routine is used to determine if the OP_Affinity operation
2915 ** can be omitted. When in doubt return FALSE. A false negative
2916 ** is harmless. A false positive, however, can result in the wrong
2917 ** answer.
2919 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2920 u8 op;
2921 int unaryMinus = 0;
2922 if( aff==SQLITE_AFF_BLOB ) return 1;
2923 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2924 if( p->op==TK_UMINUS ) unaryMinus = 1;
2925 p = p->pLeft;
2927 op = p->op;
2928 if( op==TK_REGISTER ) op = p->op2;
2929 switch( op ){
2930 case TK_INTEGER: {
2931 return aff>=SQLITE_AFF_NUMERIC;
2933 case TK_FLOAT: {
2934 return aff>=SQLITE_AFF_NUMERIC;
2936 case TK_STRING: {
2937 return !unaryMinus && aff==SQLITE_AFF_TEXT;
2939 case TK_BLOB: {
2940 return !unaryMinus;
2942 case TK_COLUMN: {
2943 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
2944 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
2946 default: {
2947 return 0;
2953 ** Return TRUE if the given string is a row-id column name.
2955 int sqlite3IsRowid(const char *z){
2956 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2957 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2958 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2959 return 0;
2963 ** Return a pointer to a buffer containing a usable rowid alias for table
2964 ** pTab. An alias is usable if there is not an explicit user-defined column
2965 ** of the same name.
2967 const char *sqlite3RowidAlias(Table *pTab){
2968 const char *azOpt[] = {"_ROWID_", "ROWID", "OID"};
2969 int ii;
2970 assert( VisibleRowid(pTab) );
2971 for(ii=0; ii<ArraySize(azOpt); ii++){
2972 int iCol;
2973 for(iCol=0; iCol<pTab->nCol; iCol++){
2974 if( sqlite3_stricmp(azOpt[ii], pTab->aCol[iCol].zCnName)==0 ) break;
2976 if( iCol==pTab->nCol ){
2977 return azOpt[ii];
2980 return 0;
2984 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2985 ** that can be simplified to a direct table access, then return
2986 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2987 ** or if the SELECT statement needs to be materialized into a transient
2988 ** table, then return NULL.
2990 #ifndef SQLITE_OMIT_SUBQUERY
2991 static Select *isCandidateForInOpt(const Expr *pX){
2992 Select *p;
2993 SrcList *pSrc;
2994 ExprList *pEList;
2995 Table *pTab;
2996 int i;
2997 if( !ExprUseXSelect(pX) ) return 0; /* Not a subquery */
2998 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
2999 p = pX->x.pSelect;
3000 if( p->pPrior ) return 0; /* Not a compound SELECT */
3001 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
3002 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
3003 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
3004 return 0; /* No DISTINCT keyword and no aggregate functions */
3006 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
3007 if( p->pLimit ) return 0; /* Has no LIMIT clause */
3008 if( p->pWhere ) return 0; /* Has no WHERE clause */
3009 pSrc = p->pSrc;
3010 assert( pSrc!=0 );
3011 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
3012 if( pSrc->a[0].fg.isSubquery) return 0;/* FROM is not a subquery or view */
3013 pTab = pSrc->a[0].pSTab;
3014 assert( pTab!=0 );
3015 assert( !IsView(pTab) ); /* FROM clause is not a view */
3016 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
3017 pEList = p->pEList;
3018 assert( pEList!=0 );
3019 /* All SELECT results must be columns. */
3020 for(i=0; i<pEList->nExpr; i++){
3021 Expr *pRes = pEList->a[i].pExpr;
3022 if( pRes->op!=TK_COLUMN ) return 0;
3023 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
3025 return p;
3027 #endif /* SQLITE_OMIT_SUBQUERY */
3029 #ifndef SQLITE_OMIT_SUBQUERY
3031 ** Generate code that checks the left-most column of index table iCur to see if
3032 ** it contains any NULL entries. Cause the register at regHasNull to be set
3033 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
3034 ** to be set to NULL if iCur contains one or more NULL values.
3036 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
3037 int addr1;
3038 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
3039 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
3040 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
3041 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
3042 VdbeComment((v, "first_entry_in(%d)", iCur));
3043 sqlite3VdbeJumpHere(v, addr1);
3045 #endif
3048 #ifndef SQLITE_OMIT_SUBQUERY
3050 ** The argument is an IN operator with a list (not a subquery) on the
3051 ** right-hand side. Return TRUE if that list is constant.
3053 static int sqlite3InRhsIsConstant(Parse *pParse, Expr *pIn){
3054 Expr *pLHS;
3055 int res;
3056 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
3057 pLHS = pIn->pLeft;
3058 pIn->pLeft = 0;
3059 res = sqlite3ExprIsConstant(pParse, pIn);
3060 pIn->pLeft = pLHS;
3061 return res;
3063 #endif
3066 ** This function is used by the implementation of the IN (...) operator.
3067 ** The pX parameter is the expression on the RHS of the IN operator, which
3068 ** might be either a list of expressions or a subquery.
3070 ** The job of this routine is to find or create a b-tree object that can
3071 ** be used either to test for membership in the RHS set or to iterate through
3072 ** all members of the RHS set, skipping duplicates.
3074 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
3075 ** and the *piTab parameter is set to the index of that cursor.
3077 ** The returned value of this function indicates the b-tree type, as follows:
3079 ** IN_INDEX_ROWID - The cursor was opened on a database table.
3080 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
3081 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
3082 ** IN_INDEX_EPH - The cursor was opened on a specially created and
3083 ** populated ephemeral table.
3084 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
3085 ** implemented as a sequence of comparisons.
3087 ** An existing b-tree might be used if the RHS expression pX is a simple
3088 ** subquery such as:
3090 ** SELECT <column1>, <column2>... FROM <table>
3092 ** If the RHS of the IN operator is a list or a more complex subquery, then
3093 ** an ephemeral table might need to be generated from the RHS and then
3094 ** pX->iTable made to point to the ephemeral table instead of an
3095 ** existing table. In this case, the creation and initialization of the
3096 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag
3097 ** will be set on pX and the pX->y.sub fields will be set to show where
3098 ** the subroutine is coded.
3100 ** The inFlags parameter must contain, at a minimum, one of the bits
3101 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
3102 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
3103 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
3104 ** be used to loop over all values of the RHS of the IN operator.
3106 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
3107 ** through the set members) then the b-tree must not contain duplicates.
3108 ** An ephemeral table will be created unless the selected columns are guaranteed
3109 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
3110 ** a UNIQUE constraint or index.
3112 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
3113 ** for fast set membership tests) then an ephemeral table must
3114 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
3115 ** index can be found with the specified <columns> as its left-most.
3117 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
3118 ** if the RHS of the IN operator is a list (not a subquery) then this
3119 ** routine might decide that creating an ephemeral b-tree for membership
3120 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
3121 ** calling routine should implement the IN operator using a sequence
3122 ** of Eq or Ne comparison operations.
3124 ** When the b-tree is being used for membership tests, the calling function
3125 ** might need to know whether or not the RHS side of the IN operator
3126 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
3127 ** if there is any chance that the (...) might contain a NULL value at
3128 ** runtime, then a register is allocated and the register number written
3129 ** to *prRhsHasNull. If there is no chance that the (...) contains a
3130 ** NULL value, then *prRhsHasNull is left unchanged.
3132 ** If a register is allocated and its location stored in *prRhsHasNull, then
3133 ** the value in that register will be NULL if the b-tree contains one or more
3134 ** NULL values, and it will be some non-NULL value if the b-tree contains no
3135 ** NULL values.
3137 ** If the aiMap parameter is not NULL, it must point to an array containing
3138 ** one element for each column returned by the SELECT statement on the RHS
3139 ** of the IN(...) operator. The i'th entry of the array is populated with the
3140 ** offset of the index column that matches the i'th column returned by the
3141 ** SELECT. For example, if the expression and selected index are:
3143 ** (?,?,?) IN (SELECT a, b, c FROM t1)
3144 ** CREATE INDEX i1 ON t1(b, c, a);
3146 ** then aiMap[] is populated with {2, 0, 1}.
3148 #ifndef SQLITE_OMIT_SUBQUERY
3149 int sqlite3FindInIndex(
3150 Parse *pParse, /* Parsing context */
3151 Expr *pX, /* The IN expression */
3152 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
3153 int *prRhsHasNull, /* Register holding NULL status. See notes */
3154 int *aiMap, /* Mapping from Index fields to RHS fields */
3155 int *piTab /* OUT: index to use */
3157 Select *p; /* SELECT to the right of IN operator */
3158 int eType = 0; /* Type of RHS table. IN_INDEX_* */
3159 int iTab; /* Cursor of the RHS table */
3160 int mustBeUnique; /* True if RHS must be unique */
3161 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
3163 assert( pX->op==TK_IN );
3164 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
3165 iTab = pParse->nTab++;
3167 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
3168 ** whether or not the SELECT result contains NULL values, check whether
3169 ** or not NULL is actually possible (it may not be, for example, due
3170 ** to NOT NULL constraints in the schema). If no NULL values are possible,
3171 ** set prRhsHasNull to 0 before continuing. */
3172 if( prRhsHasNull && ExprUseXSelect(pX) ){
3173 int i;
3174 ExprList *pEList = pX->x.pSelect->pEList;
3175 for(i=0; i<pEList->nExpr; i++){
3176 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
3178 if( i==pEList->nExpr ){
3179 prRhsHasNull = 0;
3183 /* Check to see if an existing table or index can be used to
3184 ** satisfy the query. This is preferable to generating a new
3185 ** ephemeral table. */
3186 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
3187 sqlite3 *db = pParse->db; /* Database connection */
3188 Table *pTab; /* Table <table>. */
3189 int iDb; /* Database idx for pTab */
3190 ExprList *pEList = p->pEList;
3191 int nExpr = pEList->nExpr;
3193 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
3194 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
3195 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
3196 pTab = p->pSrc->a[0].pSTab;
3198 /* Code an OP_Transaction and OP_TableLock for <table>. */
3199 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3200 assert( iDb>=0 && iDb<SQLITE_MAX_DB );
3201 sqlite3CodeVerifySchema(pParse, iDb);
3202 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
3204 assert(v); /* sqlite3GetVdbe() has always been previously called */
3205 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
3206 /* The "x IN (SELECT rowid FROM table)" case */
3207 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
3208 VdbeCoverage(v);
3210 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3211 eType = IN_INDEX_ROWID;
3212 ExplainQueryPlan((pParse, 0,
3213 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
3214 sqlite3VdbeJumpHere(v, iAddr);
3215 }else{
3216 Index *pIdx; /* Iterator variable */
3217 int affinity_ok = 1;
3218 int i;
3220 /* Check that the affinity that will be used to perform each
3221 ** comparison is the same as the affinity of each column in table
3222 ** on the RHS of the IN operator. If it not, it is not possible to
3223 ** use any index of the RHS table. */
3224 for(i=0; i<nExpr && affinity_ok; i++){
3225 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
3226 int iCol = pEList->a[i].pExpr->iColumn;
3227 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
3228 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
3229 testcase( cmpaff==SQLITE_AFF_BLOB );
3230 testcase( cmpaff==SQLITE_AFF_TEXT );
3231 switch( cmpaff ){
3232 case SQLITE_AFF_BLOB:
3233 break;
3234 case SQLITE_AFF_TEXT:
3235 /* sqlite3CompareAffinity() only returns TEXT if one side or the
3236 ** other has no affinity and the other side is TEXT. Hence,
3237 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
3238 ** and for the term on the LHS of the IN to have no affinity. */
3239 assert( idxaff==SQLITE_AFF_TEXT );
3240 break;
3241 default:
3242 affinity_ok = sqlite3IsNumericAffinity(idxaff);
3246 if( affinity_ok ){
3247 /* Search for an existing index that will work for this IN operator */
3248 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
3249 Bitmask colUsed; /* Columns of the index used */
3250 Bitmask mCol; /* Mask for the current column */
3251 if( pIdx->nColumn<nExpr ) continue;
3252 if( pIdx->pPartIdxWhere!=0 ) continue;
3253 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
3254 ** BITMASK(nExpr) without overflowing */
3255 testcase( pIdx->nColumn==BMS-2 );
3256 testcase( pIdx->nColumn==BMS-1 );
3257 if( pIdx->nColumn>=BMS-1 ) continue;
3258 if( mustBeUnique ){
3259 if( pIdx->nKeyCol>nExpr
3260 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
3262 continue; /* This index is not unique over the IN RHS columns */
3266 colUsed = 0; /* Columns of index used so far */
3267 for(i=0; i<nExpr; i++){
3268 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
3269 Expr *pRhs = pEList->a[i].pExpr;
3270 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
3271 int j;
3273 for(j=0; j<nExpr; j++){
3274 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
3275 assert( pIdx->azColl[j] );
3276 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
3277 continue;
3279 break;
3281 if( j==nExpr ) break;
3282 mCol = MASKBIT(j);
3283 if( mCol & colUsed ) break; /* Each column used only once */
3284 colUsed |= mCol;
3285 if( aiMap ) aiMap[i] = j;
3288 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
3289 if( colUsed==(MASKBIT(nExpr)-1) ){
3290 /* If we reach this point, that means the index pIdx is usable */
3291 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3292 ExplainQueryPlan((pParse, 0,
3293 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
3294 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
3295 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
3296 VdbeComment((v, "%s", pIdx->zName));
3297 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
3298 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
3300 if( prRhsHasNull ){
3301 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3302 i64 mask = (1<<nExpr)-1;
3303 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
3304 iTab, 0, 0, (u8*)&mask, P4_INT64);
3305 #endif
3306 *prRhsHasNull = ++pParse->nMem;
3307 if( nExpr==1 ){
3308 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
3311 sqlite3VdbeJumpHere(v, iAddr);
3313 } /* End loop over indexes */
3314 } /* End if( affinity_ok ) */
3315 } /* End if not an rowid index */
3316 } /* End attempt to optimize using an index */
3318 /* If no preexisting index is available for the IN clause
3319 ** and IN_INDEX_NOOP is an allowed reply
3320 ** and the RHS of the IN operator is a list, not a subquery
3321 ** and the RHS is not constant or has two or fewer terms,
3322 ** then it is not worth creating an ephemeral table to evaluate
3323 ** the IN operator so return IN_INDEX_NOOP.
3325 if( eType==0
3326 && (inFlags & IN_INDEX_NOOP_OK)
3327 && ExprUseXList(pX)
3328 && (!sqlite3InRhsIsConstant(pParse,pX) || pX->x.pList->nExpr<=2)
3330 pParse->nTab--; /* Back out the allocation of the unused cursor */
3331 iTab = -1; /* Cursor is not allocated */
3332 eType = IN_INDEX_NOOP;
3335 if( eType==0 ){
3336 /* Could not find an existing table or index to use as the RHS b-tree.
3337 ** We will have to generate an ephemeral table to do the job.
3339 u32 savedNQueryLoop = pParse->nQueryLoop;
3340 int rMayHaveNull = 0;
3341 eType = IN_INDEX_EPH;
3342 if( inFlags & IN_INDEX_LOOP ){
3343 pParse->nQueryLoop = 0;
3344 }else if( prRhsHasNull ){
3345 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
3347 assert( pX->op==TK_IN );
3348 sqlite3CodeRhsOfIN(pParse, pX, iTab);
3349 if( rMayHaveNull ){
3350 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
3352 pParse->nQueryLoop = savedNQueryLoop;
3355 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
3356 int i, n;
3357 n = sqlite3ExprVectorSize(pX->pLeft);
3358 for(i=0; i<n; i++) aiMap[i] = i;
3360 *piTab = iTab;
3361 return eType;
3363 #endif
3365 #ifndef SQLITE_OMIT_SUBQUERY
3367 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3368 ** function allocates and returns a nul-terminated string containing
3369 ** the affinities to be used for each column of the comparison.
3371 ** It is the responsibility of the caller to ensure that the returned
3372 ** string is eventually freed using sqlite3DbFree().
3374 static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
3375 Expr *pLeft = pExpr->pLeft;
3376 int nVal = sqlite3ExprVectorSize(pLeft);
3377 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
3378 char *zRet;
3380 assert( pExpr->op==TK_IN );
3381 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
3382 if( zRet ){
3383 int i;
3384 for(i=0; i<nVal; i++){
3385 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
3386 char a = sqlite3ExprAffinity(pA);
3387 if( pSelect ){
3388 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
3389 }else{
3390 zRet[i] = a;
3393 zRet[nVal] = '\0';
3395 return zRet;
3397 #endif
3399 #ifndef SQLITE_OMIT_SUBQUERY
3401 ** Load the Parse object passed as the first argument with an error
3402 ** message of the form:
3404 ** "sub-select returns N columns - expected M"
3406 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
3407 if( pParse->nErr==0 ){
3408 const char *zFmt = "sub-select returns %d columns - expected %d";
3409 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
3412 #endif
3415 ** Expression pExpr is a vector that has been used in a context where
3416 ** it is not permitted. If pExpr is a sub-select vector, this routine
3417 ** loads the Parse object with a message of the form:
3419 ** "sub-select returns N columns - expected 1"
3421 ** Or, if it is a regular scalar vector:
3423 ** "row value misused"
3425 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
3426 #ifndef SQLITE_OMIT_SUBQUERY
3427 if( ExprUseXSelect(pExpr) ){
3428 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
3429 }else
3430 #endif
3432 sqlite3ErrorMsg(pParse, "row value misused");
3436 #ifndef SQLITE_OMIT_SUBQUERY
3438 ** Scan all previously generated bytecode looking for an OP_BeginSubrtn
3439 ** that is compatible with pExpr. If found, add the y.sub values
3440 ** to pExpr and return true. If not found, return false.
3442 static int findCompatibleInRhsSubrtn(
3443 Parse *pParse, /* Parsing context */
3444 Expr *pExpr, /* IN operator with RHS that we want to reuse */
3445 SubrtnSig *pNewSig /* Signature for the IN operator */
3447 VdbeOp *pOp, *pEnd;
3448 SubrtnSig *pSig;
3449 Vdbe *v;
3451 if( pNewSig==0 ) return 0;
3452 if( (pParse->mSubrtnSig & (1<<(pNewSig->selId&7)))==0 ) return 0;
3453 assert( pExpr->op==TK_IN );
3454 assert( !ExprUseYSub(pExpr) );
3455 assert( ExprUseXSelect(pExpr) );
3456 assert( pExpr->x.pSelect!=0 );
3457 assert( (pExpr->x.pSelect->selFlags & SF_All)==0 );
3458 v = pParse->pVdbe;
3459 assert( v!=0 );
3460 pOp = sqlite3VdbeGetOp(v, 1);
3461 pEnd = sqlite3VdbeGetLastOp(v);
3462 for(; pOp<pEnd; pOp++){
3463 if( pOp->p4type!=P4_SUBRTNSIG ) continue;
3464 assert( pOp->opcode==OP_BeginSubrtn );
3465 pSig = pOp->p4.pSubrtnSig;
3466 assert( pSig!=0 );
3467 if( pNewSig->selId!=pSig->selId ) continue;
3468 if( strcmp(pNewSig->zAff,pSig->zAff)!=0 ) continue;
3469 pExpr->y.sub.iAddr = pSig->iAddr;
3470 pExpr->y.sub.regReturn = pSig->regReturn;
3471 pExpr->iTable = pSig->iTable;
3472 ExprSetProperty(pExpr, EP_Subrtn);
3473 return 1;
3475 return 0;
3477 #endif /* SQLITE_OMIT_SUBQUERY */
3479 #ifndef SQLITE_OMIT_SUBQUERY
3481 ** Generate code that will construct an ephemeral table containing all terms
3482 ** in the RHS of an IN operator. The IN operator can be in either of two
3483 ** forms:
3485 ** x IN (4,5,11) -- IN operator with list on right-hand side
3486 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3488 ** The pExpr parameter is the IN operator. The cursor number for the
3489 ** constructed ephemeral table is returned. The first time the ephemeral
3490 ** table is computed, the cursor number is also stored in pExpr->iTable,
3491 ** however the cursor number returned might not be the same, as it might
3492 ** have been duplicated using OP_OpenDup.
3494 ** If the LHS expression ("x" in the examples) is a column value, or
3495 ** the SELECT statement returns a column value, then the affinity of that
3496 ** column is used to build the index keys. If both 'x' and the
3497 ** SELECT... statement are columns, then numeric affinity is used
3498 ** if either column has NUMERIC or INTEGER affinity. If neither
3499 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3500 ** is used.
3502 void sqlite3CodeRhsOfIN(
3503 Parse *pParse, /* Parsing context */
3504 Expr *pExpr, /* The IN operator */
3505 int iTab /* Use this cursor number */
3507 int addrOnce = 0; /* Address of the OP_Once instruction at top */
3508 int addr; /* Address of OP_OpenEphemeral instruction */
3509 Expr *pLeft; /* the LHS of the IN operator */
3510 KeyInfo *pKeyInfo = 0; /* Key information */
3511 int nVal; /* Size of vector pLeft */
3512 Vdbe *v; /* The prepared statement under construction */
3514 v = pParse->pVdbe;
3515 assert( v!=0 );
3517 /* The evaluation of the IN must be repeated every time it
3518 ** is encountered if any of the following is true:
3520 ** * The right-hand side is a correlated subquery
3521 ** * The right-hand side is an expression list containing variables
3522 ** * We are inside a trigger
3524 ** If all of the above are false, then we can compute the RHS just once
3525 ** and reuse it many names.
3527 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
3528 /* Reuse of the RHS is allowed
3530 ** Compute a signature for the RHS of the IN operator to facility
3531 ** finding and reusing prior instances of the same IN operator.
3533 SubrtnSig *pSig = 0;
3534 assert( !ExprUseXSelect(pExpr) || pExpr->x.pSelect!=0 );
3535 if( ExprUseXSelect(pExpr) && (pExpr->x.pSelect->selFlags & SF_All)==0 ){
3536 pSig = sqlite3DbMallocRawNN(pParse->db, sizeof(pSig[0]));
3537 if( pSig ){
3538 pSig->selId = pExpr->x.pSelect->selId;
3539 pSig->zAff = exprINAffinity(pParse, pExpr);
3543 /* Check to see if there is a prior materialization of the RHS of
3544 ** this IN operator. If there is, then make use of that prior
3545 ** materialization rather than recomputing it.
3547 if( ExprHasProperty(pExpr, EP_Subrtn)
3548 || findCompatibleInRhsSubrtn(pParse, pExpr, pSig)
3550 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3551 if( ExprUseXSelect(pExpr) ){
3552 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
3553 pExpr->x.pSelect->selId));
3555 assert( ExprUseYSub(pExpr) );
3556 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3557 pExpr->y.sub.iAddr);
3558 assert( iTab!=pExpr->iTable );
3559 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
3560 sqlite3VdbeJumpHere(v, addrOnce);
3561 if( pSig ){
3562 sqlite3DbFree(pParse->db, pSig->zAff);
3563 sqlite3DbFree(pParse->db, pSig);
3565 return;
3568 /* Begin coding the subroutine */
3569 assert( !ExprUseYWin(pExpr) );
3570 ExprSetProperty(pExpr, EP_Subrtn);
3571 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3572 pExpr->y.sub.regReturn = ++pParse->nMem;
3573 pExpr->y.sub.iAddr =
3574 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3575 if( pSig ){
3576 pSig->iAddr = pExpr->y.sub.iAddr;
3577 pSig->regReturn = pExpr->y.sub.regReturn;
3578 pSig->iTable = iTab;
3579 pParse->mSubrtnSig = 1 << (pSig->selId&7);
3580 sqlite3VdbeChangeP4(v, -1, (const char*)pSig, P4_SUBRTNSIG);
3582 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3585 /* Check to see if this is a vector IN operator */
3586 pLeft = pExpr->pLeft;
3587 nVal = sqlite3ExprVectorSize(pLeft);
3589 /* Construct the ephemeral table that will contain the content of
3590 ** RHS of the IN operator.
3592 pExpr->iTable = iTab;
3593 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
3594 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3595 if( ExprUseXSelect(pExpr) ){
3596 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
3597 }else{
3598 VdbeComment((v, "RHS of IN operator"));
3600 #endif
3601 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
3603 if( ExprUseXSelect(pExpr) ){
3604 /* Case 1: expr IN (SELECT ...)
3606 ** Generate code to write the results of the select into the temporary
3607 ** table allocated and opened above.
3609 Select *pSelect = pExpr->x.pSelect;
3610 ExprList *pEList = pSelect->pEList;
3612 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
3613 addrOnce?"":"CORRELATED ", pSelect->selId
3615 /* If the LHS and RHS of the IN operator do not match, that
3616 ** error will have been caught long before we reach this point. */
3617 if( ALWAYS(pEList->nExpr==nVal) ){
3618 Select *pCopy;
3619 SelectDest dest;
3620 int i;
3621 int rc;
3622 int addrBloom = 0;
3623 sqlite3SelectDestInit(&dest, SRT_Set, iTab);
3624 dest.zAffSdst = exprINAffinity(pParse, pExpr);
3625 pSelect->iLimit = 0;
3626 if( addrOnce && OptimizationEnabled(pParse->db, SQLITE_BloomFilter) ){
3627 int regBloom = ++pParse->nMem;
3628 addrBloom = sqlite3VdbeAddOp2(v, OP_Blob, 10000, regBloom);
3629 VdbeComment((v, "Bloom filter"));
3630 dest.iSDParm2 = regBloom;
3632 testcase( pSelect->selFlags & SF_Distinct );
3633 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3634 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
3635 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
3636 sqlite3SelectDelete(pParse->db, pCopy);
3637 sqlite3DbFree(pParse->db, dest.zAffSdst);
3638 if( addrBloom ){
3639 sqlite3VdbeGetOp(v, addrOnce)->p3 = dest.iSDParm2;
3640 if( dest.iSDParm2==0 ){
3641 sqlite3VdbeChangeToNoop(v, addrBloom);
3642 }else{
3643 sqlite3VdbeGetOp(v, addrOnce)->p3 = dest.iSDParm2;
3646 if( rc ){
3647 sqlite3KeyInfoUnref(pKeyInfo);
3648 return;
3650 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
3651 assert( pEList!=0 );
3652 assert( pEList->nExpr>0 );
3653 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3654 for(i=0; i<nVal; i++){
3655 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
3656 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
3657 pParse, p, pEList->a[i].pExpr
3661 }else if( ALWAYS(pExpr->x.pList!=0) ){
3662 /* Case 2: expr IN (exprlist)
3664 ** For each expression, build an index key from the evaluation and
3665 ** store it in the temporary table. If <expr> is a column, then use
3666 ** that columns affinity when building index keys. If <expr> is not
3667 ** a column, use numeric affinity.
3669 char affinity; /* Affinity of the LHS of the IN */
3670 int i;
3671 ExprList *pList = pExpr->x.pList;
3672 struct ExprList_item *pItem;
3673 int r1, r2;
3674 affinity = sqlite3ExprAffinity(pLeft);
3675 if( affinity<=SQLITE_AFF_NONE ){
3676 affinity = SQLITE_AFF_BLOB;
3677 }else if( affinity==SQLITE_AFF_REAL ){
3678 affinity = SQLITE_AFF_NUMERIC;
3680 if( pKeyInfo ){
3681 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3682 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3685 /* Loop through each expression in <exprlist>. */
3686 r1 = sqlite3GetTempReg(pParse);
3687 r2 = sqlite3GetTempReg(pParse);
3688 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
3689 Expr *pE2 = pItem->pExpr;
3691 /* If the expression is not constant then we will need to
3692 ** disable the test that was generated above that makes sure
3693 ** this code only executes once. Because for a non-constant
3694 ** expression we need to rerun this code each time.
3696 if( addrOnce && !sqlite3ExprIsConstant(pParse, pE2) ){
3697 sqlite3VdbeChangeToNoop(v, addrOnce-1);
3698 sqlite3VdbeChangeToNoop(v, addrOnce);
3699 ExprClearProperty(pExpr, EP_Subrtn);
3700 addrOnce = 0;
3703 /* Evaluate the expression and insert it into the temp table */
3704 sqlite3ExprCode(pParse, pE2, r1);
3705 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
3706 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
3708 sqlite3ReleaseTempReg(pParse, r1);
3709 sqlite3ReleaseTempReg(pParse, r2);
3711 if( pKeyInfo ){
3712 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
3714 if( addrOnce ){
3715 sqlite3VdbeAddOp1(v, OP_NullRow, iTab);
3716 sqlite3VdbeJumpHere(v, addrOnce);
3717 /* Subroutine return */
3718 assert( ExprUseYSub(pExpr) );
3719 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3720 || pParse->nErr );
3721 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3722 pExpr->y.sub.iAddr, 1);
3723 VdbeCoverage(v);
3724 sqlite3ClearTempRegCache(pParse);
3727 #endif /* SQLITE_OMIT_SUBQUERY */
3730 ** Generate code for scalar subqueries used as a subquery expression
3731 ** or EXISTS operator:
3733 ** (SELECT a FROM b) -- subquery
3734 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3736 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3738 ** Return the register that holds the result. For a multi-column SELECT,
3739 ** the result is stored in a contiguous array of registers and the
3740 ** return value is the register of the left-most result column.
3741 ** Return 0 if an error occurs.
3743 #ifndef SQLITE_OMIT_SUBQUERY
3744 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
3745 int addrOnce = 0; /* Address of OP_Once at top of subroutine */
3746 int rReg = 0; /* Register storing resulting */
3747 Select *pSel; /* SELECT statement to encode */
3748 SelectDest dest; /* How to deal with SELECT result */
3749 int nReg; /* Registers to allocate */
3750 Expr *pLimit; /* New limit expression */
3751 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3752 int addrExplain; /* Address of OP_Explain instruction */
3753 #endif
3755 Vdbe *v = pParse->pVdbe;
3756 assert( v!=0 );
3757 if( pParse->nErr ) return 0;
3758 testcase( pExpr->op==TK_EXISTS );
3759 testcase( pExpr->op==TK_SELECT );
3760 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
3761 assert( ExprUseXSelect(pExpr) );
3762 pSel = pExpr->x.pSelect;
3764 /* If this routine has already been coded, then invoke it as a
3765 ** subroutine. */
3766 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3767 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
3768 assert( ExprUseYSub(pExpr) );
3769 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3770 pExpr->y.sub.iAddr);
3771 return pExpr->iTable;
3774 /* Begin coding the subroutine */
3775 assert( !ExprUseYWin(pExpr) );
3776 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
3777 ExprSetProperty(pExpr, EP_Subrtn);
3778 pExpr->y.sub.regReturn = ++pParse->nMem;
3779 pExpr->y.sub.iAddr =
3780 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3782 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3783 ** is encountered if any of the following is true:
3785 ** * The right-hand side is a correlated subquery
3786 ** * The right-hand side is an expression list containing variables
3787 ** * We are inside a trigger
3789 ** If all of the above are false, then we can run this code just once
3790 ** save the results, and reuse the same result on subsequent invocations.
3792 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
3793 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3796 /* For a SELECT, generate code to put the values for all columns of
3797 ** the first row into an array of registers and return the index of
3798 ** the first register.
3800 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3801 ** into a register and return that register number.
3803 ** In both cases, the query is augmented with "LIMIT 1". Any
3804 ** preexisting limit is discarded in place of the new LIMIT 1.
3806 ExplainQueryPlan2(addrExplain, (pParse, 1, "%sSCALAR SUBQUERY %d",
3807 addrOnce?"":"CORRELATED ", pSel->selId));
3808 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1);
3809 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
3810 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
3811 pParse->nMem += nReg;
3812 if( pExpr->op==TK_SELECT ){
3813 dest.eDest = SRT_Mem;
3814 dest.iSdst = dest.iSDParm;
3815 dest.nSdst = nReg;
3816 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
3817 VdbeComment((v, "Init subquery result"));
3818 }else{
3819 dest.eDest = SRT_Exists;
3820 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
3821 VdbeComment((v, "Init EXISTS result"));
3823 if( pSel->pLimit ){
3824 /* The subquery already has a limit. If the pre-existing limit is X
3825 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3826 sqlite3 *db = pParse->db;
3827 pLimit = sqlite3Expr(db, TK_INTEGER, "0");
3828 if( pLimit ){
3829 pLimit->affExpr = SQLITE_AFF_NUMERIC;
3830 pLimit = sqlite3PExpr(pParse, TK_NE,
3831 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
3833 sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);
3834 pSel->pLimit->pLeft = pLimit;
3835 }else{
3836 /* If there is no pre-existing limit add a limit of 1 */
3837 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
3838 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
3840 pSel->iLimit = 0;
3841 if( sqlite3Select(pParse, pSel, &dest) ){
3842 pExpr->op2 = pExpr->op;
3843 pExpr->op = TK_ERROR;
3844 return 0;
3846 pExpr->iTable = rReg = dest.iSDParm;
3847 ExprSetVVAProperty(pExpr, EP_NoReduce);
3848 if( addrOnce ){
3849 sqlite3VdbeJumpHere(v, addrOnce);
3851 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
3853 /* Subroutine return */
3854 assert( ExprUseYSub(pExpr) );
3855 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3856 || pParse->nErr );
3857 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3858 pExpr->y.sub.iAddr, 1);
3859 VdbeCoverage(v);
3860 sqlite3ClearTempRegCache(pParse);
3861 return rReg;
3863 #endif /* SQLITE_OMIT_SUBQUERY */
3865 #ifndef SQLITE_OMIT_SUBQUERY
3867 ** Expr pIn is an IN(...) expression. This function checks that the
3868 ** sub-select on the RHS of the IN() operator has the same number of
3869 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3870 ** a sub-query, that the LHS is a vector of size 1.
3872 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
3873 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
3874 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
3875 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
3876 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
3877 return 1;
3879 }else if( nVector!=1 ){
3880 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
3881 return 1;
3883 return 0;
3885 #endif
3887 #ifndef SQLITE_OMIT_SUBQUERY
3889 ** Generate code for an IN expression.
3891 ** x IN (SELECT ...)
3892 ** x IN (value, value, ...)
3894 ** The left-hand side (LHS) is a scalar or vector expression. The
3895 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3896 ** subquery. If the RHS is a subquery, the number of result columns must
3897 ** match the number of columns in the vector on the LHS. If the RHS is
3898 ** a list of values, the LHS must be a scalar.
3900 ** The IN operator is true if the LHS value is contained within the RHS.
3901 ** The result is false if the LHS is definitely not in the RHS. The
3902 ** result is NULL if the presence of the LHS in the RHS cannot be
3903 ** determined due to NULLs.
3905 ** This routine generates code that jumps to destIfFalse if the LHS is not
3906 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3907 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3908 ** within the RHS then fall through.
3910 ** See the separate in-operator.md documentation file in the canonical
3911 ** SQLite source tree for additional information.
3913 static void sqlite3ExprCodeIN(
3914 Parse *pParse, /* Parsing and code generating context */
3915 Expr *pExpr, /* The IN expression */
3916 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
3917 int destIfNull /* Jump here if the results are unknown due to NULLs */
3919 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
3920 int eType; /* Type of the RHS */
3921 int rLhs; /* Register(s) holding the LHS values */
3922 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
3923 Vdbe *v; /* Statement under construction */
3924 int *aiMap = 0; /* Map from vector field to index column */
3925 char *zAff = 0; /* Affinity string for comparisons */
3926 int nVector; /* Size of vectors for this IN operator */
3927 int iDummy; /* Dummy parameter to exprCodeVector() */
3928 Expr *pLeft; /* The LHS of the IN operator */
3929 int i; /* loop counter */
3930 int destStep2; /* Where to jump when NULLs seen in step 2 */
3931 int destStep6 = 0; /* Start of code for Step 6 */
3932 int addrTruthOp; /* Address of opcode that determines the IN is true */
3933 int destNotNull; /* Jump here if a comparison is not true in step 6 */
3934 int addrTop; /* Top of the step-6 loop */
3935 int iTab = 0; /* Index to use */
3936 u8 okConstFactor = pParse->okConstFactor;
3938 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3939 pLeft = pExpr->pLeft;
3940 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3941 zAff = exprINAffinity(pParse, pExpr);
3942 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3943 aiMap = (int*)sqlite3DbMallocZero(pParse->db, nVector*sizeof(int));
3944 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3946 /* Attempt to compute the RHS. After this step, if anything other than
3947 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3948 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3949 ** the RHS has not yet been coded. */
3950 v = pParse->pVdbe;
3951 assert( v!=0 ); /* OOM detected prior to this routine */
3952 VdbeNoopComment((v, "begin IN expr"));
3953 eType = sqlite3FindInIndex(pParse, pExpr,
3954 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
3955 destIfFalse==destIfNull ? 0 : &rRhsHasNull,
3956 aiMap, &iTab);
3958 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3959 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3961 #ifdef SQLITE_DEBUG
3962 /* Confirm that aiMap[] contains nVector integer values between 0 and
3963 ** nVector-1. */
3964 for(i=0; i<nVector; i++){
3965 int j, cnt;
3966 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3967 assert( cnt==1 );
3969 #endif
3971 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3972 ** vector, then it is stored in an array of nVector registers starting
3973 ** at r1.
3975 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3976 ** so that the fields are in the same order as an existing index. The
3977 ** aiMap[] array contains a mapping from the original LHS field order to
3978 ** the field order that matches the RHS index.
3980 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3981 ** even if it is constant, as OP_Affinity may be used on the register
3982 ** by code generated below. */
3983 assert( pParse->okConstFactor==okConstFactor );
3984 pParse->okConstFactor = 0;
3985 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3986 pParse->okConstFactor = okConstFactor;
3987 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3988 if( i==nVector ){
3989 /* LHS fields are not reordered */
3990 rLhs = rLhsOrig;
3991 }else{
3992 /* Need to reorder the LHS fields according to aiMap */
3993 rLhs = sqlite3GetTempRange(pParse, nVector);
3994 for(i=0; i<nVector; i++){
3995 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3999 /* If sqlite3FindInIndex() did not find or create an index that is
4000 ** suitable for evaluating the IN operator, then evaluate using a
4001 ** sequence of comparisons.
4003 ** This is step (1) in the in-operator.md optimized algorithm.
4005 if( eType==IN_INDEX_NOOP ){
4006 ExprList *pList;
4007 CollSeq *pColl;
4008 int labelOk = sqlite3VdbeMakeLabel(pParse);
4009 int r2, regToFree;
4010 int regCkNull = 0;
4011 int ii;
4012 assert( ExprUseXList(pExpr) );
4013 pList = pExpr->x.pList;
4014 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
4015 if( destIfNull!=destIfFalse ){
4016 regCkNull = sqlite3GetTempReg(pParse);
4017 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
4019 for(ii=0; ii<pList->nExpr; ii++){
4020 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
4021 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
4022 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
4024 sqlite3ReleaseTempReg(pParse, regToFree);
4025 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
4026 int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
4027 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
4028 (void*)pColl, P4_COLLSEQ);
4029 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
4030 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
4031 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
4032 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
4033 sqlite3VdbeChangeP5(v, zAff[0]);
4034 }else{
4035 int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
4036 assert( destIfNull==destIfFalse );
4037 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
4038 (void*)pColl, P4_COLLSEQ);
4039 VdbeCoverageIf(v, op==OP_Ne);
4040 VdbeCoverageIf(v, op==OP_IsNull);
4041 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
4044 if( regCkNull ){
4045 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
4046 sqlite3VdbeGoto(v, destIfFalse);
4048 sqlite3VdbeResolveLabel(v, labelOk);
4049 sqlite3ReleaseTempReg(pParse, regCkNull);
4050 goto sqlite3ExprCodeIN_finished;
4053 /* Step 2: Check to see if the LHS contains any NULL columns. If the
4054 ** LHS does contain NULLs then the result must be either FALSE or NULL.
4055 ** We will then skip the binary search of the RHS.
4057 if( destIfNull==destIfFalse ){
4058 destStep2 = destIfFalse;
4059 }else{
4060 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
4062 for(i=0; i<nVector; i++){
4063 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
4064 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
4065 if( sqlite3ExprCanBeNull(p) ){
4066 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
4067 VdbeCoverage(v);
4071 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
4072 ** of the RHS using the LHS as a probe. If found, the result is
4073 ** true.
4075 if( eType==IN_INDEX_ROWID ){
4076 /* In this case, the RHS is the ROWID of table b-tree and so we also
4077 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
4078 ** into a single opcode. */
4079 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
4080 VdbeCoverage(v);
4081 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
4082 }else{
4083 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
4084 if( destIfFalse==destIfNull ){
4085 /* Combine Step 3 and Step 5 into a single opcode */
4086 if( ExprHasProperty(pExpr, EP_Subrtn) ){
4087 const VdbeOp *pOp = sqlite3VdbeGetOp(v, pExpr->y.sub.iAddr);
4088 assert( pOp->opcode==OP_Once || pParse->nErr );
4089 if( pOp->opcode==OP_Once && pOp->p3>0 ){
4090 assert( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) );
4091 sqlite3VdbeAddOp4Int(v, OP_Filter, pOp->p3, destIfFalse,
4092 rLhs, nVector); VdbeCoverage(v);
4095 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
4096 rLhs, nVector); VdbeCoverage(v);
4097 goto sqlite3ExprCodeIN_finished;
4099 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
4100 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
4101 rLhs, nVector); VdbeCoverage(v);
4104 /* Step 4. If the RHS is known to be non-NULL and we did not find
4105 ** an match on the search above, then the result must be FALSE.
4107 if( rRhsHasNull && nVector==1 ){
4108 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
4109 VdbeCoverage(v);
4112 /* Step 5. If we do not care about the difference between NULL and
4113 ** FALSE, then just return false.
4115 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
4117 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
4118 ** If any comparison is NULL, then the result is NULL. If all
4119 ** comparisons are FALSE then the final result is FALSE.
4121 ** For a scalar LHS, it is sufficient to check just the first row
4122 ** of the RHS.
4124 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
4125 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
4126 VdbeCoverage(v);
4127 if( nVector>1 ){
4128 destNotNull = sqlite3VdbeMakeLabel(pParse);
4129 }else{
4130 /* For nVector==1, combine steps 6 and 7 by immediately returning
4131 ** FALSE if the first comparison is not NULL */
4132 destNotNull = destIfFalse;
4134 for(i=0; i<nVector; i++){
4135 Expr *p;
4136 CollSeq *pColl;
4137 int r3 = sqlite3GetTempReg(pParse);
4138 p = sqlite3VectorFieldSubexpr(pLeft, i);
4139 pColl = sqlite3ExprCollSeq(pParse, p);
4140 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
4141 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
4142 (void*)pColl, P4_COLLSEQ);
4143 VdbeCoverage(v);
4144 sqlite3ReleaseTempReg(pParse, r3);
4146 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
4147 if( nVector>1 ){
4148 sqlite3VdbeResolveLabel(v, destNotNull);
4149 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
4150 VdbeCoverage(v);
4152 /* Step 7: If we reach this point, we know that the result must
4153 ** be false. */
4154 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
4157 /* Jumps here in order to return true. */
4158 sqlite3VdbeJumpHere(v, addrTruthOp);
4160 sqlite3ExprCodeIN_finished:
4161 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
4162 VdbeComment((v, "end IN expr"));
4163 sqlite3ExprCodeIN_oom_error:
4164 sqlite3DbFree(pParse->db, aiMap);
4165 sqlite3DbFree(pParse->db, zAff);
4167 #endif /* SQLITE_OMIT_SUBQUERY */
4169 #ifndef SQLITE_OMIT_FLOATING_POINT
4171 ** Generate an instruction that will put the floating point
4172 ** value described by z[0..n-1] into register iMem.
4174 ** The z[] string will probably not be zero-terminated. But the
4175 ** z[n] character is guaranteed to be something that does not look
4176 ** like the continuation of the number.
4178 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
4179 if( ALWAYS(z!=0) ){
4180 double value;
4181 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
4182 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
4183 if( negateFlag ) value = -value;
4184 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
4187 #endif
4191 ** Generate an instruction that will put the integer describe by
4192 ** text z[0..n-1] into register iMem.
4194 ** Expr.u.zToken is always UTF8 and zero-terminated.
4196 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
4197 Vdbe *v = pParse->pVdbe;
4198 if( pExpr->flags & EP_IntValue ){
4199 int i = pExpr->u.iValue;
4200 assert( i>=0 );
4201 if( negFlag ) i = -i;
4202 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
4203 }else{
4204 int c;
4205 i64 value;
4206 const char *z = pExpr->u.zToken;
4207 assert( z!=0 );
4208 c = sqlite3DecOrHexToI64(z, &value);
4209 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
4210 #ifdef SQLITE_OMIT_FLOATING_POINT
4211 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
4212 #else
4213 #ifndef SQLITE_OMIT_HEX_INTEGER
4214 if( sqlite3_strnicmp(z,"0x",2)==0 ){
4215 sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T",
4216 negFlag?"-":"",pExpr);
4217 }else
4218 #endif
4220 codeReal(v, z, negFlag, iMem);
4222 #endif
4223 }else{
4224 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
4225 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
4231 /* Generate code that will load into register regOut a value that is
4232 ** appropriate for the iIdxCol-th column of index pIdx.
4234 void sqlite3ExprCodeLoadIndexColumn(
4235 Parse *pParse, /* The parsing context */
4236 Index *pIdx, /* The index whose column is to be loaded */
4237 int iTabCur, /* Cursor pointing to a table row */
4238 int iIdxCol, /* The column of the index to be loaded */
4239 int regOut /* Store the index column value in this register */
4241 i16 iTabCol = pIdx->aiColumn[iIdxCol];
4242 if( iTabCol==XN_EXPR ){
4243 assert( pIdx->aColExpr );
4244 assert( pIdx->aColExpr->nExpr>iIdxCol );
4245 pParse->iSelfTab = iTabCur + 1;
4246 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
4247 pParse->iSelfTab = 0;
4248 }else{
4249 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
4250 iTabCol, regOut);
4254 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4256 ** Generate code that will compute the value of generated column pCol
4257 ** and store the result in register regOut
4259 void sqlite3ExprCodeGeneratedColumn(
4260 Parse *pParse, /* Parsing context */
4261 Table *pTab, /* Table containing the generated column */
4262 Column *pCol, /* The generated column */
4263 int regOut /* Put the result in this register */
4265 int iAddr;
4266 Vdbe *v = pParse->pVdbe;
4267 int nErr = pParse->nErr;
4268 assert( v!=0 );
4269 assert( pParse->iSelfTab!=0 );
4270 if( pParse->iSelfTab>0 ){
4271 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
4272 }else{
4273 iAddr = 0;
4275 sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
4276 if( pCol->affinity>=SQLITE_AFF_TEXT ){
4277 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
4279 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
4280 if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1;
4282 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4285 ** Generate code to extract the value of the iCol-th column of a table.
4287 void sqlite3ExprCodeGetColumnOfTable(
4288 Vdbe *v, /* Parsing context */
4289 Table *pTab, /* The table containing the value */
4290 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
4291 int iCol, /* Index of the column to extract */
4292 int regOut /* Extract the value into this register */
4294 Column *pCol;
4295 assert( v!=0 );
4296 assert( pTab!=0 );
4297 assert( iCol!=XN_EXPR );
4298 if( iCol<0 || iCol==pTab->iPKey ){
4299 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
4300 VdbeComment((v, "%s.rowid", pTab->zName));
4301 }else{
4302 int op;
4303 int x;
4304 if( IsVirtual(pTab) ){
4305 op = OP_VColumn;
4306 x = iCol;
4307 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4308 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
4309 Parse *pParse = sqlite3VdbeParser(v);
4310 if( pCol->colFlags & COLFLAG_BUSY ){
4311 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4312 pCol->zCnName);
4313 }else{
4314 int savedSelfTab = pParse->iSelfTab;
4315 pCol->colFlags |= COLFLAG_BUSY;
4316 pParse->iSelfTab = iTabCur+1;
4317 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut);
4318 pParse->iSelfTab = savedSelfTab;
4319 pCol->colFlags &= ~COLFLAG_BUSY;
4321 return;
4322 #endif
4323 }else if( !HasRowid(pTab) ){
4324 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
4325 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
4326 op = OP_Column;
4327 }else{
4328 x = sqlite3TableColumnToStorage(pTab,iCol);
4329 testcase( x!=iCol );
4330 op = OP_Column;
4332 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
4333 sqlite3ColumnDefault(v, pTab, iCol, regOut);
4338 ** Generate code that will extract the iColumn-th column from
4339 ** table pTab and store the column value in register iReg.
4341 ** There must be an open cursor to pTab in iTable when this routine
4342 ** is called. If iColumn<0 then code is generated that extracts the rowid.
4344 int sqlite3ExprCodeGetColumn(
4345 Parse *pParse, /* Parsing and code generating context */
4346 Table *pTab, /* Description of the table we are reading from */
4347 int iColumn, /* Index of the table column */
4348 int iTable, /* The cursor pointing to the table */
4349 int iReg, /* Store results here */
4350 u8 p5 /* P5 value for OP_Column + FLAGS */
4352 assert( pParse->pVdbe!=0 );
4353 assert( (p5 & (OPFLAG_NOCHNG|OPFLAG_TYPEOFARG|OPFLAG_LENGTHARG))==p5 );
4354 assert( IsVirtual(pTab) || (p5 & OPFLAG_NOCHNG)==0 );
4355 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
4356 if( p5 ){
4357 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
4358 if( pOp->opcode==OP_Column ) pOp->p5 = p5;
4359 if( pOp->opcode==OP_VColumn ) pOp->p5 = (p5 & OPFLAG_NOCHNG);
4361 return iReg;
4365 ** Generate code to move content from registers iFrom...iFrom+nReg-1
4366 ** over to iTo..iTo+nReg-1.
4368 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
4369 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
4373 ** Convert a scalar expression node to a TK_REGISTER referencing
4374 ** register iReg. The caller must ensure that iReg already contains
4375 ** the correct value for the expression.
4377 void sqlite3ExprToRegister(Expr *pExpr, int iReg){
4378 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
4379 if( NEVER(p==0) ) return;
4380 if( p->op==TK_REGISTER ){
4381 assert( p->iTable==iReg );
4382 }else{
4383 p->op2 = p->op;
4384 p->op = TK_REGISTER;
4385 p->iTable = iReg;
4386 ExprClearProperty(p, EP_Skip);
4391 ** Evaluate an expression (either a vector or a scalar expression) and store
4392 ** the result in contiguous temporary registers. Return the index of
4393 ** the first register used to store the result.
4395 ** If the returned result register is a temporary scalar, then also write
4396 ** that register number into *piFreeable. If the returned result register
4397 ** is not a temporary or if the expression is a vector set *piFreeable
4398 ** to 0.
4400 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
4401 int iResult;
4402 int nResult = sqlite3ExprVectorSize(p);
4403 if( nResult==1 ){
4404 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
4405 }else{
4406 *piFreeable = 0;
4407 if( p->op==TK_SELECT ){
4408 #if SQLITE_OMIT_SUBQUERY
4409 iResult = 0;
4410 #else
4411 iResult = sqlite3CodeSubselect(pParse, p);
4412 #endif
4413 }else{
4414 int i;
4415 iResult = pParse->nMem+1;
4416 pParse->nMem += nResult;
4417 assert( ExprUseXList(p) );
4418 for(i=0; i<nResult; i++){
4419 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
4423 return iResult;
4427 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
4428 ** so that a subsequent copy will not be merged into this one.
4430 static void setDoNotMergeFlagOnCopy(Vdbe *v){
4431 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){
4432 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergeable */
4437 ** Generate code to implement special SQL functions that are implemented
4438 ** in-line rather than by using the usual callbacks.
4440 static int exprCodeInlineFunction(
4441 Parse *pParse, /* Parsing context */
4442 ExprList *pFarg, /* List of function arguments */
4443 int iFuncId, /* Function ID. One of the INTFUNC_... values */
4444 int target /* Store function result in this register */
4446 int nFarg;
4447 Vdbe *v = pParse->pVdbe;
4448 assert( v!=0 );
4449 assert( pFarg!=0 );
4450 nFarg = pFarg->nExpr;
4451 assert( nFarg>0 ); /* All in-line functions have at least one argument */
4452 switch( iFuncId ){
4453 case INLINEFUNC_coalesce: {
4454 /* Attempt a direct implementation of the built-in COALESCE() and
4455 ** IFNULL() functions. This avoids unnecessary evaluation of
4456 ** arguments past the first non-NULL argument.
4458 int endCoalesce = sqlite3VdbeMakeLabel(pParse);
4459 int i;
4460 assert( nFarg>=2 );
4461 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
4462 for(i=1; i<nFarg; i++){
4463 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
4464 VdbeCoverage(v);
4465 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
4467 setDoNotMergeFlagOnCopy(v);
4468 sqlite3VdbeResolveLabel(v, endCoalesce);
4469 break;
4471 case INLINEFUNC_iif: {
4472 Expr caseExpr;
4473 memset(&caseExpr, 0, sizeof(caseExpr));
4474 caseExpr.op = TK_CASE;
4475 caseExpr.x.pList = pFarg;
4476 return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
4478 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4479 case INLINEFUNC_sqlite_offset: {
4480 Expr *pArg = pFarg->a[0].pExpr;
4481 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){
4482 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
4483 }else{
4484 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4486 break;
4488 #endif
4489 default: {
4490 /* The UNLIKELY() function is a no-op. The result is the value
4491 ** of the first argument.
4493 assert( nFarg==1 || nFarg==2 );
4494 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
4495 break;
4498 /***********************************************************************
4499 ** Test-only SQL functions that are only usable if enabled
4500 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4502 #if !defined(SQLITE_UNTESTABLE)
4503 case INLINEFUNC_expr_compare: {
4504 /* Compare two expressions using sqlite3ExprCompare() */
4505 assert( nFarg==2 );
4506 sqlite3VdbeAddOp2(v, OP_Integer,
4507 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4508 target);
4509 break;
4512 case INLINEFUNC_expr_implies_expr: {
4513 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4514 assert( nFarg==2 );
4515 sqlite3VdbeAddOp2(v, OP_Integer,
4516 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4517 target);
4518 break;
4521 case INLINEFUNC_implies_nonnull_row: {
4522 /* Result of sqlite3ExprImpliesNonNullRow() */
4523 Expr *pA1;
4524 assert( nFarg==2 );
4525 pA1 = pFarg->a[1].pExpr;
4526 if( pA1->op==TK_COLUMN ){
4527 sqlite3VdbeAddOp2(v, OP_Integer,
4528 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable,1),
4529 target);
4530 }else{
4531 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4533 break;
4536 case INLINEFUNC_affinity: {
4537 /* The AFFINITY() function evaluates to a string that describes
4538 ** the type affinity of the argument. This is used for testing of
4539 ** the SQLite type logic.
4541 const char *azAff[] = { "blob", "text", "numeric", "integer",
4542 "real", "flexnum" };
4543 char aff;
4544 assert( nFarg==1 );
4545 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
4546 assert( aff<=SQLITE_AFF_NONE
4547 || (aff>=SQLITE_AFF_BLOB && aff<=SQLITE_AFF_FLEXNUM) );
4548 sqlite3VdbeLoadString(v, target,
4549 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
4550 break;
4552 #endif /* !defined(SQLITE_UNTESTABLE) */
4554 return target;
4558 ** Expression Node callback for sqlite3ExprCanReturnSubtype().
4560 ** Only a function call is able to return a subtype. So if the node
4561 ** is not a function call, return WRC_Prune immediately.
4563 ** A function call is able to return a subtype if it has the
4564 ** SQLITE_RESULT_SUBTYPE property.
4566 ** Assume that every function is able to pass-through a subtype from
4567 ** one of its argument (using sqlite3_result_value()). Most functions
4568 ** are not this way, but we don't have a mechanism to distinguish those
4569 ** that are from those that are not, so assume they all work this way.
4570 ** That means that if one of its arguments is another function and that
4571 ** other function is able to return a subtype, then this function is
4572 ** able to return a subtype.
4574 static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){
4575 int n;
4576 FuncDef *pDef;
4577 sqlite3 *db;
4578 if( pExpr->op!=TK_FUNCTION ){
4579 return WRC_Prune;
4581 assert( ExprUseXList(pExpr) );
4582 db = pWalker->pParse->db;
4583 n = ALWAYS(pExpr->x.pList) ? pExpr->x.pList->nExpr : 0;
4584 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
4585 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
4586 pWalker->eCode = 1;
4587 return WRC_Prune;
4589 return WRC_Continue;
4593 ** Return TRUE if expression pExpr is able to return a subtype.
4595 ** A TRUE return does not guarantee that a subtype will be returned.
4596 ** It only indicates that a subtype return is possible. False positives
4597 ** are acceptable as they only disable an optimization. False negatives,
4598 ** on the other hand, can lead to incorrect answers.
4600 static int sqlite3ExprCanReturnSubtype(Parse *pParse, Expr *pExpr){
4601 Walker w;
4602 memset(&w, 0, sizeof(w));
4603 w.pParse = pParse;
4604 w.xExprCallback = exprNodeCanReturnSubtype;
4605 sqlite3WalkExpr(&w, pExpr);
4606 return w.eCode;
4611 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4612 ** If it is, then resolve the expression by reading from the index and
4613 ** return the register into which the value has been read. If pExpr is
4614 ** not an indexed expression, then return negative.
4616 static SQLITE_NOINLINE int sqlite3IndexedExprLookup(
4617 Parse *pParse, /* The parsing context */
4618 Expr *pExpr, /* The expression to potentially bypass */
4619 int target /* Where to store the result of the expression */
4621 IndexedExpr *p;
4622 Vdbe *v;
4623 for(p=pParse->pIdxEpr; p; p=p->pIENext){
4624 u8 exprAff;
4625 int iDataCur = p->iDataCur;
4626 if( iDataCur<0 ) continue;
4627 if( pParse->iSelfTab ){
4628 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
4629 iDataCur = -1;
4631 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
4632 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
4633 exprAff = sqlite3ExprAffinity(pExpr);
4634 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
4635 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
4636 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
4638 /* Affinity mismatch on a generated column */
4639 continue;
4643 /* Functions that might set a subtype should not be replaced by the
4644 ** value taken from an expression index if they are themselves an
4645 ** argument to another scalar function or aggregate.
4646 ** https://sqlite.org/forum/forumpost/68d284c86b082c3e */
4647 if( ExprHasProperty(pExpr, EP_SubtArg)
4648 && sqlite3ExprCanReturnSubtype(pParse, pExpr)
4650 continue;
4653 v = pParse->pVdbe;
4654 assert( v!=0 );
4655 if( p->bMaybeNullRow ){
4656 /* If the index is on a NULL row due to an outer join, then we
4657 ** cannot extract the value from the index. The value must be
4658 ** computed using the original expression. */
4659 int addr = sqlite3VdbeCurrentAddr(v);
4660 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
4661 VdbeCoverage(v);
4662 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4663 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4664 sqlite3VdbeGoto(v, 0);
4665 p = pParse->pIdxEpr;
4666 pParse->pIdxEpr = 0;
4667 sqlite3ExprCode(pParse, pExpr, target);
4668 pParse->pIdxEpr = p;
4669 sqlite3VdbeJumpHere(v, addr+2);
4670 }else{
4671 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4672 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4674 return target;
4676 return -1; /* Not found */
4681 ** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This
4682 ** function checks the Parse.pIdxPartExpr list to see if this column
4683 ** can be replaced with a constant value. If so, it generates code to
4684 ** put the constant value in a register (ideally, but not necessarily,
4685 ** register iTarget) and returns the register number.
4687 ** Or, if the TK_COLUMN cannot be replaced by a constant, zero is
4688 ** returned.
4690 static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){
4691 IndexedExpr *p;
4692 for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
4693 if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
4694 Vdbe *v = pParse->pVdbe;
4695 int addr = 0;
4696 int ret;
4698 if( p->bMaybeNullRow ){
4699 addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
4701 ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
4702 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
4703 (const char*)&p->aff, 1);
4704 if( addr ){
4705 sqlite3VdbeJumpHere(v, addr);
4706 sqlite3VdbeChangeP3(v, addr, ret);
4708 return ret;
4711 return 0;
4716 ** Generate code into the current Vdbe to evaluate the given
4717 ** expression. Attempt to store the results in register "target".
4718 ** Return the register where results are stored.
4720 ** With this routine, there is no guarantee that results will
4721 ** be stored in target. The result might be stored in some other
4722 ** register if it is convenient to do so. The calling function
4723 ** must check the return code and move the results to the desired
4724 ** register.
4726 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
4727 Vdbe *v = pParse->pVdbe; /* The VM under construction */
4728 int op; /* The opcode being coded */
4729 int inReg = target; /* Results stored in register inReg */
4730 int regFree1 = 0; /* If non-zero free this temporary register */
4731 int regFree2 = 0; /* If non-zero free this temporary register */
4732 int r1, r2; /* Various register numbers */
4733 Expr tempX; /* Temporary expression node */
4734 int p5 = 0;
4736 assert( target>0 && target<=pParse->nMem );
4737 assert( v!=0 );
4739 expr_code_doover:
4740 if( pExpr==0 ){
4741 op = TK_NULL;
4742 }else if( pParse->pIdxEpr!=0
4743 && !ExprHasProperty(pExpr, EP_Leaf)
4744 && (r1 = sqlite3IndexedExprLookup(pParse, pExpr, target))>=0
4746 return r1;
4747 }else{
4748 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
4749 op = pExpr->op;
4751 assert( op!=TK_ORDER );
4752 switch( op ){
4753 case TK_AGG_COLUMN: {
4754 AggInfo *pAggInfo = pExpr->pAggInfo;
4755 struct AggInfo_col *pCol;
4756 assert( pAggInfo!=0 );
4757 assert( pExpr->iAgg>=0 );
4758 if( pExpr->iAgg>=pAggInfo->nColumn ){
4759 /* Happens when the left table of a RIGHT JOIN is null and
4760 ** is using an expression index */
4761 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4762 #ifdef SQLITE_VDBE_COVERAGE
4763 /* Verify that the OP_Null above is exercised by tests
4764 ** tag-20230325-2 */
4765 sqlite3VdbeAddOp3(v, OP_NotNull, target, 1, 20230325);
4766 VdbeCoverageNeverTaken(v);
4767 #endif
4768 break;
4770 pCol = &pAggInfo->aCol[pExpr->iAgg];
4771 if( !pAggInfo->directMode ){
4772 return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
4773 }else if( pAggInfo->useSortingIdx ){
4774 Table *pTab = pCol->pTab;
4775 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
4776 pCol->iSorterColumn, target);
4777 if( pTab==0 ){
4778 /* No comment added */
4779 }else if( pCol->iColumn<0 ){
4780 VdbeComment((v,"%s.rowid",pTab->zName));
4781 }else{
4782 VdbeComment((v,"%s.%s",
4783 pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
4784 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
4785 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4788 return target;
4789 }else if( pExpr->y.pTab==0 ){
4790 /* This case happens when the argument to an aggregate function
4791 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4792 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target);
4793 return target;
4795 /* Otherwise, fall thru into the TK_COLUMN case */
4796 /* no break */ deliberate_fall_through
4798 case TK_COLUMN: {
4799 int iTab = pExpr->iTable;
4800 int iReg;
4801 if( ExprHasProperty(pExpr, EP_FixedCol) ){
4802 /* This COLUMN expression is really a constant due to WHERE clause
4803 ** constraints, and that constant is coded by the pExpr->pLeft
4804 ** expression. However, make sure the constant has the correct
4805 ** datatype by applying the Affinity of the table column to the
4806 ** constant.
4808 int aff;
4809 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
4810 assert( ExprUseYTab(pExpr) );
4811 assert( pExpr->y.pTab!=0 );
4812 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
4813 if( aff>SQLITE_AFF_BLOB ){
4814 static const char zAff[] = "B\000C\000D\000E\000F";
4815 assert( SQLITE_AFF_BLOB=='A' );
4816 assert( SQLITE_AFF_TEXT=='B' );
4817 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
4818 &zAff[(aff-'B')*2], P4_STATIC);
4820 return iReg;
4822 if( iTab<0 ){
4823 if( pParse->iSelfTab<0 ){
4824 /* Other columns in the same row for CHECK constraints or
4825 ** generated columns or for inserting into partial index.
4826 ** The row is unpacked into registers beginning at
4827 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4828 ** immediately prior to the first column.
4830 Column *pCol;
4831 Table *pTab;
4832 int iSrc;
4833 int iCol = pExpr->iColumn;
4834 assert( ExprUseYTab(pExpr) );
4835 pTab = pExpr->y.pTab;
4836 assert( pTab!=0 );
4837 assert( iCol>=XN_ROWID );
4838 assert( iCol<pTab->nCol );
4839 if( iCol<0 ){
4840 return -1-pParse->iSelfTab;
4842 pCol = pTab->aCol + iCol;
4843 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
4844 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
4845 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4846 if( pCol->colFlags & COLFLAG_GENERATED ){
4847 if( pCol->colFlags & COLFLAG_BUSY ){
4848 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4849 pCol->zCnName);
4850 return 0;
4852 pCol->colFlags |= COLFLAG_BUSY;
4853 if( pCol->colFlags & COLFLAG_NOTAVAIL ){
4854 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc);
4856 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
4857 return iSrc;
4858 }else
4859 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4860 if( pCol->affinity==SQLITE_AFF_REAL ){
4861 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
4862 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4863 return target;
4864 }else{
4865 return iSrc;
4867 }else{
4868 /* Coding an expression that is part of an index where column names
4869 ** in the index refer to the table to which the index belongs */
4870 iTab = pParse->iSelfTab - 1;
4873 else if( pParse->pIdxPartExpr
4874 && 0!=(r1 = exprPartidxExprLookup(pParse, pExpr, target))
4876 return r1;
4878 assert( ExprUseYTab(pExpr) );
4879 assert( pExpr->y.pTab!=0 );
4880 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
4881 pExpr->iColumn, iTab, target,
4882 pExpr->op2);
4883 return iReg;
4885 case TK_INTEGER: {
4886 codeInteger(pParse, pExpr, 0, target);
4887 return target;
4889 case TK_TRUEFALSE: {
4890 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
4891 return target;
4893 #ifndef SQLITE_OMIT_FLOATING_POINT
4894 case TK_FLOAT: {
4895 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4896 codeReal(v, pExpr->u.zToken, 0, target);
4897 return target;
4899 #endif
4900 case TK_STRING: {
4901 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4902 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
4903 return target;
4905 default: {
4906 /* Make NULL the default case so that if a bug causes an illegal
4907 ** Expr node to be passed into this function, it will be handled
4908 ** sanely and not crash. But keep the assert() to bring the problem
4909 ** to the attention of the developers. */
4910 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
4911 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4912 return target;
4914 #ifndef SQLITE_OMIT_BLOB_LITERAL
4915 case TK_BLOB: {
4916 int n;
4917 const char *z;
4918 char *zBlob;
4919 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4920 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
4921 assert( pExpr->u.zToken[1]=='\'' );
4922 z = &pExpr->u.zToken[2];
4923 n = sqlite3Strlen30(z) - 1;
4924 assert( z[n]=='\'' );
4925 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
4926 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
4927 return target;
4929 #endif
4930 case TK_VARIABLE: {
4931 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4932 assert( pExpr->u.zToken!=0 );
4933 assert( pExpr->u.zToken[0]!=0 );
4934 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
4935 return target;
4937 case TK_REGISTER: {
4938 return pExpr->iTable;
4940 #ifndef SQLITE_OMIT_CAST
4941 case TK_CAST: {
4942 /* Expressions of the form: CAST(pLeft AS token) */
4943 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4944 assert( inReg==target );
4945 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4946 sqlite3VdbeAddOp2(v, OP_Cast, target,
4947 sqlite3AffinityType(pExpr->u.zToken, 0));
4948 return inReg;
4950 #endif /* SQLITE_OMIT_CAST */
4951 case TK_IS:
4952 case TK_ISNOT:
4953 op = (op==TK_IS) ? TK_EQ : TK_NE;
4954 p5 = SQLITE_NULLEQ;
4955 /* fall-through */
4956 case TK_LT:
4957 case TK_LE:
4958 case TK_GT:
4959 case TK_GE:
4960 case TK_NE:
4961 case TK_EQ: {
4962 Expr *pLeft = pExpr->pLeft;
4963 if( sqlite3ExprIsVector(pLeft) ){
4964 codeVectorCompare(pParse, pExpr, target, op, p5);
4965 }else{
4966 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
4967 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4968 sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);
4969 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
4970 sqlite3VdbeCurrentAddr(v)+2, p5,
4971 ExprHasProperty(pExpr,EP_Commuted));
4972 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4973 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4974 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4975 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4976 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
4977 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
4978 if( p5==SQLITE_NULLEQ ){
4979 sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);
4980 }else{
4981 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);
4983 testcase( regFree1==0 );
4984 testcase( regFree2==0 );
4986 break;
4988 case TK_AND:
4989 case TK_OR:
4990 case TK_PLUS:
4991 case TK_STAR:
4992 case TK_MINUS:
4993 case TK_REM:
4994 case TK_BITAND:
4995 case TK_BITOR:
4996 case TK_SLASH:
4997 case TK_LSHIFT:
4998 case TK_RSHIFT:
4999 case TK_CONCAT: {
5000 assert( TK_AND==OP_And ); testcase( op==TK_AND );
5001 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
5002 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
5003 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
5004 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
5005 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
5006 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
5007 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
5008 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
5009 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
5010 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
5011 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5012 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5013 sqlite3VdbeAddOp3(v, op, r2, r1, target);
5014 testcase( regFree1==0 );
5015 testcase( regFree2==0 );
5016 break;
5018 case TK_UMINUS: {
5019 Expr *pLeft = pExpr->pLeft;
5020 assert( pLeft );
5021 if( pLeft->op==TK_INTEGER ){
5022 codeInteger(pParse, pLeft, 1, target);
5023 return target;
5024 #ifndef SQLITE_OMIT_FLOATING_POINT
5025 }else if( pLeft->op==TK_FLOAT ){
5026 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5027 codeReal(v, pLeft->u.zToken, 1, target);
5028 return target;
5029 #endif
5030 }else{
5031 tempX.op = TK_INTEGER;
5032 tempX.flags = EP_IntValue|EP_TokenOnly;
5033 tempX.u.iValue = 0;
5034 ExprClearVVAProperties(&tempX);
5035 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
5036 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
5037 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
5038 testcase( regFree2==0 );
5040 break;
5042 case TK_BITNOT:
5043 case TK_NOT: {
5044 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
5045 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
5046 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5047 testcase( regFree1==0 );
5048 sqlite3VdbeAddOp2(v, op, r1, inReg);
5049 break;
5051 case TK_TRUTH: {
5052 int isTrue; /* IS TRUE or IS NOT TRUE */
5053 int bNormal; /* IS TRUE or IS FALSE */
5054 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5055 testcase( regFree1==0 );
5056 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5057 bNormal = pExpr->op2==TK_IS;
5058 testcase( isTrue && bNormal);
5059 testcase( !isTrue && bNormal);
5060 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
5061 break;
5063 case TK_ISNULL:
5064 case TK_NOTNULL: {
5065 int addr;
5066 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
5067 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
5068 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
5069 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5070 testcase( regFree1==0 );
5071 addr = sqlite3VdbeAddOp1(v, op, r1);
5072 VdbeCoverageIf(v, op==TK_ISNULL);
5073 VdbeCoverageIf(v, op==TK_NOTNULL);
5074 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
5075 sqlite3VdbeJumpHere(v, addr);
5076 break;
5078 case TK_AGG_FUNCTION: {
5079 AggInfo *pInfo = pExpr->pAggInfo;
5080 if( pInfo==0
5081 || NEVER(pExpr->iAgg<0)
5082 || NEVER(pExpr->iAgg>=pInfo->nFunc)
5084 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5085 sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr);
5086 }else{
5087 return AggInfoFuncReg(pInfo, pExpr->iAgg);
5089 break;
5091 case TK_FUNCTION: {
5092 ExprList *pFarg; /* List of function arguments */
5093 int nFarg; /* Number of function arguments */
5094 FuncDef *pDef; /* The function definition object */
5095 const char *zId; /* The function name */
5096 u32 constMask = 0; /* Mask of function arguments that are constant */
5097 int i; /* Loop counter */
5098 sqlite3 *db = pParse->db; /* The database connection */
5099 u8 enc = ENC(db); /* The text encoding used by this database */
5100 CollSeq *pColl = 0; /* A collating sequence */
5102 #ifndef SQLITE_OMIT_WINDOWFUNC
5103 if( ExprHasProperty(pExpr, EP_WinFunc) ){
5104 return pExpr->y.pWin->regResult;
5106 #endif
5108 if( ConstFactorOk(pParse)
5109 && sqlite3ExprIsConstantNotJoin(pParse,pExpr)
5111 /* SQL functions can be expensive. So try to avoid running them
5112 ** multiple times if we know they always give the same result */
5113 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
5115 assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
5116 assert( ExprUseXList(pExpr) );
5117 pFarg = pExpr->x.pList;
5118 nFarg = pFarg ? pFarg->nExpr : 0;
5119 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5120 zId = pExpr->u.zToken;
5121 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
5122 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
5123 if( pDef==0 && pParse->explain ){
5124 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
5126 #endif
5127 if( pDef==0 || pDef->xFinalize!=0 ){
5128 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
5129 break;
5131 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
5132 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
5133 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
5134 return exprCodeInlineFunction(pParse, pFarg,
5135 SQLITE_PTR_TO_INT(pDef->pUserData), target);
5136 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
5137 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
5140 for(i=0; i<nFarg; i++){
5141 if( i<32 && sqlite3ExprIsConstant(pParse, pFarg->a[i].pExpr) ){
5142 testcase( i==31 );
5143 constMask |= MASKBIT32(i);
5145 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
5146 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
5149 if( pFarg ){
5150 if( constMask ){
5151 r1 = pParse->nMem+1;
5152 pParse->nMem += nFarg;
5153 }else{
5154 r1 = sqlite3GetTempRange(pParse, nFarg);
5157 /* For length() and typeof() and octet_length() functions,
5158 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
5159 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid
5160 ** unnecessary data loading.
5162 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
5163 u8 exprOp;
5164 assert( nFarg==1 );
5165 assert( pFarg->a[0].pExpr!=0 );
5166 exprOp = pFarg->a[0].pExpr->op;
5167 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
5168 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
5169 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
5170 assert( SQLITE_FUNC_BYTELEN==OPFLAG_BYTELENARG );
5171 assert( (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG)==OPFLAG_BYTELENARG );
5172 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_LENGTHARG );
5173 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_TYPEOFARG );
5174 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_BYTELENARG);
5175 pFarg->a[0].pExpr->op2 = pDef->funcFlags & OPFLAG_BYTELENARG;
5179 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_FACTOR);
5180 }else{
5181 r1 = 0;
5183 #ifndef SQLITE_OMIT_VIRTUALTABLE
5184 /* Possibly overload the function if the first argument is
5185 ** a virtual table column.
5187 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
5188 ** second argument, not the first, as the argument to test to
5189 ** see if it is a column in a virtual table. This is done because
5190 ** the left operand of infix functions (the operand we want to
5191 ** control overloading) ends up as the second argument to the
5192 ** function. The expression "A glob B" is equivalent to
5193 ** "glob(B,A). We want to use the A in "A glob B" to test
5194 ** for function overloading. But we use the B term in "glob(B,A)".
5196 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
5197 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
5198 }else if( nFarg>0 ){
5199 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
5201 #endif
5202 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
5203 if( !pColl ) pColl = db->pDfltColl;
5204 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
5206 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
5207 pDef, pExpr->op2);
5208 if( nFarg ){
5209 if( constMask==0 ){
5210 sqlite3ReleaseTempRange(pParse, r1, nFarg);
5211 }else{
5212 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
5215 return target;
5217 #ifndef SQLITE_OMIT_SUBQUERY
5218 case TK_EXISTS:
5219 case TK_SELECT: {
5220 int nCol;
5221 testcase( op==TK_EXISTS );
5222 testcase( op==TK_SELECT );
5223 if( pParse->db->mallocFailed ){
5224 return 0;
5225 }else if( op==TK_SELECT
5226 && ALWAYS( ExprUseXSelect(pExpr) )
5227 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
5229 sqlite3SubselectError(pParse, nCol, 1);
5230 }else{
5231 return sqlite3CodeSubselect(pParse, pExpr);
5233 break;
5235 case TK_SELECT_COLUMN: {
5236 int n;
5237 Expr *pLeft = pExpr->pLeft;
5238 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){
5239 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft);
5240 pLeft->op2 = pParse->withinRJSubrtn;
5242 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR );
5243 n = sqlite3ExprVectorSize(pLeft);
5244 if( pExpr->iTable!=n ){
5245 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
5246 pExpr->iTable, n);
5248 return pLeft->iTable + pExpr->iColumn;
5250 case TK_IN: {
5251 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
5252 int destIfNull = sqlite3VdbeMakeLabel(pParse);
5253 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
5254 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
5255 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
5256 sqlite3VdbeResolveLabel(v, destIfFalse);
5257 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
5258 sqlite3VdbeResolveLabel(v, destIfNull);
5259 return target;
5261 #endif /* SQLITE_OMIT_SUBQUERY */
5265 ** x BETWEEN y AND z
5267 ** This is equivalent to
5269 ** x>=y AND x<=z
5271 ** X is stored in pExpr->pLeft.
5272 ** Y is stored in pExpr->pList->a[0].pExpr.
5273 ** Z is stored in pExpr->pList->a[1].pExpr.
5275 case TK_BETWEEN: {
5276 exprCodeBetween(pParse, pExpr, target, 0, 0);
5277 return target;
5279 case TK_COLLATE: {
5280 if( !ExprHasProperty(pExpr, EP_Collate) ){
5281 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
5282 ** "SOFT-COLLATE" that is added to constraints that are pushed down
5283 ** from outer queries into sub-queries by the WHERE-clause push-down
5284 ** optimization. Clear subtypes as subtypes may not cross a subquery
5285 ** boundary.
5287 assert( pExpr->pLeft );
5288 sqlite3ExprCode(pParse, pExpr->pLeft, target);
5289 sqlite3VdbeAddOp1(v, OP_ClrSubtype, target);
5290 return target;
5291 }else{
5292 pExpr = pExpr->pLeft;
5293 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
5296 case TK_SPAN:
5297 case TK_UPLUS: {
5298 pExpr = pExpr->pLeft;
5299 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
5302 case TK_TRIGGER: {
5303 /* If the opcode is TK_TRIGGER, then the expression is a reference
5304 ** to a column in the new.* or old.* pseudo-tables available to
5305 ** trigger programs. In this case Expr.iTable is set to 1 for the
5306 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
5307 ** is set to the column of the pseudo-table to read, or to -1 to
5308 ** read the rowid field.
5310 ** The expression is implemented using an OP_Param opcode. The p1
5311 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
5312 ** to reference another column of the old.* pseudo-table, where
5313 ** i is the index of the column. For a new.rowid reference, p1 is
5314 ** set to (n+1), where n is the number of columns in each pseudo-table.
5315 ** For a reference to any other column in the new.* pseudo-table, p1
5316 ** is set to (n+2+i), where n and i are as defined previously. For
5317 ** example, if the table on which triggers are being fired is
5318 ** declared as:
5320 ** CREATE TABLE t1(a, b);
5322 ** Then p1 is interpreted as follows:
5324 ** p1==0 -> old.rowid p1==3 -> new.rowid
5325 ** p1==1 -> old.a p1==4 -> new.a
5326 ** p1==2 -> old.b p1==5 -> new.b
5328 Table *pTab;
5329 int iCol;
5330 int p1;
5332 assert( ExprUseYTab(pExpr) );
5333 pTab = pExpr->y.pTab;
5334 iCol = pExpr->iColumn;
5335 p1 = pExpr->iTable * (pTab->nCol+1) + 1
5336 + sqlite3TableColumnToStorage(pTab, iCol);
5338 assert( pExpr->iTable==0 || pExpr->iTable==1 );
5339 assert( iCol>=-1 && iCol<pTab->nCol );
5340 assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
5341 assert( p1>=0 && p1<(pTab->nCol*2+2) );
5343 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
5344 VdbeComment((v, "r[%d]=%s.%s", target,
5345 (pExpr->iTable ? "new" : "old"),
5346 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
5349 #ifndef SQLITE_OMIT_FLOATING_POINT
5350 /* If the column has REAL affinity, it may currently be stored as an
5351 ** integer. Use OP_RealAffinity to make sure it is really real.
5353 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
5354 ** floating point when extracting it from the record. */
5355 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
5356 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
5358 #endif
5359 break;
5362 case TK_VECTOR: {
5363 sqlite3ErrorMsg(pParse, "row value misused");
5364 break;
5367 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
5368 ** that derive from the right-hand table of a LEFT JOIN. The
5369 ** Expr.iTable value is the table number for the right-hand table.
5370 ** The expression is only evaluated if that table is not currently
5371 ** on a LEFT JOIN NULL row.
5373 case TK_IF_NULL_ROW: {
5374 int addrINR;
5375 u8 okConstFactor = pParse->okConstFactor;
5376 AggInfo *pAggInfo = pExpr->pAggInfo;
5377 if( pAggInfo ){
5378 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
5379 if( !pAggInfo->directMode ){
5380 inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg);
5381 break;
5383 if( pExpr->pAggInfo->useSortingIdx ){
5384 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
5385 pAggInfo->aCol[pExpr->iAgg].iSorterColumn,
5386 target);
5387 inReg = target;
5388 break;
5391 addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target);
5392 /* The OP_IfNullRow opcode above can overwrite the result register with
5393 ** NULL. So we have to ensure that the result register is not a value
5394 ** that is suppose to be a constant. Two defenses are needed:
5395 ** (1) Temporarily disable factoring of constant expressions
5396 ** (2) Make sure the computed value really is stored in register
5397 ** "target" and not someplace else.
5399 pParse->okConstFactor = 0; /* note (1) above */
5400 sqlite3ExprCode(pParse, pExpr->pLeft, target);
5401 assert( target==inReg );
5402 pParse->okConstFactor = okConstFactor;
5403 sqlite3VdbeJumpHere(v, addrINR);
5404 break;
5408 ** Form A:
5409 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5411 ** Form B:
5412 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5414 ** Form A is can be transformed into the equivalent form B as follows:
5415 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
5416 ** WHEN x=eN THEN rN ELSE y END
5418 ** X (if it exists) is in pExpr->pLeft.
5419 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
5420 ** odd. The Y is also optional. If the number of elements in x.pList
5421 ** is even, then Y is omitted and the "otherwise" result is NULL.
5422 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
5424 ** The result of the expression is the Ri for the first matching Ei,
5425 ** or if there is no matching Ei, the ELSE term Y, or if there is
5426 ** no ELSE term, NULL.
5428 case TK_CASE: {
5429 int endLabel; /* GOTO label for end of CASE stmt */
5430 int nextCase; /* GOTO label for next WHEN clause */
5431 int nExpr; /* 2x number of WHEN terms */
5432 int i; /* Loop counter */
5433 ExprList *pEList; /* List of WHEN terms */
5434 struct ExprList_item *aListelem; /* Array of WHEN terms */
5435 Expr opCompare; /* The X==Ei expression */
5436 Expr *pX; /* The X expression */
5437 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
5438 Expr *pDel = 0;
5439 sqlite3 *db = pParse->db;
5441 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
5442 assert(pExpr->x.pList->nExpr > 0);
5443 pEList = pExpr->x.pList;
5444 aListelem = pEList->a;
5445 nExpr = pEList->nExpr;
5446 endLabel = sqlite3VdbeMakeLabel(pParse);
5447 if( (pX = pExpr->pLeft)!=0 ){
5448 pDel = sqlite3ExprDup(db, pX, 0);
5449 if( db->mallocFailed ){
5450 sqlite3ExprDelete(db, pDel);
5451 break;
5453 testcase( pX->op==TK_COLUMN );
5454 sqlite3ExprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
5455 testcase( regFree1==0 );
5456 memset(&opCompare, 0, sizeof(opCompare));
5457 opCompare.op = TK_EQ;
5458 opCompare.pLeft = pDel;
5459 pTest = &opCompare;
5460 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
5461 ** The value in regFree1 might get SCopy-ed into the file result.
5462 ** So make sure that the regFree1 register is not reused for other
5463 ** purposes and possibly overwritten. */
5464 regFree1 = 0;
5466 for(i=0; i<nExpr-1; i=i+2){
5467 if( pX ){
5468 assert( pTest!=0 );
5469 opCompare.pRight = aListelem[i].pExpr;
5470 }else{
5471 pTest = aListelem[i].pExpr;
5473 nextCase = sqlite3VdbeMakeLabel(pParse);
5474 testcase( pTest->op==TK_COLUMN );
5475 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
5476 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
5477 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
5478 sqlite3VdbeGoto(v, endLabel);
5479 sqlite3VdbeResolveLabel(v, nextCase);
5481 if( (nExpr&1)!=0 ){
5482 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
5483 }else{
5484 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
5486 sqlite3ExprDelete(db, pDel);
5487 setDoNotMergeFlagOnCopy(v);
5488 sqlite3VdbeResolveLabel(v, endLabel);
5489 break;
5491 #ifndef SQLITE_OMIT_TRIGGER
5492 case TK_RAISE: {
5493 assert( pExpr->affExpr==OE_Rollback
5494 || pExpr->affExpr==OE_Abort
5495 || pExpr->affExpr==OE_Fail
5496 || pExpr->affExpr==OE_Ignore
5498 if( !pParse->pTriggerTab && !pParse->nested ){
5499 sqlite3ErrorMsg(pParse,
5500 "RAISE() may only be used within a trigger-program");
5501 return 0;
5503 if( pExpr->affExpr==OE_Abort ){
5504 sqlite3MayAbort(pParse);
5506 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5507 if( pExpr->affExpr==OE_Ignore ){
5508 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, OE_Ignore);
5509 VdbeCoverage(v);
5510 }else{
5511 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5512 sqlite3VdbeAddOp3(v, OP_Halt,
5513 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
5514 pExpr->affExpr, r1);
5516 break;
5518 #endif
5520 sqlite3ReleaseTempReg(pParse, regFree1);
5521 sqlite3ReleaseTempReg(pParse, regFree2);
5522 return inReg;
5526 ** Generate code that will evaluate expression pExpr just one time
5527 ** per prepared statement execution.
5529 ** If the expression uses functions (that might throw an exception) then
5530 ** guard them with an OP_Once opcode to ensure that the code is only executed
5531 ** once. If no functions are involved, then factor the code out and put it at
5532 ** the end of the prepared statement in the initialization section.
5534 ** If regDest>0 then the result is always stored in that register and the
5535 ** result is not reusable. If regDest<0 then this routine is free to
5536 ** store the value wherever it wants. The register where the expression
5537 ** is stored is returned. When regDest<0, two identical expressions might
5538 ** code to the same register, if they do not contain function calls and hence
5539 ** are factored out into the initialization section at the end of the
5540 ** prepared statement.
5542 int sqlite3ExprCodeRunJustOnce(
5543 Parse *pParse, /* Parsing context */
5544 Expr *pExpr, /* The expression to code when the VDBE initializes */
5545 int regDest /* Store the value in this register */
5547 ExprList *p;
5548 assert( ConstFactorOk(pParse) );
5549 assert( regDest!=0 );
5550 p = pParse->pConstExpr;
5551 if( regDest<0 && p ){
5552 struct ExprList_item *pItem;
5553 int i;
5554 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
5555 if( pItem->fg.reusable
5556 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0
5558 return pItem->u.iConstExprReg;
5562 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
5563 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
5564 Vdbe *v = pParse->pVdbe;
5565 int addr;
5566 assert( v );
5567 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
5568 pParse->okConstFactor = 0;
5569 if( !pParse->db->mallocFailed ){
5570 if( regDest<0 ) regDest = ++pParse->nMem;
5571 sqlite3ExprCode(pParse, pExpr, regDest);
5573 pParse->okConstFactor = 1;
5574 sqlite3ExprDelete(pParse->db, pExpr);
5575 sqlite3VdbeJumpHere(v, addr);
5576 }else{
5577 p = sqlite3ExprListAppend(pParse, p, pExpr);
5578 if( p ){
5579 struct ExprList_item *pItem = &p->a[p->nExpr-1];
5580 pItem->fg.reusable = regDest<0;
5581 if( regDest<0 ) regDest = ++pParse->nMem;
5582 pItem->u.iConstExprReg = regDest;
5584 pParse->pConstExpr = p;
5586 return regDest;
5590 ** Generate code to evaluate an expression and store the results
5591 ** into a register. Return the register number where the results
5592 ** are stored.
5594 ** If the register is a temporary register that can be deallocated,
5595 ** then write its number into *pReg. If the result register is not
5596 ** a temporary, then set *pReg to zero.
5598 ** If pExpr is a constant, then this routine might generate this
5599 ** code to fill the register in the initialization section of the
5600 ** VDBE program, in order to factor it out of the evaluation loop.
5602 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
5603 int r2;
5604 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
5605 if( ConstFactorOk(pParse)
5606 && ALWAYS(pExpr!=0)
5607 && pExpr->op!=TK_REGISTER
5608 && sqlite3ExprIsConstantNotJoin(pParse, pExpr)
5610 *pReg = 0;
5611 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
5612 }else{
5613 int r1 = sqlite3GetTempReg(pParse);
5614 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
5615 if( r2==r1 ){
5616 *pReg = r1;
5617 }else{
5618 sqlite3ReleaseTempReg(pParse, r1);
5619 *pReg = 0;
5622 return r2;
5626 ** Generate code that will evaluate expression pExpr and store the
5627 ** results in register target. The results are guaranteed to appear
5628 ** in register target.
5630 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
5631 int inReg;
5633 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
5634 assert( target>0 && target<=pParse->nMem );
5635 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
5636 if( pParse->pVdbe==0 ) return;
5637 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
5638 if( inReg!=target ){
5639 u8 op;
5640 Expr *pX = sqlite3ExprSkipCollateAndLikely(pExpr);
5641 testcase( pX!=pExpr );
5642 if( ALWAYS(pX)
5643 && (ExprHasProperty(pX,EP_Subquery) || pX->op==TK_REGISTER)
5645 op = OP_Copy;
5646 }else{
5647 op = OP_SCopy;
5649 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
5654 ** Make a transient copy of expression pExpr and then code it using
5655 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5656 ** except that the input expression is guaranteed to be unchanged.
5658 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
5659 sqlite3 *db = pParse->db;
5660 pExpr = sqlite3ExprDup(db, pExpr, 0);
5661 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
5662 sqlite3ExprDelete(db, pExpr);
5666 ** Generate code that will evaluate expression pExpr and store the
5667 ** results in register target. The results are guaranteed to appear
5668 ** in register target. If the expression is constant, then this routine
5669 ** might choose to code the expression at initialization time.
5671 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
5672 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pParse,pExpr) ){
5673 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
5674 }else{
5675 sqlite3ExprCodeCopy(pParse, pExpr, target);
5680 ** Generate code that pushes the value of every element of the given
5681 ** expression list into a sequence of registers beginning at target.
5683 ** Return the number of elements evaluated. The number returned will
5684 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5685 ** is defined.
5687 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5688 ** filled using OP_SCopy. OP_Copy must be used instead.
5690 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5691 ** factored out into initialization code.
5693 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5694 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5695 ** in registers at srcReg, and so the value can be copied from there.
5696 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5697 ** are simply omitted rather than being copied from srcReg.
5699 int sqlite3ExprCodeExprList(
5700 Parse *pParse, /* Parsing context */
5701 ExprList *pList, /* The expression list to be coded */
5702 int target, /* Where to write results */
5703 int srcReg, /* Source registers if SQLITE_ECEL_REF */
5704 u8 flags /* SQLITE_ECEL_* flags */
5706 struct ExprList_item *pItem;
5707 int i, j, n;
5708 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
5709 Vdbe *v = pParse->pVdbe;
5710 assert( pList!=0 );
5711 assert( target>0 );
5712 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
5713 n = pList->nExpr;
5714 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
5715 for(pItem=pList->a, i=0; i<n; i++, pItem++){
5716 Expr *pExpr = pItem->pExpr;
5717 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5718 if( pItem->fg.bSorterRef ){
5719 i--;
5720 n--;
5721 }else
5722 #endif
5723 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
5724 if( flags & SQLITE_ECEL_OMITREF ){
5725 i--;
5726 n--;
5727 }else{
5728 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
5730 }else if( (flags & SQLITE_ECEL_FACTOR)!=0
5731 && sqlite3ExprIsConstantNotJoin(pParse,pExpr)
5733 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
5734 }else{
5735 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
5736 if( inReg!=target+i ){
5737 VdbeOp *pOp;
5738 if( copyOp==OP_Copy
5739 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy
5740 && pOp->p1+pOp->p3+1==inReg
5741 && pOp->p2+pOp->p3+1==target+i
5742 && pOp->p5==0 /* The do-not-merge flag must be clear */
5744 pOp->p3++;
5745 }else{
5746 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
5751 return n;
5755 ** Generate code for a BETWEEN operator.
5757 ** x BETWEEN y AND z
5759 ** The above is equivalent to
5761 ** x>=y AND x<=z
5763 ** Code it as such, taking care to do the common subexpression
5764 ** elimination of x.
5766 ** The xJumpIf parameter determines details:
5768 ** NULL: Store the boolean result in reg[dest]
5769 ** sqlite3ExprIfTrue: Jump to dest if true
5770 ** sqlite3ExprIfFalse: Jump to dest if false
5772 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5774 static void exprCodeBetween(
5775 Parse *pParse, /* Parsing and code generating context */
5776 Expr *pExpr, /* The BETWEEN expression */
5777 int dest, /* Jump destination or storage location */
5778 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
5779 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
5781 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
5782 Expr compLeft; /* The x>=y term */
5783 Expr compRight; /* The x<=z term */
5784 int regFree1 = 0; /* Temporary use register */
5785 Expr *pDel = 0;
5786 sqlite3 *db = pParse->db;
5788 memset(&compLeft, 0, sizeof(Expr));
5789 memset(&compRight, 0, sizeof(Expr));
5790 memset(&exprAnd, 0, sizeof(Expr));
5792 assert( ExprUseXList(pExpr) );
5793 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
5794 if( db->mallocFailed==0 ){
5795 exprAnd.op = TK_AND;
5796 exprAnd.pLeft = &compLeft;
5797 exprAnd.pRight = &compRight;
5798 compLeft.op = TK_GE;
5799 compLeft.pLeft = pDel;
5800 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
5801 compRight.op = TK_LE;
5802 compRight.pLeft = pDel;
5803 compRight.pRight = pExpr->x.pList->a[1].pExpr;
5804 sqlite3ExprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
5805 if( xJump ){
5806 xJump(pParse, &exprAnd, dest, jumpIfNull);
5807 }else{
5808 /* Mark the expression is being from the ON or USING clause of a join
5809 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5810 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5811 ** for clarity, but we are out of bits in the Expr.flags field so we
5812 ** have to reuse the EP_OuterON bit. Bummer. */
5813 pDel->flags |= EP_OuterON;
5814 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
5816 sqlite3ReleaseTempReg(pParse, regFree1);
5818 sqlite3ExprDelete(db, pDel);
5820 /* Ensure adequate test coverage */
5821 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
5822 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
5823 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
5824 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
5825 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
5826 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
5827 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
5828 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
5829 testcase( xJump==0 );
5833 ** Generate code for a boolean expression such that a jump is made
5834 ** to the label "dest" if the expression is true but execution
5835 ** continues straight thru if the expression is false.
5837 ** If the expression evaluates to NULL (neither true nor false), then
5838 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5840 ** This code depends on the fact that certain token values (ex: TK_EQ)
5841 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5842 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5843 ** the make process cause these values to align. Assert()s in the code
5844 ** below verify that the numbers are aligned correctly.
5846 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5847 Vdbe *v = pParse->pVdbe;
5848 int op = 0;
5849 int regFree1 = 0;
5850 int regFree2 = 0;
5851 int r1, r2;
5853 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5854 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5855 if( NEVER(pExpr==0) ) return; /* No way this can happen */
5856 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
5857 op = pExpr->op;
5858 switch( op ){
5859 case TK_AND:
5860 case TK_OR: {
5861 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5862 if( pAlt!=pExpr ){
5863 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
5864 }else if( op==TK_AND ){
5865 int d2 = sqlite3VdbeMakeLabel(pParse);
5866 testcase( jumpIfNull==0 );
5867 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
5868 jumpIfNull^SQLITE_JUMPIFNULL);
5869 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5870 sqlite3VdbeResolveLabel(v, d2);
5871 }else{
5872 testcase( jumpIfNull==0 );
5873 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5874 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5876 break;
5878 case TK_NOT: {
5879 testcase( jumpIfNull==0 );
5880 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5881 break;
5883 case TK_TRUTH: {
5884 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5885 int isTrue; /* IS TRUE or IS NOT TRUE */
5886 testcase( jumpIfNull==0 );
5887 isNot = pExpr->op2==TK_ISNOT;
5888 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5889 testcase( isTrue && isNot );
5890 testcase( !isTrue && isNot );
5891 if( isTrue ^ isNot ){
5892 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5893 isNot ? SQLITE_JUMPIFNULL : 0);
5894 }else{
5895 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5896 isNot ? SQLITE_JUMPIFNULL : 0);
5898 break;
5900 case TK_IS:
5901 case TK_ISNOT:
5902 testcase( op==TK_IS );
5903 testcase( op==TK_ISNOT );
5904 op = (op==TK_IS) ? TK_EQ : TK_NE;
5905 jumpIfNull = SQLITE_NULLEQ;
5906 /* no break */ deliberate_fall_through
5907 case TK_LT:
5908 case TK_LE:
5909 case TK_GT:
5910 case TK_GE:
5911 case TK_NE:
5912 case TK_EQ: {
5913 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5914 testcase( jumpIfNull==0 );
5915 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5916 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5917 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5918 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
5919 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5920 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5921 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5922 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5923 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5924 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5925 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5926 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5927 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5928 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5929 testcase( regFree1==0 );
5930 testcase( regFree2==0 );
5931 break;
5933 case TK_ISNULL:
5934 case TK_NOTNULL: {
5935 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
5936 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
5937 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5938 sqlite3VdbeTypeofColumn(v, r1);
5939 sqlite3VdbeAddOp2(v, op, r1, dest);
5940 VdbeCoverageIf(v, op==TK_ISNULL);
5941 VdbeCoverageIf(v, op==TK_NOTNULL);
5942 testcase( regFree1==0 );
5943 break;
5945 case TK_BETWEEN: {
5946 testcase( jumpIfNull==0 );
5947 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
5948 break;
5950 #ifndef SQLITE_OMIT_SUBQUERY
5951 case TK_IN: {
5952 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
5953 int destIfNull = jumpIfNull ? dest : destIfFalse;
5954 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
5955 sqlite3VdbeGoto(v, dest);
5956 sqlite3VdbeResolveLabel(v, destIfFalse);
5957 break;
5959 #endif
5960 default: {
5961 default_expr:
5962 if( ExprAlwaysTrue(pExpr) ){
5963 sqlite3VdbeGoto(v, dest);
5964 }else if( ExprAlwaysFalse(pExpr) ){
5965 /* No-op */
5966 }else{
5967 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5968 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
5969 VdbeCoverage(v);
5970 testcase( regFree1==0 );
5971 testcase( jumpIfNull==0 );
5973 break;
5976 sqlite3ReleaseTempReg(pParse, regFree1);
5977 sqlite3ReleaseTempReg(pParse, regFree2);
5981 ** Generate code for a boolean expression such that a jump is made
5982 ** to the label "dest" if the expression is false but execution
5983 ** continues straight thru if the expression is true.
5985 ** If the expression evaluates to NULL (neither true nor false) then
5986 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5987 ** is 0.
5989 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5990 Vdbe *v = pParse->pVdbe;
5991 int op = 0;
5992 int regFree1 = 0;
5993 int regFree2 = 0;
5994 int r1, r2;
5996 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5997 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5998 if( pExpr==0 ) return;
5999 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
6001 /* The value of pExpr->op and op are related as follows:
6003 ** pExpr->op op
6004 ** --------- ----------
6005 ** TK_ISNULL OP_NotNull
6006 ** TK_NOTNULL OP_IsNull
6007 ** TK_NE OP_Eq
6008 ** TK_EQ OP_Ne
6009 ** TK_GT OP_Le
6010 ** TK_LE OP_Gt
6011 ** TK_GE OP_Lt
6012 ** TK_LT OP_Ge
6014 ** For other values of pExpr->op, op is undefined and unused.
6015 ** The value of TK_ and OP_ constants are arranged such that we
6016 ** can compute the mapping above using the following expression.
6017 ** Assert()s verify that the computation is correct.
6019 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
6021 /* Verify correct alignment of TK_ and OP_ constants
6023 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
6024 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
6025 assert( pExpr->op!=TK_NE || op==OP_Eq );
6026 assert( pExpr->op!=TK_EQ || op==OP_Ne );
6027 assert( pExpr->op!=TK_LT || op==OP_Ge );
6028 assert( pExpr->op!=TK_LE || op==OP_Gt );
6029 assert( pExpr->op!=TK_GT || op==OP_Le );
6030 assert( pExpr->op!=TK_GE || op==OP_Lt );
6032 switch( pExpr->op ){
6033 case TK_AND:
6034 case TK_OR: {
6035 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
6036 if( pAlt!=pExpr ){
6037 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
6038 }else if( pExpr->op==TK_AND ){
6039 testcase( jumpIfNull==0 );
6040 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
6041 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
6042 }else{
6043 int d2 = sqlite3VdbeMakeLabel(pParse);
6044 testcase( jumpIfNull==0 );
6045 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
6046 jumpIfNull^SQLITE_JUMPIFNULL);
6047 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
6048 sqlite3VdbeResolveLabel(v, d2);
6050 break;
6052 case TK_NOT: {
6053 testcase( jumpIfNull==0 );
6054 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
6055 break;
6057 case TK_TRUTH: {
6058 int isNot; /* IS NOT TRUE or IS NOT FALSE */
6059 int isTrue; /* IS TRUE or IS NOT TRUE */
6060 testcase( jumpIfNull==0 );
6061 isNot = pExpr->op2==TK_ISNOT;
6062 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
6063 testcase( isTrue && isNot );
6064 testcase( !isTrue && isNot );
6065 if( isTrue ^ isNot ){
6066 /* IS TRUE and IS NOT FALSE */
6067 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
6068 isNot ? 0 : SQLITE_JUMPIFNULL);
6070 }else{
6071 /* IS FALSE and IS NOT TRUE */
6072 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
6073 isNot ? 0 : SQLITE_JUMPIFNULL);
6075 break;
6077 case TK_IS:
6078 case TK_ISNOT:
6079 testcase( pExpr->op==TK_IS );
6080 testcase( pExpr->op==TK_ISNOT );
6081 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
6082 jumpIfNull = SQLITE_NULLEQ;
6083 /* no break */ deliberate_fall_through
6084 case TK_LT:
6085 case TK_LE:
6086 case TK_GT:
6087 case TK_GE:
6088 case TK_NE:
6089 case TK_EQ: {
6090 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
6091 testcase( jumpIfNull==0 );
6092 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
6093 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
6094 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
6095 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
6096 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
6097 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
6098 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
6099 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
6100 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
6101 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
6102 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
6103 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
6104 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
6105 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
6106 testcase( regFree1==0 );
6107 testcase( regFree2==0 );
6108 break;
6110 case TK_ISNULL:
6111 case TK_NOTNULL: {
6112 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
6113 sqlite3VdbeTypeofColumn(v, r1);
6114 sqlite3VdbeAddOp2(v, op, r1, dest);
6115 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
6116 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
6117 testcase( regFree1==0 );
6118 break;
6120 case TK_BETWEEN: {
6121 testcase( jumpIfNull==0 );
6122 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
6123 break;
6125 #ifndef SQLITE_OMIT_SUBQUERY
6126 case TK_IN: {
6127 if( jumpIfNull ){
6128 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
6129 }else{
6130 int destIfNull = sqlite3VdbeMakeLabel(pParse);
6131 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
6132 sqlite3VdbeResolveLabel(v, destIfNull);
6134 break;
6136 #endif
6137 default: {
6138 default_expr:
6139 if( ExprAlwaysFalse(pExpr) ){
6140 sqlite3VdbeGoto(v, dest);
6141 }else if( ExprAlwaysTrue(pExpr) ){
6142 /* no-op */
6143 }else{
6144 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
6145 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
6146 VdbeCoverage(v);
6147 testcase( regFree1==0 );
6148 testcase( jumpIfNull==0 );
6150 break;
6153 sqlite3ReleaseTempReg(pParse, regFree1);
6154 sqlite3ReleaseTempReg(pParse, regFree2);
6158 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
6159 ** code generation, and that copy is deleted after code generation. This
6160 ** ensures that the original pExpr is unchanged.
6162 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
6163 sqlite3 *db = pParse->db;
6164 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
6165 if( db->mallocFailed==0 ){
6166 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
6168 sqlite3ExprDelete(db, pCopy);
6172 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
6173 ** type of expression.
6175 ** If pExpr is a simple SQL value - an integer, real, string, blob
6176 ** or NULL value - then the VDBE currently being prepared is configured
6177 ** to re-prepare each time a new value is bound to variable pVar.
6179 ** Additionally, if pExpr is a simple SQL value and the value is the
6180 ** same as that currently bound to variable pVar, non-zero is returned.
6181 ** Otherwise, if the values are not the same or if pExpr is not a simple
6182 ** SQL value, zero is returned.
6184 static int exprCompareVariable(
6185 const Parse *pParse,
6186 const Expr *pVar,
6187 const Expr *pExpr
6189 int res = 0;
6190 int iVar;
6191 sqlite3_value *pL, *pR = 0;
6193 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
6194 if( pR ){
6195 iVar = pVar->iColumn;
6196 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
6197 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
6198 if( pL ){
6199 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
6200 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
6202 res = 0==sqlite3MemCompare(pL, pR, 0);
6204 sqlite3ValueFree(pR);
6205 sqlite3ValueFree(pL);
6208 return res;
6212 ** Do a deep comparison of two expression trees. Return 0 if the two
6213 ** expressions are completely identical. Return 1 if they differ only
6214 ** by a COLLATE operator at the top level. Return 2 if there are differences
6215 ** other than the top-level COLLATE operator.
6217 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6218 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6220 ** The pA side might be using TK_REGISTER. If that is the case and pB is
6221 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
6223 ** Sometimes this routine will return 2 even if the two expressions
6224 ** really are equivalent. If we cannot prove that the expressions are
6225 ** identical, we return 2 just to be safe. So if this routine
6226 ** returns 2, then you do not really know for certain if the two
6227 ** expressions are the same. But if you get a 0 or 1 return, then you
6228 ** can be sure the expressions are the same. In the places where
6229 ** this routine is used, it does not hurt to get an extra 2 - that
6230 ** just might result in some slightly slower code. But returning
6231 ** an incorrect 0 or 1 could lead to a malfunction.
6233 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
6234 ** pParse->pReprepare can be matched against literals in pB. The
6235 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
6236 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
6237 ** Argument pParse should normally be NULL. If it is not NULL and pA or
6238 ** pB causes a return value of 2.
6240 int sqlite3ExprCompare(
6241 const Parse *pParse,
6242 const Expr *pA,
6243 const Expr *pB,
6244 int iTab
6246 u32 combinedFlags;
6247 if( pA==0 || pB==0 ){
6248 return pB==pA ? 0 : 2;
6250 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
6251 return 0;
6253 combinedFlags = pA->flags | pB->flags;
6254 if( combinedFlags & EP_IntValue ){
6255 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
6256 return 0;
6258 return 2;
6260 if( pA->op!=pB->op || pA->op==TK_RAISE ){
6261 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
6262 return 1;
6264 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
6265 return 1;
6267 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN
6268 && pB->iTable<0 && pA->iTable==iTab
6270 /* fall through */
6271 }else{
6272 return 2;
6275 assert( !ExprHasProperty(pA, EP_IntValue) );
6276 assert( !ExprHasProperty(pB, EP_IntValue) );
6277 if( pA->u.zToken ){
6278 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
6279 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
6280 #ifndef SQLITE_OMIT_WINDOWFUNC
6281 assert( pA->op==pB->op );
6282 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
6283 return 2;
6285 if( ExprHasProperty(pA,EP_WinFunc) ){
6286 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
6287 return 2;
6290 #endif
6291 }else if( pA->op==TK_NULL ){
6292 return 0;
6293 }else if( pA->op==TK_COLLATE ){
6294 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
6295 }else
6296 if( pB->u.zToken!=0
6297 && pA->op!=TK_COLUMN
6298 && pA->op!=TK_AGG_COLUMN
6299 && strcmp(pA->u.zToken,pB->u.zToken)!=0
6301 return 2;
6304 if( (pA->flags & (EP_Distinct|EP_Commuted))
6305 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
6306 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
6307 if( combinedFlags & EP_xIsSelect ) return 2;
6308 if( (combinedFlags & EP_FixedCol)==0
6309 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
6310 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
6311 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
6312 if( pA->op!=TK_STRING
6313 && pA->op!=TK_TRUEFALSE
6314 && ALWAYS((combinedFlags & EP_Reduced)==0)
6316 if( pA->iColumn!=pB->iColumn ) return 2;
6317 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
6318 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
6319 return 2;
6323 return 0;
6327 ** Compare two ExprList objects. Return 0 if they are identical, 1
6328 ** if they are certainly different, or 2 if it is not possible to
6329 ** determine if they are identical or not.
6331 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6332 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6334 ** This routine might return non-zero for equivalent ExprLists. The
6335 ** only consequence will be disabled optimizations. But this routine
6336 ** must never return 0 if the two ExprList objects are different, or
6337 ** a malfunction will result.
6339 ** Two NULL pointers are considered to be the same. But a NULL pointer
6340 ** always differs from a non-NULL pointer.
6342 int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){
6343 int i;
6344 if( pA==0 && pB==0 ) return 0;
6345 if( pA==0 || pB==0 ) return 1;
6346 if( pA->nExpr!=pB->nExpr ) return 1;
6347 for(i=0; i<pA->nExpr; i++){
6348 int res;
6349 Expr *pExprA = pA->a[i].pExpr;
6350 Expr *pExprB = pB->a[i].pExpr;
6351 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1;
6352 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
6354 return 0;
6358 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
6359 ** are ignored.
6361 int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){
6362 return sqlite3ExprCompare(0,
6363 sqlite3ExprSkipCollate(pA),
6364 sqlite3ExprSkipCollate(pB),
6365 iTab);
6369 ** Return non-zero if Expr p can only be true if pNN is not NULL.
6371 ** Or if seenNot is true, return non-zero if Expr p can only be
6372 ** non-NULL if pNN is not NULL
6374 static int exprImpliesNotNull(
6375 const Parse *pParse,/* Parsing context */
6376 const Expr *p, /* The expression to be checked */
6377 const Expr *pNN, /* The expression that is NOT NULL */
6378 int iTab, /* Table being evaluated */
6379 int seenNot /* Return true only if p can be any non-NULL value */
6381 assert( p );
6382 assert( pNN );
6383 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
6384 return pNN->op!=TK_NULL;
6386 switch( p->op ){
6387 case TK_IN: {
6388 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
6389 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
6390 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6392 case TK_BETWEEN: {
6393 ExprList *pList;
6394 assert( ExprUseXList(p) );
6395 pList = p->x.pList;
6396 assert( pList!=0 );
6397 assert( pList->nExpr==2 );
6398 if( seenNot ) return 0;
6399 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
6400 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
6402 return 1;
6404 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6406 case TK_EQ:
6407 case TK_NE:
6408 case TK_LT:
6409 case TK_LE:
6410 case TK_GT:
6411 case TK_GE:
6412 case TK_PLUS:
6413 case TK_MINUS:
6414 case TK_BITOR:
6415 case TK_LSHIFT:
6416 case TK_RSHIFT:
6417 case TK_CONCAT:
6418 seenNot = 1;
6419 /* no break */ deliberate_fall_through
6420 case TK_STAR:
6421 case TK_REM:
6422 case TK_BITAND:
6423 case TK_SLASH: {
6424 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
6425 /* no break */ deliberate_fall_through
6427 case TK_SPAN:
6428 case TK_COLLATE:
6429 case TK_UPLUS:
6430 case TK_UMINUS: {
6431 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
6433 case TK_TRUTH: {
6434 if( seenNot ) return 0;
6435 if( p->op2!=TK_IS ) return 0;
6436 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6438 case TK_BITNOT:
6439 case TK_NOT: {
6440 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6443 return 0;
6447 ** Return true if we can prove the pE2 will always be true if pE1 is
6448 ** true. Return false if we cannot complete the proof or if pE2 might
6449 ** be false. Examples:
6451 ** pE1: x==5 pE2: x==5 Result: true
6452 ** pE1: x>0 pE2: x==5 Result: false
6453 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
6454 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
6455 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
6456 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
6457 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false
6459 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
6460 ** Expr.iTable<0 then assume a table number given by iTab.
6462 ** If pParse is not NULL, then the values of bound variables in pE1 are
6463 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
6464 ** modified to record which bound variables are referenced. If pParse
6465 ** is NULL, then false will be returned if pE1 contains any bound variables.
6467 ** When in doubt, return false. Returning true might give a performance
6468 ** improvement. Returning false might cause a performance reduction, but
6469 ** it will always give the correct answer and is hence always safe.
6471 int sqlite3ExprImpliesExpr(
6472 const Parse *pParse,
6473 const Expr *pE1,
6474 const Expr *pE2,
6475 int iTab
6477 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
6478 return 1;
6480 if( pE2->op==TK_OR
6481 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
6482 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
6484 return 1;
6486 if( pE2->op==TK_NOTNULL
6487 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
6489 return 1;
6491 return 0;
6494 /* This is a helper function to impliesNotNullRow(). In this routine,
6495 ** set pWalker->eCode to one only if *both* of the input expressions
6496 ** separately have the implies-not-null-row property.
6498 static void bothImplyNotNullRow(Walker *pWalker, Expr *pE1, Expr *pE2){
6499 if( pWalker->eCode==0 ){
6500 sqlite3WalkExpr(pWalker, pE1);
6501 if( pWalker->eCode ){
6502 pWalker->eCode = 0;
6503 sqlite3WalkExpr(pWalker, pE2);
6509 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
6510 ** If the expression node requires that the table at pWalker->iCur
6511 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
6513 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
6514 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when
6515 ** evaluating terms in the ON clause of an inner join.
6517 ** This routine controls an optimization. False positives (setting
6518 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
6519 ** (never setting pWalker->eCode) is a harmless missed optimization.
6521 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
6522 testcase( pExpr->op==TK_AGG_COLUMN );
6523 testcase( pExpr->op==TK_AGG_FUNCTION );
6524 if( ExprHasProperty(pExpr, EP_OuterON) ) return WRC_Prune;
6525 if( ExprHasProperty(pExpr, EP_InnerON) && pWalker->mWFlags ){
6526 /* If iCur is used in an inner-join ON clause to the left of a
6527 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
6528 ** But it is difficult to check for that condition precisely.
6529 ** To keep things simple, any use of iCur from any inner-join is
6530 ** ignored while attempting to simplify a RIGHT JOIN. */
6531 return WRC_Prune;
6533 switch( pExpr->op ){
6534 case TK_ISNOT:
6535 case TK_ISNULL:
6536 case TK_NOTNULL:
6537 case TK_IS:
6538 case TK_VECTOR:
6539 case TK_FUNCTION:
6540 case TK_TRUTH:
6541 case TK_CASE:
6542 testcase( pExpr->op==TK_ISNOT );
6543 testcase( pExpr->op==TK_ISNULL );
6544 testcase( pExpr->op==TK_NOTNULL );
6545 testcase( pExpr->op==TK_IS );
6546 testcase( pExpr->op==TK_VECTOR );
6547 testcase( pExpr->op==TK_FUNCTION );
6548 testcase( pExpr->op==TK_TRUTH );
6549 testcase( pExpr->op==TK_CASE );
6550 return WRC_Prune;
6552 case TK_COLUMN:
6553 if( pWalker->u.iCur==pExpr->iTable ){
6554 pWalker->eCode = 1;
6555 return WRC_Abort;
6557 return WRC_Prune;
6559 case TK_OR:
6560 case TK_AND:
6561 /* Both sides of an AND or OR must separately imply non-null-row.
6562 ** Consider these cases:
6563 ** 1. NOT (x AND y)
6564 ** 2. x OR y
6565 ** If only one of x or y is non-null-row, then the overall expression
6566 ** can be true if the other arm is false (case 1) or true (case 2).
6568 testcase( pExpr->op==TK_OR );
6569 testcase( pExpr->op==TK_AND );
6570 bothImplyNotNullRow(pWalker, pExpr->pLeft, pExpr->pRight);
6571 return WRC_Prune;
6573 case TK_IN:
6574 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
6575 ** both of which can be true. But apart from these cases, if
6576 ** the left-hand side of the IN is NULL then the IN itself will be
6577 ** NULL. */
6578 if( ExprUseXList(pExpr) && ALWAYS(pExpr->x.pList->nExpr>0) ){
6579 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6581 return WRC_Prune;
6583 case TK_BETWEEN:
6584 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
6585 ** both y and z must be non-null row */
6586 assert( ExprUseXList(pExpr) );
6587 assert( pExpr->x.pList->nExpr==2 );
6588 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6589 bothImplyNotNullRow(pWalker, pExpr->x.pList->a[0].pExpr,
6590 pExpr->x.pList->a[1].pExpr);
6591 return WRC_Prune;
6593 /* Virtual tables are allowed to use constraints like x=NULL. So
6594 ** a term of the form x=y does not prove that y is not null if x
6595 ** is the column of a virtual table */
6596 case TK_EQ:
6597 case TK_NE:
6598 case TK_LT:
6599 case TK_LE:
6600 case TK_GT:
6601 case TK_GE: {
6602 Expr *pLeft = pExpr->pLeft;
6603 Expr *pRight = pExpr->pRight;
6604 testcase( pExpr->op==TK_EQ );
6605 testcase( pExpr->op==TK_NE );
6606 testcase( pExpr->op==TK_LT );
6607 testcase( pExpr->op==TK_LE );
6608 testcase( pExpr->op==TK_GT );
6609 testcase( pExpr->op==TK_GE );
6610 /* The y.pTab=0 assignment in wherecode.c always happens after the
6611 ** impliesNotNullRow() test */
6612 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
6613 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
6614 if( (pLeft->op==TK_COLUMN
6615 && ALWAYS(pLeft->y.pTab!=0)
6616 && IsVirtual(pLeft->y.pTab))
6617 || (pRight->op==TK_COLUMN
6618 && ALWAYS(pRight->y.pTab!=0)
6619 && IsVirtual(pRight->y.pTab))
6621 return WRC_Prune;
6623 /* no break */ deliberate_fall_through
6625 default:
6626 return WRC_Continue;
6631 ** Return true (non-zero) if expression p can only be true if at least
6632 ** one column of table iTab is non-null. In other words, return true
6633 ** if expression p will always be NULL or false if every column of iTab
6634 ** is NULL.
6636 ** False negatives are acceptable. In other words, it is ok to return
6637 ** zero even if expression p will never be true of every column of iTab
6638 ** is NULL. A false negative is merely a missed optimization opportunity.
6640 ** False positives are not allowed, however. A false positive may result
6641 ** in an incorrect answer.
6643 ** Terms of p that are marked with EP_OuterON (and hence that come from
6644 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6646 ** This routine is used to check if a LEFT JOIN can be converted into
6647 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6648 ** clause requires that some column of the right table of the LEFT JOIN
6649 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6650 ** ordinary join.
6652 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab, int isRJ){
6653 Walker w;
6654 p = sqlite3ExprSkipCollateAndLikely(p);
6655 if( p==0 ) return 0;
6656 if( p->op==TK_NOTNULL ){
6657 p = p->pLeft;
6658 }else{
6659 while( p->op==TK_AND ){
6660 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab, isRJ) ) return 1;
6661 p = p->pRight;
6664 w.xExprCallback = impliesNotNullRow;
6665 w.xSelectCallback = 0;
6666 w.xSelectCallback2 = 0;
6667 w.eCode = 0;
6668 w.mWFlags = isRJ!=0;
6669 w.u.iCur = iTab;
6670 sqlite3WalkExpr(&w, p);
6671 return w.eCode;
6675 ** An instance of the following structure is used by the tree walker
6676 ** to determine if an expression can be evaluated by reference to the
6677 ** index only, without having to do a search for the corresponding
6678 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6679 ** is the cursor for the table.
6681 struct IdxCover {
6682 Index *pIdx; /* The index to be tested for coverage */
6683 int iCur; /* Cursor number for the table corresponding to the index */
6687 ** Check to see if there are references to columns in table
6688 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6689 ** pWalker->u.pIdxCover->pIdx.
6691 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
6692 if( pExpr->op==TK_COLUMN
6693 && pExpr->iTable==pWalker->u.pIdxCover->iCur
6694 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
6696 pWalker->eCode = 1;
6697 return WRC_Abort;
6699 return WRC_Continue;
6703 ** Determine if an index pIdx on table with cursor iCur contains will
6704 ** the expression pExpr. Return true if the index does cover the
6705 ** expression and false if the pExpr expression references table columns
6706 ** that are not found in the index pIdx.
6708 ** An index covering an expression means that the expression can be
6709 ** evaluated using only the index and without having to lookup the
6710 ** corresponding table entry.
6712 int sqlite3ExprCoveredByIndex(
6713 Expr *pExpr, /* The index to be tested */
6714 int iCur, /* The cursor number for the corresponding table */
6715 Index *pIdx /* The index that might be used for coverage */
6717 Walker w;
6718 struct IdxCover xcov;
6719 memset(&w, 0, sizeof(w));
6720 xcov.iCur = iCur;
6721 xcov.pIdx = pIdx;
6722 w.xExprCallback = exprIdxCover;
6723 w.u.pIdxCover = &xcov;
6724 sqlite3WalkExpr(&w, pExpr);
6725 return !w.eCode;
6729 /* Structure used to pass information throughout the Walker in order to
6730 ** implement sqlite3ReferencesSrcList().
6732 struct RefSrcList {
6733 sqlite3 *db; /* Database connection used for sqlite3DbRealloc() */
6734 SrcList *pRef; /* Looking for references to these tables */
6735 i64 nExclude; /* Number of tables to exclude from the search */
6736 int *aiExclude; /* Cursor IDs for tables to exclude from the search */
6740 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6742 ** When entering a new subquery on the pExpr argument, add all FROM clause
6743 ** entries for that subquery to the exclude list.
6745 ** When leaving the subquery, remove those entries from the exclude list.
6747 static int selectRefEnter(Walker *pWalker, Select *pSelect){
6748 struct RefSrcList *p = pWalker->u.pRefSrcList;
6749 SrcList *pSrc = pSelect->pSrc;
6750 i64 i, j;
6751 int *piNew;
6752 if( pSrc->nSrc==0 ) return WRC_Continue;
6753 j = p->nExclude;
6754 p->nExclude += pSrc->nSrc;
6755 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
6756 if( piNew==0 ){
6757 p->nExclude = 0;
6758 return WRC_Abort;
6759 }else{
6760 p->aiExclude = piNew;
6762 for(i=0; i<pSrc->nSrc; i++, j++){
6763 p->aiExclude[j] = pSrc->a[i].iCursor;
6765 return WRC_Continue;
6767 static void selectRefLeave(Walker *pWalker, Select *pSelect){
6768 struct RefSrcList *p = pWalker->u.pRefSrcList;
6769 SrcList *pSrc = pSelect->pSrc;
6770 if( p->nExclude ){
6771 assert( p->nExclude>=pSrc->nSrc );
6772 p->nExclude -= pSrc->nSrc;
6776 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6778 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6779 ** of the tables shown in RefSrcList.pRef.
6781 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6782 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6784 static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){
6785 if( pExpr->op==TK_COLUMN
6786 || pExpr->op==TK_AGG_COLUMN
6788 int i;
6789 struct RefSrcList *p = pWalker->u.pRefSrcList;
6790 SrcList *pSrc = p->pRef;
6791 int nSrc = pSrc ? pSrc->nSrc : 0;
6792 for(i=0; i<nSrc; i++){
6793 if( pExpr->iTable==pSrc->a[i].iCursor ){
6794 pWalker->eCode |= 1;
6795 return WRC_Continue;
6798 for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
6799 if( i>=p->nExclude ){
6800 pWalker->eCode |= 2;
6803 return WRC_Continue;
6807 ** Check to see if pExpr references any tables in pSrcList.
6808 ** Possible return values:
6810 ** 1 pExpr does references a table in pSrcList.
6812 ** 0 pExpr references some table that is not defined in either
6813 ** pSrcList or in subqueries of pExpr itself.
6815 ** -1 pExpr only references no tables at all, or it only
6816 ** references tables defined in subqueries of pExpr itself.
6818 ** As currently used, pExpr is always an aggregate function call. That
6819 ** fact is exploited for efficiency.
6821 int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){
6822 Walker w;
6823 struct RefSrcList x;
6824 assert( pParse->db!=0 );
6825 memset(&w, 0, sizeof(w));
6826 memset(&x, 0, sizeof(x));
6827 w.xExprCallback = exprRefToSrcList;
6828 w.xSelectCallback = selectRefEnter;
6829 w.xSelectCallback2 = selectRefLeave;
6830 w.u.pRefSrcList = &x;
6831 x.db = pParse->db;
6832 x.pRef = pSrcList;
6833 assert( pExpr->op==TK_AGG_FUNCTION );
6834 assert( ExprUseXList(pExpr) );
6835 sqlite3WalkExprList(&w, pExpr->x.pList);
6836 if( pExpr->pLeft ){
6837 assert( pExpr->pLeft->op==TK_ORDER );
6838 assert( ExprUseXList(pExpr->pLeft) );
6839 assert( pExpr->pLeft->x.pList!=0 );
6840 sqlite3WalkExprList(&w, pExpr->pLeft->x.pList);
6842 #ifndef SQLITE_OMIT_WINDOWFUNC
6843 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6844 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
6846 #endif
6847 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude);
6848 if( w.eCode & 0x01 ){
6849 return 1;
6850 }else if( w.eCode ){
6851 return 0;
6852 }else{
6853 return -1;
6858 ** This is a Walker expression node callback.
6860 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6861 ** object that is referenced does not refer directly to the Expr. If
6862 ** it does, make a copy. This is done because the pExpr argument is
6863 ** subject to change.
6865 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6866 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6868 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
6869 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
6870 && pExpr->pAggInfo!=0
6872 AggInfo *pAggInfo = pExpr->pAggInfo;
6873 int iAgg = pExpr->iAgg;
6874 Parse *pParse = pWalker->pParse;
6875 sqlite3 *db = pParse->db;
6876 assert( iAgg>=0 );
6877 if( pExpr->op!=TK_AGG_FUNCTION ){
6878 if( iAgg<pAggInfo->nColumn
6879 && pAggInfo->aCol[iAgg].pCExpr==pExpr
6881 pExpr = sqlite3ExprDup(db, pExpr, 0);
6882 if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){
6883 pAggInfo->aCol[iAgg].pCExpr = pExpr;
6886 }else{
6887 assert( pExpr->op==TK_AGG_FUNCTION );
6888 if( ALWAYS(iAgg<pAggInfo->nFunc)
6889 && pAggInfo->aFunc[iAgg].pFExpr==pExpr
6891 pExpr = sqlite3ExprDup(db, pExpr, 0);
6892 if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){
6893 pAggInfo->aFunc[iAgg].pFExpr = pExpr;
6898 return WRC_Continue;
6902 ** Initialize a Walker object so that will persist AggInfo entries referenced
6903 ** by the tree that is walked.
6905 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
6906 memset(pWalker, 0, sizeof(*pWalker));
6907 pWalker->pParse = pParse;
6908 pWalker->xExprCallback = agginfoPersistExprCb;
6909 pWalker->xSelectCallback = sqlite3SelectWalkNoop;
6913 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6914 ** the new element. Return a negative number if malloc fails.
6916 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
6917 int i;
6918 pInfo->aCol = sqlite3ArrayAllocate(
6920 pInfo->aCol,
6921 sizeof(pInfo->aCol[0]),
6922 &pInfo->nColumn,
6925 return i;
6929 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6930 ** the new element. Return a negative number if malloc fails.
6932 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
6933 int i;
6934 pInfo->aFunc = sqlite3ArrayAllocate(
6936 pInfo->aFunc,
6937 sizeof(pInfo->aFunc[0]),
6938 &pInfo->nFunc,
6941 return i;
6945 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6946 ** Return the index in aCol[] of the entry that describes that column.
6948 ** If no prior entry is found, create a new one and return -1. The
6949 ** new column will have an index of pAggInfo->nColumn-1.
6951 static void findOrCreateAggInfoColumn(
6952 Parse *pParse, /* Parsing context */
6953 AggInfo *pAggInfo, /* The AggInfo object to search and/or modify */
6954 Expr *pExpr /* Expr describing the column to find or insert */
6956 struct AggInfo_col *pCol;
6957 int k;
6959 assert( pAggInfo->iFirstReg==0 );
6960 pCol = pAggInfo->aCol;
6961 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
6962 if( pCol->pCExpr==pExpr ) return;
6963 if( pCol->iTable==pExpr->iTable
6964 && pCol->iColumn==pExpr->iColumn
6965 && pExpr->op!=TK_IF_NULL_ROW
6967 goto fix_up_expr;
6970 k = addAggInfoColumn(pParse->db, pAggInfo);
6971 if( k<0 ){
6972 /* OOM on resize */
6973 assert( pParse->db->mallocFailed );
6974 return;
6976 pCol = &pAggInfo->aCol[k];
6977 assert( ExprUseYTab(pExpr) );
6978 pCol->pTab = pExpr->y.pTab;
6979 pCol->iTable = pExpr->iTable;
6980 pCol->iColumn = pExpr->iColumn;
6981 pCol->iSorterColumn = -1;
6982 pCol->pCExpr = pExpr;
6983 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){
6984 int j, n;
6985 ExprList *pGB = pAggInfo->pGroupBy;
6986 struct ExprList_item *pTerm = pGB->a;
6987 n = pGB->nExpr;
6988 for(j=0; j<n; j++, pTerm++){
6989 Expr *pE = pTerm->pExpr;
6990 if( pE->op==TK_COLUMN
6991 && pE->iTable==pExpr->iTable
6992 && pE->iColumn==pExpr->iColumn
6994 pCol->iSorterColumn = j;
6995 break;
6999 if( pCol->iSorterColumn<0 ){
7000 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
7002 fix_up_expr:
7003 ExprSetVVAProperty(pExpr, EP_NoReduce);
7004 assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo );
7005 pExpr->pAggInfo = pAggInfo;
7006 if( pExpr->op==TK_COLUMN ){
7007 pExpr->op = TK_AGG_COLUMN;
7009 pExpr->iAgg = (i16)k;
7013 ** This is the xExprCallback for a tree walker. It is used to
7014 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
7015 ** for additional information.
7017 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
7018 int i;
7019 NameContext *pNC = pWalker->u.pNC;
7020 Parse *pParse = pNC->pParse;
7021 SrcList *pSrcList = pNC->pSrcList;
7022 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
7024 assert( pNC->ncFlags & NC_UAggInfo );
7025 assert( pAggInfo->iFirstReg==0 );
7026 switch( pExpr->op ){
7027 default: {
7028 IndexedExpr *pIEpr;
7029 Expr tmp;
7030 assert( pParse->iSelfTab==0 );
7031 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
7032 if( pParse->pIdxEpr==0 ) break;
7033 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
7034 int iDataCur = pIEpr->iDataCur;
7035 if( iDataCur<0 ) continue;
7036 if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
7038 if( pIEpr==0 ) break;
7039 if( NEVER(!ExprUseYTab(pExpr)) ) break;
7040 for(i=0; i<pSrcList->nSrc; i++){
7041 if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
7043 if( i>=pSrcList->nSrc ) break;
7044 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
7045 if( pParse->nErr ){ return WRC_Abort; }
7047 /* If we reach this point, it means that expression pExpr can be
7048 ** translated into a reference to an index column as described by
7049 ** pIEpr.
7051 memset(&tmp, 0, sizeof(tmp));
7052 tmp.op = TK_AGG_COLUMN;
7053 tmp.iTable = pIEpr->iIdxCur;
7054 tmp.iColumn = pIEpr->iIdxCol;
7055 findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp);
7056 if( pParse->nErr ){ return WRC_Abort; }
7057 assert( pAggInfo->aCol!=0 );
7058 assert( tmp.iAgg<pAggInfo->nColumn );
7059 pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
7060 pExpr->pAggInfo = pAggInfo;
7061 pExpr->iAgg = tmp.iAgg;
7062 return WRC_Prune;
7064 case TK_IF_NULL_ROW:
7065 case TK_AGG_COLUMN:
7066 case TK_COLUMN: {
7067 testcase( pExpr->op==TK_AGG_COLUMN );
7068 testcase( pExpr->op==TK_COLUMN );
7069 testcase( pExpr->op==TK_IF_NULL_ROW );
7070 /* Check to see if the column is in one of the tables in the FROM
7071 ** clause of the aggregate query */
7072 if( ALWAYS(pSrcList!=0) ){
7073 SrcItem *pItem = pSrcList->a;
7074 for(i=0; i<pSrcList->nSrc; i++, pItem++){
7075 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
7076 if( pExpr->iTable==pItem->iCursor ){
7077 findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr);
7078 break;
7079 } /* endif pExpr->iTable==pItem->iCursor */
7080 } /* end loop over pSrcList */
7082 return WRC_Continue;
7084 case TK_AGG_FUNCTION: {
7085 if( (pNC->ncFlags & NC_InAggFunc)==0
7086 && pWalker->walkerDepth==pExpr->op2
7087 && pExpr->pAggInfo==0
7089 /* Check to see if pExpr is a duplicate of another aggregate
7090 ** function that is already in the pAggInfo structure
7092 struct AggInfo_func *pItem = pAggInfo->aFunc;
7093 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
7094 if( NEVER(pItem->pFExpr==pExpr) ) break;
7095 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
7096 break;
7099 if( i>=pAggInfo->nFunc ){
7100 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
7102 u8 enc = ENC(pParse->db);
7103 i = addAggInfoFunc(pParse->db, pAggInfo);
7104 if( i>=0 ){
7105 int nArg;
7106 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
7107 pItem = &pAggInfo->aFunc[i];
7108 pItem->pFExpr = pExpr;
7109 assert( ExprUseUToken(pExpr) );
7110 nArg = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
7111 pItem->pFunc = sqlite3FindFunction(pParse->db,
7112 pExpr->u.zToken, nArg, enc, 0);
7113 assert( pItem->bOBUnique==0 );
7114 if( pExpr->pLeft
7115 && (pItem->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)==0
7117 /* The NEEDCOLL test above causes any ORDER BY clause on
7118 ** aggregate min() or max() to be ignored. */
7119 ExprList *pOBList;
7120 assert( nArg>0 );
7121 assert( pExpr->pLeft->op==TK_ORDER );
7122 assert( ExprUseXList(pExpr->pLeft) );
7123 pItem->iOBTab = pParse->nTab++;
7124 pOBList = pExpr->pLeft->x.pList;
7125 assert( pOBList->nExpr>0 );
7126 assert( pItem->bOBUnique==0 );
7127 if( pOBList->nExpr==1
7128 && nArg==1
7129 && sqlite3ExprCompare(0,pOBList->a[0].pExpr,
7130 pExpr->x.pList->a[0].pExpr,0)==0
7132 pItem->bOBPayload = 0;
7133 pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct);
7134 }else{
7135 pItem->bOBPayload = 1;
7137 pItem->bUseSubtype =
7138 (pItem->pFunc->funcFlags & SQLITE_SUBTYPE)!=0;
7139 }else{
7140 pItem->iOBTab = -1;
7142 if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){
7143 pItem->iDistinct = pParse->nTab++;
7144 }else{
7145 pItem->iDistinct = -1;
7149 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
7151 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
7152 ExprSetVVAProperty(pExpr, EP_NoReduce);
7153 pExpr->iAgg = (i16)i;
7154 pExpr->pAggInfo = pAggInfo;
7155 return WRC_Prune;
7156 }else{
7157 return WRC_Continue;
7161 return WRC_Continue;
7165 ** Analyze the pExpr expression looking for aggregate functions and
7166 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
7167 ** points to. Additional entries are made on the AggInfo object as
7168 ** necessary.
7170 ** This routine should only be called after the expression has been
7171 ** analyzed by sqlite3ResolveExprNames().
7173 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
7174 Walker w;
7175 w.xExprCallback = analyzeAggregate;
7176 w.xSelectCallback = sqlite3WalkerDepthIncrease;
7177 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
7178 w.walkerDepth = 0;
7179 w.u.pNC = pNC;
7180 w.pParse = 0;
7181 assert( pNC->pSrcList!=0 );
7182 sqlite3WalkExpr(&w, pExpr);
7186 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
7187 ** expression list. Return the number of errors.
7189 ** If an error is found, the analysis is cut short.
7191 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
7192 struct ExprList_item *pItem;
7193 int i;
7194 if( pList ){
7195 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
7196 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
7202 ** Allocate a single new register for use to hold some intermediate result.
7204 int sqlite3GetTempReg(Parse *pParse){
7205 if( pParse->nTempReg==0 ){
7206 return ++pParse->nMem;
7208 return pParse->aTempReg[--pParse->nTempReg];
7212 ** Deallocate a register, making available for reuse for some other
7213 ** purpose.
7215 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
7216 if( iReg ){
7217 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
7218 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
7219 pParse->aTempReg[pParse->nTempReg++] = iReg;
7225 ** Allocate or deallocate a block of nReg consecutive registers.
7227 int sqlite3GetTempRange(Parse *pParse, int nReg){
7228 int i, n;
7229 if( nReg==1 ) return sqlite3GetTempReg(pParse);
7230 i = pParse->iRangeReg;
7231 n = pParse->nRangeReg;
7232 if( nReg<=n ){
7233 pParse->iRangeReg += nReg;
7234 pParse->nRangeReg -= nReg;
7235 }else{
7236 i = pParse->nMem+1;
7237 pParse->nMem += nReg;
7239 return i;
7241 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
7242 if( nReg==1 ){
7243 sqlite3ReleaseTempReg(pParse, iReg);
7244 return;
7246 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
7247 if( nReg>pParse->nRangeReg ){
7248 pParse->nRangeReg = nReg;
7249 pParse->iRangeReg = iReg;
7254 ** Mark all temporary registers as being unavailable for reuse.
7256 ** Always invoke this procedure after coding a subroutine or co-routine
7257 ** that might be invoked from other parts of the code, to ensure that
7258 ** the sub/co-routine does not use registers in common with the code that
7259 ** invokes the sub/co-routine.
7261 void sqlite3ClearTempRegCache(Parse *pParse){
7262 pParse->nTempReg = 0;
7263 pParse->nRangeReg = 0;
7267 ** Make sure sufficient registers have been allocated so that
7268 ** iReg is a valid register number.
7270 void sqlite3TouchRegister(Parse *pParse, int iReg){
7271 if( pParse->nMem<iReg ) pParse->nMem = iReg;
7274 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
7276 ** Return the latest reusable register in the set of all registers.
7277 ** The value returned is no less than iMin. If any register iMin or
7278 ** greater is in permanent use, then return one more than that last
7279 ** permanent register.
7281 int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){
7282 const ExprList *pList = pParse->pConstExpr;
7283 if( pList ){
7284 int i;
7285 for(i=0; i<pList->nExpr; i++){
7286 if( pList->a[i].u.iConstExprReg>=iMin ){
7287 iMin = pList->a[i].u.iConstExprReg + 1;
7291 pParse->nTempReg = 0;
7292 pParse->nRangeReg = 0;
7293 return iMin;
7295 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
7298 ** Validate that no temporary register falls within the range of
7299 ** iFirst..iLast, inclusive. This routine is only call from within assert()
7300 ** statements.
7302 #ifdef SQLITE_DEBUG
7303 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
7304 int i;
7305 if( pParse->nRangeReg>0
7306 && pParse->iRangeReg+pParse->nRangeReg > iFirst
7307 && pParse->iRangeReg <= iLast
7309 return 0;
7311 for(i=0; i<pParse->nTempReg; i++){
7312 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
7313 return 0;
7316 if( pParse->pConstExpr ){
7317 ExprList *pList = pParse->pConstExpr;
7318 for(i=0; i<pList->nExpr; i++){
7319 int iReg = pList->a[i].u.iConstExprReg;
7320 if( iReg==0 ) continue;
7321 if( iReg>=iFirst && iReg<=iLast ) return 0;
7324 return 1;
7326 #endif /* SQLITE_DEBUG */